/**
* HTML 转 Markdown 转换器(增强版)
* 适用于微信小程序环境
* 支持处理大文本和复杂 HTML 结构
*/
/**
* HTML 节点类型
*/
interface HtmlNode {
type: 'element' | 'text';
tag?: string;
content?: string;
children?: HtmlNode[];
attributes?: Map;
}
/**
* 将 HTML 字符串转换为 Markdown 字符串(增强版)
* @param html HTML 字符串
* @param options 转换选项
* @returns Markdown 字符串
*/
export function htmlToMarkdown(html: string, options?: {
preserveNewlines?: boolean;
codeBlockLanguage?: string;
maxNestingDepth?: number;
}): string {
if (!html) return '';
const opts = {
preserveNewlines: options?.preserveNewlines ?? false,
codeBlockLanguage: options?.codeBlockLanguage ?? '',
maxNestingDepth: options?.maxNestingDepth ?? 20
};
// 预处理:移除注释和脚本
let processed = preprocess(html);
// 使用流式处理来处理大文本
let markdown = processHtmlStream(processed, opts);
// 后处理:清理和格式化
markdown = postprocess(markdown);
return markdown;
}
/**
* 预处理 HTML
*/
function preprocess(html: string): string {
let result = html;
// 移除注释
result = result.replace(//g, '');
// 移除 script 标签
result = result.replace(/