来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
272 lines
13 KiB
JavaScript
272 lines
13 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* V3 设计文档 → 自包含 HTML 预览(2026-09-29 建立)
|
||
*
|
||
* 为什么需要:V3 是 **16,000+ 行 / 1.8 MB 的 Markdown**,直接读不现实;
|
||
* 仓库里**没有 markdown 解析器**(无 marked / markdown-it),所以本文件内联一个最小实现。
|
||
*
|
||
* 支持的语法(按 V3 实际用到的):
|
||
* 标题 #~#### | 表格(含 `\|` 转义)| 围栏代码块 | 行内 `code` / **粗体** / *斜体* / ~~删除~~
|
||
* | 有序/无序列表 | 引用 `>` | 分割线 | 链接与裸 URL | `<details>` 原样保留
|
||
*
|
||
* 另加三个「读得动」的功能:
|
||
* · 左侧目录(按 H1/H2 生成,可折叠)+ 顶部搜索框(只显示命中的章节)
|
||
* · 表格横向滚动(V3 有很宽的表)
|
||
* · 打印友好
|
||
*
|
||
* 用法:node tools/doc-preview/md2html.mjs <输入.md> [输出.html]
|
||
*/
|
||
|
||
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||
import { dirname } from 'node:path';
|
||
|
||
const IN = process.argv[2];
|
||
const OUT = process.argv[3];
|
||
if (!IN || !OUT) { console.error('用法:node md2html.mjs <输入.md> <输出.html>'); process.exit(2); }
|
||
|
||
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||
const slug = (s, seen) => {
|
||
let base = s.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'sec';
|
||
let id = base, i = 2;
|
||
while (seen.has(id)) id = base + '-' + i++;
|
||
seen.add(id);
|
||
return id;
|
||
};
|
||
|
||
// ── 行内元素 ────────────────────────────────────────────────────────
|
||
// ⚠️ 两个必须处理的坑(都是实测出来的,否则渲染会坏):
|
||
// ① **行内 `<code>` 会被二次转义**:V3 里有大量"引用写法示例"(如 `](x.md)`、`\`x.sql\``),
|
||
// 它们**本身就是** `<code>…</code>`。旧实现先 esc() 再套 code 标签 ⇒ 变成
|
||
// `<code> </code>x.md<code> </code>` 这种坏输出(实测 14 行)。
|
||
// ② **原生 HTML 标签要保留**:文档里嵌了 `<details>`/`<summary>` 等,esc() 会把它们显示成字面量。
|
||
// ⇒ 统一做法:先把「代码跨距」与「原生标签」抽成占位符,再对其他部分做转义与行内替换,最后还原。
|
||
function inline(s) {
|
||
// ⚠️ 不能用正则一次替换代码跨距:本项目文档里有 `` `a\`b` `` 这种**含转义反引号**的写法
|
||
// (如 `sql` 块),正则会在第一个反引号就闭合 ⇒ 后半行文字跑到代码外、`**` 裸露。
|
||
// ⇒ 改用**状态机**:逐字符走,只有非转义的单个反引号才切换代码态。
|
||
// ① 先保护**行内原生 HTML 标签**:V3 里有 `**…<code>x</code>…**` 这种把标签包在粗体里的写法,
|
||
// 不保护的话标签会被 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, '<strong>$1</strong>');
|
||
x = x.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
|
||
x = x.replace(/~~([^~]+)~~/g, '<del>$1</del>');
|
||
x = x.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, txt, href) => {
|
||
const safe = /^(https?:|\/|#|\.)/.test(href) ? href : '#';
|
||
return `<a href="${safe}" target="_blank" rel="noopener">${txt}</a>`;
|
||
});
|
||
out += x;
|
||
buf = '';
|
||
};
|
||
const flushCode = () => { out += `<code>${esc(buf)}</code>`; 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 标签原样保留(文档里嵌了 <details>/<summary>/<br> 等,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>|<\/strong>$/.test(inner)) return '**' + inner + '**';
|
||
const parts = inner.split(/(<code>[\s\S]*?<\/code>)/g).filter((x) => x !== '');
|
||
return parts.map((seg) => (/^<code>/.test(seg) ? seg : `<strong>${seg}</strong>`)).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(`<pre class="code"${lang ? ` data-lang="${esc(lang)}"` : ''}><code>${esc(buf.join('\n'))}</code></pre>`);
|
||
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('<div class="tw"><table><thead><tr>' + head.map((h) => `<th>${inline(h)}</th>`).join('')
|
||
+ '</tr></thead><tbody>' + rows.map((r) => '<tr>' + head.map((_, k) => `<td>${inline(r[k] ?? '')}</td>`).join('') + '</tr>').join('')
|
||
+ '</tbody></table></div>');
|
||
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(`<h${lv} id="${id}">${inline(text)}</h${lv}>`);
|
||
i++; continue;
|
||
}
|
||
|
||
// 分割线
|
||
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) { out.push('<hr>'); 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('<blockquote>' + render(buf.join('\n')).html + '</blockquote>');
|
||
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) => `<li>${inline(x)}</li>`).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('<p>' + inline(buf.join(' ')) + '</p>');
|
||
}
|
||
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) =>
|
||
`<a class="t${x.lv}" href="#${x.id}" data-k="${esc(plain(x.text).toLowerCase())}">${inline(x.text)}</a>`).join('\n');
|
||
|
||
const page = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>${esc(title)}</title>
|
||
<style>
|
||
:root{--ink:#0f172a;--muted:#64748b;--line:#e2e8f0;--bg:#fff;--accent:#0f766e}
|
||
*{box-sizing:border-box}
|
||
body{margin:0;background:#f6f8fa;color:var(--ink);
|
||
font:15.5px/1.75 -apple-system,BlinkMacSystemFont,"PingFang SC","HarmonyOS Sans","Microsoft YaHei",sans-serif}
|
||
header{background:#fff;border-bottom:1px solid var(--line);padding:14px 20px;position:sticky;top:0;z-index:20;
|
||
display:flex;gap:14px;align-items:center;flex-wrap:wrap}
|
||
header h1{font-size:16px;margin:0;flex:1;min-width:200px}
|
||
header input{border:1px solid var(--line);border-radius:8px;padding:6px 11px;font-size:13.5px;min-width:190px}
|
||
header .cnt{font-size:12.5px;color:var(--muted)}
|
||
.wrap{display:flex;align-items:flex-start;max-width:1400px;margin:0 auto;padding:18px 16px 80px;gap:20px}
|
||
nav{position:sticky;top:62px;width:290px;flex:0 0 290px;max-height:calc(100vh - 90px);overflow:auto;
|
||
background:#fff;border:1px solid var(--line);border-radius:10px;padding:10px}
|
||
nav a{display:block;padding:3px 8px;border-radius:6px;text-decoration:none;color:#334155;font-size:13px;line-height:1.45}
|
||
nav a.t1{font-weight:700;margin-top:7px;color:var(--ink)}
|
||
nav a.t2{padding-left:16px;color:#475569}
|
||
nav a:hover{background:#f1f5f9}
|
||
nav a.hit{background:#fff7ed;color:#9a3412;font-weight:600}
|
||
main{flex:1;min-width:0;background:#fff;border:1px solid var(--line);border-radius:10px;padding:26px 30px}
|
||
main h1{font-size:24px;border-bottom:2px solid var(--accent);padding-bottom:8px;margin:30px 0 14px}
|
||
main h2{font-size:19px;margin:30px 0 12px;padding-left:9px;border-left:4px solid var(--accent)}
|
||
main h3{font-size:16.5px;margin:24px 0 10px;color:#1e293b}
|
||
main h4{font-size:15px;margin:18px 0 8px;color:#334155}
|
||
.tw{overflow-x:auto;margin:12px 0;border:1px solid var(--line);border-radius:8px}
|
||
table{border-collapse:collapse;font-size:13.5px;min-width:100%}
|
||
th,td{border:1px solid var(--line);padding:7px 10px;text-align:left;vertical-align:top}
|
||
th{background:#f1f5f9;font-weight:600;white-space:nowrap}
|
||
tr:nth-child(even) td{background:#fafbfc}
|
||
pre.code{background:#0f172a;color:#e2e8f0;border-radius:9px;padding:14px 16px;overflow-x:auto;font-size:13px;line-height:1.6}
|
||
pre.code code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
||
code{background:#f1f5f9;border-radius:4px;padding:1px 5px;font-size:13px}
|
||
pre code{background:none;padding:0}
|
||
blockquote{margin:12px 0;padding:10px 16px;background:#f8fafc;border-left:4px solid #94a3b8;color:#475569;border-radius:0 8px 8px 0}
|
||
blockquote blockquote{margin:8px 0}
|
||
ul,ol{margin:10px 0;padding-left:26px} li{margin:4px 0}
|
||
a{color:#0f766e}
|
||
hr{border:none;border-top:1px solid var(--line);margin:26px 0}
|
||
details{margin:10px 0;padding:8px 12px;background:#f8fafc;border:1px solid var(--line);border-radius:8px}
|
||
.hidden{display:none!important}
|
||
@media(max-width:900px){.wrap{flex-direction:column;padding:12px 10px 60px}nav{position:static;width:100%;flex:1 1 auto;max-height:260px}main{padding:16px 14px}}
|
||
@media print{header,nav{display:none}main{border:none;padding:0}.tw{overflow:visible}pre.code{background:#f1f5f9;color:#0f172a}}
|
||
</style></head><body>
|
||
<header>
|
||
<h1>${esc(title)}</h1>
|
||
<input id="q" type="search" placeholder="搜索章节(标题)…" autocomplete="off">
|
||
<span class="cnt" id="cnt">${toc.filter((x) => x.lv <= 2).length} 个章节</span>
|
||
</header>
|
||
<div class="wrap">
|
||
<nav id="toc">${tocHtml}</nav>
|
||
<main id="doc">${html}</main>
|
||
</div>
|
||
<script>
|
||
var links=[].slice.call(document.querySelectorAll('#toc a'));
|
||
var q=document.getElementById('q'),cnt=document.getElementById('cnt');
|
||
q.addEventListener('input',function(){
|
||
var k=q.value.trim().toLowerCase(),hit=0;
|
||
links.forEach(function(a){
|
||
var ok=!k||a.dataset.k.indexOf(k)>=0;
|
||
a.classList.toggle('hidden',!ok); a.classList.toggle('hit',!!k&&ok); if(ok)hit++;
|
||
});
|
||
cnt.textContent=k?(hit+' 个匹配章节'):(links.length+' 个章节');
|
||
});
|
||
</script>
|
||
</body></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})`);
|