Files
Thing/src/modules/notes/editor/markdownExport.test.ts
T

297 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* markdownExport 单测(Node 内置 test runner)。
*
* # 为什么用 `renderMarkdownFragmentRaw`
*
* DOMPurify 需要 `window`/`document`:Node 里 `isSupported === false` 且对象上**根本
* 没有** `sanitize`,所以「消毒后的片段」在纯 Node 下无法断言(本文件里如实
* `t.skip()`,不装 jsdom、更不为跑通测试降低消毒强度)。
* 但「fence 语言识别、任务列表、表格、链接、图片」这些**渲染**行为是纯字符串逻辑,
* 必须能脱离浏览器回归,所以走模块里明确标注为「仅供单测」的未消毒入口。
*
* # 为什么两个方向都断言
*
* 一边断言「未消毒的片段里确实带着 `onerror=` / `<script>`」(证明消毒不是可选项),
* 一边断言「无 DOM 时消毒入口失败关闭,返回空串而不是原文」(证明降级方向是安全的那
* 一侧)。有 DOM 的环境(浏览器/未来的 DOM shim)会自动改跑真正的消毒断言。
*/
import { test } from 'node:test'
import assert from 'node:assert/strict'
import DOMPurify from 'dompurify'
import {
markdownToPlainText,
renderMarkdownFragment,
renderMarkdownFragmentRaw,
renderNoteHtml,
stripFrontMatter
} from './markdownExport.ts'
/** 当前环境能不能真消毒(浏览器/happy-dom 之类为 true,纯 Node 为 false) */
const domAvailable = DOMPurify.isSupported && typeof DOMPurify.sanitize === 'function'
// ===== front-matter =====
test('stripFrontMatter:剥掉闭合的 front-matter', () => {
const src = ['---', 'title: 周报', 'tags:', ' - 工作', '---', '# 正文', '', '内容'].join('\n')
assert.equal(stripFrontMatter(src), '# 正文\n\n内容')
})
test('stripFrontMatter:闭合行是末行(末尾没有换行)也能处理', () => {
assert.equal(stripFrontMatter('---\ntitle: x\n---'), '')
assert.equal(stripFrontMatter('---\ntitle: x\n---\n正文'), '正文')
})
test('stripFrontMatter:未闭合时整篇当正文,一个字符都不吃', () => {
const unclosed = '---\ntitle: x\n# 正文\n--- 少了点什么'
assert.equal(stripFrontMatter(unclosed), unclosed)
// 只有一行 `---` 时同样不认
assert.equal(stripFrontMatter('---'), '---')
})
test('stripFrontMatter:CRLF 与 UTF-8 BOM', () => {
assert.equal(stripFrontMatter('---\r\ntitle: x\r\n---\r\n正文\r\n'), '正文\r\n')
assert.equal(stripFrontMatter('\uFEFF---\r\ntitle: x\r\n---\r\n正文'), '正文')
// 没有 front-matter 时也要剥 BOM:留着它 markdown-it 会渲染成不可见怪字符
assert.equal(stripFrontMatter('\uFEFF# 正文'), '# 正文')
})
test('stripFrontMatter:第一行不是整行 --- 时不认', () => {
assert.equal(stripFrontMatter('--- x\na: 1\n---\n正文'), '--- x\na: 1\n---\n正文')
assert.equal(stripFrontMatter(' ---\na: 1\n---\n正文'), ' ---\na: 1\n---\n正文')
})
test('stripFrontMatter:只剥第一段,正文里的 --- 原样保留', () => {
assert.equal(stripFrontMatter('---\na: 1\n---\n正文\n---\n更多'), '正文\n---\n更多')
})
// ===== 纯文本摘要 =====
test('markdownToPlainText:去掉标记、保留文字、折叠空白', () => {
const src = [
'---',
'title: 元数据不该出现',
'---',
'# 标题一',
'',
'这是 **粗体**、*斜体*、`行内代码`,还有 [链接文字](https://example.com/a) 和 ![图片说明](images/x.png)。',
'',
'> 引用行',
'',
'- [ ] 待办',
'- 普通项',
'',
'```js',
'const a = 1',
'```',
'',
'<p>html 段落</p>'
].join('\n')
const text = markdownToPlainText(src)
assert.ok(!text.includes('元数据不该出现'), 'front-matter 必须被剥掉')
for (const kept of ['标题一', '粗体', '斜体', '行内代码', '链接文字', '图片说明', '引用行', '待办', '普通项', 'const a = 1', 'html 段落']) {
assert.ok(text.includes(kept), `摘要应保留「${kept}」:${text}`)
}
for (const dropped of ['**', '`', '](', 'https://example.com', 'images/x.png', '<p>', '#', '>']) {
assert.ok(!text.includes(dropped), `摘要不该残留「${dropped}」:${text}`)
}
assert.ok(!/ {2}/.test(text), `空白应折叠成单空格:${text}`)
})
test('markdownToPlainText:默认 120 字符截断并加省略号', () => {
const text = markdownToPlainText(`# ${'x'.repeat(200)}`)
assert.equal(text.length, 121)
assert.ok(text.endsWith('…'))
assert.equal(text, `${'x'.repeat(120)}…`)
})
test('markdownToPlainText:按码点截断,emoji 不会被劈成半个', () => {
const text = markdownToPlainText('😀'.repeat(10), 3)
assert.equal(text, '😀😀😀…')
assert.equal(Array.from(text).length, 4)
})
test('markdownToPlainText:maxChars 为 0 时返回空串', () => {
assert.equal(markdownToPlainText('随便什么内容', 0), '')
})
test('markdownToPlainText:#tag 不算标题,分隔线要清干净', () => {
// 与 outline.ts 同一套判断:`#` 后必须有空白才算 ATX 标题
assert.equal(markdownToPlainText('#hashtag 不是标题'), '#hashtag 不是标题')
assert.equal(markdownToPlainText('* * *\n\n正文'), '正文')
assert.equal(markdownToPlainText('***'), '')
assert.equal(markdownToPlainText('标题\n==='), '标题')
// 表格:对齐分隔行是纯标记,要丢;单元格文字留着
const table = markdownToPlainText('| 模块 | 状态 |\n| --- | --- |\n| 导出 | 完成 |')
assert.ok(!table.includes('---'), table)
assert.ok(table.includes('模块'), table)
assert.ok(table.includes('导出'), table)
})
// ===== 渲染(未消毒片段)=====
test('围栏代码块:info string 命中注册表时按该语言高亮', () => {
const html = renderMarkdownFragmentRaw('```ts\nconst n: number = 1\n```')
assert.match(html, /<pre class="hljs">/)
assert.match(html, /<code class="hljs language-ts">/)
assert.match(html, /hljs-keyword/)
})
test('围栏代码块:`.js` 这类写法也能归一成语言名', () => {
const html = renderMarkdownFragmentRaw('```.js\nlet a = 1\n```')
assert.match(html, /<code class="hljs language-js">/)
})
test('围栏代码块:未注册的语言不抛错,猜不准的散文保持纯文本', () => {
const html = renderMarkdownFragmentRaw('```notalang\nplain text here\n```')
assert.match(html, /<pre class="hljs">/)
assert.match(html, /plain text here/)
// 相关度低于下限时不许上色:给散文瞎上色比没颜色更糟
assert.match(html, /<code class="hljs">/)
assert.doesNotMatch(html, /language-notalang/)
})
test('围栏代码块:语言名拼错时在候选集里自动识别', () => {
const html = renderMarkdownFragmentRaw('```typescrpt\ndef f(x):\n return x + 1\n```')
assert.match(html, /<code class="hljs language-python">/)
assert.match(html, /hljs-keyword/)
})
test('围栏代码块:内容被转义,原始 HTML 不会漏出去', () => {
const html = renderMarkdownFragmentRaw('```\n<b>&"x\n```')
assert.match(html, /&lt;b&gt;&amp;&quot;x/)
assert.doesNotMatch(html, /<b>/)
})
test('表格渲染', () => {
const html = renderMarkdownFragmentRaw('| 列 A | 列 B |\n| --- | --- |\n| 1 | 2 |')
assert.match(html, /<table>/)
assert.match(html, /<th>列 A<\/th>/)
assert.match(html, /<td>2<\/td>/)
})
test('任务列表渲染成 disabled 复选框', () => {
const html = renderMarkdownFragmentRaw('- [ ] 未完成\n- [x] 已完成\n- 普通项')
assert.match(html, /<input class="task-list-item-checkbox" type="checkbox" disabled>/)
assert.match(html, /type="checkbox" disabled checked>/)
assert.match(html, /class="task-list-item"/)
assert.match(html, /普通项/)
})
test('链接渲染与裸 URL 自动识别', () => {
const html = renderMarkdownFragmentRaw('[Thing](https://example.com/a) 与 https://example.org/b')
assert.match(html, /<a href="https:\/\/example\.com\/a">Thing<\/a>/)
assert.match(html, /href="https:\/\/example\.org\/b"/)
})
test('图片渲染(保留相对路径与 alt)', () => {
const html = renderMarkdownFragmentRaw('![示意图](images/demo.png)')
assert.match(html, /<img src="images\/demo\.png" alt="示意图">/)
})
test('未消毒片段确实会带出 XSS 载荷(说明消毒不是可选项)', () => {
const raw = renderMarkdownFragmentRaw('<img src=x onerror=alert(1)>\n\n<script>alert(1)</script>')
assert.match(raw, /onerror=/)
assert.match(raw, /<script>/)
})
// ===== 消毒 =====
test('无 DOM 环境:消毒入口失败关闭,返回空串而不是原文', t => {
if (domAvailable) {
t.skip('本环境有 DOM,消毒可用,该降级分支不适用')
return
}
assert.equal(renderMarkdownFragment('<script>alert(1)</script>'), '')
assert.equal(renderMarkdownFragment('# 正常标题'), '')
})
test('XSS:<script>、onerror、javascript: 被剥掉,该留的留着', t => {
if (!domAvailable) {
t.skip('Node 无 window/document:DOMPurify.isSupported=false,无 sanitize 可调')
return
}
const dirty = [
'<script>alert(1)</script>',
'',
'<img src=x onerror=alert(1)>',
'',
'[点我](javascript:alert(1))',
'',
'<span style="position:fixed;top:0">覆盖界面</span>',
'',
'<img src="a.png" srcset="https://evil.example/x.png 1x">',
'',
'<style>body{display:none}</style>'
].join('\n')
const html = renderMarkdownFragment(dirty)
assert.ok(!html.includes('onerror='), html)
assert.ok(!html.includes('<script'), html)
assert.ok(!html.includes('javascript:'), html)
assert.ok(!html.includes('style='), html)
assert.ok(!html.includes('srcset='), html)
assert.ok(!html.includes('<style'), html)
const kept = renderMarkdownFragment(
'```ts\nconst a = 1\n```\n\n| a |\n| --- |\n| 1 |\n\n- [x] 完成\n\n![图](a.png)\n\n<a href="https://example.com" target="_blank">外链</a>'
)
assert.match(kept, /class="hljs"/)
assert.match(kept, /<table>/)
assert.match(kept, /type="checkbox" disabled checked/)
assert.match(kept, /<img src="a\.png"/)
assert.match(kept, /target="_blank"/)
})
// ===== 导出文档 =====
test('renderNoteHtml:结构完整、<title> 与页首标题都转义', () => {
const html = renderNoteHtml({
title: 'A & B <C>',
fileName: 'a.md',
markdown: '# 正文',
exportedAt: new Date(2026, 0, 2, 3, 4)
})
assert.ok(html.startsWith('<!doctype html>'))
assert.ok(html.includes('<html lang="zh-CN">'))
assert.ok(html.includes('<meta charset="utf-8">'))
assert.ok(html.includes('name="viewport"'))
assert.ok(html.includes('<title>A &amp; B &lt;C&gt;</title>'))
assert.ok(html.includes('<h1 class="note-title">A &amp; B &lt;C&gt;</h1>'))
assert.ok(html.includes('导出自 Thing · 2026-01-02 03:04'))
assert.ok(html.includes('@media print'))
})
test('renderNoteHtml:内联样式自带排版与高亮配色,不依赖外部资源', () => {
const html = renderNoteHtml({ title: '排版', fileName: 'style.md', markdown: '正文' })
assert.ok(html.includes('780px'))
assert.ok(html.includes('line-height: 1.7'))
assert.ok(html.includes('overflow-x: auto'))
assert.ok(html.includes('background: #f6f8fa'))
assert.ok(html.includes('border-collapse: collapse'))
assert.ok(html.includes('border-left: 4px solid'))
assert.ok(html.includes('img { max-width: 100%'))
assert.ok(html.includes('.note-body mark'))
for (const token of ['hljs-keyword', 'hljs-string', 'hljs-comment', 'hljs-number', 'hljs-title', 'hljs-attr']) {
assert.ok(html.includes(`.${token}`), `缺少高亮配色 ${token}`)
}
})
test('renderNoteHtml:样式与外壳里没有任何外部地址', () => {
const html = renderNoteHtml({
title: '离线笔记',
fileName: 'offline.md',
markdown: '# 标题\n\n纯文本,没有任何链接。'
})
const style = /<style>([\s\S]*?)<\/style>/.exec(html)?.[1] ?? ''
assert.ok(style.length > 0)
assert.ok(!/https?:\/\//.test(style), '内联样式里不能出现外链')
assert.ok(!/https?:\/\//.test(html), '正文没有链接时整份文档都不该有外链')
assert.ok(!/<link|<script|@import/i.test(html))
})
test('renderNoteHtml:标题为空串时用 fileName 兜底,时间缺省用当前时间', () => {
const html = renderNoteHtml({ title: ' ', fileName: '周报.md', markdown: '正文' })
assert.ok(html.includes('<title>周报.md</title>'))
assert.ok(html.includes('<h1 class="note-title">周报.md</h1>'))
assert.match(html, /导出自 Thing · \d{4}-\d{2}-\d{2} \d{2}:\d{2}/)
})