Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes. Co-authored-by: Cursor <cursoragent@cursor.com>
158 lines
5.0 KiB
Python
158 lines
5.0 KiB
Python
#!/usr/bin/env python3
|
||
"""Compile local markdown into offline book-data.js for 小红书小工具."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
DEFAULT_MD = ROOT / "content" / "数字游民一人公司小册.md"
|
||
OUT_JS = ROOT / "tool" / "book-data.js"
|
||
OUT_JS_SRC = ROOT / "src" / "book-data.js"
|
||
|
||
|
||
def split_by_h2(md: str) -> tuple[str, list[dict]]:
|
||
"""Title from first # line; chapters from ## headings."""
|
||
text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip()
|
||
title = "未命名"
|
||
m = re.match(r"^#\s+(.+?)\s*$", text, re.M)
|
||
if m:
|
||
title = m.group(1).strip()
|
||
# drop the H1 line itself from body
|
||
text = re.sub(r"^#\s+.+\n?", "", text, count=1)
|
||
|
||
parts = re.split(r"(?m)^(#{2} .+)$", text)
|
||
chapters: list[dict] = []
|
||
preamble = (parts[0] or "").strip()
|
||
order = 1
|
||
|
||
# skip thin preamble (quotes / --- only) — fold into first chapter if tiny
|
||
if preamble and len(parts) == 1:
|
||
chapters.append(
|
||
{"id": "c1", "title": "正文", "order": 1, "content": preamble + "\n"}
|
||
)
|
||
return title, chapters
|
||
|
||
i = 1
|
||
while i < len(parts):
|
||
heading = parts[i].strip()
|
||
body = parts[i + 1] if i + 1 < len(parts) else ""
|
||
ch_title = re.sub(r"^##\s+", "", heading).strip() or f"第{order}章"
|
||
# Skip pure TOC chapter — links are useless offline; keep a short note
|
||
content = f"{heading}\n{body}".strip() + "\n"
|
||
if ch_title == "目录":
|
||
content = (
|
||
"## 目录\n\n"
|
||
"> 请用右上角「目」打开章节列表跳转。\n\n"
|
||
)
|
||
chapters.append(
|
||
{
|
||
"id": f"c{order}",
|
||
"title": ch_title,
|
||
"order": order,
|
||
"content": content,
|
||
}
|
||
)
|
||
order += 1
|
||
i += 2
|
||
|
||
# If there was meaningful preamble before first ##, fold into first chapter
|
||
if preamble and chapters:
|
||
chapters[0]["content"] = preamble + "\n\n" + chapters[0]["content"]
|
||
elif preamble:
|
||
chapters.append(
|
||
{
|
||
"id": "c0",
|
||
"title": "卷首",
|
||
"order": 1,
|
||
"content": preamble + "\n",
|
||
}
|
||
)
|
||
return title, chapters
|
||
|
||
|
||
def offline_sanitize(md: str) -> str:
|
||
"""Strip network-dependent media; keep readable offline text."""
|
||
text = md or ""
|
||
text = re.sub(r"<!--[\s\S]*?-->", "", text)
|
||
text = re.sub(
|
||
r"<video[\s\S]*?</video>",
|
||
"\n> 🎬 视频请在公众号查看\n",
|
||
text,
|
||
flags=re.IGNORECASE,
|
||
)
|
||
text = re.sub(
|
||
r"<img\b[\s\S]*?>",
|
||
"\n> 🖼 配图已省略(离线版)\n",
|
||
text,
|
||
flags=re.IGNORECASE,
|
||
)
|
||
text = re.sub(
|
||
r"!\[[^\]]*\]\(https?://[^)]+\)",
|
||
"\n> 🖼 配图已省略(离线版)\n",
|
||
text,
|
||
)
|
||
text = re.sub(
|
||
r"!\[[^\]]*\]\((?:[A-Za-z]:\\|/)[^)]+\)",
|
||
"\n> 🖼 本地图片暂不可用\n",
|
||
text,
|
||
)
|
||
# Keep link text, drop navigable href (container blocks external nav)
|
||
text = re.sub(r"\[([^\]]+)\]\(https?://[^)]+\)", r"**\1**", text)
|
||
text = re.sub(r"\[([^\]]+)\]\(#[^)]+\)", r"**\1**", text)
|
||
return text
|
||
|
||
|
||
def word_count(chapters: list[dict]) -> int:
|
||
total = 0
|
||
for ch in chapters:
|
||
body = re.sub(r"[#>*`\-\[\]\(\)|]", "", ch.get("content") or "")
|
||
total += len(re.findall(r"[\u4e00-\u9fff]|[A-Za-z0-9]+", body))
|
||
return total
|
||
|
||
|
||
def main() -> int:
|
||
md_path = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_MD
|
||
if not md_path.is_file():
|
||
print(f"missing ebook: {md_path}", file=sys.stderr)
|
||
return 1
|
||
|
||
raw = md_path.read_text(encoding="utf-8")
|
||
title, chapters = split_by_h2(raw)
|
||
for ch in chapters:
|
||
ch["content"] = offline_sanitize(ch["content"])
|
||
|
||
book = {
|
||
"id": "nomad-solopreneur",
|
||
"title": title,
|
||
"subtitle": "写给想把生活与工作重新排布的人",
|
||
"author": "Eric的云游日记",
|
||
"cover_emoji": "🌏",
|
||
"description": "数字游民与一人公司行动地图:地理套利、技能变现、内容资产与30天清单。",
|
||
"tags": ["数字游民", "一人公司", "远程工作", "副业"],
|
||
"chapter_count": len(chapters),
|
||
"word_count": word_count(chapters),
|
||
"is_free": True,
|
||
"chapters": chapters,
|
||
}
|
||
|
||
payload = (
|
||
"// Auto-generated by scripts/build_book_data.py — do not edit by hand.\n"
|
||
"var BOOK_DATA = "
|
||
+ json.dumps(book, ensure_ascii=False, indent=2)
|
||
.replace("\u2028", "\\u2028")
|
||
.replace("\u2029", "\\u2029")
|
||
+ ";\n"
|
||
)
|
||
for dest in (OUT_JS, OUT_JS_SRC):
|
||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||
dest.write_text(payload, encoding="utf-8")
|
||
print(f"wrote {OUT_JS} chapters={len(chapters)} words~={book['word_count']}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|