/* eslint-disable no-undef, no-control-regex */ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' const currentDir = path.dirname(fileURLToPath(import.meta.url)) const escapeHtml = (str = '') => String(str).replace(/&/g, '&').replace(//g, '>') const slugify = (text = '') => String(text).replace(/[^\w\u4e00-\u9fa5-]/g, '') // 行内解析:`code`、**bold**、[text](url),并透传 标签 const inline = (text = '') => { const codes = [] const spans = [] let out = String(text) out = out.replace(/`([^`]+)`/g, (_, c) => { codes.push(`${escapeHtml(c)}`) return `\u0000C${codes.length - 1}\u0000` }) out = out.replace(/<\/?span[^>]*>/g, (m) => { spans.push(m) return `\u0000S${spans.length - 1}\u0000` }) out = escapeHtml(out) out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1') out = out.replace(/\*\*([^*]+)\*\*/g, '$1') out = out.replace(/\u0000C(\d+)\u0000/g, (_, i) => codes[+i]) out = out.replace(/\u0000S(\d+)\u0000/g, (_, i) => spans[+i]) return out } const splitRow = (line = '') => line .trim() .replace(/^\|/, '') .replace(/\|$/, '') .split('|') .map((s) => s.trim()) const isTableSep = (line = '') => /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && line.includes('-') const markdownToHtml = (md = '') => { const lines = String(md).replace(/\r\n/g, '\n').split('\n') const n = lines.length let i = 0 let html = '' let listType = null const closeList = () => { if (listType) { html += `\n` listType = null } } while (i < n) { const line = lines[i] // 代码块 const fence = line.match(/^```(\w*)\s*$/) if (fence) { closeList() const lang = fence[1] i++ const buf = [] while (i < n && !/^```\s*$/.test(lines[i])) { buf.push(lines[i]) i++ } i++ html += `
${escapeHtml(buf.join('\n'))}
\n` continue } // 空行 if (/^\s*$/.test(line)) { closeList() i++ continue } // 分隔线 if (/^-{3,}\s*$/.test(line)) { closeList() html += '
\n' i++ continue } // 标题 const heading = line.match(/^(#{1,6})\s+(.*)$/) if (heading) { closeList() const level = heading[1].length const text = heading[2].trim() html += `${inline(text)}\n` i++ continue } // 引用 if (/^>\s?/.test(line)) { closeList() const buf = [] while (i < n && /^>\s?/.test(lines[i])) { buf.push(lines[i].replace(/^>\s?/, '')) i++ } html += `
${markdownToHtml(buf.join('\n'))}
\n` continue } // 表格 if (/^\s*\|/.test(line) && i + 1 < n && isTableSep(lines[i + 1])) { closeList() const header = splitRow(line) i += 2 const rows = [] while (i < n && /^\s*\|/.test(lines[i])) { rows.push(splitRow(lines[i])) i++ } html += '' + header.map((c) => ``).join('') + '' + rows .map((r) => '' + r.map((c) => ``).join('') + '') .join('') + '
${inline(c)}
${inline(c)}
\n' continue } // 无序列表 if (/^\s*[-*]\s+/.test(line)) { if (listType !== 'ul') { closeList() html += '