featherdown 0.2.0 → 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
@@ -1,30 +1,10 @@
1
1
  # featherdown
2
2
 
3
- **featherdown** is an ESM-first Markdown publishing engine for **Node, browsers, and Deno**.
3
+ **featherdown** is a publishing-focused Markdown engine for apps, blogs, docs, and product surfaces that want **sanitized HTML**, **publishing metadata**, **diagnostics**, **code and math support**, and **asset hints**—without hand-wiring a full [unified](https://github.com/unifiedjs/unified) pipeline.
4
4
 
5
- It turns Markdown into sanitized HTML with a production-friendly pipeline that includes:
5
+ It is **not** a static site generator and does not ship client runtimes for charts, copy-to-clipboard behavior, or Mermaid in the browser. It produces HTML contracts and metadata your app can integrate.
6
6
 
7
- - GFM
8
- - math via KaTeX
9
- - syntax highlighting
10
- - heading anchors
11
- - chart placeholder blocks
12
- - optional manifest-based image rewriting
13
- - non-fatal render diagnostics
14
- - an optional **Node-only Mermaid** entry for static SVG rendering
15
-
16
- It is built for publishing workflows that want more than raw Markdown parsing, but less complexity than assembling and maintaining a full unified stack by hand.
17
-
18
- ## Why featherdown?
19
-
20
- Use `featherdown` when you want:
21
-
22
- - a ready-to-use Markdown → HTML pipeline
23
- - a browser-safe default entry
24
- - explicit sanitization instead of “bring your own sanitizer”
25
- - publishing-oriented extras like chart placeholders and image rewriting
26
- - optional diagnostics for content issues that should not crash rendering
27
- - a separate Node-only Mermaid path instead of bundling Node-specific behavior into the default entry
7
+ The default npm entry is **browser-safe**. Optional **Node-only** Mermaid (inline SVG) lives behind `featherdown/node`.
28
8
 
29
9
  ## Install
30
10
 
@@ -32,496 +12,448 @@ Use `featherdown` when you want:
32
12
  npm install featherdown
33
13
  ```
34
14
 
35
- JSR / Deno:
15
+ Node.js **18+** is required.
36
16
 
37
- ```ts
38
- import { renderMarkdownToHtml } from "jsr:@karuifeather/featherdown";
39
- ```
17
+ ### JSR / Deno
40
18
 
41
- Node.js 18+ is required.
19
+ You can import the library from JSR (see [@karuifeather/featherdown](https://jsr.io/@karuifeather/featherdown)). **npm** publishes **CSS subpath exports** (`featherdown/styles.css`, `featherdown/styles/base.css`, and the other `featherdown/styles/*` entries in `package.json`). **Deno/JSR** (`deno.json` exports) does **not** mirror those CSS paths today—**CSS parity for JSR is deferred**; treat stylesheet wiring as environment-specific. **CSS packaging and `@import` resolution for JSR/Deno consumers are not treated as equivalent to npm bundler workflows.** Prefer npm (or a bundler) when you want the documented CSS entry points without extra setup.
42
20
 
43
- If you use Mermaid rendering from `featherdown/node`, install Playwright and Chromium:
21
+ ## Quick start
44
22
 
45
- ```bash
46
- npm install playwright
47
- npx playwright install chromium
48
- ```
23
+ ```ts
24
+ import { Featherdown } from "featherdown";
25
+ import "featherdown/styles.css";
49
26
 
50
- ## Quick Start
27
+ const featherdown = new Featherdown();
51
28
 
52
- ```ts
53
- import { renderMarkdownToHtml } from "featherdown";
29
+ const result = await featherdown.parse("# Hello");
54
30
 
55
- const html = await renderMarkdownToHtml("## Hello **world**");
31
+ console.log(result.html);
56
32
  ```
57
33
 
58
34
  The default entry is browser-safe and does **not** include Mermaid rendering.
59
35
 
60
- ## Which API should I use?
36
+ ## Rendering Markdown
61
37
 
62
- | If you need... | Use... |
63
- | --- | --- |
64
- | Just sanitized HTML output | `renderMarkdownToHtml` |
65
- | HTML plus non-fatal warnings | `renderMarkdown` |
66
- | HTML plus publishing metadata (`toc`, `headings`, excerpt, reading stats) | `renderMarkdownDocument` |
67
- | Direct unified processor access with featherdown defaults | `createMarkdownProcessor` |
68
- | A custom unified pipeline with focused helpers | `rehypeChartBlocks`, `rehypeCdnImages` |
69
- | Mermaid-to-inline-SVG rendering in Node publishing flows | `renderMarkdownToHtmlWithMermaid` from `featherdown/node` |
70
-
71
- Rule of thumb:
38
+ Use the **`Featherdown`** class as the primary API. Constructor options set defaults; each call to **`parse(markdown, parseOptions?)`** can override them (with a shallow merge and one-level merge for nested groups like `code` and `publishing`).
72
39
 
73
- - Start with `renderMarkdownToHtml`.
74
- - Move to `renderMarkdown` when content warnings matter.
75
- - Move to `renderMarkdownDocument` when you need TOC/sidebar/preview metadata.
76
- - Use `createMarkdownProcessor` only when you need lower-level unified control.
40
+ ```ts
41
+ const featherdown = new Featherdown({
42
+ frontmatter: "auto",
43
+ math: true,
44
+ code: true,
45
+ diagnostics: "warn",
46
+ });
77
47
 
78
- ## Common Use Cases
48
+ const result = await featherdown.parse(markdown);
49
+ ```
79
50
 
80
- ### Render Markdown to HTML
51
+ ### Image manifest example
81
52
 
82
53
  ```ts
83
- import { renderMarkdownToHtml } from "featherdown";
84
-
85
- const html = await renderMarkdownToHtml(`
86
- # Post Title
87
-
88
- Here is some math: $E = mc^2$
54
+ const featherdown = new Featherdown({
55
+ kind: "post",
56
+ slug: "hello-world",
57
+ manifest: {
58
+ map: {
59
+ "post/hello-world/images/logo.png": { url: "https://cdn.example.com/logo.png" },
60
+ },
61
+ },
62
+ });
89
63
 
90
- | Name | Value |
91
- | ---- | ----- |
92
- | A | 1 |
93
- `);
64
+ const result = await featherdown.parse(markdown);
94
65
  ```
95
66
 
96
- ### Render HTML with warnings
67
+ ## Result object
97
68
 
98
- Use `renderMarkdown` when you want HTML plus non-fatal diagnostics.
69
+ `Featherdown.parse()` resolves to a **`FeatherdownResult`**. Commonly used fields:
99
70
 
100
- ````ts
101
- import { renderMarkdown } from "featherdown";
71
+ | Field | Meaning |
72
+ | --- | --- |
73
+ | **`html`** | Sanitized HTML string. |
74
+ | **`body`** | Markdown body after front matter is stripped when front matter parsing is enabled and a valid block exists; otherwise the full input string. |
75
+ | **`frontmatter`** | Parsed YAML object, or `{}` when absent or when front matter parsing is disabled. |
76
+ | **`metadata`** | Normalized subset of common publishing fields (`title`, `description`, `tags`, etc.) derived from front matter. |
77
+ | **`toc`** | Compact heading list for navigation (`depth`, `text`, `id`). |
78
+ | **`headings`** | Richer heading metadata in document order (includes `hasCustomId`). |
79
+ | **`excerpt`** | First meaningful plain-text excerpt from rendered flow content, or `null` when disabled or unavailable. |
80
+ | **`wordCount`** / **`estimatedReadingMinutes`** | Derived from the rendered document text (subject to `publishing` options). |
81
+ | **`stats`** | Mirrors `wordCount` and reading time for convenience. |
82
+ | **`diagnostics`** | Non-fatal warnings (for example invalid chart JSON or manifest misses). |
83
+ | **`assets`** | Hints such as **`assets.styles`** (selective package CSS paths) and **`assets.features`** (`math`, `code`, `charts`, `mermaid`). |
102
84
 
103
- const { html, diagnostics } = await renderMarkdown(
104
- "```chart-line\nnot json\n```",
105
- );
85
+ `assets.styles` lists **selective** style paths (for example `featherdown/styles/base.css`), not the all-in `featherdown/styles.css` aggregate.
106
86
 
107
- console.log(html);
108
- console.log(diagnostics);
109
- ````
87
+ ## Styles
110
88
 
111
- Diagnostics are intended for developer feedback, not end-user rendering.
89
+ Official styles target the **`featherdown-content`** wrapper class and related HTML contracts.
112
90
 
113
- ### Render a docs/blog page bundle
91
+ ### All-in (recommended starting point)
114
92
 
115
- Use `renderMarkdownDocument` to produce HTML and page metadata in one pass.
93
+ These entry points are intended for **npm / bundler** workflows where the toolchain resolves package paths and nested `@import`s.
116
94
 
117
95
  ```ts
118
- import { renderMarkdownDocument } from "featherdown";
119
-
120
- const page = await renderMarkdownDocument(markdown);
121
-
122
- const html = page.html;
123
- const sidebarItems = page.headings;
124
- const legacyToc = page.toc;
125
- const previewText = page.excerpt;
126
- const readingMinutes = page.estimatedReadingMinutes;
96
+ import "featherdown/styles.css";
127
97
  ```
128
98
 
129
- ### Render HTML with document metadata
130
-
131
- Use `renderMarkdownDocument` when publishing workflows need HTML plus heading metadata, excerpt text, and reading stats from the final browser-safe output.
99
+ This aggregates base, KaTeX, code, and highlight layers. It is the simplest path when you want the full default look.
132
100
 
133
- ```ts
134
- import { renderMarkdownDocument } from "featherdown";
101
+ ### Selective imports
135
102
 
136
- const document = await renderMarkdownDocument(`
137
- # Post Title
103
+ For smaller CSS payloads, import only what you need:
138
104
 
139
- This first paragraph can be used as preview text.
105
+ ```ts
106
+ import "featherdown/styles/base.css";
107
+ import "featherdown/styles/katex.css"; // when math is enabled
108
+ import "featherdown/styles/code.css"; // when code blocks / shell chrome are used
109
+ import "featherdown/styles/highlight.css"; // only when syntax highlighting is enabled
110
+ ```
140
111
 
141
- ## Section A
142
- Body text here.
143
- `);
112
+ - **`base.css`** — Prose/layout and structural contracts for rendered content.
113
+ - **`katex.css`** — Bundler-oriented entry that pulls in KaTeX’s distribution CSS for math output.
114
+ - **`code.css`** — Featherdown code-block shell / chrome (titles, line layout hooks, etc.).
115
+ - **`highlight.css`** — Default highlight.js theme CSS; **include this only when syntax highlighting is enabled** (`code` with default highlighting, or equivalent).
144
116
 
145
- console.log(document.html);
146
- console.log(document.toc);
147
- console.log(document.headings);
148
- console.log(document.excerpt);
149
- console.log(document.wordCount, document.estimatedReadingMinutes);
150
- ```
117
+ Do **not** assume raw `<link href="node_modules/.../featherdown/styles.css">` without a bundler will resolve nested `@import`s the same way a bundler does.
151
118
 
152
- Returned metadata:
119
+ ### Custom themes
153
120
 
154
- - `toc`: ordered heading list with `depth`, final `text`, and final `id`
155
- - `headings`: richer ordered heading metadata with `index`, `depth`, final `text`, final `id`, and `hasCustomId`
156
- - `excerpt`: first meaningful plain-text content from rendered `p`, `blockquote`, or `li`, or `null`
157
- - `wordCount`: deterministic plain-text word count from rendered document text
158
- - `estimatedReadingMinutes`: whole-minute estimate from word count (minimum `1` when text exists, `0` when none)
121
+ You can start from Featherdown's baseline styles and override them:
159
122
 
160
- `toc` stays intentionally compact for backwards-compatible navigation use, while `headings` is better for richer sidebars, heading-aware tooling, and workflows that need to detect explicit custom heading ids.
123
+ ```ts
124
+ import "featherdown/styles/base.css";
125
+ import "./markdown-theme.css";
126
+ import "./code-theme.css";
127
+ ```
161
128
 
162
- The metadata is derived from the same processed document structure that produces the final HTML, so heading ids and text stay aligned with rendered output.
129
+ Or skip `base.css` and fully own the rendered Markdown styles in your app.
163
130
 
164
- Common uses include TOC sidebars, preview cards, and reading-time badges.
131
+ When code highlighting is enabled, rendered code uses highlight.js-style `hljs` token classes, so custom code themes can target classes such as `.hljs-keyword`, `.hljs-string`, and `.hljs-comment`.
165
132
 
166
- ### Parse front matter
133
+ ### Asset hints
167
134
 
168
135
  ```ts
169
- import { parseMarkdownFile } from "featherdown";
136
+ const result = await featherdown.parse(markdown);
137
+ console.log(result.assets.styles);
138
+ ```
170
139
 
171
- const result = parseMarkdownFile(`---
172
- title: Hello
173
- tags:
174
- - docs
175
- ---
140
+ Use this in SSR or static generators to decide which stylesheets to emit alongside HTML.
176
141
 
177
- # Hello world
178
- `);
142
+ ## Options
179
143
 
180
- console.log(result.frontMatter);
181
- console.log(result.content);
182
- ```
183
-
184
- ### Publish styled code blocks (title + ranges + numbers + copy hooks)
144
+ These options are wired end-to-end today:
185
145
 
186
146
  ```ts
187
- import { renderMarkdownToHtml } from "featherdown";
147
+ const featherdown = new Featherdown({
148
+ frontmatter: "auto",
149
+ math: true,
150
+ code: true,
151
+ sanitize: true,
152
+ diagnostics: true,
153
+ charts: true,
154
+ headings: true,
155
+ publishing: true,
156
+ });
157
+ ```
188
158
 
189
- const markdown = `
190
- \`\`\`ts title="example.ts" {2} showLineNumbers showCopyButton
191
- const a = 1;
192
- const b = 2;
193
- \`\`\`
194
- `;
159
+ Object forms for nested groups:
195
160
 
196
- const html = await renderMarkdownToHtml(markdown);
161
+ ```ts
162
+ const featherdown = new Featherdown({
163
+ code: {
164
+ enabled: true,
165
+ highlighting: true,
166
+ },
167
+ publishing: {
168
+ excerpt: true,
169
+ wordCount: true,
170
+ readingTime: true,
171
+ },
172
+ });
197
173
  ```
198
174
 
199
- ## Publishing Features
200
-
201
- ### Chart placeholder blocks
175
+ - **`math`** — Toggle KaTeX HTML output for `$…$` / `$$…$$`.
176
+ - **`code`** — Toggle code pipeline features; **`highlighting`** controls whether highlight.js classes and **`highlight.css`** are relevant.
177
+ - **`frontmatter`** — `false`, `true`, or `"auto"`; controls whether leading YAML front matter is parsed and stripped from `body`.
178
+ - **`sanitize`** — When enabled, output passes through `rehype-sanitize` with the package schema.
179
+ - **`diagnostics`** — Controls whether warnings appear on the result and whether strict mode fails the parse.
180
+ - **`false`** — `result.diagnostics` is always `[]` (issues may still be detected internally).
181
+ - **`true`** or **`"warn"`** — Non-fatal diagnostics are returned on `result.diagnostics`; the parse does not throw.
182
+ - **`"strict"`** — Same collection as warn; if any diagnostic exists after rendering, the parse throws **`FeatherdownDiagnosticsError`** with **`error.diagnostics`** and optional **`error.result`** (full `FeatherdownResult`, including `html`). Use `instanceof FeatherdownDiagnosticsError` in callers that need to branch.
202
183
 
203
- Supported `chart-*` code fences with valid JSON are transformed into placeholder mount nodes.
184
+ ```ts
185
+ import { Featherdown, FeatherdownDiagnosticsError } from "featherdown";
204
186
 
205
- ````md
206
- ```chart-line
207
- {"labels":["a"],"datasets":[]}
208
- ```
209
- ````
187
+ const featherdown = new Featherdown({
188
+ diagnostics: "warn",
189
+ });
210
190
 
211
- Rendered HTML shape:
191
+ const strict = new Featherdown({
192
+ diagnostics: "strict",
193
+ });
212
194
 
213
- ```html
214
- <div
215
- class="chart-mount"
216
- data-chart="line"
217
- data-chart-data='{"labels":["a"],"datasets":[]}'
218
- ></div>
195
+ try {
196
+ await strict.parse(markdown);
197
+ } catch (e) {
198
+ if (e instanceof FeatherdownDiagnosticsError) {
199
+ console.error(e.diagnostics);
200
+ }
201
+ }
219
202
  ```
203
+ - **`charts`** — When enabled, valid `chart-*` fences become mount placeholders; invalid JSON surfaces diagnostics when diagnostics are enabled.
204
+ - **`headings`** — Controls **`result.headings`** and **`result.toc`** (metadata extracted after render). Heading markup in **`html`** is unchanged; this option gates the arrays on the result.
205
+ - **`false`** — **`result.headings`** and **`result.toc`** are both empty arrays.
206
+ - **`true`** — Default heading metadata: both arrays are populated when rendered headings have ids.
207
+ - **Object** — Shape matches **`FeatherdownHeadingOptions`**: optional **`toc`**. When **`toc`** is **`false`**, **`result.toc`** is empty while **`result.headings`** can still be filled. Optional **`slugs`** and **`anchors`** are part of the public type and merge like other nested options; they do not toggle the Markdown processor in this release.
208
+ - **`publishing`** — Gates excerpt, word count, and reading-time fields on the result.
220
209
 
221
- `featherdown` does not bundle a chart runtime. It only emits mount markup that your app can hydrate later.
210
+ **`kind`**, **`slug`**, and **`manifest`** (local `map` and optional `remote`) drive manifest-based image URL rewriting—the same shape supported historically on render helpers.
222
211
 
223
- ### Code block titles
212
+ Avoid treating every nested field on `FeatherdownOptions` as a global behavioral switch unless documented below (for example line numbers and copy UI remain **per-fence** in Markdown).
224
213
 
225
- Fenced code blocks can include a title using `title="..."` metadata.
214
+ ## Front matter
226
215
 
227
- ````md
228
- ```ts title="example.ts"
229
- const value = 1;
230
- ```
231
- ````
216
+ Publishing-style front matter is **opt in**. The default constructor does **not** strip YAML; pass **`frontmatter: "auto"`** (or `true`) when you want leading `---` YAML parsed and removed from the body string.
232
217
 
233
- Emitted HTML contract:
218
+ ```ts
219
+ const featherdown = new Featherdown({
220
+ frontmatter: "auto",
221
+ });
234
222
 
235
- ```html
236
- <div class="code-block">
237
- <div class="code-block-title">example.ts</div>
238
- <pre><code class="hljs language-ts">...</code></pre>
239
- </div>
223
+ const result = await featherdown.parse(`---
224
+ title: Hello World
225
+ tags:
226
+ - docs
227
+ ---
228
+
229
+ # Hello`);
240
230
  ```
241
231
 
242
- Title text is treated as plain text, and styling of `code-block` / `code-block-title` is left to the consuming application.
232
+ Then:
243
233
 
244
- ### Code line highlights
234
+ - `result.frontmatter.title`, `result.metadata.title`
235
+ - `result.body` — Markdown after the front matter block
236
+ - `result.html` — Rendered from `body` only
245
237
 
246
- Fenced code blocks can mark highlighted lines using brace metadata:
238
+ **Lenient behavior:** invalid or non-mapping YAML does not throw; the raw document is treated as body content with empty `frontmatter` / `metadata` where applicable.
247
239
 
248
- - `{2}`
249
- - `{2,4-5}`
250
- - `{1-3,6}`
240
+ **Strict legacy utility:** `parseMarkdownFile()` still throws on invalid YAML and returns **`frontMatter`** / **`content`**. Use it only when you need that contract; otherwise prefer `Featherdown` with `frontmatter: "auto"`.
251
241
 
252
- Highlighted lines receive `code-line-highlighted` in the rendered code, with minimal line wrappers:
242
+ ## Code blocks
253
243
 
254
- ```html
255
- <pre><code class="hljs language-ts">
256
- <span class="code-line">...</span>
257
- <span class="code-line code-line-highlighted">...</span>
258
- </code></pre>
259
- ```
244
+ - **Fenced code** renders as sanitized `<pre><code>` with highlight.js classes when highlighting is on.
245
+ - **Titles:** ` ```ts title="example.ts" ` — emits `code-block` / `code-block-title` markup.
246
+ - **Line highlights:** ` ```ts {2,4-5} ` — `code-line` / `code-line-highlighted` wrappers.
247
+ - **Line numbers:** ` ```ts showLineNumbers ` — `code-line-numbered` and per-line number spans (per fence).
248
+ - **Copy UI hooks:** `showCopyButton` / `copyButton` on the fence emit button markup and `data-*` attributes for your app to wire up. **The package does not ship clipboard JavaScript.**
260
249
 
261
- When a code block also has `title="..."`, title markup and line highlighting compose in the same block. Styling is left to the consuming application.
250
+ Styling for these contracts comes from **`code.css`** and **`highlight.css`** (when highlighting is enabled).
262
251
 
263
- ### Code line numbers
252
+ ## Math
264
253
 
265
- Fenced code blocks can opt into line numbers with `showLineNumbers`.
254
+ Enable math on the instance or per parse:
266
255
 
267
- ````md
268
- ```ts showLineNumbers
269
- const a = 1;
270
- const b = 2;
271
- ```
272
- ````
273
-
274
- Emitted HTML contract:
275
-
276
- ```html
277
- <pre><code class="hljs language-ts code-line-numbered">
278
- <span class="code-line">
279
- <span class="code-line-number">1</span>
280
- ...
281
- </span>
282
- <span class="code-line code-line-highlighted">
283
- <span class="code-line-number">2</span>
284
- ...
285
- </span>
286
- </code></pre>
256
+ ```ts
257
+ const featherdown = new Featherdown({
258
+ math: true,
259
+ });
287
260
  ```
288
261
 
289
- Line number styling is left to the consuming application. Line numbers compose with both `title="..."` and `{...}` line highlight metadata on the same fenced code block.
262
+ Ensure KaTeX styles are loaded (all-in `featherdown/styles.css`, or `featherdown/styles/katex.css`). The public option name is **`math`**; KaTeX is used internally for HTML output.
290
263
 
291
- ### Code copy button markup
264
+ ## Charts, callouts, and publishing features
292
265
 
293
- Fenced code blocks can opt into copy-button markup with `showCopyButton` or `copyButton`.
266
+ ### Chart placeholders
294
267
 
295
- ````md
296
- ```ts title="example.ts" {2} showLineNumbers showCopyButton
297
- const a = 1;
298
- const b = 2;
299
- ```
300
- ````
301
-
302
- Emitted HTML contract:
303
-
304
- ```html
305
- <div class="code-block code-block-copyable">
306
- <div class="code-block-title">example.ts</div>
307
- <button
308
- type="button"
309
- class="code-block-copy-button"
310
- data-code-copy
311
- data-code-copy-target="code-copy-target-1"
312
- >
313
- Copy
314
- </button>
315
- <pre><code data-code-copy-target="code-copy-target-1" class="hljs language-ts code-line-numbered">...</code></pre>
316
- </div>
317
- ```
268
+ Valid `chart-*` fenced JSON becomes a **`chart-mount`** placeholder with `data-chart` and `data-chart-data`. The package does **not** bundle a chart runtime—your app hydrates or renders charts.
269
+
270
+ ### Callouts (admonitions)
318
271
 
319
- Styling and clipboard behavior are left to the consuming application. This package emits only HTML contract hooks and does not include built-in clipboard runtime logic.
272
+ `:::note`, `:::warning`, `:::tip`, etc. (with optional `:::type[Title]`) render to **`callout`** / **`callout-<type>`** structures. Body markdown is processed normally.
320
273
 
321
- ### Admonitions / callouts
274
+ ### Images
322
275
 
323
- The default browser-safe pipeline supports fenced admonitions using `:::type` with a closing `:::`.
324
- You can optionally provide a title with bracket syntax: `:::type[Title]`.
276
+ Optional **`manifest`** + **`kind`** + **`slug`** rewrite relative `![alt](./path)` sources using deterministic keys. No CDN fetching is built in.
325
277
 
326
- Supported types:
278
+ ### TOC, excerpt, counts
327
279
 
328
- - `note`
329
- - `tip`
330
- - `warning`
331
- - `info`
332
- - `success`
333
- - `danger`
334
- - `error`
335
- - `caution`
336
- - `important`
280
+ `toc`, `headings`, `excerpt`, `wordCount`, and `estimatedReadingMinutes` come from the **same** render pass as `html`, gated by **`headings`** and **`publishing`** options.
337
281
 
338
- Example:
282
+ ## Node usage
339
283
 
340
- ````md
341
- :::note[Install CSS]
342
- Remember to install KaTeX CSS.
343
- :::
344
- ````
284
+ Import **`Featherdown` from `featherdown/node`** for filesystem helpers and optional Mermaid.
345
285
 
346
- Emitted HTML contract:
286
+ ```ts
287
+ import { Featherdown } from "featherdown/node";
347
288
 
348
- ```html
349
- <div class="callout callout-note">
350
- <div class="callout-title">Install CSS</div>
351
- <p>Remember to install KaTeX CSS.</p>
352
- </div>
289
+ const featherdown = new Featherdown({
290
+ frontmatter: "auto",
291
+ });
292
+
293
+ const result = await featherdown.parseFile("./posts/hello.md");
353
294
  ```
354
295
 
355
- When no custom title is provided, a default title is emitted from the callout type (for example `warning` -> `Warning`).
356
- Callout body content continues through the normal Markdown pipeline, and styling is left to the consuming application.
296
+ - **`parseFile(path)`** reads UTF-8 and returns the same **`FeatherdownResult`** as **`parse(markdown)`** for the same file contents and options.
357
297
 
358
- ### Image rewriting
298
+ ## Mermaid (Node only)
359
299
 
360
- Use manifest-based rewriting for relative Markdown images in publishing workflows.
300
+ Inline SVG Mermaid is available **only** through the Node entry, with **`mermaid: { render: "svg" }`**. There is **no** placeholder-only mode documented today.
361
301
 
362
302
  ```ts
363
- import { renderMarkdownToHtml } from "featherdown";
303
+ import { Featherdown } from "featherdown/node";
364
304
 
365
- const html = await renderMarkdownToHtml("![Logo](./images/logo.png)", {
366
- kind: "post",
367
- slug: "hello-world",
368
- manifest: {
369
- map: {
370
- "post/hello-world/images/logo.png": {
371
- url: "https://cdn.example.com/blog/hello-world/logo.hash.png",
372
- },
373
- },
305
+ const featherdown = new Featherdown({
306
+ mermaid: {
307
+ render: "svg",
374
308
  },
375
309
  });
376
- ```
377
-
378
- Relative image rewriting is optional and entirely caller-driven. No CDN logic or fetch behavior is bundled into the package.
379
310
 
380
- ## Styling hooks
311
+ const result = await featherdown.parse(markdown);
312
+ ```
381
313
 
382
- featherdown emits stable classes/data hooks you can style in your own CSS:
314
+ - Uses **`rehype-mermaid`** and may require the **optional Playwright / Chromium** peer setup (`playwright` + `npx playwright install chromium`). Failures can be **environment-sensitive** in CI.
315
+ - Valid diagrams become inline **SVG** in `html`; **`result.assets.features.mermaid`** is **`true`** when this path is active.
316
+ - The Node Mermaid pipeline uses a **final SVG-aware sanitize** step and does **not** match every rehype plugin order detail of the default browser pipeline—expect rare edge differences for exotic inputs.
383
317
 
384
- - callouts: `callout`, `callout-<type>`, `callout-title`
385
- - code wrappers/titles: `code-block`, `code-block-title`
386
- - highlighted lines: `code-line`, `code-line-highlighted`
387
- - numbered lines: `code-line-numbered`, `code-line-number`
388
- - copy hooks: `code-block-copyable`, `code-block-copy-button`, `data-code-copy`, `data-code-copy-target`
389
- - chart placeholders: `chart-mount`
390
- - markdown images: `markdown-inline-img`
318
+ The default **`featherdown`** entry remains Mermaid-free for bundle safety.
391
319
 
392
- These are contract hooks, not a built-in theme system. You own the final visual design.
320
+ ## Advanced and compatibility APIs
393
321
 
394
- ## Common publishing patterns
322
+ ### `featherdown/advanced`
395
323
 
396
- - **Basic post page**: `renderMarkdownToHtml` + app-level CSS.
397
- - **Editorial QA**: `renderMarkdown` and surface `diagnostics` in author tooling.
398
- - **Docs/blog navigation**: `renderMarkdownDocument` and drive sidebars from `headings`.
399
- - **CDN assets**: pass `kind`, `slug`, and `manifest.map`/`manifest.remote`.
400
- - **Static Mermaid output**: use `featherdown/node` in a trusted Node build step.
324
+ The advanced subpath is for **existing low-level unified integrations**. Most applications should use **`Featherdown`**. The subpath exists for **existing unified pipelines** and low-level compatibility:
401
325
 
402
- ## Advanced Usage
326
+ ```ts
327
+ import {
328
+ createMarkdownProcessor,
329
+ rehypeChartBlocks,
330
+ rehypeCdnImages,
331
+ } from "featherdown/advanced";
332
+ ```
403
333
 
404
- ### Create the default processor directly
334
+ The same symbols remain re-exported from the **root** package for backward compatibility; prefer **`Featherdown`** for normal Markdown rendering.
405
335
 
406
- Use `createMarkdownProcessor` when you want direct control over processing calls while keeping featherdown’s default browser-safe pipeline.
336
+ ### Legacy function exports
407
337
 
408
- ```ts
409
- import { createMarkdownProcessor } from "featherdown";
338
+ Older helpers (`renderMarkdownToHtml`, `renderMarkdown`, `renderMarkdownDocument`, `parseMarkdownFile`, `createMarkdownProcessor`, …) remain exported and marked **`@deprecated`**. They take **`RenderMarkdownOptions`**, not the full **`FeatherdownOptions`** surface (for example **`math`**, **`code`**, **`charts`**, **`frontmatter`**, and **`diagnostics: "strict"`** are **`Featherdown`** features). Prefer **`new Featherdown().parse()`** for new code.
410
339
 
411
- const processor = createMarkdownProcessor();
412
- const file = await processor.process("# Hello");
413
- const html = String(file);
414
- ```
340
+ ## Migration from legacy helpers
415
341
 
416
- ### Use the plugins directly
342
+ Legacy helpers remain available for compatibility, but new code should use **`Featherdown`**.
417
343
 
418
- The package also exports focused plugins for custom unified pipelines.
344
+ For default rendering behavior (what the legacy helpers covered under **`RenderMarkdownOptions`**), the closest migration is:
419
345
 
420
346
  ```ts
421
- import { unified } from "unified";
422
- import remarkParse from "remark-parse";
423
- import remarkRehype from "remark-rehype";
424
- import rehypeStringify from "rehype-stringify";
425
- import { rehypeChartBlocks, rehypeCdnImages } from "featherdown";
426
-
427
- const html = String(
428
- await unified()
429
- .use(remarkParse)
430
- .use(remarkRehype)
431
- .use(rehypeChartBlocks)
432
- .use(rehypeCdnImages, { kind: "post", slug: "hello-world" })
433
- .use(rehypeStringify)
434
- .process(markdown),
435
- );
347
+ // Before
348
+ const html = await renderMarkdownToHtml(markdown);
349
+
350
+ // After
351
+ const { html } = await new Featherdown().parse(markdown);
436
352
  ```
437
353
 
438
- ## Node-only Mermaid Rendering
354
+ > **Migration note:** The legacy helpers are kept for compatibility and use the older **`RenderMarkdownOptions`** surface. They are not a full alias for **`FeatherdownOptions`**. For feature gates such as **`math`**, **`code`**, **`charts`**, **`frontmatter`**, and **`diagnostics: "strict"`**, use the **`Featherdown`** class.
439
355
 
440
- For static Mermaid rendering, use the separate Node-only entry:
356
+ | Legacy | Prefer |
357
+ | --- | --- |
358
+ | `renderMarkdownToHtml(md, opts)` | `(await new Featherdown().parse(md)).html` — legacy **`opts`** only apply the older options shape; pass **`FeatherdownOptions`** on **`Featherdown`** when you need feature gates |
359
+ | `renderMarkdown(md, opts)` | `await new Featherdown().parse(md)` — use **`r.html`** and **`r.diagnostics`**; same **`RenderMarkdownOptions`** limitation as above |
360
+ | `renderMarkdownDocument(md, opts)` | `await new Featherdown().parse(md)` for the default document pipeline when **`opts`** are legacy **`RenderMarkdownOptions`**. The **`Featherdown`** result adds **`body`**, **`frontmatter`**, **`assets`**, and related fields—configure **`Featherdown`** directly if you need **`FeatherdownOptions`** (not understood by the helper) |
361
+ | `parseMarkdownFile(md)` | `new Featherdown({ frontmatter: "auto" }).parse(md)` returns **`frontmatter`**, **`metadata`**, **`body`**, and **`html`** in one result. Keep **`parseMarkdownFile`** only when you need its strict **`{ frontMatter, content }`** contract |
362
+ | `renderMarkdownToHtmlWithMermaid(md, opts)` (Node) | `new Featherdown({ mermaid: { render: "svg" } }).parse(md)` then read **`html`** from **`featherdown/node`** — add **`kind`**, **`manifest`**, and other options in the same object as needed; **do not spread** an options object that might already define **`mermaid`** (merge carefully or use a dedicated instance). Legacy **`opts`** remain **`RenderMarkdownOptions`**-shaped |
363
+ | `createMarkdownProcessor(opts)` | **`Featherdown`** for normal use; **`featherdown/advanced`** only for custom unified graphs |
441
364
 
442
- ````ts
443
- import { renderMarkdownToHtmlWithMermaid } from "featherdown/node";
365
+ **Strict diagnostics:** **`diagnostics: "strict"`** exists only on **`Featherdown`**; legacy render helpers do not use it.
444
366
 
445
- const html = await renderMarkdownToHtmlWithMermaid(
446
- "```mermaid\ngraph TD; A-->B;\n```",
447
- );
448
- ````
367
+ ## Styling reference (HTML contracts)
449
368
 
450
- Use this entry in Node publishing/build environments where Playwright + Chromium dependencies are acceptable.
369
+ Rendered output uses stable classes including:
451
370
 
452
- Behavior contract for Mermaid blocks in this entry:
371
+ - **Article surface:** wrap content in **`featherdown-content`** (see shipped CSS).
372
+ - **Callouts:** `callout`, `callout-<type>`, `callout-title`
373
+ - **Code:** `code-block`, `code-block-title`, `code-line`, `code-line-highlighted`, `code-line-numbered`, `code-line-number`, `code-block-copyable`, `code-block-copy-button`
374
+ - **Charts:** `chart-mount`
375
+ - **Images:** `markdown-inline-img`
453
376
 
454
- - valid Mermaid fences render to inline sanitized SVG
455
- - invalid Mermaid fences fall back to a normal rendered code block
456
- - one Mermaid failure does not stop the rest of the document from rendering
377
+ ## Security and trust
457
378
 
458
- The Mermaid subpath is npm-focused and is **not** part of the JSR export surface.
379
+ - Input is sanitized (`rehype-sanitize`); scripts are stripped in the default pipeline.
380
+ - Prefer the **default** entry for untrusted user content.
381
+ - The **Node Mermaid** path is better suited to **trusted** publishing inputs.
459
382
 
460
383
  ## Runtime boundaries
461
384
 
462
- - `featherdown` default entry is browser-safe and Mermaid-free.
463
- - `featherdown/node` is Node-only and includes Mermaid rendering dependencies.
464
- - `featherdown/node` requires Playwright Chromium setup in the runtime environment.
465
- - JSR export surface is default-entry focused; Mermaid entry is npm subpath only.
385
+ | Entry | Role |
386
+ | --- | --- |
387
+ | **`featherdown`** | Browser-safe; no Mermaid / Playwright in the default bundle. |
388
+ | **`featherdown/node`** | Node **`Featherdown`**, optional Mermaid SVG, **`parseFile`**. |
389
+ | **`featherdown/advanced`** | Processor + rehype plugins for unified integrations. |
390
+
391
+ Mermaid is **npm subpath–oriented**; JSR usage focuses on the default library surface.
466
392
 
467
- ## CSS / Asset Expectations
393
+ ### Client-side Mermaid previews
468
394
 
469
- - KaTeX CSS is required for correct math styling.
470
- - Syntax highlighting output includes highlight.js classes; include matching styles in your app.
471
- - Mermaid rendering from `featherdown/node` depends on Playwright Chromium availability.
395
+ The default `featherdown` entry does not render Mermaid in the browser. If your app needs live Mermaid previews, parse Markdown first, then hydrate `code.language-mermaid` blocks with the `mermaid` package in your own app code. This keeps Mermaid out of Featherdown's browser bundle. Use `featherdown/node` when you want build-time SVG output.
472
396
 
473
- ## Security and Trust Guidance
397
+ ```ts
398
+ import mermaid from "mermaid";
474
399
 
475
- - Input is sanitized with `rehype-sanitize`.
476
- - Script tags are stripped.
477
- - The default entry is designed to be browser-safe.
478
- - The Mermaid entry is Node-only and is better suited to trusted or controlled publishing inputs than arbitrary user-generated content.
479
- - For general-purpose rendering of untrusted content, prefer the default `featherdown` entry.
480
- - Always review your final HTML integration, especially if you add custom plugins around the built-in pipeline.
400
+ const result = await featherdown.parse(markdown);
401
+ mermaid.initialize({ startOnLoad: false, securityLevel: "strict" });
402
+ ```
481
403
 
482
- ## Why not just wire unified yourself?
404
+ ## Public API (summary)
483
405
 
484
- You absolutely can.
406
+ **Primary**
485
407
 
486
- `featherdown` exists for teams that want:
408
+ - **`Featherdown`**, **`FeatherdownOptions`**, **`FeatherdownParseOptions`**, **`FeatherdownResult`**, and related types from **`featherdown`**.
487
409
 
488
- - a production-friendly default pipeline
489
- - deliberate plugin ordering
490
- - sanitization already considered
491
- - publishing-oriented features beyond plain Markdown parsing
492
- - a clean split between browser-safe rendering and Node-only Mermaid rendering
410
+ **Node**
493
411
 
494
- ## Public API
412
+ - **`Featherdown`** from **`featherdown/node`** with optional **`NodeFeatherdownOptions`** / Mermaid config.
495
413
 
496
- Default entry (`featherdown`):
414
+ **Styles (package exports)**
497
415
 
498
- - `renderMarkdownToHtml`
499
- - `renderMarkdown`
500
- - `renderMarkdownDocument`
501
- - `createMarkdownProcessor`
502
- - `rehypeChartBlocks`
503
- - `rehypeCdnImages`
504
- - `parseMarkdownFile`
505
- - `libraryId`
416
+ - `featherdown/styles.css`, `featherdown/styles/base.css`, `featherdown/styles/katex.css`, `featherdown/styles/code.css`, `featherdown/styles/highlight.css`
506
417
 
507
- Node-only entry (`featherdown/node`):
418
+ **Compatibility**
508
419
 
509
- - `renderMarkdownToHtmlWithMermaid`
420
+ - Legacy render helpers and **`parseMarkdownFile`** on the default entry; **`renderMarkdownToHtmlWithMermaid`** on **`featherdown/node`**; **`featherdown/advanced`** for processor/plugins.
510
421
 
511
422
  ## Scripts
512
423
 
513
- | Script | Description |
514
- | ---------------------- | --------------------------------- |
515
- | `npm run build` | Build ESM artifacts in `dist/` |
516
- | `npm test` | Run Vitest once |
517
- | `npm run test:watch` | Run Vitest in watch mode |
518
- | `npm run lint` | Run ESLint |
519
- | `npm run typecheck` | Run TypeScript checks |
520
- | `npm run test:exports` | Build and run export smoke checks |
424
+ | Script | Description |
425
+ | --- | --- |
426
+ | `npm run build` | Build ESM artifacts in `dist/` |
427
+ | `npm test` | Run Vitest once |
428
+ | `npm run test:watch` | Vitest watch mode |
429
+ | `npm run lint` | ESLint |
430
+ | `npm run typecheck` | TypeScript `--noEmit` |
431
+ | `npm run test:exports` | Build + export smoke checks |
432
+
433
+ ## Site
434
+
435
+ A demo site lives in **`site/`**.
436
+
437
+ ```bash
438
+ npm run site:install
439
+ npm run site:dev
440
+ ```
441
+
442
+ Build:
443
+
444
+ ```bash
445
+ npm run site:build
446
+ ```
447
+
448
+ GitHub Pages base path:
449
+
450
+ ```bash
451
+ SITE_BASE_PATH=/featherdown/ npm run site:build
452
+ ```
521
453
 
522
454
  ## Maintainers
523
455
 
524
- CI and publishing are documented in [RELEASING.md](./RELEASING.md).
456
+ CI and publishing: [RELEASING.md](./RELEASING.md).
525
457
 
526
458
  ## License
527
459