### TypeScript Server Example with Metadata Source: https://github.com/unjs/md4x/blob/main/website/samples/2.code-and-tables.md An example of a TypeScript server setup using the 'bun' runtime. The code block includes metadata for the filename (server.ts) and highlights lines 2 through 4, demonstrating server initialization and request handling. ```ts import { serve } from "bun"; serve({ port: 3000, fetch(req) { return new Response("Hello!"); }, }); ``` -------------------------------- ### Node Format Examples Source: https://github.com/unjs/md4x/blob/main/docs/comark-ast.md Examples showing how various markdown elements are represented in the Comark AST format. ```APIDOC ## Node Format Examples ### Paragraphs Markdown: `This is a paragraph with **bold** text.` AST Representation: ```json ["p", {}, "This is a paragraph with ", ["strong", {}, "bold"], " text."] ``` ### Links Markdown: `[Link text](https://example.com)` AST Representation: ```json ["a", { "href": "https://example.com" }, "Link text"] ``` ### Code Blocks Markdown: ```javascript [app.js] {1-2} const a = 1 ``` AST Representation: ```json ["pre", { "language": "javascript", "filename": "app.js", "highlights": [1, 2] }, ["code", {}, "const a = 1"]] ``` ``` -------------------------------- ### CLI Usage Examples for MD4X Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Demonstrates various command-line interface commands for using MD4X to parse and render markdown files. Includes examples for local files, remote URLs, GitHub repositories, npm packages, stdin, and outputting to files. ```bash npx md4x README.md # ANSI output npx md4x README.md -t html # HTML output npx md4x README.md -t text # Plain text output (strip markdown) npx md4x README.md -t ast # JSON AST output (comark) npx md4x README.md -t meta # Metadata JSON output npx md4x README.md -t markdown # Clean markdown (strip MDC/frontmatter/HTML) npx md4x README.md -t heal # Heal incomplete markdown npx md4x README.md --heal # Heal before rendering (any format) npx md4x README.md --heal -t json # Heal + JSON AST output # Remote sources npx md4x https://nitro.build/guide # Fetch and render any URL npx md4x gh:nitrojs/nitro # GitHub repo → README.md npx md4x npm:vue@3 # npm package at specific version # Stdin echo "# Hello" | npx md4x -t text cat README.md | npx md4x -t html # Output to file npx md4x README.md -t meta -o README.json # Full HTML document npx md4x README.md -t html -f --html-title="My Docs" # Wrap in full HTML with npx md4x README.md -t html -f --html-css=style.css # Add CSS link ``` -------------------------------- ### Markdown Inline Link Syntax Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt A collection of examples demonstrating various inline link configurations, including optional titles, empty destinations, and handling of spaces using pointy brackets. ```markdown [link](/uri "title") [link](/uri) [](./target.md) [link]() [link](<>) []() [link]() [a]() ``` ```html

link

link

link

link

link

a

