@godxjp/markdown

中文文档
33.30.5发布于 2026/11/14Apache-2.0TypeScriptES Module近 30 天下载 1.2万

The one Markdown renderer for GoDX apps: GFM + heading anchors, KaTeX math, highlighted code, one sanitiser schema, a shared fixture corpus, and Mermaid drawn only after its SVG passes a fail-closed gate.

原始使用文档
文档目录10 节
  1. What it renders
  2. Safety
  3. Host extension points
  4. Directive blocks
  5. Grammar v1 and the codec ( @godxjp/markdown/codec )
  6. Syntax
  7. Codec
  8. Loading KaTeX and highlight.js on demand ( @godxjp/markdown…
  9. Stored versions
  10. Fixtures

@godxjp/markdown

The one Markdown renderer for GoDX apps (godx-task, godx-content, and later mailer, chatter and approval). One pipeline, one sanitiser schema, one fixture corpus — so a security fix happens once.

pnpm add @godxjp/markdown        # + `mermaid` (optional) to draw ```mermaid fences
import "@godxjp/markdown/katex.css"; // once, in the app entry: KaTeX's stylesheet + fonts
import { Prose } from "@godxjp/ui/data-display";
import { Markdown } from "@godxjp/markdown";

<Prose>
  <Markdown>{page.body}</Markdown>
</Prose>;

What it renders

GFM — tables, task lists (read-only), fenced code with language-* classes, autolinks, footnotes, strikethrough — and an id on every heading (GitHub slugs, de-duplicated). The output is the same as react-markdown + remark-gfm + rehype-sanitize, which is what the apps rendered before.

Math — $…$ and $$…$$ inline, a $$ block or a ```math fence for display — is drawn by KaTeX at parse time (no DOM: the same HTML in a browser, on a server, in a Worker), as HTML plus MathML, so a screen reader reads the formula. The content is literal TeX: \, keeps its backslash. A single $ follows Pandoc's rule, so prices stay prose: $5 and $10 and $5-$10 are text (the opening $ is followed by a non-space, the closing one preceded by a non-space and not by \, and not followed by a digit). Write \$ for a literal dollar anywhere. A formula that does not parse shows its source in .katex-error.

The KaTeX stylesheet is the host's to load, once: import "@godxjp/markdown/katex.css". It @imports katex/dist/katex.min.css from the KaTeX this package depends on (so the CSS always matches the renderer; any bundler that resolves CSS @import from node_modules — Vite, webpack, esbuild — copies the fonts) and lets a wide display formula scroll instead of widening the page. Without it, formulas render as unstyled text plus MathML.

Syntax colour — a fence in a known language is tokenised at parse time and every token is a <span data-code-token="…">, with the kit's names (comment, keyword, string, string-expression, function, constant, parameter, punctuation, link, inserted, deleted, changed). Prose colours them from the --code-block-token-* knobs, in light and dark — this package ships no code palette. Languages: bash, shell, css, diff, dockerfile, go, ini/toml, java, javascript, json, markdown, php, python, rust, sql, typescript, xml/html, yaml (with their aliases: ts, js, jsx, tsx, sh, zsh, yml, html, py, rs, …). Any other language, a fence without one, ```mermaid and ```math stay plain text.

Every table renders inside a scroll box (.ui-prose-table-scroll, styled by Prose), keyboard- focusable only while it overflows, so a wide table scrolls instead of widening the page.

Safety

  • No raw HTML. HTML in the source is dropped, never parsed into elements.
  • One schema (markdownSchema): links allow http, https, mailto and relative URLs; images allow http, https and relative URLs. javascript:, data: and every other scheme are removed — including a scheme split by tabs or newlines. SVG is never inlined from a URL.
  • KaTeX runs with trust: false, strict: "error" and maxSize: 10, before the sanitiser, and the schema allows exactly what KaTeX emits: MathML elements, KaTeX's own class names, geometry-only inline styles (lengths, colours, keywords — no url(), no parentheses at all) and svg / path / line for radicals and stretchy arrows (no href, no <image>). \href, \url, \includegraphics, \htmlClass, \htmlId, \htmlStyle and \htmlData render as their own source text. A non-standard construct still draws (rehype-katex retries leniently, trust is never relaxed); a user-sized box (\rule{9999em}{9999em}) is capped at 10em.
  • Code tokens are spans whose only attribute is data-code-token, pinned to the twelve names; a body cannot mint one (raw HTML is dropped).
  • Mermaid is a picture only after its SVG passes checkMermaidSvg: no <script>, <foreignObject>, <a>, <image>, event handlers, non-fragment href, url() that leaves the document, or @import. A diagram that fails, or a host without mermaid, shows the code.

Host extension points

propuse
remarkPluginsHost markers (callouts, embeds). Their output is still sanitised.
schema{ tagNames, attributes } the markers need. A rule for an attribute the base already constrains is merged into it (code className + math-inline). Cannot widen the URL policy.
resolveUrl(url, key)Map a host scheme (asset:…) to a real URL before the sanitiser judges it.
headingId({ depth, text, index })Use server-assigned anchors instead of slugs.
componentsElement overrides. Mermaid fences are drawn before a host pre is asked, so a host code renderer keeps Mermaid.
rehypePluginsRun after the sanitiser — presentation only.
mermaid={false}Keep ```mermaid fences as code (or hand them to the host pre).
highlight={false}Leave fenced code as plain text — a host pre that runs its own highlighter. A host pre otherwise receives the tokenised <code>.
allowedElements / unwrapDisallowedNarrow a body (an activity feed: strong, em, del, code). Only removes.
shortCellLengthA table cell holding one short token (no whitespace, ≤ 24 characters by default) gets data-short; Prose keeps it on one line. false turns it off.
directivesHost renderers for container directives the kit does not model, by name — see "Directive blocks".

Directive blocks

A container directive the kit does not model — :::poll[…]{…}, a ::::form holding polls — renders its content in a div.ui-prose-directive (the label as a paragraph). A host gives it meaning by registering a renderer for its name:

<Markdown
  directives={{
    // { name, label, attributes, source, body, children }: label / source / body as written
    // (free of a containing callout's `> `), children = the rendered body without the label.
    poll: (block) => {
      const poll = parsePoll(block.source); // the host's own grammar and validation
      return poll ? <PollCard poll={poll} /> : undefined; // undefined: render it as before
    },
    form: (block) => <SurveyForm title={block.label}>{block.children}</SurveyForm>,
  }}
>
  {page.body}
</Markdown>

The kit validates nothing inside a directive; toggle, columns and column are its own and cannot be registered. The block's parts come from the same reader as the codec's (readDirective(source) in @godxjp/markdown/codec returns { name, label, attributes, source, body }), so the editor and the page agree on what a block says.

Images: wrap the body in <Prose imagePreview> and every body image opens the kit preview, paging through the others — no img override needed. Images in table cells keep min(natural width, 20rem), so a narrow table scrolls instead of squashing them.

Grammar v1 and the codec (@godxjp/markdown/codec)

The renderer (RENDERER_VERSION 6), the codec and @godxjp/block-editor read one syntax, from one set of parsers, so a body means the same thing in the editor, on a server and on the page.

Syntax

  • GFM — tables, task lists, strikethrough, autolinks, footnotes.

  • CJK-friendly emphasis — の**「強調」**です is strong. CommonMark's flanking rules leave literal asterisks next to 、。「」(); the codec, the renderer and the editor all use the CJK-friendly extension.

  • Callout — a GitHub alert: > [!NOTE], [!TIP], [!IMPORTANT], [!WARNING], [!CAUTION] (kind case-insensitive on input, written uppercase), optional plain-text title on the same line (> [!WARNING] Title); the rest of the quote is the body. A fold marker ([!NOTE]- / +) or an unknown kind is NOT a callout: it stays an ordinary blockquote, marker verbatim.

  • Toggle — :::toggle[Summary *inline*] … :::. Body is any blocks; toggles nest, and sit inside callouts and columns. Open state is not stored.

  • Columns — 2–4 columns, each with an optional width (integer percent 1–100; columns without one share the remainder equally). Columns never nest.

    ::::columns
    :::column{width=40}
    Left
    :::
    
    :::column
    Right
    :::
    ::::
    

    Only container directives exist: the fence of a directive is one colon longer than the deepest directive inside it, so the innermost fence is always :::. There are no text (:name) or leaf (::name) directives — 10:30 is prose.

  • Wikilinks and embeds, verbatim — [[target]], [[target#heading]], [[target|label]], ![[embed]] (a block when alone on its line; the inner text is kept verbatim — ![[B#見出し]], ![[img.png|300]]). Marks around them survive (**[[x]]**). Inside a table cell write [[x\|label]].

  • Math — $x$, $$x$$, a $$ block, a ```math fence (Pandoc's single-dollar rule, above). The codec keeps math verbatim as a raw inline / raw block (a fence is an ordinary codeBlock{language: "math"}), so the block editor needs no math node. Because $ is now special, a literal $x$ in text is written \$x$; a lone $ (a price) is never escaped.

  • asset: images — ![alt](asset:id) round-trips as written (the renderer resolves it through resolveUrl).

  • Directive blocks — any other container directive (:::poll[label]{id=x anonymous} … :::, nesting by fence length) is one directive{name, source} node holding its canonical source, so normalize is idempotent on it and the editor keeps it as one block. Attribute values with a character outside [\w.-] are written quoted (closes="2026-11-10T09:00"); {#x} / {.x} are written id=x / class=x.

  • Raw blocks — anything else the document does not model (raw HTML, footnote definitions, link reference definitions, a malformed toggle or column row, a fence with a meta string) is kept as Markdown that parses back to the same thing. Mermaid is an ordinary ```mermaid fence.

Codec

import { CODEC_ID, normalize, parse, serialize } from "@godxjp/markdown/codec";

CODEC_ID; // "kit-md@2" — bumped whenever serialize would write a body differently (@2: math)
const doc = parse(markdown); // plain JSON, ProseMirror/Tiptap shape
const md = serialize(doc); // canonical Markdown
normalize(markdown) === serialize(parse(markdown)); // what the editor saves
normalize(normalize(x)) === normalize(x); // idempotent, for every fixture

Pure: no React, no DOM, no editor — it runs on a server and in a Cloudflare Worker.

Canonical form (what serialize writes): ATX headings; - bullets; 1. ordered lists; *em*; **strong**; ``` fences (an indented code block becomes fenced); --- rules; - [ ] / - [x] todos; GFM tables with padded cells and an alignment row; a callout's body after a > blank line; one blank line between blocks; LF; a trailing newline; an empty document is "".

Loading KaTeX and highlight.js on demand (@godxjp/markdown/lazy)

KaTeX with its stylesheet and fonts, and highlight.js, are most of this package's weight. The default entry bundles them so the first render is final everywhere. A client-rendered app imports the same component from /lazy instead:

import { Markdown } from "@godxjp/markdown/lazy"; // and drop the global katex.css import

Each engine is then a separate chunk, fetched the first time a rendered body needs it (math, or a fence with a language) — KaTeX's chunk brings katex.css with it — and the body re-renders once it arrives. Until then math shows its TeX source as code and fences are plain, the same as highlight={false}. Measured with Vite on a host that imports only Markdown: the entry goes from 560 KB JS (173 KB gzip) + 23.5 KB CSS to 220 KB JS (70 KB gzip) and no CSS; KaTeX is a 262 KB (78 KB gzip) chunk + the CSS, highlight.js an 81 KB (26 KB gzip) chunk.

Why the default stays eager. A server render or a Worker is synchronous and cannot wait for an import(), and the output must not depend on what happened to be loaded. With /lazy, a server (or a client hydrating server HTML) awaits preloadMarkdownRuntime(body) before rendering, so its HTML matches the eager entry's byte for byte; RENDERER_VERSION describes that finished output from both entries.

Stored versions

Record MARKDOWN_FORMAT ("md") and RENDERER_VERSION on every saved version. RENDERER_VERSION changes when the same input renders differently.

Fixtures

MARKDOWN_FIXTURES is the shared corpus: input Markdown → the exact sanitised HTML, with forbidden substrings for the hostile ones. A server or export path conforms to this list.

版本与发布记录

@godxjp/markdown 共发布 144 个版本,首次发布于 2026/10/02;过去 12 个月发布了 144 个版本。

版本发布日期距今
33.30.5latest2026/11/143 天前
33.30.42026/11/133 天前
33.30.32026/11/133 天前
33.28.62026/11/106 天前
33.28.42026/11/106 天前
33.28.32026/11/106 天前

关于 @godxjp/markdown 的常见问题

@godxjp/markdown 是什么?

The one Markdown renderer for GoDX apps: GFM + heading anchors, KaTeX math, highlighted code, one sanitiser schema, a shared fixture corpus, and Mermaid drawn only after its SVG passes a fail-closed gate.

如何安装 @godxjp/markdown?

在项目目录运行 npm install @godxjp/markdown,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@godxjp/markdown 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@godxjp/markdown 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@godxjp/markdown 可以商用吗?

@godxjp/markdown 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@godxjp/markdown 的下载量有多少?

根据 npm 官方下载统计,@godxjp/markdown 在 2026/10/17 – 2026/11/15 这 30 天内被下载 12,035 次,日均约 401 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@godxjp/markdown 还在维护吗?

最新版本 33.30.5 发布于 2026/11/14(3 天前);至今共发布 144 个版本,其中过去 12 个月发布了 144 个;首次发布于 2026/10/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。