` 会被二次转义**:V3 里有大量"引用写法示例"(如 `](x.md)`、`\`x.sql\``),
// 它们**本身就是** `…`。旧实现先 esc() 再套 code 标签 ⇒ 变成
// ` x.md ` 这种坏输出(实测 14 行)。
// ② **原生 HTML 标签要保留**:文档里嵌了 ``/`` 等,esc() 会把它们显示成字面量。
// ⇒ 统一做法:先把「代码跨距」与「原生标签」抽成占位符,再对其他部分做转义与行内替换,最后还原。
function inline(s) {
// ⚠️ 不能用正则一次替换代码跨距:本项目文档里有 `` `a\`b` `` 这种**含转义反引号**的写法
// (如 `sql` 块),正则会在第一个反引号就闭合 ⇒ 后半行文字跑到代码外、`**` 裸露。
// ⇒ 改用**状态机**:逐字符走,只有非转义的单个反引号才切换代码态。
// ① 先保护**行内原生 HTML 标签**:V3 里有 `**…x…**` 这种把标签包在粗体里的写法,
// 不保护的话标签会被 esc 成文本,`**` 就匹配不到(实测残留 9 处)。
const stash = [];
s = String(s).replace(/<\/?(?:code|strong|em|del|sub|sup|kbd|mark|br)\s*\/?>/gi,
(m) => { stash.push(m); return `\u0001${stash.length - 1}\u0001`; });
let out = '';
let buf = '';
let inCode = false;
const flushText = () => {
if (!buf) return;
let x = esc(buf);
x = x.replace(/\*\*([^*]+)\*\*/g, '$1');
x = x.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1$2');
x = x.replace(/~~([^~]+)~~/g, '$1');
x = x.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, txt, href) => {
const safe = /^(https?:|\/|#|\.)/.test(href) ? href : '#';
return `${txt}`;
});
out += x;
buf = '';
};
const flushCode = () => { out += `${esc(buf)}`; buf = ''; };
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch === '\\' && s[i + 1] === '`') { buf += '`'; i++; continue; } // 转义反引号 → 字面量
if (ch === '`') { inCode ? flushCode() : flushText(); inCode = !inCode; continue; }
buf += ch;
}
inCode ? flushCode() : flushText(); // 未闭合的跨距按代码收尾,避免丢字符
// 原生 HTML 标签原样保留(文档里嵌了 //
等,esc 后会显示成字面量)
out = out.replace(/<(\/?)(details|summary|br|sub|sup|kbd|mark)(\s*\/?)>/gi, '<$1$2$3>');
// 收尾:**粗体里嵌代码跨距** 的形态(如 `**甲组:`P1`~`P10`**`)会被上面的切分打断 ——
// 切出代码段后,`**` 落在两段纯文本里,正则匹配不到,于是原样显示成 `**`。
// ⇒ 把「`**` + 若干代码/文本 + `**`」重组成正确的 strong/code 结构。
for (let pass = 0; pass < 4; pass++) {
const before = out;
out = out.replace(/\*\*((?:(?!\*\*)[\s\S])*?)\*\*/g, (_, inner) => {
if (!inner || /^|<\/strong>$/.test(inner)) return '**' + inner + '**';
const parts = inner.split(/([\s\S]*?<\/code>)/g).filter((x) => x !== '');
return parts.map((seg) => (/^/.test(seg) ? seg : `${seg}`)).join('');
});
if (out === before) break;
}
// ② 还原被保护的原生标签(反复还原以支持嵌套)
for (let k = 0; k < 3 && out.indexOf('\u0001') >= 0; k++) {
out = out.replace(/\u0001(\d+)\u0001/g, (_, idx) => stash[+idx] ?? '');
}
return out;
}
// ── 表格 ────────────────────────────────────────────────────────────
const isSep = (l) => /^\|[\s\-:|]+\|?\s*$/.test(l.trim());
const cells = (l) => {
// `\|` 是转义管道,不算分隔符(本项目文档里大量出现)
const t = l.trim().replace(/^\||\|$/g, '').replace(/\\\|/g, '\u0000');
return t.split('|').map((c) => c.replace(/\u0000/g, '\\|').trim());
};
function render(md) {
const lines = md.split('\n');
const out = [];
const toc = [];
const seen = new Set();
let i = 0;
while (i < lines.length) {
const line = lines[i];
// 围栏代码块
const fence = line.match(/^\s*```(\w*)/);
if (fence) {
const lang = fence[1] || '';
const buf = [];
i++;
while (i < lines.length && !/^\s*```/.test(lines[i])) buf.push(lines[i++]);
i++;
out.push(`${esc(buf.join('\n'))}
`);
continue;
}
// 表格
if (line.trim().startsWith('|') && i + 1 < lines.length && isSep(lines[i + 1])) {
const head = cells(line);
i += 2;
const rows = [];
while (i < lines.length && lines[i].trim().startsWith('|')) rows.push(cells(lines[i++]));
out.push('' + head.map((h) => `${inline(h)} `).join('')
+ ' ' + rows.map((r) => '' + head.map((_, k) => `${inline(r[k] ?? '')} `).join('') + ' ').join('')
+ '
');
continue;
}
// 标题
const h = line.match(/^(#{1,6})\s+(.*)$/);
if (h) {
const lv = h[1].length;
const text = h[2].replace(/\s*#+\s*$/, '').trim();
const id = slug(text, seen);
if (lv <= 3) toc.push({ lv, id, text });
out.push(`${inline(text)} `);
i++; continue;
}
// 分割线
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) { out.push('
'); i++; continue; }
// 引用(连续多行合并)
if (/^\s*>/.test(line)) {
const buf = [];
while (i < lines.length && /^\s*>/.test(lines[i])) buf.push(lines[i++].replace(/^\s*>\s?/, ''));
out.push('' + render(buf.join('\n')).html + '
');
continue;
}
// 列表
if (/^\s*([-*+]|\d+\.)\s+/.test(line)) {
const ordered = /^\s*\d+\./.test(line);
const items = [];
while (i < lines.length && /^\s*([-*+]|\d+\.)\s+/.test(lines[i])) {
items.push(lines[i++].replace(/^\s*([-*+]|\d+\.)\s+/, ''));
}
const tag = ordered ? 'ol' : 'ul';
out.push(`<${tag}>` + items.map((x) => `${inline(x)} `).join('') + `${tag}>`);
continue;
}
// 空行 / 段落
if (!line.trim()) { i++; continue; }
const buf = [line];
i++;
while (i < lines.length && lines[i].trim() && !/^(\s*```|\s*>|\s*([-*+]|\d+\.)\s|#{1,6}\s|\|)/.test(lines[i])) buf.push(lines[i++]);
out.push('' + inline(buf.join(' ')) + '
');
}
return { html: out.join('\n'), toc };
}
// ── 主流程 ──────────────────────────────────────────────────────────
const md = readFileSync(IN, 'utf8');
const { html, toc } = render(md);
const title = (md.match(/^#\s+(.+)$/m) || [, '文档'])[1].trim();
// 目录标签也要走行内渲染,否则 `**总索引**` 会原样显示(实测 65 处);
// data-k 保持纯文本(去掉标记),供搜索匹配用。
const plain = (s) => s.replace(/[`*~]/g, '');
const tocHtml = toc.filter((x) => x.lv <= 2).map((x) =>
`${inline(x.text)}`).join('\n');
const page = `
${esc(title)}
${esc(title)}
${toc.filter((x) => x.lv <= 2).length} 个章节
${html}
`;
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, page);
console.log(`✅ ${OUT}`);
console.log(` 输入 ${(Buffer.byteLength(md) / 1024).toFixed(0)} KB → 输出 ${(Buffer.byteLength(page) / 1024).toFixed(0)} KB`);
console.log(` 章节:H1/H2/H3 共 ${toc.length}(导航列 H1/H2 = ${toc.filter((x) => x.lv <= 2).length})`);