Gathering detailed insights and metrics for remark-rehype
Gathering detailed insights and metrics for remark-rehype
Gathering detailed insights and metrics for remark-rehype
Gathering detailed insights and metrics for remark-rehype
plugin that turns markdown into HTML to support rehype
npm install remark-rehype
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
273 Stars
146 Commits
18 Forks
9 Watching
1 Branches
15 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-1.5%
890,416
Compared to previous day
Last week
5.3%
4,746,493
Compared to previous week
Last month
14%
19,598,815
Compared to previous month
Last year
75%
188,862,315
Compared to previous year
remark plugin that turns markdown into HTML to support rehype.
This package is a unified (remark) plugin that switches from remark (the
markdown ecosystem) to rehype (the HTML ecosystem).
It does this by transforming the current markdown (mdast) syntax tree into an
HTML (hast) syntax tree.
remark plugins deal with mdast and rehype plugins deal with hast, so plugins
used after remark-rehype
have to be rehype plugins.
The reason that there are different ecosystems for markdown and HTML is that
turning markdown into HTML is, while frequently needed, not the only purpose of
markdown.
Checking (linting) and formatting markdown are also common use cases for
remark and markdown.
There are several aspects of markdown that do not translate 1-to-1 to HTML.
In some cases markdown contains more information than HTML: for example, there
are several ways to add a link in markdown (as in, autolinks: <https://url>
,
resource links: [label](url)
, and reference links with definitions:
[label][id]
and [id]: url
).
In other cases HTML contains more information than markdown: there are many
tags, which add new meaning (semantics), available in HTML that aren’t available
in markdown.
If there was just one AST, it would be quite hard to perform the tasks that
several remark and rehype plugins currently do.
This project is useful when you want to turn markdown to HTML. It opens up a whole new ecosystem with tons of plugins to do all kinds of things. You can minify HTML, format HTML, make sure it’s safe, highlight code, add metadata, and a lot more.
A different plugin, rehype-raw
, adds support for raw HTML
written inside markdown.
This is a separate plugin because supporting HTML inside markdown is a heavy
task (performance and bundle size) and not always needed.
To use both together, you also have to configure remark-rehype
with
allowDangerousHtml: true
and then use rehype-raw
.
The rehype plugin rehype-remark
does the inverse of this
plugin.
It turns HTML into markdown.
If you don’t use plugins and want to access syntax trees, you can use
mdast-util-to-hast
.
This package is ESM only. In Node.js (version 16+), install with npm:
1npm install remark-rehype
In Deno with esm.sh
:
1import remarkRehype from 'https://esm.sh/remark-rehype@11'
In browsers with esm.sh
:
1<script type="module"> 2 import remarkRehype from 'https://esm.sh/remark-rehype@11?bundle' 3</script>
Say our document example.md
contains:
1# Pluto 2 3**Pluto** (minor-planet designation: **134340 Pluto**) is a 4[dwarf planet](https://en.wikipedia.org/wiki/Dwarf_planet) in the 5[Kuiper belt](https://en.wikipedia.org/wiki/Kuiper_belt).
…and our module example.js
contains:
1import rehypeDocument from 'rehype-document' 2import rehypeFormat from 'rehype-format' 3import rehypeStringify from 'rehype-stringify' 4import remarkParse from 'remark-parse' 5import remarkRehype from 'remark-rehype' 6import {read} from 'to-vfile' 7import {unified} from 'unified' 8import {reporter} from 'vfile-reporter' 9 10const file = await unified() 11 .use(remarkParse) 12 .use(remarkRehype) 13 .use(rehypeDocument) 14 .use(rehypeFormat) 15 .use(rehypeStringify) 16 .process(await read('example.md')) 17 18console.error(reporter(file)) 19console.log(String(file))
…then running node example.js
yields:
1example.md: no issues found
1<!doctype html> 2<html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>example</title> 6 <meta content="width=device-width, initial-scale=1" name="viewport"> 7 </head> 8 <body> 9 <h1>Pluto</h1> 10 <p> 11 <strong>Pluto</strong> (minor-planet designation: <strong>134340 Pluto</strong>) is a 12 <a href="https://en.wikipedia.org/wiki/Dwarf_planet">dwarf planet</a> in the 13 <a href="https://en.wikipedia.org/wiki/Kuiper_belt">Kuiper belt</a>. 14 </p> 15 </body> 16</html>
This package exports the identifiers
defaultFootnoteBackContent
,
defaultFootnoteBackLabel
, and
defaultHandlers
.
The default export is remarkRehype
.
defaultFootnoteBackContent(referenceIndex, rereferenceIndex)
See defaultFootnoteBackContent
from
mdast-util-to-hast
defaultFootnoteBackLabel(referenceIndex, rereferenceIndex)
See defaultFootnoteBackLabel
from
mdast-util-to-hast
defaultHandlers
See defaultHandlers
from
mdast-util-to-hast
unified().use(remarkRehype[, destination][, options])
Turn markdown into HTML.
Transform (Transformer
).
remarkRehype
are rehype plugins (mutate mode)👉 Note: It’s highly unlikely that you want to pass a
processor
.
Raw HTML is available in mdast as html
nodes and can be embedded
in hast as semistandard raw
nodes.
Most plugins ignore raw
nodes but two notable ones don’t:
rehype-stringify
also has an option
allowDangerousHtml
which will output the raw HTML.
This is typically discouraged as noted by the option name but is useful if
you completely trust authorsrehype-raw
can handle the raw embedded HTML strings by
parsing them into standard hast nodes (element
, text
, etc).
This is a heavy task as it needs a full HTML parser, but it is the only way
to support untrusted contentMany options supported here relate to footnotes.
Footnotes are not specified by CommonMark, which we follow by default.
They are supported by GitHub, so footnotes can be enabled in markdown with
remark-gfm
.
The options footnoteBackLabel
and footnoteLabel
define natural language
that explains footnotes, which is hidden for sighted users but shown to
assistive technology.
When your page is not in English, you must define translated values.
Back references use ARIA attributes, but the section label itself uses a
heading that is hidden with an sr-only
class.
To show it to sighted users, define different attributes in
footnoteLabelProperties
.
Footnotes introduces a problem, as it links footnote calls to footnote
definitions on the page through id
attributes generated from user content,
which results in DOM clobbering.
DOM clobbering is this:
1<p id=x></p> 2<script>alert(x) // `x` now refers to the DOM `p#x` element</script>
Elements by their ID are made available by browsers on the window
object,
which is a security risk.
Using a prefix solves this problem.
More information on how to handle clobbering and the prefix is explained in
Example: headings (DOM clobbering) in
rehype-sanitize
.
Unknown nodes are nodes with a type that isn’t in handlers
or passThrough
.
The default behavior for unknown nodes is:
value
(and doesn’t have data.hName
,
data.hProperties
, or data.hChildren
, see later), create a hast text
node<div>
element (which could be changed with
data.hName
), with its children mapped from mdast to hast as wellThis behavior can be changed by passing an unknownHandler
.
Options
Configuration (TypeScript type).
allowDangerousHtml
(boolean
, default: false
)
— whether to persist raw HTML in markdown in the hast treeclobberPrefix
(string
, default: 'user-content-'
)
— prefix to use before the id
property on footnotes to prevent them from
clobberingfootnoteBackContent
(FootnoteBackContentTemplate
from
mdast-util-to-hast
or string
, default:
defaultFootnoteBackContent
from
mdast-util-to-hast
)
— content of the backreference back to referencesfootnoteBackLabel
(FootnoteBackLabelTemplate
from
mdast-util-to-hast
or string
, default:
defaultFootnoteBackLabel
from
mdast-util-to-hast
)
— label to describe the backreference back to referencesfootnoteLabel
(string
, default: 'Footnotes'
)
— label to use for the footnotes section (affects screen readers)footnoteLabelProperties
(Properties
from @types/hast
, default:
{className: ['sr-only']}
)
— properties to use on the footnote label
(note that id: 'footnote-label'
is always added as footnote calls use it
with aria-describedby
to provide an accessible label)footnoteLabelTagName
(string
, default: h2
)
— tag name to use for the footnote labelhandlers
(Handlers
from
mdast-util-to-hast
, optional)
— extra handlers for nodespassThrough
(Array<Nodes['type']>
, optional)
— list of custom mdast node types to pass through (keep) in hast (note that
the node itself is passed, but eventual children are transformed)unknownHandler
(Handler
from
mdast-util-to-hast
, optional)
— handle all unknown nodesIf you completely trust the authors of the input markdown and want to allow them
to write HTML inside markdown, you can pass allowDangerousHtml
to
remark-rehype
and rehype-stringify
:
1import rehypeStringify from 'rehype-stringify' 2import remarkParse from 'remark-parse' 3import remarkRehype from 'remark-rehype' 4import {unified} from 'unified' 5 6const file = await unified() 7 .use(remarkParse) 8 .use(remarkRehype, {allowDangerousHtml: true}) 9 .use(rehypeStringify, {allowDangerousHtml: true}) 10 .process('<a href="/wiki/Dysnomia_(moon)" onclick="alert(1)">Dysnomia</a>') 11 12console.log(String(file))
Yields:
1<p><a href="/wiki/Dysnomia_(moon)" onclick="alert(1)">Dysnomia</a></p>
⚠️ Danger: observe that the XSS attack through
onclick
is present.
If you do not trust the authors of the input markdown, or if you want to make
sure that rehype plugins can see HTML embedded in markdown, use
rehype-raw
.
The following example passes allowDangerousHtml
to remark-rehype
, then
turns the raw embedded HTML into proper HTML nodes with rehype-raw
, and
finally sanitizes the HTML by only allowing safe things with
rehype-sanitize
:
1import rehypeSanitize from 'rehype-sanitize' 2import rehypeStringify from 'rehype-stringify' 3import rehypeRaw from 'rehype-raw' 4import remarkParse from 'remark-parse' 5import remarkRehype from 'remark-rehype' 6import {unified} from 'unified' 7 8const file = await unified() 9 .use(remarkParse) 10 .use(remarkRehype, {allowDangerousHtml: true}) 11 .use(rehypeRaw) 12 .use(rehypeSanitize) 13 .use(rehypeStringify) 14 .process('<a href="/wiki/Dysnomia_(moon)" onclick="alert(1)">Dysnomia</a>') 15 16console.log(String(file))
Running that code yields:
1<p><a href="/wiki/Dysnomia_(moon)">Dysnomia</a></p>
⚠️ Danger: observe that the XSS attack through
onclick
is not present.
If you know that the markdown is authored in a language other than English,
and you’re using remark-gfm
to match how GitHub renders markdown, and you know
that footnotes are (or can?) be used, you should translate the labels associated
with them.
Let’s first set the stage:
1import {unified} from 'unified' 2import remarkParse from 'remark-parse' 3import remarkGfm from 'remark-gfm' 4import remarkRehype from 'remark-rehype' 5import rehypeStringify from 'rehype-stringify' 6 7const doc = ` 8Ceres ist nach der römischen Göttin des Ackerbaus benannt; 9ihr astronomisches Symbol ist daher eine stilisierte Sichel: ⚳.[^nasa-2015] 10 11[^nasa-2015]: JPL/NASA: 12 [*What is a Dwarf Planet?*](https://www.jpl.nasa.gov/infographics/what-is-a-dwarf-planet) 13 In: Jet Propulsion Laboratory. 14 22. April 2015, 15 abgerufen am 19. Januar 2022 (englisch). 16` 17 18const file = await unified() 19 .use(remarkParse) 20 .use(remarkGfm) 21 .use(remarkRehype) 22 .use(rehypeStringify) 23 .process(doc) 24 25console.log(String(file))
Yields:
1<p>Ceres ist nach der römischen Göttin des Ackerbaus benannt; 2ihr astronomisches Symbol ist daher eine stilisierte Sichel: ⚳.<sup><a href="#user-content-fn-nasa-2015" id="user-content-fnref-nasa-2015" data-footnote-ref aria-describedby="footnote-label">1</a></sup></p> 3<section data-footnotes class="footnotes"><h2 class="sr-only" id="footnote-label">Footnotes</h2> 4<ol> 5<li id="user-content-fn-nasa-2015"> 6<p>JPL/NASA: 7<a href="https://www.jpl.nasa.gov/infographics/what-is-a-dwarf-planet"><em>What is a Dwarf Planet?</em></a> 8In: Jet Propulsion Laboratory. 922. April 2015, 10abgerufen am 19. Januar 2022 (englisch). <a href="#user-content-fnref-nasa-2015" data-footnote-backref="" aria-label="Back to reference 1" class="data-footnote-backref">↩</a></p> 11</li> 12</ol> 13</section>
This is a mix of English and German that isn’t very accessible, such as that screen readers can’t handle it nicely. Let’s say our program does know that the markdown is in German. In that case, it’s important to translate and define the labels relating to footnotes so that screen reader users can properly pronounce the page:
1@@ -18,7 +18,16 @@ ihr astronomisches Symbol ist daher eine stilisierte Sichel: ⚳.[^nasa-2015] 2 const file = await unified() 3 .use(remarkParse) 4 .use(remarkGfm) 5- .use(remarkRehype) 6+ .use(remarkRehype, { 7+ footnoteBackLabel(referenceIndex, rereferenceIndex) { 8+ return ( 9+ 'Hochspringen nach: ' + 10+ (referenceIndex + 1) + 11+ (rereferenceIndex > 1 ? '-' + rereferenceIndex : '') 12+ ) 13+ }, 14+ footnoteLabel: 'Fußnoten' 15+ }) 16 .use(rehypeStringify) 17 .process(doc)
Running the code with the above patch applied, yields:
1@@ -1,13 +1,13 @@ 2 <p>Ceres ist nach der römischen Göttin des Ackerbaus benannt; 3 ihr astronomisches Symbol ist daher eine stilisierte Sichel: ⚳.<sup><a href="#user-content-fn-nasa-2015" id="user-content-fnref-nasa-2015" data-footnote-ref aria-describedby="footnote-label">1</a></sup></p> 4-<section data-footnotes class="footnotes"><h2 class="sr-only" id="footnote-label">Footnotes</h2> 5+<section data-footnotes class="footnotes"><h2 class="sr-only" id="footnote-label">Fußnoten</h2> 6 <ol> 7 <li id="user-content-fn-nasa-2015"> 8 <p>JPL/NASA: 9 <a href="https://www.jpl.nasa.gov/infographics/what-is-a-dwarf-planet"><em>What is a Dwarf Planet?</em></a> 10 In: Jet Propulsion Laboratory. 11 22. April 2015, 12-abgerufen am 19. Januar 2022 (englisch). <a href="#user-content-fnref-nasa-2015" data-footnote-backref="" aria-label="Back to reference 1" class="data-footnote-backref">↩</a></p> 13+abgerufen am 19. Januar 2022 (englisch). <a href="#user-content-fnref-nasa-2015" data-footnote-backref="" aria-label="Hochspringen nach: 1" class="data-footnote-backref">↩</a></p> 14 </li> 15 </ol> 16 </section>
See Algorithm in
mdast-util-to-hast
for info on how mdast (markdown) nodes are transformed to hast (HTML).
Assuming you know how to use (semantic) HTML and CSS, then it should generally be straightforward to style the HTML produced by this plugin. With CSS, you can get creative and style the results as you please.
Some semistandard features, notably GFMs tasklists and footnotes, generate HTML
that be unintuitive, as it matches exactly what GitHub produces for their
website.
There is a project, sindresorhus/github-markdown-css
,
that exposes the stylesheet that GitHub uses for rendered markdown, which might
either be inspirational for more complex features, or can be used as-is to
exactly match how GitHub styles rendered markdown.
The following CSS is needed to make footnotes look a bit like GitHub:
1/* Style the footnotes section. */ 2.footnotes { 3 font-size: smaller; 4 color: #8b949e; 5 border-top: 1px solid #30363d; 6} 7 8/* Hide the section label for visual users. */ 9.sr-only { 10 position: absolute; 11 width: 1px; 12 height: 1px; 13 padding: 0; 14 overflow: hidden; 15 clip: rect(0, 0, 0, 0); 16 word-wrap: normal; 17 border: 0; 18} 19 20/* Place `[` and `]` around footnote calls. */ 21[data-footnote-ref]::before { 22 content: '['; 23} 24 25[data-footnote-ref]::after { 26 content: ']'; 27}
This projects turns mdast (markdown) into hast (HTML).
It extends mdast by supporting data
fields on mdast nodes to specify how they
should be transformed.
See Fields on nodes in
mdast-util-to-hast
for info on how these fields work.
It extends hast by using a semistandard raw nodes for raw HTML. See the HTML note above for more info.
This package is fully typed with TypeScript.
It exports the types
Options
.
The types of mdast-util-to-hast
can be referenced to register data fields
with @types/mdast
and Raw
nodes with @types/hast
.
1/** 2 * @import {Root as HastRoot} from 'hast' 3 * @import {Root as MdastRoot} from 'mdast' 4 * @import {} from 'mdast-util-to-hast' 5 */ 6 7import {visit} from 'unist-util-visit' 8 9const mdastNode = /** @type {MdastRoot} */ ({/* … */}) 10console.log(mdastNode.data?.hName) // Typed as `string | undefined`. 11 12const hastNode = /** @type {HastRoot} */ ({/* … */}) 13 14visit(hastNode, function (node) { 15 // `node` can now be `raw`. 16})
Projects maintained by the unified collective are compatible with maintained versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, remark-rehype@^11
,
compatible with Node.js 16.
This plugin works with unified
version 6+, remark-parse
version 3+ (used in
remark
version 7), and rehype-stringify
version 3+ (used in rehype
version 5).
Use of remark-rehype
can open you up to a
cross-site scripting (XSS) attack.
Embedded hast properties (hName
, hProperties
, hChildren
) in
mdast, custom handlers, and the allowDangerousHtml
option all provide
openings.
Use rehype-sanitize
to make the tree safe.
rehype-raw
— rehype plugin to parse the tree again and support raw
nodesrehype-sanitize
— rehype plugin to sanitize HTMLrehype-remark
— rehype plugin to turn HTML into markdownrehype-retext
— rehype plugin to support retextremark-retext
— remark plugin to support retextSee contributing.md
in remarkjs/.github
for ways
to get started.
See support.md
for ways to get help.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
8 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 8
Reason
Found 3/30 approved changesets -- score normalized to 1
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More