flatmarkdown-ast2html 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hidekazu Kubota
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/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # flatmarkdown-ast2html
2
+
3
+ Renders a [flatmarkdown](https://github.com/sosuisen/flatmarkdown) JSON AST to HTML in TypeScript.
4
+
5
+ The `flatmarkdown` Rust crate exposes `markdown_to_ast()` which converts Markdown into a JSON AST. This library takes that AST and produces HTML — no Rust toolchain needed at render time.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add flatmarkdown-ast2html
11
+ # or
12
+ npm install flatmarkdown-ast2html
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```ts
18
+ import { renderToHtml } from 'flatmarkdown-ast2html';
19
+
20
+ // From a parsed AST object
21
+ const ast = {
22
+ type: 'document',
23
+ children: [
24
+ {
25
+ type: 'paragraph',
26
+ children: [
27
+ { type: 'text', value: 'Hello ' },
28
+ { type: 'strong', children: [{ type: 'text', value: 'world' }] },
29
+ ],
30
+ },
31
+ ],
32
+ };
33
+
34
+ const html = renderToHtml(ast);
35
+ // => '<p>Hello <strong>world</strong></p>\n'
36
+
37
+ // From a JSON string (e.g. directly from flatmarkdown CLI/WASM output)
38
+ const json = '{"type":"document","children":[{"type":"paragraph","children":[{"type":"text","value":"Hi"}]}]}';
39
+ const html2 = renderToHtml(json);
40
+ // => '<p>Hi</p>\n'
41
+ ```
42
+
43
+ ## API
44
+
45
+ ### `renderToHtml(ast, options?)`
46
+
47
+ ```ts
48
+ function renderToHtml(ast: AstNode | string, options?: RenderOptions): string;
49
+ ```
50
+
51
+ | Parameter | Type | Description |
52
+ |-----------|------|-------------|
53
+ | `ast` | `AstNode \| string` | Parsed AST object or JSON string |
54
+ | `options` | `RenderOptions` | Optional rendering configuration |
55
+
56
+ Returns an HTML string.
57
+
58
+ ### `RenderOptions`
59
+
60
+ ```ts
61
+ interface RenderOptions {
62
+ wikilink?: WikiLinkOptions;
63
+ }
64
+ ```
65
+
66
+ ### `WikiLinkOptions`
67
+
68
+ Customize how `[[wikilinks]]` are rendered. This makes the output compatible with any routing library or framework.
69
+
70
+ ```ts
71
+ interface WikiLinkOptions {
72
+ tagName?: string; // default: 'a'
73
+ urlAttr?: string; // default: 'href'
74
+ urlPrefix?: string; // default: ''
75
+ attrs?: Record<string, string>; // default: { 'data-wikilink': 'true' }
76
+ }
77
+ ```
78
+
79
+ | Field | Default | Description |
80
+ |-------|---------|-------------|
81
+ | `tagName` | `'a'` | HTML/component tag name. Use `'Link'` for React Router, `'A'` for SolidJS, etc. |
82
+ | `urlAttr` | `'href'` | Attribute name for the URL. Use `'to'` for React Router, `'routerLink'` for Angular. |
83
+ | `urlPrefix` | `''` | String prepended to the wikilink URL value. |
84
+ | `attrs` | `{ 'data-wikilink': 'true' }` | Extra attributes on the tag. Replaces defaults when provided. |
85
+
86
+ #### Examples
87
+
88
+ **Default** — `[[page-name|label]]` renders as:
89
+
90
+ ```html
91
+ <a href="page-name" data-wikilink="true">label</a>
92
+ ```
93
+
94
+ **React Router**:
95
+
96
+ ```ts
97
+ renderToHtml(ast, {
98
+ wikilink: {
99
+ tagName: 'Link',
100
+ urlAttr: 'to',
101
+ urlPrefix: '/wiki/',
102
+ attrs: { className: 'wikilink', 'data-wikilink': 'true' },
103
+ },
104
+ });
105
+ ```
106
+
107
+ ```html
108
+ <Link to="/wiki/page-name" className="wikilink" data-wikilink="true">label</Link>
109
+ ```
110
+
111
+ **URL prefix only**:
112
+
113
+ ```ts
114
+ renderToHtml(ast, {
115
+ wikilink: { urlPrefix: '/docs/' },
116
+ });
117
+ ```
118
+
119
+ ```html
120
+ <a href="/docs/page-name" data-wikilink="true">label</a>
121
+ ```
122
+
123
+ ## HTML Output Reference
124
+
125
+ ### Block Nodes
126
+
127
+ | AST `type` | HTML |
128
+ |------------|------|
129
+ | `document` | Children concatenated (no wrapper) |
130
+ | `paragraph` | `<p>…</p>` (omitted in tight lists) |
131
+ | `heading` | `<h1>`–`<h6>` based on `level` |
132
+ | `code_block` | `<pre><code class="language-{info}">…</code></pre>` |
133
+ | `block_quote` | `<blockquote>…</blockquote>` |
134
+ | `multiline_block_quote` | `<blockquote>…</blockquote>` |
135
+ | `list` (bullet) | `<ul>…</ul>` |
136
+ | `list` (ordered) | `<ol start="{start}">…</ol>` |
137
+ | `item` | `<li>…</li>` |
138
+ | `task_item` | `<li><input type="checkbox" checked="" disabled="" />…</li>` |
139
+ | `table` | `<table>…</table>` |
140
+ | `table_row` | `<tr>…</tr>` |
141
+ | `table_cell` | `<td>…</td>` or `<th>…</th>` (header row), with `align` attr |
142
+ | `thematic_break` | `<hr />` |
143
+ | `html_block` | Raw passthrough |
144
+ | `footnote_definition` | `<div class="footnote" id="fn-{name}">…</div>` |
145
+ | `description_list` | `<dl>…</dl>` |
146
+ | `description_term` | `<dt>…</dt>` |
147
+ | `description_details` | `<dd>…</dd>` |
148
+ | `alert` | `<div class="alert alert-{type}">…</div>` |
149
+ | `front_matter` | Skipped (not rendered) |
150
+
151
+ ### Inline Nodes
152
+
153
+ | AST `type` | HTML |
154
+ |------------|------|
155
+ | `text` | HTML-escaped text |
156
+ | `softbreak` | `\n` |
157
+ | `linebreak` | `<br />` |
158
+ | `emph` | `<em>…</em>` |
159
+ | `strong` | `<strong>…</strong>` |
160
+ | `strikethrough` | `<del>…</del>` |
161
+ | `underline` | `<u>…</u>` |
162
+ | `highlight` | `<mark>…</mark>` |
163
+ | `superscript` | `<sup>…</sup>` |
164
+ | `subscript` | `<sub>…</sub>` |
165
+ | `spoilered_text` | `<span class="spoiler">…</span>` |
166
+ | `code` | `<code>…</code>` |
167
+ | `link` | `<a href="{url}" title="{title}">…</a>` |
168
+ | `image` | `<img src="{url}" alt="…" title="{title}" />` |
169
+ | `wikilink` | `<a href="{url}" data-wikilink="true">…</a>` (configurable) |
170
+ | `footnote_reference` | `<sup><a href="#fn-{name}">[{n}]</a></sup>` |
171
+ | `shortcode` | Emoji character directly |
172
+ | `math` (inline) | `<code class="math math-inline">…</code>` |
173
+ | `math` (display) | `<pre><code class="math math-display">…</code></pre>` |
174
+ | `html_inline` | Raw passthrough |
175
+ | `escaped` | Skipped |
176
+ | `escaped_tag` | HTML-escaped value |
177
+
178
+ ## Supported AST Node Types
179
+
180
+ 46 node types total, matching the `flatmarkdown` Rust crate output.
181
+
182
+ **Block (23):** `document`, `paragraph`, `heading`, `code_block`, `block_quote`, `multiline_block_quote`, `list`, `item`, `task_item`, `table`, `table_row`, `table_cell`, `thematic_break`, `html_block`, `footnote_definition`, `description_list`, `description_item`, `description_term`, `description_details`, `alert`, `front_matter`, `heex_block`, `subtext`
183
+
184
+ **Inline (23):** `text`, `softbreak`, `linebreak`, `emph`, `strong`, `strikethrough`, `underline`, `highlight`, `superscript`, `subscript`, `spoilered_text`, `code`, `link`, `image`, `footnote_reference`, `shortcode`, `math`, `html_inline`, `heex_inline`, `raw`, `escaped`, `escaped_tag`, `wikilink`
185
+
186
+ All node types are exported as individual TypeScript interfaces, plus the `AstNode` discriminated union.
187
+
188
+ ## Build
189
+
190
+ ```bash
191
+ bun install
192
+ bun run build # outputs dist/ with ESM, CJS, and .d.ts
193
+ bun test # runs vitest
194
+ ```
195
+
196
+ ## License
197
+
198
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ renderToHtml: () => renderToHtml
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/renderer.ts
28
+ function defaultContext(options = {}) {
29
+ return {
30
+ options,
31
+ inHeaderRow: false,
32
+ tableAlignments: [],
33
+ cellIndex: 0,
34
+ tightList: false
35
+ };
36
+ }
37
+ function escapeHtml(str) {
38
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
39
+ }
40
+ function renderChildren(node, ctx) {
41
+ if (!node.children) return "";
42
+ return node.children.map((child) => renderNode(child, ctx)).join("");
43
+ }
44
+ function extractText(node) {
45
+ if (node.type === "text") return node.value;
46
+ if ("children" in node && node.children) {
47
+ return node.children.map(extractText).join("");
48
+ }
49
+ return "";
50
+ }
51
+ function renderNode(node, ctx) {
52
+ switch (node.type) {
53
+ // ── Block Nodes ──
54
+ case "document":
55
+ return renderChildren(node, ctx);
56
+ case "paragraph": {
57
+ const inner = renderChildren(node, ctx);
58
+ if (ctx.tightList) return `${inner}
59
+ `;
60
+ return `<p>${inner}</p>
61
+ `;
62
+ }
63
+ case "heading": {
64
+ const tag = `h${node.level}`;
65
+ return `<${tag}>${renderChildren(node, ctx)}</${tag}>
66
+ `;
67
+ }
68
+ case "code_block": {
69
+ const info = node.info;
70
+ const cls = info ? ` class="language-${escapeHtml(info)}"` : "";
71
+ return `<pre><code${cls}>${escapeHtml(node.literal)}</code></pre>
72
+ `;
73
+ }
74
+ case "block_quote":
75
+ return `<blockquote>
76
+ ${renderChildren(node, ctx)}</blockquote>
77
+ `;
78
+ case "multiline_block_quote":
79
+ return `<blockquote>
80
+ ${renderChildren(node, ctx)}</blockquote>
81
+ `;
82
+ case "list": {
83
+ if (node.list_type === "ordered") {
84
+ const startAttr = node.start != null && node.start !== 1 ? ` start="${node.start}"` : "";
85
+ return `<ol${startAttr}>
86
+ ${renderChildren(node, ctx)}</ol>
87
+ `;
88
+ }
89
+ return `<ul>
90
+ ${renderChildren(node, ctx)}</ul>
91
+ `;
92
+ }
93
+ case "item": {
94
+ const childCtx = { ...ctx, tightList: node.tight };
95
+ return `<li>${renderChildren(node, childCtx)}</li>
96
+ `;
97
+ }
98
+ case "task_item": {
99
+ const checked = node.symbol != null ? ' checked=""' : "";
100
+ const childCtx = { ...ctx, tightList: true };
101
+ return `<li><input type="checkbox"${checked} disabled="" />${renderChildren(node, childCtx)}</li>
102
+ `;
103
+ }
104
+ case "table": {
105
+ const childCtx = { ...ctx, tableAlignments: node.alignments };
106
+ return `<table>
107
+ ${renderChildren(node, childCtx)}</table>
108
+ `;
109
+ }
110
+ case "table_row": {
111
+ const cells = (node.children || []).map((cell, i) => {
112
+ const cellCtx = {
113
+ ...ctx,
114
+ inHeaderRow: node.header,
115
+ cellIndex: i
116
+ };
117
+ return renderNode(cell, cellCtx);
118
+ });
119
+ return `<tr>
120
+ ${cells.join("")}</tr>
121
+ `;
122
+ }
123
+ case "table_cell": {
124
+ const tag = ctx.inHeaderRow ? "th" : "td";
125
+ const alignment = ctx.tableAlignments[ctx.cellIndex];
126
+ const alignAttr = alignment && alignment !== "none" ? ` align="${alignment}"` : "";
127
+ return `<${tag}${alignAttr}>${renderChildren(node, ctx)}</${tag}>
128
+ `;
129
+ }
130
+ case "thematic_break":
131
+ return "<hr />\n";
132
+ case "html_block":
133
+ return node.literal;
134
+ case "footnote_definition":
135
+ return `<div class="footnote" id="fn-${escapeHtml(node.name)}">
136
+ ${renderChildren(node, ctx)}</div>
137
+ `;
138
+ case "description_list":
139
+ return `<dl>
140
+ ${renderChildren(node, ctx)}</dl>
141
+ `;
142
+ case "description_item":
143
+ return renderChildren(node, ctx);
144
+ case "description_term":
145
+ return `<dt>${renderChildren(node, ctx)}</dt>
146
+ `;
147
+ case "description_details":
148
+ return `<dd>${renderChildren(node, ctx)}</dd>
149
+ `;
150
+ case "alert":
151
+ return `<div class="alert alert-${escapeHtml(node.alert_type)}">
152
+ ${renderChildren(node, ctx)}</div>
153
+ `;
154
+ case "front_matter":
155
+ return "";
156
+ case "heex_block":
157
+ return renderChildren(node, ctx);
158
+ case "subtext":
159
+ return renderChildren(node, ctx);
160
+ // ── Inline Nodes ──
161
+ case "text":
162
+ return escapeHtml(node.value);
163
+ case "softbreak":
164
+ return "\n";
165
+ case "linebreak":
166
+ return "<br />\n";
167
+ case "emph":
168
+ return `<em>${renderChildren(node, ctx)}</em>`;
169
+ case "strong":
170
+ return `<strong>${renderChildren(node, ctx)}</strong>`;
171
+ case "strikethrough":
172
+ return `<del>${renderChildren(node, ctx)}</del>`;
173
+ case "underline":
174
+ return `<u>${renderChildren(node, ctx)}</u>`;
175
+ case "highlight":
176
+ return `<mark>${renderChildren(node, ctx)}</mark>`;
177
+ case "superscript":
178
+ return `<sup>${renderChildren(node, ctx)}</sup>`;
179
+ case "subscript":
180
+ return `<sub>${renderChildren(node, ctx)}</sub>`;
181
+ case "spoilered_text":
182
+ return `<span class="spoiler">${renderChildren(node, ctx)}</span>`;
183
+ case "code":
184
+ return `<code>${escapeHtml(node.literal)}</code>`;
185
+ case "link": {
186
+ const titleAttr = node.title ? ` title="${escapeHtml(node.title)}"` : "";
187
+ return `<a href="${escapeHtml(node.url)}"${titleAttr}>${renderChildren(node, ctx)}</a>`;
188
+ }
189
+ case "image": {
190
+ const alt = extractText(node);
191
+ const titleAttr = node.title ? ` title="${escapeHtml(node.title)}"` : "";
192
+ return `<img src="${escapeHtml(node.url)}" alt="${escapeHtml(alt)}"${titleAttr} />`;
193
+ }
194
+ case "wikilink": {
195
+ const opts = ctx.options.wikilink;
196
+ const tagName = opts?.tagName ?? "a";
197
+ const urlAttr = opts?.urlAttr ?? "href";
198
+ const urlPrefix = opts?.urlPrefix ?? "";
199
+ const extraAttrs = opts?.attrs ?? { "data-wikilink": "true" };
200
+ const url = `${urlPrefix}${node.url}`;
201
+ let attrStr = `${urlAttr}="${escapeHtml(url)}"`;
202
+ for (const [key, val] of Object.entries(extraAttrs)) {
203
+ attrStr += ` ${key}="${escapeHtml(val)}"`;
204
+ }
205
+ return `<${tagName} ${attrStr}>${renderChildren(node, ctx)}</${tagName}>`;
206
+ }
207
+ case "footnote_reference":
208
+ return `<sup><a href="#fn-${escapeHtml(node.name)}">[${node.ix + 1}]</a></sup>`;
209
+ case "shortcode":
210
+ return node.emoji;
211
+ case "math": {
212
+ if (node.display_math) {
213
+ return `<pre><code class="math math-display">${escapeHtml(node.literal)}</code></pre>
214
+ `;
215
+ }
216
+ return `<code class="math math-inline">${escapeHtml(node.literal)}</code>`;
217
+ }
218
+ case "html_inline":
219
+ return node.value;
220
+ case "heex_inline":
221
+ return node.value;
222
+ case "raw":
223
+ return node.value;
224
+ case "escaped":
225
+ return "";
226
+ case "escaped_tag":
227
+ return escapeHtml(node.value);
228
+ default: {
229
+ const _exhaustive = node;
230
+ return "";
231
+ }
232
+ }
233
+ }
234
+ function renderToHtml(ast, options) {
235
+ const node = typeof ast === "string" ? JSON.parse(ast) : ast;
236
+ return renderNode(node, defaultContext(options));
237
+ }
238
+ // Annotate the CommonJS export names for ESM import in node:
239
+ 0 && (module.exports = {
240
+ renderToHtml
241
+ });
@@ -0,0 +1,235 @@
1
+ interface DocumentNode {
2
+ type: 'document';
3
+ children?: AstNode[];
4
+ }
5
+ interface ParagraphNode {
6
+ type: 'paragraph';
7
+ children?: AstNode[];
8
+ }
9
+ interface HeadingNode {
10
+ type: 'heading';
11
+ level: number;
12
+ setext: boolean;
13
+ children?: AstNode[];
14
+ }
15
+ interface CodeBlockNode {
16
+ type: 'code_block';
17
+ fenced: boolean;
18
+ info: string;
19
+ literal: string;
20
+ }
21
+ interface BlockQuoteNode {
22
+ type: 'block_quote';
23
+ children?: AstNode[];
24
+ }
25
+ interface MultilineBlockQuoteNode {
26
+ type: 'multiline_block_quote';
27
+ children?: AstNode[];
28
+ }
29
+ interface ListNode {
30
+ type: 'list';
31
+ list_type: string;
32
+ start: number | null;
33
+ tight: boolean;
34
+ delimiter: string;
35
+ children?: AstNode[];
36
+ }
37
+ interface ItemNode {
38
+ type: 'item';
39
+ list_type: string;
40
+ start: number;
41
+ tight: boolean;
42
+ children?: AstNode[];
43
+ }
44
+ interface TaskItemNode {
45
+ type: 'task_item';
46
+ symbol: string | null;
47
+ children?: AstNode[];
48
+ }
49
+ interface TableNode {
50
+ type: 'table';
51
+ alignments: string[];
52
+ num_columns: number;
53
+ num_rows: number;
54
+ children?: AstNode[];
55
+ }
56
+ interface TableRowNode {
57
+ type: 'table_row';
58
+ header: boolean;
59
+ children?: AstNode[];
60
+ }
61
+ interface TableCellNode {
62
+ type: 'table_cell';
63
+ children?: AstNode[];
64
+ }
65
+ interface ThematicBreakNode {
66
+ type: 'thematic_break';
67
+ }
68
+ interface HtmlBlockNode {
69
+ type: 'html_block';
70
+ block_type: number;
71
+ literal: string;
72
+ }
73
+ interface FootnoteDefinitionNode {
74
+ type: 'footnote_definition';
75
+ name: string;
76
+ children?: AstNode[];
77
+ }
78
+ interface DescriptionListNode {
79
+ type: 'description_list';
80
+ children?: AstNode[];
81
+ }
82
+ interface DescriptionItemNode {
83
+ type: 'description_item';
84
+ children?: AstNode[];
85
+ }
86
+ interface DescriptionTermNode {
87
+ type: 'description_term';
88
+ children?: AstNode[];
89
+ }
90
+ interface DescriptionDetailsNode {
91
+ type: 'description_details';
92
+ children?: AstNode[];
93
+ }
94
+ interface AlertNode {
95
+ type: 'alert';
96
+ alert_type: string;
97
+ title: string | null;
98
+ children?: AstNode[];
99
+ }
100
+ interface FrontMatterNode {
101
+ type: 'front_matter';
102
+ value: string;
103
+ }
104
+ interface HeexBlockNode {
105
+ type: 'heex_block';
106
+ children?: AstNode[];
107
+ }
108
+ interface SubtextNode {
109
+ type: 'subtext';
110
+ children?: AstNode[];
111
+ }
112
+ interface TextNode {
113
+ type: 'text';
114
+ value: string;
115
+ }
116
+ interface SoftbreakNode {
117
+ type: 'softbreak';
118
+ }
119
+ interface LinebreakNode {
120
+ type: 'linebreak';
121
+ }
122
+ interface EmphNode {
123
+ type: 'emph';
124
+ children?: AstNode[];
125
+ }
126
+ interface StrongNode {
127
+ type: 'strong';
128
+ children?: AstNode[];
129
+ }
130
+ interface StrikethroughNode {
131
+ type: 'strikethrough';
132
+ children?: AstNode[];
133
+ }
134
+ interface UnderlineNode {
135
+ type: 'underline';
136
+ children?: AstNode[];
137
+ }
138
+ interface HighlightNode {
139
+ type: 'highlight';
140
+ children?: AstNode[];
141
+ }
142
+ interface SuperscriptNode {
143
+ type: 'superscript';
144
+ children?: AstNode[];
145
+ }
146
+ interface SubscriptNode {
147
+ type: 'subscript';
148
+ children?: AstNode[];
149
+ }
150
+ interface SpoileredTextNode {
151
+ type: 'spoilered_text';
152
+ children?: AstNode[];
153
+ }
154
+ interface CodeNode {
155
+ type: 'code';
156
+ literal: string;
157
+ }
158
+ interface LinkNode {
159
+ type: 'link';
160
+ url: string;
161
+ title: string;
162
+ children?: AstNode[];
163
+ }
164
+ interface ImageNode {
165
+ type: 'image';
166
+ url: string;
167
+ title: string;
168
+ children?: AstNode[];
169
+ }
170
+ interface FootnoteReferenceNode {
171
+ type: 'footnote_reference';
172
+ name: string;
173
+ ref_num: number;
174
+ ix: number;
175
+ }
176
+ interface ShortcodeNode {
177
+ type: 'shortcode';
178
+ code: string;
179
+ emoji: string;
180
+ }
181
+ interface MathNode {
182
+ type: 'math';
183
+ dollar_math: boolean;
184
+ display_math: boolean;
185
+ literal: string;
186
+ }
187
+ interface HtmlInlineNode {
188
+ type: 'html_inline';
189
+ value: string;
190
+ }
191
+ interface HeexInlineNode {
192
+ type: 'heex_inline';
193
+ value: string;
194
+ }
195
+ interface RawNode {
196
+ type: 'raw';
197
+ value: string;
198
+ }
199
+ interface EscapedNode {
200
+ type: 'escaped';
201
+ }
202
+ interface EscapedTagNode {
203
+ type: 'escaped_tag';
204
+ value: string;
205
+ }
206
+ interface WikilinkNode {
207
+ type: 'wikilink';
208
+ url: string;
209
+ children?: AstNode[];
210
+ }
211
+ type AstNode = DocumentNode | ParagraphNode | HeadingNode | CodeBlockNode | BlockQuoteNode | MultilineBlockQuoteNode | ListNode | ItemNode | TaskItemNode | TableNode | TableRowNode | TableCellNode | ThematicBreakNode | HtmlBlockNode | FootnoteDefinitionNode | DescriptionListNode | DescriptionItemNode | DescriptionTermNode | DescriptionDetailsNode | AlertNode | FrontMatterNode | HeexBlockNode | SubtextNode | TextNode | SoftbreakNode | LinebreakNode | EmphNode | StrongNode | StrikethroughNode | UnderlineNode | HighlightNode | SuperscriptNode | SubscriptNode | SpoileredTextNode | CodeNode | LinkNode | ImageNode | FootnoteReferenceNode | ShortcodeNode | MathNode | HtmlInlineNode | HeexInlineNode | RawNode | EscapedNode | EscapedTagNode | WikilinkNode;
212
+ interface WikiLinkOptions {
213
+ /** Tag name. Default: 'a'. Use 'Link' for React Router, etc. */
214
+ tagName?: string;
215
+ /** URL attribute name. Default: 'href'. Use 'to' for React Router, etc. */
216
+ urlAttr?: string;
217
+ /** Prefix prepended to the wikilink url. Default: '' */
218
+ urlPrefix?: string;
219
+ /** Extra attributes added to the tag. Default: { 'data-wikilink': 'true' } */
220
+ attrs?: Record<string, string>;
221
+ }
222
+ interface RenderOptions {
223
+ wikilink?: WikiLinkOptions;
224
+ }
225
+
226
+ /**
227
+ * Render a flatmarkdown AST to HTML.
228
+ *
229
+ * @param ast - Either a parsed AstNode object or a JSON string of the AST
230
+ * @param options - Rendering options (e.g. wikilink customization)
231
+ * @returns HTML string
232
+ */
233
+ declare function renderToHtml(ast: AstNode | string, options?: RenderOptions): string;
234
+
235
+ export { type AlertNode, type AstNode, type BlockQuoteNode, type CodeBlockNode, type CodeNode, type DescriptionDetailsNode, type DescriptionItemNode, type DescriptionListNode, type DescriptionTermNode, type DocumentNode, type EmphNode, type EscapedNode, type EscapedTagNode, type FootnoteDefinitionNode, type FootnoteReferenceNode, type FrontMatterNode, type HeadingNode, type HeexBlockNode, type HeexInlineNode, type HighlightNode, type HtmlBlockNode, type HtmlInlineNode, type ImageNode, type ItemNode, type LinebreakNode, type LinkNode, type ListNode, type MathNode, type MultilineBlockQuoteNode, type ParagraphNode, type RawNode, type RenderOptions, type ShortcodeNode, type SoftbreakNode, type SpoileredTextNode, type StrikethroughNode, type StrongNode, type SubscriptNode, type SubtextNode, type SuperscriptNode, type TableCellNode, type TableNode, type TableRowNode, type TaskItemNode, type TextNode, type ThematicBreakNode, type UnderlineNode, type WikiLinkOptions, type WikilinkNode, renderToHtml };
@@ -0,0 +1,235 @@
1
+ interface DocumentNode {
2
+ type: 'document';
3
+ children?: AstNode[];
4
+ }
5
+ interface ParagraphNode {
6
+ type: 'paragraph';
7
+ children?: AstNode[];
8
+ }
9
+ interface HeadingNode {
10
+ type: 'heading';
11
+ level: number;
12
+ setext: boolean;
13
+ children?: AstNode[];
14
+ }
15
+ interface CodeBlockNode {
16
+ type: 'code_block';
17
+ fenced: boolean;
18
+ info: string;
19
+ literal: string;
20
+ }
21
+ interface BlockQuoteNode {
22
+ type: 'block_quote';
23
+ children?: AstNode[];
24
+ }
25
+ interface MultilineBlockQuoteNode {
26
+ type: 'multiline_block_quote';
27
+ children?: AstNode[];
28
+ }
29
+ interface ListNode {
30
+ type: 'list';
31
+ list_type: string;
32
+ start: number | null;
33
+ tight: boolean;
34
+ delimiter: string;
35
+ children?: AstNode[];
36
+ }
37
+ interface ItemNode {
38
+ type: 'item';
39
+ list_type: string;
40
+ start: number;
41
+ tight: boolean;
42
+ children?: AstNode[];
43
+ }
44
+ interface TaskItemNode {
45
+ type: 'task_item';
46
+ symbol: string | null;
47
+ children?: AstNode[];
48
+ }
49
+ interface TableNode {
50
+ type: 'table';
51
+ alignments: string[];
52
+ num_columns: number;
53
+ num_rows: number;
54
+ children?: AstNode[];
55
+ }
56
+ interface TableRowNode {
57
+ type: 'table_row';
58
+ header: boolean;
59
+ children?: AstNode[];
60
+ }
61
+ interface TableCellNode {
62
+ type: 'table_cell';
63
+ children?: AstNode[];
64
+ }
65
+ interface ThematicBreakNode {
66
+ type: 'thematic_break';
67
+ }
68
+ interface HtmlBlockNode {
69
+ type: 'html_block';
70
+ block_type: number;
71
+ literal: string;
72
+ }
73
+ interface FootnoteDefinitionNode {
74
+ type: 'footnote_definition';
75
+ name: string;
76
+ children?: AstNode[];
77
+ }
78
+ interface DescriptionListNode {
79
+ type: 'description_list';
80
+ children?: AstNode[];
81
+ }
82
+ interface DescriptionItemNode {
83
+ type: 'description_item';
84
+ children?: AstNode[];
85
+ }
86
+ interface DescriptionTermNode {
87
+ type: 'description_term';
88
+ children?: AstNode[];
89
+ }
90
+ interface DescriptionDetailsNode {
91
+ type: 'description_details';
92
+ children?: AstNode[];
93
+ }
94
+ interface AlertNode {
95
+ type: 'alert';
96
+ alert_type: string;
97
+ title: string | null;
98
+ children?: AstNode[];
99
+ }
100
+ interface FrontMatterNode {
101
+ type: 'front_matter';
102
+ value: string;
103
+ }
104
+ interface HeexBlockNode {
105
+ type: 'heex_block';
106
+ children?: AstNode[];
107
+ }
108
+ interface SubtextNode {
109
+ type: 'subtext';
110
+ children?: AstNode[];
111
+ }
112
+ interface TextNode {
113
+ type: 'text';
114
+ value: string;
115
+ }
116
+ interface SoftbreakNode {
117
+ type: 'softbreak';
118
+ }
119
+ interface LinebreakNode {
120
+ type: 'linebreak';
121
+ }
122
+ interface EmphNode {
123
+ type: 'emph';
124
+ children?: AstNode[];
125
+ }
126
+ interface StrongNode {
127
+ type: 'strong';
128
+ children?: AstNode[];
129
+ }
130
+ interface StrikethroughNode {
131
+ type: 'strikethrough';
132
+ children?: AstNode[];
133
+ }
134
+ interface UnderlineNode {
135
+ type: 'underline';
136
+ children?: AstNode[];
137
+ }
138
+ interface HighlightNode {
139
+ type: 'highlight';
140
+ children?: AstNode[];
141
+ }
142
+ interface SuperscriptNode {
143
+ type: 'superscript';
144
+ children?: AstNode[];
145
+ }
146
+ interface SubscriptNode {
147
+ type: 'subscript';
148
+ children?: AstNode[];
149
+ }
150
+ interface SpoileredTextNode {
151
+ type: 'spoilered_text';
152
+ children?: AstNode[];
153
+ }
154
+ interface CodeNode {
155
+ type: 'code';
156
+ literal: string;
157
+ }
158
+ interface LinkNode {
159
+ type: 'link';
160
+ url: string;
161
+ title: string;
162
+ children?: AstNode[];
163
+ }
164
+ interface ImageNode {
165
+ type: 'image';
166
+ url: string;
167
+ title: string;
168
+ children?: AstNode[];
169
+ }
170
+ interface FootnoteReferenceNode {
171
+ type: 'footnote_reference';
172
+ name: string;
173
+ ref_num: number;
174
+ ix: number;
175
+ }
176
+ interface ShortcodeNode {
177
+ type: 'shortcode';
178
+ code: string;
179
+ emoji: string;
180
+ }
181
+ interface MathNode {
182
+ type: 'math';
183
+ dollar_math: boolean;
184
+ display_math: boolean;
185
+ literal: string;
186
+ }
187
+ interface HtmlInlineNode {
188
+ type: 'html_inline';
189
+ value: string;
190
+ }
191
+ interface HeexInlineNode {
192
+ type: 'heex_inline';
193
+ value: string;
194
+ }
195
+ interface RawNode {
196
+ type: 'raw';
197
+ value: string;
198
+ }
199
+ interface EscapedNode {
200
+ type: 'escaped';
201
+ }
202
+ interface EscapedTagNode {
203
+ type: 'escaped_tag';
204
+ value: string;
205
+ }
206
+ interface WikilinkNode {
207
+ type: 'wikilink';
208
+ url: string;
209
+ children?: AstNode[];
210
+ }
211
+ type AstNode = DocumentNode | ParagraphNode | HeadingNode | CodeBlockNode | BlockQuoteNode | MultilineBlockQuoteNode | ListNode | ItemNode | TaskItemNode | TableNode | TableRowNode | TableCellNode | ThematicBreakNode | HtmlBlockNode | FootnoteDefinitionNode | DescriptionListNode | DescriptionItemNode | DescriptionTermNode | DescriptionDetailsNode | AlertNode | FrontMatterNode | HeexBlockNode | SubtextNode | TextNode | SoftbreakNode | LinebreakNode | EmphNode | StrongNode | StrikethroughNode | UnderlineNode | HighlightNode | SuperscriptNode | SubscriptNode | SpoileredTextNode | CodeNode | LinkNode | ImageNode | FootnoteReferenceNode | ShortcodeNode | MathNode | HtmlInlineNode | HeexInlineNode | RawNode | EscapedNode | EscapedTagNode | WikilinkNode;
212
+ interface WikiLinkOptions {
213
+ /** Tag name. Default: 'a'. Use 'Link' for React Router, etc. */
214
+ tagName?: string;
215
+ /** URL attribute name. Default: 'href'. Use 'to' for React Router, etc. */
216
+ urlAttr?: string;
217
+ /** Prefix prepended to the wikilink url. Default: '' */
218
+ urlPrefix?: string;
219
+ /** Extra attributes added to the tag. Default: { 'data-wikilink': 'true' } */
220
+ attrs?: Record<string, string>;
221
+ }
222
+ interface RenderOptions {
223
+ wikilink?: WikiLinkOptions;
224
+ }
225
+
226
+ /**
227
+ * Render a flatmarkdown AST to HTML.
228
+ *
229
+ * @param ast - Either a parsed AstNode object or a JSON string of the AST
230
+ * @param options - Rendering options (e.g. wikilink customization)
231
+ * @returns HTML string
232
+ */
233
+ declare function renderToHtml(ast: AstNode | string, options?: RenderOptions): string;
234
+
235
+ export { type AlertNode, type AstNode, type BlockQuoteNode, type CodeBlockNode, type CodeNode, type DescriptionDetailsNode, type DescriptionItemNode, type DescriptionListNode, type DescriptionTermNode, type DocumentNode, type EmphNode, type EscapedNode, type EscapedTagNode, type FootnoteDefinitionNode, type FootnoteReferenceNode, type FrontMatterNode, type HeadingNode, type HeexBlockNode, type HeexInlineNode, type HighlightNode, type HtmlBlockNode, type HtmlInlineNode, type ImageNode, type ItemNode, type LinebreakNode, type LinkNode, type ListNode, type MathNode, type MultilineBlockQuoteNode, type ParagraphNode, type RawNode, type RenderOptions, type ShortcodeNode, type SoftbreakNode, type SpoileredTextNode, type StrikethroughNode, type StrongNode, type SubscriptNode, type SubtextNode, type SuperscriptNode, type TableCellNode, type TableNode, type TableRowNode, type TaskItemNode, type TextNode, type ThematicBreakNode, type UnderlineNode, type WikiLinkOptions, type WikilinkNode, renderToHtml };
package/dist/index.js ADDED
@@ -0,0 +1,214 @@
1
+ // src/renderer.ts
2
+ function defaultContext(options = {}) {
3
+ return {
4
+ options,
5
+ inHeaderRow: false,
6
+ tableAlignments: [],
7
+ cellIndex: 0,
8
+ tightList: false
9
+ };
10
+ }
11
+ function escapeHtml(str) {
12
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
13
+ }
14
+ function renderChildren(node, ctx) {
15
+ if (!node.children) return "";
16
+ return node.children.map((child) => renderNode(child, ctx)).join("");
17
+ }
18
+ function extractText(node) {
19
+ if (node.type === "text") return node.value;
20
+ if ("children" in node && node.children) {
21
+ return node.children.map(extractText).join("");
22
+ }
23
+ return "";
24
+ }
25
+ function renderNode(node, ctx) {
26
+ switch (node.type) {
27
+ // ── Block Nodes ──
28
+ case "document":
29
+ return renderChildren(node, ctx);
30
+ case "paragraph": {
31
+ const inner = renderChildren(node, ctx);
32
+ if (ctx.tightList) return `${inner}
33
+ `;
34
+ return `<p>${inner}</p>
35
+ `;
36
+ }
37
+ case "heading": {
38
+ const tag = `h${node.level}`;
39
+ return `<${tag}>${renderChildren(node, ctx)}</${tag}>
40
+ `;
41
+ }
42
+ case "code_block": {
43
+ const info = node.info;
44
+ const cls = info ? ` class="language-${escapeHtml(info)}"` : "";
45
+ return `<pre><code${cls}>${escapeHtml(node.literal)}</code></pre>
46
+ `;
47
+ }
48
+ case "block_quote":
49
+ return `<blockquote>
50
+ ${renderChildren(node, ctx)}</blockquote>
51
+ `;
52
+ case "multiline_block_quote":
53
+ return `<blockquote>
54
+ ${renderChildren(node, ctx)}</blockquote>
55
+ `;
56
+ case "list": {
57
+ if (node.list_type === "ordered") {
58
+ const startAttr = node.start != null && node.start !== 1 ? ` start="${node.start}"` : "";
59
+ return `<ol${startAttr}>
60
+ ${renderChildren(node, ctx)}</ol>
61
+ `;
62
+ }
63
+ return `<ul>
64
+ ${renderChildren(node, ctx)}</ul>
65
+ `;
66
+ }
67
+ case "item": {
68
+ const childCtx = { ...ctx, tightList: node.tight };
69
+ return `<li>${renderChildren(node, childCtx)}</li>
70
+ `;
71
+ }
72
+ case "task_item": {
73
+ const checked = node.symbol != null ? ' checked=""' : "";
74
+ const childCtx = { ...ctx, tightList: true };
75
+ return `<li><input type="checkbox"${checked} disabled="" />${renderChildren(node, childCtx)}</li>
76
+ `;
77
+ }
78
+ case "table": {
79
+ const childCtx = { ...ctx, tableAlignments: node.alignments };
80
+ return `<table>
81
+ ${renderChildren(node, childCtx)}</table>
82
+ `;
83
+ }
84
+ case "table_row": {
85
+ const cells = (node.children || []).map((cell, i) => {
86
+ const cellCtx = {
87
+ ...ctx,
88
+ inHeaderRow: node.header,
89
+ cellIndex: i
90
+ };
91
+ return renderNode(cell, cellCtx);
92
+ });
93
+ return `<tr>
94
+ ${cells.join("")}</tr>
95
+ `;
96
+ }
97
+ case "table_cell": {
98
+ const tag = ctx.inHeaderRow ? "th" : "td";
99
+ const alignment = ctx.tableAlignments[ctx.cellIndex];
100
+ const alignAttr = alignment && alignment !== "none" ? ` align="${alignment}"` : "";
101
+ return `<${tag}${alignAttr}>${renderChildren(node, ctx)}</${tag}>
102
+ `;
103
+ }
104
+ case "thematic_break":
105
+ return "<hr />\n";
106
+ case "html_block":
107
+ return node.literal;
108
+ case "footnote_definition":
109
+ return `<div class="footnote" id="fn-${escapeHtml(node.name)}">
110
+ ${renderChildren(node, ctx)}</div>
111
+ `;
112
+ case "description_list":
113
+ return `<dl>
114
+ ${renderChildren(node, ctx)}</dl>
115
+ `;
116
+ case "description_item":
117
+ return renderChildren(node, ctx);
118
+ case "description_term":
119
+ return `<dt>${renderChildren(node, ctx)}</dt>
120
+ `;
121
+ case "description_details":
122
+ return `<dd>${renderChildren(node, ctx)}</dd>
123
+ `;
124
+ case "alert":
125
+ return `<div class="alert alert-${escapeHtml(node.alert_type)}">
126
+ ${renderChildren(node, ctx)}</div>
127
+ `;
128
+ case "front_matter":
129
+ return "";
130
+ case "heex_block":
131
+ return renderChildren(node, ctx);
132
+ case "subtext":
133
+ return renderChildren(node, ctx);
134
+ // ── Inline Nodes ──
135
+ case "text":
136
+ return escapeHtml(node.value);
137
+ case "softbreak":
138
+ return "\n";
139
+ case "linebreak":
140
+ return "<br />\n";
141
+ case "emph":
142
+ return `<em>${renderChildren(node, ctx)}</em>`;
143
+ case "strong":
144
+ return `<strong>${renderChildren(node, ctx)}</strong>`;
145
+ case "strikethrough":
146
+ return `<del>${renderChildren(node, ctx)}</del>`;
147
+ case "underline":
148
+ return `<u>${renderChildren(node, ctx)}</u>`;
149
+ case "highlight":
150
+ return `<mark>${renderChildren(node, ctx)}</mark>`;
151
+ case "superscript":
152
+ return `<sup>${renderChildren(node, ctx)}</sup>`;
153
+ case "subscript":
154
+ return `<sub>${renderChildren(node, ctx)}</sub>`;
155
+ case "spoilered_text":
156
+ return `<span class="spoiler">${renderChildren(node, ctx)}</span>`;
157
+ case "code":
158
+ return `<code>${escapeHtml(node.literal)}</code>`;
159
+ case "link": {
160
+ const titleAttr = node.title ? ` title="${escapeHtml(node.title)}"` : "";
161
+ return `<a href="${escapeHtml(node.url)}"${titleAttr}>${renderChildren(node, ctx)}</a>`;
162
+ }
163
+ case "image": {
164
+ const alt = extractText(node);
165
+ const titleAttr = node.title ? ` title="${escapeHtml(node.title)}"` : "";
166
+ return `<img src="${escapeHtml(node.url)}" alt="${escapeHtml(alt)}"${titleAttr} />`;
167
+ }
168
+ case "wikilink": {
169
+ const opts = ctx.options.wikilink;
170
+ const tagName = opts?.tagName ?? "a";
171
+ const urlAttr = opts?.urlAttr ?? "href";
172
+ const urlPrefix = opts?.urlPrefix ?? "";
173
+ const extraAttrs = opts?.attrs ?? { "data-wikilink": "true" };
174
+ const url = `${urlPrefix}${node.url}`;
175
+ let attrStr = `${urlAttr}="${escapeHtml(url)}"`;
176
+ for (const [key, val] of Object.entries(extraAttrs)) {
177
+ attrStr += ` ${key}="${escapeHtml(val)}"`;
178
+ }
179
+ return `<${tagName} ${attrStr}>${renderChildren(node, ctx)}</${tagName}>`;
180
+ }
181
+ case "footnote_reference":
182
+ return `<sup><a href="#fn-${escapeHtml(node.name)}">[${node.ix + 1}]</a></sup>`;
183
+ case "shortcode":
184
+ return node.emoji;
185
+ case "math": {
186
+ if (node.display_math) {
187
+ return `<pre><code class="math math-display">${escapeHtml(node.literal)}</code></pre>
188
+ `;
189
+ }
190
+ return `<code class="math math-inline">${escapeHtml(node.literal)}</code>`;
191
+ }
192
+ case "html_inline":
193
+ return node.value;
194
+ case "heex_inline":
195
+ return node.value;
196
+ case "raw":
197
+ return node.value;
198
+ case "escaped":
199
+ return "";
200
+ case "escaped_tag":
201
+ return escapeHtml(node.value);
202
+ default: {
203
+ const _exhaustive = node;
204
+ return "";
205
+ }
206
+ }
207
+ }
208
+ function renderToHtml(ast, options) {
209
+ const node = typeof ast === "string" ? JSON.parse(ast) : ast;
210
+ return renderNode(node, defaultContext(options));
211
+ }
212
+ export {
213
+ renderToHtml
214
+ };
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "flatmarkdown-ast2html",
3
+ "version": "0.1.0",
4
+ "description": "A library to convert FlatMarkdown AST to HTML.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/petajournal/flatmarkdown-ast2html.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/petajournal/flatmarkdown-ast2html/issues"
18
+ },
19
+ "homepage": "https://github.com/petajournal/flatmarkdown-ast2html#readme",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js",
24
+ "require": "./dist/index.cjs"
25
+ }
26
+ },
27
+ "scripts": {
28
+ "build": "tsup",
29
+ "test": "vitest run",
30
+ "prepublishOnly": "npm run build"
31
+ },
32
+ "keywords": [
33
+ "flatmarkdown",
34
+ "ast",
35
+ "html",
36
+ "markdown",
37
+ "parser"
38
+ ],
39
+ "author": "Hidekazu Kubota",
40
+ "license": "MIT",
41
+ "devDependencies": {
42
+ "tsup": "^8.0.0",
43
+ "vitest": "^3.0.0",
44
+ "typescript": "^5.0.0"
45
+ }
46
+ }