``` -------------------------------- ### HTML Block Example: Closing Tag Start Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates an HTML block that begins with a closing tag (e.g., ). This is a valid way to start an HTML block, and subsequent Markdown content is parsed normally after the block. ```markdown *foo* . *foo* ``` -------------------------------- ### Handling URL Fragments and Queries Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Examples of including fragment identifiers and query parameters within link destinations. ```markdown [link](#fragment) [link](https://example.com#fragment) [link](https://example.com?foo=3#frag) ``` -------------------------------- ### Complex Permissive URL Autolink Example Source: https://github.com/unjs/md4x/blob/main/test/spec-permissive-autolinks.txt A comprehensive example combining scheme, host, path, query, and fragment for permissive URL autolinks, demonstrating various valid formats. ```markdown http://commonmark.org (Visit https://encrypted.google.com/search?q=Markup+(business)) Anonymous FTP is available at ftp://foo.bar.baz. ``` ```html

http://commonmark.org

(Visit https://encrypted.google.com/search?q=Markup+(business))

Anonymous FTP is available at ftp://foo.bar.baz.

``` -------------------------------- ### AUR Installation for MD4X Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Provides the command to install MD4X from the Arch User Repository (AUR). ```bash yay -S md4x # md4x-git ``` -------------------------------- ### List and Table Formatting Source: https://github.com/unjs/md4x/blob/main/test/spec-markdown.txt Examples of ordered, unordered, and task lists, as well as aligned markdown tables. ```markdown - [x] done - [ ] todo | left | center | right | |:-----|:------:|------:| | a | b | c | ``` -------------------------------- ### HTML Block Example: Partial Tag Start Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an HTML block where the opening tag is split across lines. This is permissible as long as the split occurs where whitespace would normally be, demonstrating flexibility in tag definition. ```markdown
.
``` -------------------------------- ### MD4X CLI Usage Source: https://github.com/unjs/md4x/blob/main/README.md Examples of how to use the MD4X command-line interface for parsing and rendering markdown files. ```APIDOC ## MD4X CLI Usage ### Description This section details various ways to use the MD4X CLI tool to process markdown files, including rendering to different formats, fetching remote content, and handling input/output. ### Examples #### Local Files ```sh # Render to ANSI terminal output npx md4x README.md # Render to HTML output npx md4x README.md -t html # Render to plain text (strip markdown) npx md4x README.md -t text # Render to JSON AST output (Comark) npx md4x README.md -t ast # Render to metadata JSON output npx md4x README.md -t meta # Render as clean standard markdown npx md4x README.md -t markdown # Heal incomplete markdown before rendering npx md4x README.md -t heal # Heal and render to JSON AST npx md4x README.md --heal -t json ``` #### Remote Sources ```sh # Fetch and render any URL npx md4x https://nitro.build/guide # Render README.md from a GitHub repository npx md4x gh:nitrojs/nitro # Render from a specific npm package version npx md4x npm:vue@3 ``` #### Stdin and File Output ```sh # Pipe markdown content via stdin to CLI echo "# Hello" | npx md4x -t text cat README.md | npx md4x -t html # Output metadata to a JSON file npx md4x README.md -t meta -o README.json ``` #### Full HTML Document ```sh # Wrap markdown in a full HTML document with a custom title npx md4x README.md -t html -f --html-title="My Docs" # Wrap in full HTML and include a CSS file npx md4x README.md -t html -f --html-css=style.css ``` ``` -------------------------------- ### HTML Block Example: Div Element Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an HTML block starting with a
tag. This example demonstrates how content within the div, including Markdown-like syntax, is treated as raw HTML. ```markdown
*hello* .
*hello* ``` -------------------------------- ### HTML Output for Markdown.pl Behavior (Blockquote) Source: https://github.com/unjs/md4x/blob/main/test/spec.txt HTML output for the blockquote example, demonstrating nested list item parsing. ```html
  • one

    two

``` -------------------------------- ### Markdown Block Parsing Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the step-by-step creation of a document tree from Markdown input, showing how lines are processed to form block elements like block quotes, paragraphs, and lists. ```markdown > Lorem ipsum dolor sit amet. > - Qui *quodsi iracundia* > - aliquando id ``` -------------------------------- ### HTML Comment Parsing Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows examples of valid HTML comments, including those with hyphens and special characters, as parsed by MD4X. ```html foo .

foo

``` ```html foo foo --> foo foo --> .

foo foo -->

foo foo -->

``` -------------------------------- ### C Library Rendering Source: https://github.com/unjs/md4x/blob/main/README.md Examples of using the md4x C library to render markdown into various formats like HTML, JSON, ANSI, and plain text. ```c #include "md4x.h" #include "md4x-html.h" void output(const MD_CHAR* text, MD_SIZE size, void* userdata) { fwrite(text, 1, size, (FILE*) userdata); } md_html(input, input_size, output, stdout, MD_DIALECT_GITHUB, 0); ``` -------------------------------- ### JavaScript Code Block Example Source: https://github.com/unjs/md4x/blob/main/test/fuzzers/seed-corpus/alerts.md Demonstrates a simple JavaScript code block within a Markdown alert. This example shows how to render code directly inside a note. ```javascript code block ``` -------------------------------- ### GitHub Flavored Markdown Syntax Examples Source: https://context7.com/unjs/md4x/llms.txt Showcases supported GFM extensions including tables, task lists, strikethrough, autolinks, and GitHub alerts. ```markdown | Left | Center | Right | | :------ | :-----: | ------: | | foo | bar | baz | - [x] Completed task - [ ] Pending task ~~deleted text~~ Visit https://example.com or email user@example.com > [!NOTE] > Useful information for users. > [!TIP] > Helpful advice for doing things better. > [!WARNING] > Urgent info requiring immediate attention. > [!CAUTION] > Negative consequences of an action. ``` -------------------------------- ### Markdown Block Quote Formatting Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt A collection of Markdown block quote examples demonstrating standard usage, paragraph separation, and how block quotes interact with other elements like horizontal rules and paragraphs. ```markdown > foo > bar ``` ```markdown > foo > > bar ``` ```markdown > aaa *** > bbb ``` ```markdown > > > foo bar ``` ```markdown > code > not code ``` -------------------------------- ### MDC Component Syntax Examples Source: https://context7.com/unjs/md4x/llms.txt Demonstrates the usage of Markdown Components (MDC) for inline and block-level elements, including support for props, slots, and nested components. ```markdown Check out this :badge[New]{color="blue"} feature. Click :icon-star to favorite. ::alert{type="warning" #my-alert .custom-class} This is a **warning** message with full markdown support. :: :::danger STOP Do not proceed without reading this. ::: :::outer ::inner Nested content :: ::: ::card #header ``` -------------------------------- ### Custom Code Highlighting Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Shows how to use the `highlighter` option in `renderToHtml` for custom syntax highlighting of code blocks, using Shiki as an example. ```APIDOC ## Custom Code Highlighting ### Description `renderToHtml` supports a `highlighter` option for custom syntax highlighting of fenced code blocks. The highlighter receives the raw code (HTML-unescaped) and block metadata (language, filename, highlighted lines), and returns a replacement HTML string or `undefined` to keep the default. ### Method Synchronous Rendering with Custom Highlighter ### Endpoint N/A (Client-side library) ### Parameters #### Request Body - **highlighter** (function) - A function that accepts `code` (string) and `block` (object) as arguments and returns an HTML string or `undefined`. - `block` object contains: - **lang** (string) - The language specified in the code block. - **filename** (string) - The filename specified in the code block. - **highlights** (array of numbers) - Lines to highlight. ### Request Example ````js import { renderToHtml } from "md4x"; import { createHighlighter } from "shiki"; const highlighter = await createHighlighter({ themes: ["github-dark"], langs: ["js", "ts", "html", "css"], }); const html = renderToHtml("```js\nconst x = 1;\n```", { highlighter: (code, block) => { if (!block.lang) return; // keep default for unknown languages return highlighter.codeToHtml(code, { lang: block.lang, theme: "github-dark", }); }, }); ```` ### Response #### Success Response (200) - **html** (string) - Rendered HTML content with custom highlighted code blocks. #### Response Example ```html
const x  = 1;
``` ### Code Block Metadata Parsing Code block metadata from the info string is parsed automatically. ````md ```ts [app.ts] {1,3-5} // block.lang = "ts" // block.filename = "app.ts" // block.highlights = [1, 3, 4, 5] ``` ```` ``` -------------------------------- ### Basic Setext Heading Syntax Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Examples demonstrating level 1 and level 2 headings using '=' and '-' underlines. The content can span multiple lines and is parsed as CommonMark inline content. ```markdown Foo *bar* ========= Foo *bar* --------- ``` -------------------------------- ### Standalone Inline Component Example Source: https://github.com/unjs/md4x/blob/main/test/spec-components.txt Demonstrates a basic inline component without content or properties, rendering as a self-closing HTML tag. ```markdown :icon-star .

``` -------------------------------- ### JavaScript Function Example Source: https://github.com/unjs/md4x/blob/main/website/samples/2.code-and-tables.md Demonstrates a simple JavaScript function to greet a user. This is typically used within fenced code blocks for syntax highlighting. ```js function greet(name) { return `Hello, ${name}!`; } ``` -------------------------------- ### HTML Output for Markdown.pl Behavior (Indented Marker) Source: https://github.com/unjs/md4x/blob/main/test/spec.txt HTML output for the Markdown.pl behavior example, showing 'two' as a continuation paragraph. ```html
  • one

    two

``` -------------------------------- ### HTML Closing Tag Parsing Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the parsing of HTML closing tags, including valid syntax and cases with illegal attributes. ```html
.

``` ```html .

</a href="foo">

``` -------------------------------- ### HTML Tag Parsing Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the parsing of various HTML open tags, including those with attributes, custom names, and empty elements. It also shows how illegal tag names are handled. ```html .

``` ```html .

``` ```html .

``` ```html .

``` ```html Foo .

Foo

``` ```html <33> <__> .

<33> <__>

``` -------------------------------- ### Enable Frontmatter with MD_FLAG_FRONTMATTER Source: https://github.com/unjs/md4x/blob/main/test/spec-frontmatter.txt Demonstrates the syntax for defining a YAML-style frontmatter block at the start of a document. The block must be delimited by at least three dashes and appear on the first line. ```markdown --- title: Hello date: 2024-01-01 --- ``` -------------------------------- ### Implement Web Standard Server Source: https://github.com/unjs/md4x/blob/main/packages/md4x/test/fixtures/nitro-index.md Create a server entry point using the native Web Fetch API. This approach is framework-agnostic and works across various runtimes. ```typescript export default { async fetch(req: Request): Promise { return new Response(`Hello world! (${req.url})`); }, }; ``` -------------------------------- ### Permissive URL Autolinks Example Source: https://github.com/unjs/md4x/blob/main/test/spec-permissive-autolinks.txt Demonstrates the structure and recognition of permissive URL autolinks, including scheme, host, path, query, and fragment. Recognizes http, https, and ftp schemes. ```markdown https://example.com http://example.com ftp://example.com ssh://example.com ``` ```html

https://example.com http://example.com ftp://example.com

ssh://example.com

``` -------------------------------- ### WASM Initialization and Rendering Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Demonstrates how to initialize the MD4X WASM module and render Markdown to HTML. The `init()` function must be called once before rendering. ```APIDOC ## WASM Initialization and Rendering ### Description Works anywhere with WebAssembly support. Requires a one-time async initialization. ### Method Async Initialization and Synchronous Rendering ### Endpoint N/A (Client-side library) ### Parameters #### Request Body `init()` accepts an optional options object with a `wasm` property (`ArrayBuffer`, `Response`, `WebAssembly.Module`, or `Promise`). When called with no arguments, it loads the bundled `.wasm` file automatically. ### Request Example ```js import { init, renderToHtml } from "md4x/wasm"; await init(); // call once before rendering const html = renderToHtml("# Hello"); ``` ### Response #### Success Response (200) - **html** (string) - Rendered HTML content. #### Response Example ```html

Hello

``` ``` -------------------------------- ### Permissive WWW Autolinks Example Source: https://github.com/unjs/md4x/blob/main/test/spec-permissive-autolinks.txt Shows permissive WWW autolinks, which are similar to URL autolinks but must start with 'www.' instead of an explicit scheme. ```markdown www.google.com/search?q=Markdown ``` ```html

www.google.com/search?q=Markdown

``` -------------------------------- ### Ordered List Item Starting with Indented Code Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an ordered list item where the first element is an indented code block, followed by other blocks. This example highlights the structure and indentation. ```markdown 1. indented code paragraph more code ``` ```html
  1. indented code
    

    paragraph

    more code
    
``` -------------------------------- ### Initialize md4x WASM Source: https://github.com/unjs/md4x/blob/main/README.md Demonstrates how to import and initialize the md4x WebAssembly module. The init function must be called asynchronously before any rendering occurs. ```javascript import { init, renderToHtml } from "md4x/wasm"; await init(); // call once before rendering const html = renderToHtml("# Hello"); ``` -------------------------------- ### HTML Block Example: Table with Nested Pre Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates an HTML block starting with a tag. The content within the
 tag inside the table is treated as raw HTML and does not affect the outer HTML block's parsing. The block is terminated by a blank line.

```markdown
**Hello**,

_world_.
. table>
**Hello**,

world.

``` -------------------------------- ### Ordered List with Valid Start Number Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates an ordered list item with a valid nine-digit start number. This illustrates the constraint on the maximum value for ordered list start numbers. ```markdown 123456789. ok ``` ```html
  1. ok
``` -------------------------------- ### Ordered List with Invalid Start Number Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows an ordered list item with a start number exceeding nine digits, which is not rendered as a list item. This highlights the limit on ordered list start numbers. ```markdown 1234567890. not ok ``` ```html

1234567890. not ok

``` -------------------------------- ### JavaScript Usage of MD4X WASM Target Source: https://github.com/unjs/md4x/blob/main/docs/js-bindings.md Demonstrates how to use the MD4X WASM module from JavaScript via the 'md4x/wasm' wrapper. It shows the asynchronous initialization process and synchronous rendering methods after initialization. The 'init' function can accept options to specify the WASM binary. ```js import { init, renderToHtml } from "md4x/wasm"; await init(); // load WASM binary (call once before using render methods) const html = renderToHtml("# Hello"); // sync after init ``` -------------------------------- ### Initialization API Source: https://context7.com/unjs/md4x/llms.txt The `init()` function initializes the MD4X module. For WASM builds, this must be called before any render methods. For NAPI (Node.js native), it's optional as the binding loads lazily on first use. ```APIDOC ## Initialization API ### Description The `init()` function initializes the MD4X module. For WASM builds, this must be called before any render methods. For NAPI (Node.js native), it's optional as the binding loads lazily on first use. ### Method `init(options?: { wasm?: ArrayBuffer | Response | WebAssembly.Module | Promise }): Promise ### Parameters #### Options - **wasm** (ArrayBuffer | Response | WebAssembly.Module | Promise) - Optional - Custom WASM source to use for initialization. ### Request Example ```javascript import { init, renderToHtml } from "md4x/wasm"; // WASM requires initialization before rendering await init(); // Optional: provide custom WASM source await init({ wasm: fetch("/path/to/md4x.wasm"), // ArrayBuffer, Response, WebAssembly.Module, or Promise }); const html = renderToHtml("# Hello, **world**!"); // Output:

Hello, world!

``` ``` -------------------------------- ### Build and Compile md4x Source: https://github.com/unjs/md4x/blob/main/README.md Commands to build the project using Zig, including targets for WASM and Node.js NAPI addons. ```bash zig build # ReleaseFast (default) zig build -Doptimize=Debug # Debug build zig build wasm # WASM target (~163K) zig build napi # Node.js NAPI addon ``` -------------------------------- ### Render Markdown via CLI Source: https://context7.com/unjs/md4x/llms.txt Demonstrates basic CLI usage to render markdown files into various formats including HTML, plain text, and AST. Supports local files, stdin, and remote sources. ```bash npx md4x README.md -t html npx md4x README.md -t ast npx md4x https://nitro.build/guide echo "# Hello **World**" | npx md4x -t html ``` -------------------------------- ### Non-entities and Invalid References Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Provides examples of strings that are not recognized as valid entity or numeric character references, and how they are rendered as literal text. ```html   &x; &#; &#x; � &#abcdef0; &ThisIsNotDefined; &hi?; .

&nbsp &x; &#; &#x; &#87654321; &#abcdef0; &ThisIsNotDefined; &hi?;

``` -------------------------------- ### Ordered List with Negative Start Number Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates that a negative number is not a valid start number for an ordered list item and is rendered as plain text. ```markdown -1. not ok ``` ```html

-1. not ok

``` -------------------------------- ### Execute MD4X CLI Commands Source: https://github.com/unjs/md4x/blob/main/README.md Examples of using the MD4X CLI to render Markdown files, remote URLs, or npm packages into various formats like HTML, JSON AST, or plain text. These commands support features like streaming healing and outputting to files. ```shell npx md4x README.md npx md4x README.md -t html npx md4x README.md -t ast npx md4x https://nitro.build/guide echo "# Hello" | npx md4x -t text npx md4x README.md -t html -f --html-title="My Docs" ``` -------------------------------- ### Ordered List with Leading Zeros in Start Number Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Illustrates how leading zeros in the start number of an ordered list are handled correctly. The parser interprets '003' as the number 3. ```markdown 003. ok ``` ```html
  1. ok
``` -------------------------------- ### Markdown Empty List Item Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt This markdown snippet presents an example of an empty list item. It raises the question of whether list items can be empty, which is not explicitly defined in the original syntax. ```markdown * a * * b ``` -------------------------------- ### Define Block Components with Props and Titles Source: https://github.com/unjs/md4x/blob/main/docs/markdown-syntax.md Demonstrates how to create block components using the double-colon syntax, including support for custom props, titles, and nested structures. ```markdown ::alert{type="info"} This is **important** content. :: :::info This is an info box. ::: :::details Click me to toggle Hidden content here ::: ``` -------------------------------- ### Markdown Image Syntax Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the various syntaxes for including images in Markdown, from basic inline images to reference-style and collapsed formats. It also shows how nested links within image descriptions are handled and how to escape literal '!' characters. ```markdown ![foo](/url "title") ``` ```markdown ![foo *bar*] [foo *bar*]: train.jpg "train & tracks" ``` ```markdown ![foo ![bar](/url)](/url2) ``` ```markdown ![foo [bar](/url)](/url2) ``` ```markdown ![foo *bar][] [foo *bar*]: train.jpg "train & tracks" ``` ```markdown ![foo *bar*][foobar] [FOOBAR]: train.jpg "train & tracks" ``` ```markdown ![foo](train.jpg) ``` ```markdown My ![foo bar](/path/to/train.jpg "title" ) ``` ```markdown ![foo]() ``` ```markdown ![](/url) ``` ```markdown ![foo][bar] [bar]: /url ``` ```markdown ![foo][bar] [BAR]: /url ``` ```markdown ![foo][] [foo]: /url "title" ``` ```markdown ![*foo* bar][] [*foo* bar]: /url "title" ``` ```markdown ![Foo] [foo]: /url "title" ``` ```markdown ![foo] [] [foo]: /url "title" ``` ```markdown ![foo] [foo]: /url "title" ``` ```markdown ![*foo* bar] [*foo* bar]: /url "title" ``` ```markdown ![[foo]] [[foo]]: /url "title" ``` ```markdown ![Foo] [foo]: /url "title" ``` ```markdown !\\\[foo] [foo]: /url "title" ``` ```markdown \\![foo] [foo]: /url "title" ``` -------------------------------- ### Markdown Thematic Break Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the correct syntax for creating thematic breaks (horizontal rules) in Markdown using sequences of '-', '_', or '*'. It also shows invalid examples and how indentation affects interpretation. ```markdown *** --- ___ ``` ```markdown *** *** *** ``` ```markdown - - - ** * ** * ** * ** - - - - ``` ```markdown - - - - ``` -------------------------------- ### Basic Alerts Source: https://github.com/unjs/md4x/blob/main/test/spec-alerts.txt Demonstrates the basic syntax for NOTE and WARNING alerts. ```APIDOC ## Basic NOTE alert ### Description Displays a standard note alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!NOTE] > This is a note ``` ### Response #### Success Response (200) ```html

This is a note

``` ## Basic WARNING alert ### Description Displays a standard warning alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!WARNING] > This is a warning ``` ### Response #### Success Response (200) ```html

This is a warning

``` ``` -------------------------------- ### Specialized Alerts Source: https://github.com/unjs/md4x/blob/main/test/spec-alerts.txt Shows examples for TIP, IMPORTANT, and CAUTION alerts. ```APIDOC ## TIP alert ### Description Displays a tip alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!TIP] > Tip content ``` ### Response #### Success Response (200) ```html

Tip content

``` ## IMPORTANT alert ### Description Displays an important alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!IMPORTANT] > Important content ``` ### Response #### Success Response (200) ```html

Important content

``` ## CAUTION alert ### Description Displays a caution alert. ### Method N/A (Markdown Syntax) ### Endpoint N/A (Markdown Syntax) ### Parameters N/A ### Request Example ```markdown > [!CAUTION] > Caution content ``` ### Response #### Success Response (200) ```html

Caution content

``` ``` -------------------------------- ### Normal Blockquote (No Alert Syntax) Source: https://github.com/unjs/md4x/blob/main/test/spec-alerts.txt Example of a standard blockquote that does not use the alert syntax. ```markdown > Normal blockquote ``` ```html

Normal blockquote

``` -------------------------------- ### Render AST to Formats Source: https://github.com/unjs/md4x/blob/main/docs/comark-ast.md Shows how to use the md4x rendering utilities to convert an AST back into HTML or Markdown strings. ```typescript import { renderHTML, renderMarkdown } from "comark/string"; const tree = await parse("# Hello **World**"); const html = renderHTML(tree); const markdown = renderMarkdown(tree); ``` -------------------------------- ### Markdown Heading Rendering Source: https://github.com/unjs/md4x/blob/main/test/spec-markdown.txt Examples of how different heading levels (H1-H6) are rendered in the markdown output. ```markdown # Heading 1 ## Heading 2 ### Heading 3 ###### Heading 6 ``` -------------------------------- ### Entity References in URLs Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Illustrates that entity and numeric character references are recognized within URLs. ```html . ``` -------------------------------- ### Build NAPI Target for MD4X Source: https://github.com/unjs/md4x/blob/main/docs/js-bindings.md Builds Node.js Native Addon (NAPI) binaries for MD4X using Zig. This command builds for all 9 platforms, outputting platform-specific .node files. It requires the 'node-api-headers' package. Individual platform targets can also be built. ```sh bunx nypm add node-api-headers zig build napi-all -Dnapi-include=node_modules/node-api-headers/include ``` -------------------------------- ### Implement Custom Syntax Highlighting Source: https://github.com/unjs/md4x/blob/main/README.md Shows how to provide a custom highlighter function to renderToHtml. This allows integration with libraries like Shiki to process fenced code blocks based on language and metadata. ```javascript import { renderToHtml } from "md4x"; import { createHighlighter } from "shiki"; const highlighter = await createHighlighter({ themes: ["github-dark"], langs: ["js", "ts", "html", "css"], }); const html = renderToHtml("```js\nconst x = 1;\n```", { highlighter: (code, block) => { if (!block.lang) return; // keep default for unknown languages return highlighter.codeToHtml(code, { lang: block.lang, theme: "github-dark", }); }, }); ``` -------------------------------- ### Define GitHub-style Alerts Source: https://github.com/unjs/md4x/blob/main/CHANGELOG.md Enable GitHub-style alerts using the MD_FLAG_ALERTS flag. Alerts are parsed from blockquotes starting with [!TYPE]. ```c /* Enable alerts in parser flags */ int flags = MD_DIALECT_GITHUB | MD_FLAG_ALERTS; // Use flags during document parsing ``` -------------------------------- ### Basic Wiki Link Syntax Source: https://github.com/unjs/md4x/blob/main/test/spec-wiki-links.txt Demonstrates the basic usage of wiki links with and without explicit labels. The destination is defined within double brackets, and an optional label can be provided after a pipe character. ```markdown [[foo]] [[foo|bar]] ``` -------------------------------- ### Invalid Autolink Examples Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates patterns that do not trigger autolink parsing, such as those containing spaces, invalid schemes, or missing brackets. ```markdown https://example.com ``` -------------------------------- ### Create Markdown Task Lists Source: https://github.com/unjs/md4x/blob/main/docs/markdown-syntax.md Shows how to represent checklist items using the task list extension. ```markdown - [x] Completed - [ ] Pending ``` -------------------------------- ### MD4X JavaScript API Source: https://github.com/unjs/md4x/blob/main/README.md Examples of using the MD4X JavaScript API for rendering markdown in Node.js, browsers, and other JavaScript runtimes. ```APIDOC ## MD4X JavaScript API ### Description This section demonstrates how to use the MD4X JavaScript API. It supports both native Node.js addons (NAPI) for maximum performance and portable WASM modules for universal compatibility. ### Initialization ```js import { init } from "md4x"; // Required for WASM, optional for NAPI // await init(); ``` ### Core Rendering Functions ```js import { renderToHtml, renderToAST, parseAST, renderToAnsi, renderToText, renderToMarkdown, renderToMeta, parseMeta, heal, } from "md4x"; // Render markdown to HTML const html = renderToHtml("# Hello, **world**!"); // Render markdown to raw JSON AST string const json = renderToAST("# Hello, **world**!"); // Parse JSON AST string into a ComarkTree object const ast = parseAST("# Hello, **world**!"); // Render markdown to ANSI terminal format const ansi = renderToAnsi("# Hello, **world**!"); // Render markdown to plain text (stripping markdown syntax) const text = renderToText("# Hello, **world**!"); // Render markdown to clean, standard markdown format const md = renderToMarkdown("# Hello, **world**!"); // Render markdown to raw JSON metadata string const metaJson = renderToMeta("# Hello, **world**!"); // Parse JSON metadata string into an object const meta = parseMeta("# Hello, **world**!"); // Heal incomplete markdown strings const healed = heal("**incomplete streaming mark"); // Returns "**incomplete streaming mark**" ``` ### NAPI (Node.js Native Addon) For optimal performance in Node.js environments, you can import the NAPI version directly. ```js import { renderToHtml } from "md4x/napi"; const html = renderToHtml("# Node.js Native Render"); ``` ``` -------------------------------- ### Parse URL with Link Source: https://github.com/unjs/md4x/blob/main/test/regressions.txt Demonstrates parsing a URL within parentheses to create an HTML link. Handles standard URLs. ```markdown *(http://example.com)* ``` -------------------------------- ### Non-Alert: Type Not on First Line Source: https://github.com/unjs/md4x/blob/main/test/spec-alerts.txt Example showing that the alert syntax is only recognized when '[!TYPE]' appears on the first line of the blockquote. ```markdown > Some text > [!NOTE] > More text ``` ```html

Some text [!NOTE] More text

``` -------------------------------- ### Initialize MD4X Module Source: https://context7.com/unjs/md4x/llms.txt Initializes the MD4X module. This is mandatory for WASM builds to load the binary, while optional for NAPI-based Node.js environments. ```javascript import { init, renderToHtml } from "md4x/wasm"; // WASM requires initialization before rendering await init(); // Optional: provide custom WASM source await init({ wasm: fetch("/path/to/md4x.wasm"), }); const html = renderToHtml("# Hello, **world**!"); ``` -------------------------------- ### Standard ATX Heading Syntax Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Demonstrates the basic usage of ATX headings from level 1 to 6. Each level is defined by the number of leading hash characters. ```markdown # foo ## foo ### foo #### foo ##### foo ###### foo ``` -------------------------------- ### Undefined Entity References Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows that entity references not present in the HTML5 named entities list are treated as literal text. ```html &MadeUpEntity; .

&MadeUpEntity;

``` -------------------------------- ### Initialize MD4X Parser Source: https://github.com/unjs/md4x/blob/main/docs/parser-api.md The md_parse function is the entry point for parsing Markdown text. It requires a text buffer, size, and a configured MD_PARSER structure containing callback functions. ```c int md_parse(const MD_CHAR* text, MD_SIZE size, const MD_PARSER* parser, void* userdata); ``` -------------------------------- ### CLI Usage Source: https://context7.com/unjs/md4x/llms.txt The md4x CLI allows rendering markdown files, URLs, or stdin into various formats including HTML, AST, and plain text. ```APIDOC ## CLI Usage ### Description The md4x CLI renders markdown files to various output formats. It supports local files, stdin, HTTP URLs, GitHub repos, and npm packages. ### Usage npx md4x [source] [options] ### Options - **-t** (string) - Optional - Target format: html, text, ast, meta, markdown, heal. - **-o** (string) - Optional - Output file path. - **-f** (boolean) - Optional - Generate full HTML document. - **-s** (boolean) - Optional - Show performance stats. ``` -------------------------------- ### Permissive URL Autolinks with Fragment Source: https://github.com/unjs/md4x/blob/main/test/spec-permissive-autolinks.txt Demonstrates permissive URL autolinks that include a fragment identifier. The fragment starts with '#' and can contain various characters. ```markdown https://example.com#fragment ``` ```html

https://example.com#fragment

``` -------------------------------- ### Run md4x Performance Benchmarks Source: https://github.com/unjs/md4x/blob/main/docs/js-bindings.md Command to execute the benchmarking suite using mitata. This compares the performance of md4x against other markdown parsers like md4w and markdown-it. ```shell bun packages/md4x/bench/index.mjs ``` -------------------------------- ### Build md4x with Zig Source: https://github.com/unjs/md4x/blob/main/packages/md4x/README.md Commands to compile the library using the Zig build system for various targets including WASM and NAPI. ```shell zig build zig build -Doptimize=Debug zig build wasm zig build napi ``` -------------------------------- ### Parse Email Autolinks Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Examples of how email addresses enclosed in angle brackets are converted into mailto links. Note that backslash-escapes are not supported inside these blocks. ```markdown ``` -------------------------------- ### Parse URI Autolinks Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Examples of how various URI formats are parsed into HTML anchor tags. This includes standard web protocols and custom schemes. ```markdown ``` -------------------------------- ### Define Main Entry Point in Python Source: https://github.com/unjs/md4x/blob/main/test/fuzzers/seed-corpus/code-meta.md Shows a standard Python script structure using a main function. It imports necessary modules and defines a function that prints a greeting and returns an exit code. ```python import os import sys def main(): print("hello") return 0 ``` -------------------------------- ### Hexadecimal Numeric Character References Example Source: https://github.com/unjs/md4x/blob/main/test/spec.txt Shows how hexadecimal numeric character references are used to specify Unicode characters using a hexadecimal numeral. ```html " ആ ಫ .

" ആ ಫ

``` -------------------------------- ### Generate JSON AST with C API Source: https://context7.com/unjs/md4x/llms.txt Demonstrates how to render markdown into a Comark AST JSON format using the C library's AST renderer. ```c #include "md4x.h" #include "md4x-ast.h" #include void output(const MD_CHAR* text, MD_SIZE size, void* userdata) { fwrite(text, 1, size, (FILE*)userdata); } int main() { const char* markdown = "---\ntitle: Doc\n---\n# Hello\n\n**Bold** text"; md_ast(markdown, strlen(markdown), output, stdout, MD_DIALECT_ALL, 0); return 0; } ``` -------------------------------- ### Handle Dynamic Routes in TypeScript Source: https://github.com/unjs/md4x/blob/main/test/fuzzers/seed-corpus/code-meta.md An example of a server-side request handler for dynamic routes. It extracts the slug parameter from the request and returns it as a JSON response. ```typescript export default function handler(req, res) { res.json({ slug: req.params.slug }); } ``` -------------------------------- ### Handling Component Slots in MD4X Source: https://github.com/unjs/md4x/blob/main/test/spec-components.txt Illustrates how MD4X manages component slots, including single and multiple named slots, default content placement, and rendering rich markdown within slots. It also shows how empty slots are handled and how non-slot identifiers are treated as literal text. ```markdown ::card #title Card Title :: . ``` ```markdown ::card #header ## Card Title #content This is the main content #footer Footer text :: . ``` ```markdown ::card Default content #title Card Title :: .

Default content

``` ```markdown ::card #body This has **bold** and *italic* text. - Item one - Item two :: . ``` ```markdown ::card #empty #content Text here :: . ``` ```markdown #not-a-slot .

#not-a-slot

```