@molecule/app-markdown
Core interface · markdown · App (browser) · v1.1.0 · Apache-2.0
Markdown rendering core interface for molecule.dev.
npm install @molecule/app-markdownHow it works
@molecule/app-markdown is the markdown core interface on the app (browser) side: the API your app calls, with no vendor inside.
Choose the implementation by bonding one of its 2 providers: @molecule/app-markdown-marked, @molecule/app-markdown-react-markdown.
import { requireProvider, setProvider } from '@molecule/app-markdown'
import { provider } from '@molecule/app-markdown-react-markdown'
setProvider(provider) // once, at startup (bonds.ts)
const result = requireProvider().render('# Hello World', { gfm: true })
console.log(result.html) // sanitized HTML stringProviders (2): @molecule/app-markdown-marked, @molecule/app-markdown-react-markdown
Works with: @molecule/app-bond, @molecule/app-i18n
Live demos
Running apps built with Molecule that install this package — open the app or study the template.
Reference
Markdown rendering core interface for molecule.dev.
Provides a standardized API for rendering markdown content into HTML,
with support for GFM and table of contents extraction.
Bond a provider (e.g. @molecule/app-markdown-react-markdown) to supply
the concrete implementation.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { requireProvider, setProvider } from '@molecule/app-markdown'
import { provider } from '@molecule/app-markdown-react-markdown'
setProvider(provider) // once, at startup (bonds.ts)
const result = requireProvider().render('# Hello World', { gfm: true })
console.log(result.html) // sanitized HTML string
Type
core
Installation
npm install @molecule/app-markdown @molecule/app-bond @molecule/app-i18n
API
Interfaces
TocEntry
Table of contents entry extracted from markdown headings.
interface TocEntry {
/** Unique identifier for the heading (slug). */
id: string
/** Text content of the heading. */
text: string
/** Heading level (1-6). */
level: number
}
RenderedMarkdown
Result of rendering markdown content.
interface RenderedMarkdown {
/** The rendered HTML string. */
html: string
/**
* Table of contents extracted from the document's headings, in document
* order. Always present: `[]` when the document has no headings.
*/
toc: TocEntry[]
}
MarkdownOptions
Options for markdown rendering.
interface MarkdownOptions {
/**
* Whether to sanitize the rendered HTML. Defaults to `true`.
*
* It controls two things: raw HTML in the markdown source is escaped to
* inert text, and a link or image whose URL `isSafeMarkdownUrl`
* refuses renders as its link text or alt text instead of an element.
* A markdown link, autolink or image with a `javascript:` or `vbscript:`
* URL is never emitted, even with `sanitize: false`; raw HTML that
* `sanitize: false` passes through is the app's own trusted markup.
*/
sanitize?: boolean
/** Whether to enable GitHub Flavored Markdown extensions. Defaults to `true`. */
gfm?: boolean
/** Whether to convert line breaks to `<br>` elements. Defaults to `false`. */
breaks?: boolean
/**
* Custom component overrides keyed by HTML element name.
*
* @deprecated The renderer returns an HTML string, so an override keeps only
* its static markup — no click handler, state, or context. Use
* `MarkdownOptions.elementAttributes` to add attributes instead. This
* option is removed at the next major.
*/
components?: Record<string, unknown>
/**
* Extra attributes for rendered elements, e.g. `{ a: { class: cm.link() } }`.
*
* Values are escaped. An attribute that is `href`, `src`, `id` or starts with
* `on` is refused with an error, as is a name that is not a valid attribute
* name; see `checkElementAttributes` in `./attributes.js`.
*/
elementAttributes?: Partial<Record<MarkdownElement, Record<string, string>>>
/** Target attribute for rendered links. */
linkTarget?: '_blank' | '_self'
}
MarkdownProvider
Markdown rendering provider interface.
All markdown providers must implement this interface to render markdown strings into HTML output with optional features.
interface MarkdownProvider {
/** Provider name identifier. */
readonly name: string
/**
* Renders a markdown string into HTML.
*
* @param markdown - The markdown source string to render.
* @param options - Optional rendering configuration.
* @returns The rendered HTML and the document's table of contents.
*/
render(markdown: string, options?: MarkdownOptions): RenderedMarkdown
}
Types
MarkdownElement
An element markdown produces, the keys allowed in elementAttributes.
type MarkdownElement = (typeof MARKDOWN_ELEMENTS)[number]
Functions
checkElementAttributes(attributes)
Validates the elementAttributes option before rendering.
Throws an I18nError when an element is not one markdown produces,
when an attribute is one the renderer owns (href, src, id, on…), or
when a name is not a valid attribute name. Valid maps pass unchanged.
function checkElementAttributes(attributes: MarkdownOptions['elementAttributes']): void
attributes— TheelementAttributesoption, if any.
escapeAttributeValue(value)
Escapes a string for use inside a double- or single-quoted HTML attribute.
&, <, >, " and ' are each escaped exactly once.
function escapeAttributeValue(value: string): string
value— The raw attribute value.
Returns: The escaped value.
setProvider(provider)
Registers a markdown provider as the active singleton.
function setProvider(provider: MarkdownProvider): void
provider— The markdown provider implementation to bond.
getProvider()
Retrieves the bonded markdown provider, or null if none is bonded.
function getProvider(): MarkdownProvider | null
Returns: The active markdown provider, or null.
hasProvider()
Checks whether a markdown provider has been bonded.
function hasProvider(): boolean
Returns: true if a markdown provider is available.
requireProvider()
Retrieves the bonded markdown provider, throwing if none is configured.
function requireProvider(): MarkdownProvider
Returns: The active markdown provider.
createHeadingSlugger(slugBase)
Creates a heading slugger for one rendered document.
Call the returned function once per heading, in document order. It applies
marked's rule (lowercase, hyphenated, Unicode letters and digits kept),
returns section for a heading with no letters or digits, and makes ids
unique: a repeat of a becomes a-2, then a-3, and a suffixed slug never
collides with a later heading whose own text slugs to it (a, a, a-2
gives a, a-2, a-2-2). Start a new slugger for each rendered document so
a new document begins again at no suffix.
function createHeadingSlugger(slugBase?: (text: string) => string): (text: string) => string
slugBase— Turns heading text into the base slug instead of the rule above (a provider's ownslugifyoption). The ids it returns get the same-2,-3suffixes, and an empty one becomessection.
Returns: A function that slugs one heading's text into a unique id.
isSafeMarkdownUrl(url)
Decides whether a markdown link or image URL is safe to emit.
Accepts http:, https:, mailto:, tel:, irc:, ircs: and xmpp:
URLs (scheme case-insensitive), relative URLs (a/b, ../a, ?q=1) and
fragments (#x). Every other scheme — javascript:, vbscript:, data:,
file: and unknown ones — is refused, including obfuscated forms a browser
still runs: whitespace and control characters inside the scheme, and mixed
case. Percent-encoded or entity-encoded text is not decoded, so %6Aavascript:
stays a relative path.
function isSafeMarkdownUrl(url: string): boolean
url— The URL exactly as it appears in the markdown link or image.
Returns: true when the URL may be emitted as-is, false when it must not.
isRefusedMarkdownUrl(url, sanitize)
Decides whether a markdown link or image renders as its text (or alt text)
instead of an element: what every provider asks of each href and src.
With sanitize on (the default) that is every URL isSafeMarkdownUrl
refuses. With sanitize off every URL is kept except a javascript: or
vbscript: one, matched the same way (whitespace and control characters
stripped, case-insensitive), which no provider emits for any option.
function isRefusedMarkdownUrl(url: string, sanitize?: boolean): boolean
url— The URL exactly as it appears in the markdown link or image.sanitize— The render'ssanitizeoption;truewhen unset.
Returns: true when the URL must not be emitted.
Constants
MARKDOWN_ELEMENTS
The elements a markdown renderer produces, as a readonly tuple.
const MARKDOWN_ELEMENTS: readonly [
'a',
'img',
'p',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'ul',
'ol',
'li',
'table',
'thead',
'tbody',
'tr',
'th',
'td',
'pre',
'code',
'blockquote',
'hr',
'em',
'strong',
'del',
'input',
'footnotes',
]
Available Providers
| Provider | Package |
|---|---|
| marked | @molecule/app-markdown-marked |
| react-markdown | @molecule/app-markdown-react-markdown |
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1@molecule/app-i18n^1.2.2
Runtime Dependencies
-
@molecule/app-bond -
@molecule/app-i18n -
Wire a bond at startup —
requireProviderthrows untilsetProvider(provider)has been called. -
sanitizedefaults totrueand is the XSS gate.render()returns{ html, toc }; inject only itshtmlstring via your framework's raw-HTML mechanism — that is only safe because it was sanitized. NEVER passsanitize: falsefor user-supplied or model-generated markdown (chat replies, comments, notes); reserve it for fully trusted, app-authored content. -
Options are per-call (
gfm,breaks,linkTarget);result.toccarries the document's headings in order ([]when there are none). Syntax highlighting is a provider concern — e.g. the react-markdown bond wires a rehype highlighter via itsrehypePluginsconfig rather than a generic option. -
Shared rules for providers.
isSafeMarkdownUrl(url)is the one URL allow-list (http/https/mailto/tel/irc/ircs/xmpp, relative URLs and fragments).createHeadingSlugger()is the one heading-id rule (Unicode letters and digits kept,sectionfallback,-2/-3suffixes).MARKDOWN_ELEMENTS,checkElementAttributes()andescapeAttributeValue()back theelementAttributesoption.
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
- Common markdown renders as real HTML wherever the app shows it (chat
reply, comment, note, README preview):
#..######become<h1>..<h6>,**bold**a<strong>,*italic*an<em>,-/1.lists become<ul>/<ol>of<li>,[text](url)an<a>anchor, and a fenced code block a<pre><code>— not the raw*/backticks shown as literal text. - GFM extras render when enabled (
gfm, default on): a pipe table| a | b |becomes a real<table>with header + rows, andan<img>. - The output tracks the source: editing the markdown updates the preview
live — change a heading's text and its
<h#>updates; add a list item and a new<li>appears. No stale or one-shot render. - SECURITY (XSS) — user- or model-supplied markdown is sanitized
(
sanitize, default on, the XSS gate): markdown containing a raw<script>alert(1)</script>, an<img src=x onerror=alert(1)>, or a[click](javascript:alert(1))link must NOT execute and must NOT produce active markup — the script is stripped, theonerroris gone, and the link'shrefis neutralized. Verify in the browser: no alert fires, and DevTools shows no<script>,onerror, orjavascript:in the rendered DOM. Never render untrusted content withsanitize: false. - Malformed markdown degrades gracefully — an unclosed
**, a broken[link](, or a half-open code fence renders as readable text and never throws, blanks the view, or breaks the surrounding page.
Translations
Translation strings are provided by @molecule/app-locales-markdown.