| 1 | /** 只执行本地 Markdown 渲染;stdin/stdout 使用 JSON,正文不经过命令行参数。 */ |
| 2 | import { renderMarkdownDocument, resolveMarkdownStyle } from 'baoyu-md'; |
| 3 | import { Marked } from 'marked'; |
| 4 | import { load } from 'cheerio'; |
| 5 | |
| 6 | let input = ''; |
| 7 | // 按字符解码流,避免长中文稿跨 Buffer 边界时出现替换字符。 |
| 8 | process.stdin.setEncoding('utf8'); |
| 9 | for await (const chunk of process.stdin) input += chunk; |
| 10 | try { |
| 11 | const { content, theme } = JSON.parse(input); |
| 12 | const markdown = new Marked({ gfm: true }); |
| 13 | // 图表扩展会产生 SVG 或远程图片,不作为普通代码块静默降级。 |
| 14 | const tokens = markdown.lexer(content); |
| 15 | markdown.walkTokens(tokens, token => { |
| 16 | if (token.type === 'html' && /<\/?(?:script|style|link|iframe|object|embed)\b/i.test(token.raw)) { |
| 17 | throw Error('Markdown 内嵌 HTML 不支持脚本、外部资源或样式表,请使用内联样式'); |
| 18 | } |
| 19 | if (token.type === 'code' && /^(mermaid|plantuml|infographic)(\s|$)/i.test(token.lang || '')) { |
| 20 | throw Error(`暂不支持 ${token.lang} 图表,请先导出为本地图片`); |
| 21 | } |
| 22 | }); |
| 23 | if (theme === 'plain') { |
| 24 | process.stdout.write(JSON.stringify({ html: markdown.parser(tokens), metadata: {} })); |
| 25 | } else { |
| 26 | // 显式给出全部选项,避免上游读取用户的 EXTEND.md 后改变本项目的默认排版。 |
| 27 | const style = resolveMarkdownStyle({ theme }); |
| 28 | const result = await renderMarkdownDocument(content, { |
| 29 | theme, primaryColor: style.primaryColor, fontFamily: style.fontFamily, |
| 30 | fontSize: style.fontSize, codeTheme: 'github', countStatus: false, |
| 31 | citeStatus: false, keepTitle: true, legend: 'none', |
| 32 | isMacCodeBlock: false, isShowLineNumber: false, themeMode: 'light', |
| 33 | }); |
| 34 | // 上游即使关闭 Mac 代码装饰也保留隐藏 SVG;只移除该装饰,不删除用户正文元素。 |
| 35 | const $ = load(result.html); |
| 36 | $('pre.code__pre > span.mac-sign').remove(); |
| 37 | // 上游用正文里的“1. / • ”和 display:block 模拟列表;平台清理 CSS 后会显示双重序号。 |
| 38 | // 恢复原生列表语义,保留其余主题样式,使本地和过滤样式后的平台都只显示一次标记。 |
| 39 | $('ol,ul').each((_, list) => { |
| 40 | const ordered = list.tagName === 'ol'; |
| 41 | $(list).children('li.listitem').each((index, item) => { |
| 42 | const first = item.children[0]; |
| 43 | if (first?.type !== 'text') return; |
| 44 | const prefix = first.data.match(ordered ? /^(\d+)\. / : /^• /); |
| 45 | if (!prefix) return; |
| 46 | if (ordered && index === 0 && Number(prefix[1]) !== 1) $(list).attr('start', prefix[1]); |
| 47 | first.data = first.data.slice(prefix[0].length); |
| 48 | $(item).attr('style', ($(item).attr('style') || '').replace(/display:\s*block\s*;/, 'display: list-item;')); |
| 49 | }); |
| 50 | }); |
| 51 | process.stdout.write(JSON.stringify({ html: $.html(), metadata: result.meta })); |
| 52 | } |
| 53 | } catch (error) { |
| 54 | process.stderr.write(error.stack || String(error)); |
| 55 | process.exitCode = 1; |
| 56 | } |
| 57 |