Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API. Co-authored-by: Cursor <cursoragent@cursor.com>
78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
/**
|
||
* 电子书 Markdown 解析 - 共享模块
|
||
*/
|
||
import { marked } from "marked";
|
||
|
||
export interface EbookChunk {
|
||
html: string;
|
||
estimatedHeight: number;
|
||
}
|
||
|
||
export interface EbookData {
|
||
chunks: EbookChunk[];
|
||
headers: string[];
|
||
}
|
||
|
||
export function parseEbookMarkdown(source: string): EbookData {
|
||
const html = marked.parse(source, { breaks: true, gfm: true }) as string;
|
||
let lazyHtml = html.replace(/<img /g, '<img loading="lazy" decoding="async" ');
|
||
|
||
const used = new Set<string>();
|
||
lazyHtml = lazyHtml.replace(
|
||
/<(h[12])(\s[^>]*)?>([\s\S]*?)<\/\1>/gi,
|
||
(_m, tag: string, attrs = "", inner: string) => {
|
||
if (/\sid\s*=/i.test(attrs || "")) {
|
||
return `<${tag}${attrs || ""}>${inner}</${tag}>`;
|
||
}
|
||
const plain = inner.replace(/<[^>]+>/g, "").trim();
|
||
let base =
|
||
plain
|
||
.toLowerCase()
|
||
.replace(/\s+/g, "-")
|
||
.replace(/[^\w\u4e00-\u9fff-]+/g, "")
|
||
.replace(/-+/g, "-")
|
||
.replace(/^-|-$/g, "")
|
||
.slice(0, 80) || "section";
|
||
let id = base;
|
||
let n = 2;
|
||
while (used.has(id)) {
|
||
id = `${base}-${n++}`;
|
||
}
|
||
used.add(id);
|
||
return `<${tag}${attrs || ""} id="${id}">${inner}</${tag}>`;
|
||
},
|
||
);
|
||
|
||
let rawChunks = lazyHtml.split(/(?=<h1[\s>])/i).filter((c) => c.trim());
|
||
if (rawChunks.length <= 1) {
|
||
rawChunks = lazyHtml.split(/(?=<h2[\s>])/i).filter((c) => c.trim());
|
||
}
|
||
|
||
const headers: string[] = [];
|
||
const headerRegex = /<h1[^>]*>(.*?)<\/h1>/gi;
|
||
let m;
|
||
while ((m = headerRegex.exec(lazyHtml)) !== null) {
|
||
headers.push(m[1].replace(/<[^>]+>/g, ""));
|
||
}
|
||
if (headers.length === 0) {
|
||
const h2Regex = /<h2[^>]*>(.*?)<\/h2>/gi;
|
||
while ((m = h2Regex.exec(lazyHtml)) !== null) {
|
||
headers.push(m[1].replace(/<[^>]+>/g, ""));
|
||
}
|
||
}
|
||
|
||
const chunks: EbookChunk[] = rawChunks.map((chunkHtml) => {
|
||
const imgCount = (chunkHtml.match(/<img\b/g) || []).length;
|
||
const textLen = chunkHtml.replace(/<[^>]+>/g, "").length;
|
||
const estimatedHeight = Math.max(300, Math.round(textLen * 0.6 + imgCount * 350));
|
||
return { html: chunkHtml, estimatedHeight };
|
||
});
|
||
|
||
return { chunks, headers };
|
||
}
|
||
|
||
/** 估算阅读时间(字/分钟,中文约 300-500) */
|
||
export function estimateReadingMinutes(textLength: number, wpm = 400): number {
|
||
return Math.max(1, Math.ceil(textLength / wpm));
|
||
}
|