openclawclaude-codev0.2.0

wechat-article-downloader

acchaacc@acchaacc⭐ 2 stars· last commit 8mo ago· 0 open issues

Downloads WeChat Official Account articles via Chrome CDP and converts to clean Markdown with locally saved images.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

1.9/10
Verified
Mar 9, 2026

// RATINGS

⭐GitHub Stars
⭐ 2 on GitHubGitHub ↗

New / niche

🟢ProSkills ScoreAI Verified
1.9/10
📍

Not yet listed on ClawHub or SkillsMP

// README

📰 微信公众号文章下载器

一键将微信公众号文章转为干净的 Markdown,图片自动保存到本地。

English

基于 Agent Skills 开放规范构建的 Claude Code 技能 — 可命令行独立运行,也可作为 AI Agent 技能直接调用。

✨ 功能特性

  • 🌐 Chrome CDP 渲染 — 完整 JavaScript 执行,自动处理懒加载图片
  • 📦 四种下载模式 — 单篇 URL / 批量文件 / 按公众号名搜索 / API 全量下载
  • 📝 Markdown 输出 — YAML 元数据(标题、作者、日期、来源)+ 干净正文
  • 🖼️ 本地图片 — 自动下载所有文章图片,URL 重写为本地相对路径
  • 🔧 微信深度适配 — 处理 data-src 懒加载、mmbiz.qpic.cn 图片、#js_content 提取
  • ⚙️ 灵活配置 — EXTEND.md 偏好设置 / 环境变量 / CLI 参数

📋 环境要求

  • Bun 运行时(或通过 npx -y bun 使用 Node.js)
  • Google Chrome 或 Chromium 浏览器

🚀 快速开始

安装依赖

bun install

下载单篇文章

bun scripts/main.ts "https://mp.weixin.qq.com/s/你的文章ID"

指定输出目录

bun scripts/main.ts "https://mp.weixin.qq.com/s/xxxx" -o ./articles/

🔍 按公众号名搜索下载

# 下载某公众号最近 5 篇文章
bun scripts/main.ts --search "无害加速" --max 5

# 仅列出搜索结果(不下载)
bun scripts/main.ts --search "无害加速" --list

📑 批量下载

创建 urls.txt 文件(每行一个 URL,# 开头为注释):

bun scripts/main.ts urls.txt -o ./backup/

🔑 下载自己公众号的所有文章

需要微信公众平台 API 凭据:

# 设置凭据
export WECHAT_APP_ID=你的AppID
export WECHAT_APP_SECRET=你的AppSecret

# 列出所有文章
bun scripts/main.ts --account --list

# 全量下载
bun scripts/main.ts --account -o ./my-articles/

# 只下载最近 20 篇
bun scripts/main.ts --account --max 20

凭据也可以存储在 .env 文件中:

# 项目级
mkdir -p .wechat-article-downloader
echo 'WECHAT_APP_ID=你的AppID' > .wechat-article-downloader/.env
echo 'WECHAT_APP_SECRET=你的AppSecret' >> .wechat-article-downloader/.env

# 或用户级(跨项目共享)
mkdir -p ~/.wechat-article-downloader
# 同上,写入 ~/.wechat-article-downloader/.env

📖 CLI 选项

选项说明
<url>单篇微信文章 URL
<file.txt>包含 URL 列表的批量文件
--search, -s <名称>🔍 按公众号名搜索并下载文章
--account🔑 通过 API 下载自己公众号的文章
-o, --output <目录>📂 输出目录(默认:./wechat-articles/)
--no-images🚫 跳过图片下载,保留远程 URL
--wait⏳ 等待模式:手动登录后按回车继续
--timeout <毫秒>⏱️ 页面加载超时(默认:30000)
--list📋 仅列出文章,不下载
--max, -n <数量>🔢 最大下载文章数

🔄 四种下载模式

模式触发方式说明
📄 单篇下载传入 mp.weixin.qq.com URL通过 Chrome CDP 抓取单篇文章
📑 批量下载传入 .txt 文件路径顺序下载文件中所有 URL
🔍 搜索下载--search "公众号名"通过搜狗微信搜索查找文章后下载
🔑 API 下载--account通过微信公众平台 API 拉取全部文章
⏳ 等待模式--wait打开 Chrome 手动登录,按回车后捕获

📂 输出格式

wechat-articles/
  📄 文章标题.md               ← Markdown + YAML 元数据
  📁 文章标题/
      📁 imgs/
          🖼️ 001.jpg            ← 本地保存的图片
          🖼️ 002.png

每篇文章的 Markdown 格式:

---
title: "文章标题"
author: "作者名"
date: "2024-01-15"
source_url: "https://mp.weixin.qq.com/s/xxxx"
description: "文章摘要..."
captured_at: "2024-01-15T12:00:00.000Z"
---

# 文章标题

正文内容...

![](imgs/001.jpg)

🤖 Claude Code 技能

安装

# 方式一:克隆到技能目录
git clone https://github.com/acchaacc/wechat-article-downloader ~/.claude/skills/wechat-article-downloader

# 方式二:从已有目录创建符号链接
ln -s /path/to/wechat-article-downloader ~/.claude/skills/wechat-article-downloader

触发关键词

安装后,在 Claude Code 中直接说:

  • 💬 "下载这篇公众号文章 https://mp.weixin.qq.com/s/xxxx"
  • 💬 "保存公众号文章到 Markdown"
  • 💬 "搜索并下载无害加速最近的文章"
  • 💬 "批量下载公众号所有文章"
  • 💬 "备份公众号文章"

⚙️ 配置

EXTEND.md 偏好设置

通过 EXTEND.md 自定义默认行为(无需修改源码):

# Preferences
- default_output: ./my-wechat-articles
- download_images: true
- timeout: 45000

查找顺序:.wechat-article-downloader/EXTEND.md → ~/.wechat-article-downloader/EXTEND.md

详见 偏好设置文档。

环境变量

变量说明
WECHAT_DL_CHROME_PATH自定义 Chrome 可执行文件路径
WECHAT_DL_CHROME_PROFILE_DIR自定义 Chrome 配置目录
WECHAT_APP_ID微信公众号 App ID(API 模式)
WECHAT_APP_SECRET微信公众号 App Secret(API 模式)

🔧 工作原理

URL → 🌐 Chrome CDP 启动 → 📄 导航到文章页 → ⬇️ 滚动触发懒加载
    → 🔍 提取元数据 + 内容 HTML → 🖼️ 下载图片 → 📝 转换 Markdown → 💾 写入文件
  1. 通过 Chrome DevTools Protocol 启动浏览器
  2. 导航到微信文章 URL,等待页面加载
  3. 自动滚动页面,触发懒加载图片(data-src → src)
  4. 从 #js_content 提取文章内容和元数据
  5. 并发下载 mmbiz.qpic.cn 图片(带正确 Referer 头)
  6. 用 Turndown + 微信专属规则将 HTML 转为 Markdown
  7. 生成带 YAML 元数据的 .md 文件

❓ 故障排除

问题解决方案
🚫 找不到 Chrome安装 Chrome 或设置 WECHAT_DL_CHROME_PATH
⏱️ 超时增大 --timeout 值
🔐 需要登录使用 --wait 模式手动登录
❌ API 错误检查 WECHAT_APP_ID 和 WECHAT_APP_SECRET
🖼️ 图片未加载页面可能需要更多滚动时间
🗑️ 文章已删除文章已被作者移除,无法下载
🤖 搜狗验证码稍后重试,或直接使用文章 URL

📄 许可证

MIT


Made with ❤️ by Harmless Acceleration

// HOW IT'S BUILT

TECHNOLOGY STACK

TypeScript
Node.js
JavaScript

This skill is built with TypeScript, Node.js, JavaScript. The repo includes a Node.js package.

// FILES

22 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md4.0 KBf969cc219403upstream ↗
    ---
    name: wechat-article-downloader
    description: >
      Downloads WeChat Official Account (微信公众号) articles and converts to
      Markdown with local images. Supports single URL, batch file, search by
      account name via Sogou, or bulk download via WeChat API. Use when user
      mentions "download wechat article", "保存公众号文章", "下载公众号",
      "微信文章转markdown", "备份公众号", or provides mp.weixin.qq.com URLs.
    license: MIT
    compatibility: >
      Requires Bun runtime (or Node.js with npx -y bun fallback) and
      Google Chrome or Chromium browser.
    allowed-tools:
      - Bash
      - Read
      - Write
      - Glob
      - AskUserQuestion
    metadata:
      author: acchaacc
      version: "0.2.0"
    ---
    
    # WeChat Article Downloader
    
    Downloads WeChat Official Account articles via Chrome CDP and converts to clean Markdown with locally saved images.
    
    ## Script Directory
    
    **Agent Execution Instructions**:
    1. Determine this SKILL.md file's directory path as `SKILL_DIR`
    2. Detect runtime: if `bun` is available use `bun`, otherwise use `npx -y bun`. Store as `${BUN_X}`
    3. Script path = `${SKILL_DIR}/scripts/main.ts`
    
    **Runtime Detection** (one-time per session):
    ```bash
    command -v bun >/dev/null 2>&1 && echo "bun" || echo "npx -y bun"
    ```
    
    Run `${BUN_X} ${SKILL_DIR}/scripts/main.ts --help` for full CLI options.
    
    ## Preferences (EXTEND.md)
    
    Check for user preferences (priority order):
    
    ```bash
    test -f .wechat-article-downloader/EXTEND.md && echo "project"
    test -f "$HOME/.wechat-article-downloader/EXTEND.md" && echo "user"
    ```
    
    | Result | Action |
    |--------|--------|
    | Found | Read, parse, apply settings |
    | Not found | Use defaults |
    
    See `references/config/preferences-schema.md` for full schema.
    
    ## Usage
    
    ### Single Article
    
    ```bash
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts "https://mp.weixin.qq.com/s/xxxx"
    ```
    
    ### Custom Output Directory
    
    ```bash
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts "https://mp.weixin.qq.com/s/xxxx" -o ./articles/
    ```
    
    ### Search by Account Name (via Sogou)
    
    ```bash
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts --search "公众号名称" --max 5
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts --search "公众号名称" --list
    ```
    
    ### Batch Download from URL List
    
    ```bash
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts urls.txt -o ./backup/
    ```
    
    ### Download from Own Account (API)
    
    Requires WeChat Official Account API credentials (see Environment Variables):
    
    ```bash
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts --account --list
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts --account -o ./my-articles/
    ${BUN_X} ${SKILL_DIR}/scripts/main.ts --account --max 20
    ```
    
    ## Download Modes
    
    | Mode | Trigger | Behavior |
    |------|---------|----------|
    | Single URL | Pass a `mp.weixin.qq.com` URL | Download one article via CDP |
    | Batch file | Pass a `.txt` file path | Download all URLs sequentially |
    | Search | `--search "name"` | Find articles via Sogou, then download |
    | Account | `--account` flag | List + download all via WeChat API |
    | Wait | `--wait` flag | Open Chrome, user logs in, press Enter to capture |
    
    ## Output Format
    
    YAML frontmatter + Markdown body:
    
    ```yaml
    ---
    title: "Article Title"
    author: "Author Name"
    date: "2024-01-15"
    source_url: "https://mp.weixin.qq.com/s/xxxx"
    description: "Article digest..."
    captured_at: "2024-01-15T12:00:00.000Z"
    ---
    ```
    
    ## Environment Variables
    
    | Variable | Description |
    |----------|-------------|
    | `WECHAT_DL_CHROME_PATH` | Custom Chrome executable path |
    | `WECHAT_DL_CHROME_PROFILE_DIR` | Custom Chrome profile directory |
    | `WECHAT_APP_ID` | WeChat Official Account App ID (for `--account` mode) |
    | `WECHAT_APP_SECRET` | WeChat Official Account App Secret (for `--account` mode) |
    
    API credentials can also be set in `.wechat-article-downloader/.env` or `~/.wechat-article-downloader/.env`.
    
    ## Troubleshooting
    
    | Issue | Fix |
    |-------|-----|
    | Chrome not found | Install Chrome or set `WECHAT_DL_CHROME_PATH` |
    | Timeout | Increase `--timeout` value |
    | Login required | Use `--wait` mode |
    | API errors | Check `WECHAT_APP_ID` and `WECHAT_APP_SECRET` |
    | Images not loading | Page may need more scroll time; increase timeout |
    | Sogou captcha | Try again later or use direct article URL |
    
  • README.md6.7 KBcfdb88acc252upstream ↗
    # 📰 微信公众号文章下载器
    
    > 一键将微信公众号文章转为干净的 Markdown,图片自动保存到本地。
    
    [English](./README.en.md)
    
    基于 [Agent Skills](https://agentskills.io/) 开放规范构建的 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 技能 — 可命令行独立运行,也可作为 AI Agent 技能直接调用。
    
    ## ✨ 功能特性
    
    - 🌐 **Chrome CDP 渲染** — 完整 JavaScript 执行,自动处理懒加载图片
    - 📦 **四种下载模式** — 单篇 URL / 批量文件 / 按公众号名搜索 / API 全量下载
    - 📝 **Markdown 输出** — YAML 元数据(标题、作者、日期、来源)+ 干净正文
    - 🖼️ **本地图片** — 自动下载所有文章图片,URL 重写为本地相对路径
    - 🔧 **微信深度适配** — 处理 `data-src` 懒加载、`mmbiz.qpic.cn` 图片、`#js_content` 提取
    - ⚙️ **灵活配置** — EXTEND.md 偏好设置 / 环境变量 / CLI 参数
    
    ## 📋 环境要求
    
    - [Bun](https://bun.sh/) 运行时(或通过 `npx -y bun` 使用 Node.js)
    - Google Chrome 或 Chromium 浏览器
    
    ## 🚀 快速开始
    
    ### 安装依赖
    
    ```bash
    bun install
    ```
    
    ### 下载单篇文章
    
    ```bash
    bun scripts/main.ts "https://mp.weixin.qq.com/s/你的文章ID"
    ```
    
    ### 指定输出目录
    
    ```bash
    bun scripts/main.ts "https://mp.weixin.qq.com/s/xxxx" -o ./articles/
    ```
    
    ### 🔍 按公众号名搜索下载
    
    ```bash
    # 下载某公众号最近 5 篇文章
    bun scripts/main.ts --search "无害加速" --max 5
    
    # 仅列出搜索结果(不下载)
    bun scripts/main.ts --search "无害加速" --list
    ```
    
    ### 📑 批量下载
    
    创建 `urls.txt` 文件(每行一个 URL,`#` 开头为注释):
    
    ```bash
    bun scripts/main.ts urls.txt -o ./backup/
    ```
    
    ### 🔑 下载自己公众号的所有文章
    
    需要微信公众平台 API 凭据:
    
    ```bash
    # 设置凭据
    export WECHAT_APP_ID=你的AppID
    export WECHAT_APP_SECRET=你的AppSecret
    
    # 列出所有文章
    bun scripts/main.ts --account --list
    
    # 全量下载
    bun scripts/main.ts --account -o ./my-articles/
    
    # 只下载最近 20 篇
    bun scripts/main.ts --account --max 20
    ```
    
    凭据也可以存储在 `.env` 文件中:
    
    ```bash
    # 项目级
    mkdir -p .wechat-article-downloader
    echo 'WECHAT_APP_ID=你的AppID' > .wechat-article-downloader/.env
    echo 'WECHAT_APP_SECRET=你的AppSecret' >> .wechat-article-downloader/.env
    
    # 或用户级(跨项目共享)
    mkdir -p ~/.wechat-article-downloader
    # 同上,写入 ~/.wechat-article-downloader/.env
    ```
    
    ## 📖 CLI 选项
    
    | 选项 | 说明 |
    |------|------|
    | `<url>` | 单篇微信文章 URL |
    | `<file.txt>` | 包含 URL 列表的批量文件 |
    | `--search, -s <名称>` | 🔍 按公众号名搜索并下载文章 |
    | `--account` | 🔑 通过 API 下载自己公众号的文章 |
    | `-o, --output <目录>` | 📂 输出目录(默认:`./wechat-articles/`) |
    | `--no-images` | 🚫 跳过图片下载,保留远程 URL |
    | `--wait` | ⏳ 等待模式:手动登录后按回车继续 |
    | `--timeout <毫秒>` | ⏱️ 页面加载超时(默认:30000) |
    | `--list` | 📋 仅列出文章,不下载 |
    | `--max, -n <数量>` | 🔢 最大下载文章数 |
    
    ## 🔄 四种下载模式
    
    | 模式 | 触发方式 | 说明 |
    |------|----------|------|
    | 📄 **单篇下载** | 传入 `mp.weixin.qq.com` URL | 通过 Chrome CDP 抓取单篇文章 |
    | 📑 **批量下载** | 传入 `.txt` 文件路径 | 顺序下载文件中所有 URL |
    | 🔍 **搜索下载** | `--search "公众号名"` | 通过搜狗微信搜索查找文章后下载 |
    | 🔑 **API 下载** | `--account` | 通过微信公众平台 API 拉取全部文章 |
    | ⏳ **等待模式** | `--wait` | 打开 Chrome 手动登录,按回车后捕获 |
    
    ## 📂 输出格式
    
    ```
    wechat-articles/
      📄 文章标题.md               ← Markdown + YAML 元数据
      📁 文章标题/
          📁 imgs/
              🖼️ 001.jpg            ← 本地保存的图片
              🖼️ 002.png
    ```
    
    每篇文章的 Markdown 格式:
    
    ```yaml
    ---
    title: "文章标题"
    author: "作者名"
    date: "2024-01-15"
    source_url: "https://mp.weixin.qq.com/s/xxxx"
    description: "文章摘要..."
    captured_at: "2024-01-15T12:00:00.000Z"
    ---
    
    # 文章标题
    
    正文内容...
    
    ![](imgs/001.jpg)
    ```
    
    ## 🤖 Claude Code 技能
    
    ### 安装
    
    ```bash
    # 方式一:克隆到技能目录
    git clone https://github.com/acchaacc/wechat-article-downloader ~/.claude/skills/wechat-article-downloader
    
    # 方式二:从已有目录创建符号链接
    ln -s /path/to/wechat-article-downloader ~/.claude/skills/wechat-article-downloader
    ```
    
    ### 触发关键词
    
    安装后,在 Claude Code 中直接说:
    
    - 💬 "下载这篇公众号文章 https://mp.weixin.qq.com/s/xxxx"
    - 💬 "保存公众号文章到 Markdown"
    - 💬 "搜索并下载无害加速最近的文章"
    - 💬 "批量下载公众号所有文章"
    - 💬 "备份公众号文章"
    
    ## ⚙️ 配置
    
    ### EXTEND.md 偏好设置
    
    通过 `EXTEND.md` 自定义默认行为(无需修改源码):
    
    ```markdown
    # Preferences
    - default_output: ./my-wechat-articles
    - download_images: true
    - timeout: 45000
    ```
    
    **查找顺序**:`.wechat-article-downloader/EXTEND.md` → `~/.wechat-article-downloader/EXTEND.md`
    
    详见 [偏好设置文档](./references/config/preferences-schema.md)。
    
    ### 环境变量
    
    | 变量 | 说明 |
    |------|------|
    | `WECHAT_DL_CHROME_PATH` | 自定义 Chrome 可执行文件路径 |
    | `WECHAT_DL_CHROME_PROFILE_DIR` | 自定义 Chrome 配置目录 |
    | `WECHAT_APP_ID` | 微信公众号 App ID(API 模式) |
    | `WECHAT_APP_SECRET` | 微信公众号 App Secret(API 模式) |
    
    ## 🔧 工作原理
    
    ```
    URL → 🌐 Chrome CDP 启动 → 📄 导航到文章页 → ⬇️ 滚动触发懒加载
        → 🔍 提取元数据 + 内容 HTML → 🖼️ 下载图片 → 📝 转换 Markdown → 💾 写入文件
    ```
    
    1. 通过 Chrome DevTools Protocol 启动浏览器
    2. 导航到微信文章 URL,等待页面加载
    3. 自动滚动页面,触发懒加载图片(`data-src` → `src`)
    4. 从 `#js_content` 提取文章内容和元数据
    5. 并发下载 `mmbiz.qpic.cn` 图片(带正确 Referer 头)
    6. 用 Turndown + 微信专属规则将 HTML 转为 Markdown
    7. 生成带 YAML 元数据的 `.md` 文件
    
    ## ❓ 故障排除
    
    | 问题 | 解决方案 |
    |------|----------|
    | 🚫 找不到 Chrome | 安装 Chrome 或设置 `WECHAT_DL_CHROME_PATH` |
    | ⏱️ 超时 | 增大 `--timeout` 值 |
    | 🔐 需要登录 | 使用 `--wait` 模式手动登录 |
    | ❌ API 错误 | 检查 `WECHAT_APP_ID` 和 `WECHAT_APP_SECRET` |
    | 🖼️ 图片未加载 | 页面可能需要更多滚动时间 |
    | 🗑️ 文章已删除 | 文章已被作者移除,无法下载 |
    | 🤖 搜狗验证码 | 稍后重试,或直接使用文章 URL |
    
    ## 📄 许可证
    
    [MIT](./LICENSE)
    
    ---
    
    Made with ❤️ by [Harmless Acceleration](https://github.com/acchaacc)
    
  • scripts/batch.ts1.4 KBa0d8159e6f3aupstream ↗
    import { readFile } from "node:fs/promises";
    import type { ArticleOutput } from "./types.js";
    
    export interface BatchResult {
      succeeded: ArticleOutput[];
      failed: Array<{ url: string; error: string }>;
    }
    
    export async function parseBatchFile(filePath: string): Promise<string[]> {
      const content = await readFile(filePath, "utf-8");
      return content
        .split("\n")
        .map(line => line.trim())
        .filter(line => line && !line.startsWith("#") && line.startsWith("http"));
    }
    
    function sleep(ms: number): Promise<void> {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    export async function processBatch(
      urls: string[],
      processOne: (url: string, index: number) => Promise<ArticleOutput>,
      options: { delayMs: number; log?: (msg: string) => void }
    ): Promise<BatchResult> {
      const succeeded: ArticleOutput[] = [];
      const failed: Array<{ url: string; error: string }> = [];
    
      for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        options.log?.(`\n[${i + 1}/${urls.length}] ${url}`);
        try {
          const result = await processOne(url, i);
          succeeded.push(result);
          options.log?.(`  OK: ${result.meta.title} (${result.imageCount} images)`);
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          failed.push({ url, error: msg });
          options.log?.(`  FAILED: ${msg}`);
        }
        if (i < urls.length - 1) {
          await sleep(options.delayMs);
        }
      }
    
      return { succeeded, failed };
    }
    
  • scripts/cdp.ts9.6 KB8e900a540fa2upstream ↗
    import { spawn, type ChildProcess } from "node:child_process";
    import fs from "node:fs";
    import { mkdir } from "node:fs/promises";
    import net from "node:net";
    import process from "node:process";
    
    import { resolveWeChatChromeProfileDir } from "./paths.js";
    import { CDP_CONNECT_TIMEOUT_MS, NETWORK_IDLE_TIMEOUT_MS } from "./constants.js";
    
    type CdpSendOptions = { sessionId?: string; timeoutMs?: number };
    
    function sleep(ms: number): Promise<void> {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    
    async function fetchWithTimeout(url: string, init: RequestInit & { timeoutMs?: number } = {}): Promise<Response> {
      const { timeoutMs, ...rest } = init;
      if (!timeoutMs || timeoutMs <= 0) return fetch(url, rest);
      const ctl = new AbortController();
      const t = setTimeout(() => ctl.abort(), timeoutMs);
      try {
        return await fetch(url, { ...rest, signal: ctl.signal });
      } finally {
        clearTimeout(t);
      }
    }
    
    export class CdpConnection {
      private ws: WebSocket;
      private nextId = 0;
      private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> | null }>();
      private eventHandlers = new Map<string, Set<(params: unknown) => void>>();
    
      private constructor(ws: WebSocket) {
        this.ws = ws;
        this.ws.addEventListener("message", (event) => {
          try {
            const data = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data as ArrayBuffer);
            const msg = JSON.parse(data) as { id?: number; method?: string; params?: unknown; result?: unknown; error?: { message?: string } };
            if (msg.id) {
              const p = this.pending.get(msg.id);
              if (p) {
                this.pending.delete(msg.id);
                if (p.timer) clearTimeout(p.timer);
                if (msg.error?.message) p.reject(new Error(msg.error.message));
                else p.resolve(msg.result);
              }
            } else if (msg.method) {
              const handlers = this.eventHandlers.get(msg.method);
              if (handlers) {
                for (const h of handlers) h(msg.params);
              }
            }
          } catch {}
        });
        this.ws.addEventListener("close", () => {
          for (const [id, p] of this.pending.entries()) {
            this.pending.delete(id);
            if (p.timer) clearTimeout(p.timer);
            p.reject(new Error("CDP connection closed."));
          }
        });
      }
    
      static async connect(url: string, timeoutMs: number): Promise<CdpConnection> {
        const ws = new WebSocket(url);
        await new Promise<void>((resolve, reject) => {
          const t = setTimeout(() => reject(new Error("CDP connection timeout.")), timeoutMs);
          ws.addEventListener("open", () => { clearTimeout(t); resolve(); });
          ws.addEventListener("error", () => { clearTimeout(t); reject(new Error("CDP connection failed.")); });
        });
        return new CdpConnection(ws);
      }
    
      on(event: string, handler: (params: unknown) => void): void {
        let handlers = this.eventHandlers.get(event);
        if (!handlers) {
          handlers = new Set();
          this.eventHandlers.set(event, handlers);
        }
        handlers.add(handler);
      }
    
      off(event: string, handler: (params: unknown) => void): void {
        this.eventHandlers.get(event)?.delete(handler);
      }
    
      async send<T = unknown>(method: string, params?: Record<string, unknown>, opts?: CdpSendOptions): Promise<T> {
        const id = ++this.nextId;
        const msg: Record<string, unknown> = { id, method };
        if (params) msg.params = params;
        if (opts?.sessionId) msg.sessionId = opts.sessionId;
        const timeoutMs = opts?.timeoutMs ?? 15_000;
        const out = await new Promise<unknown>((resolve, reject) => {
          const t = timeoutMs > 0 ? setTimeout(() => { this.pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, timeoutMs) : null;
          this.pending.set(id, { resolve, reject, timer: t });
          this.ws.send(JSON.stringify(msg));
        });
        return out as T;
      }
    
      close(): void {
        try { this.ws.close(); } catch {}
      }
    }
    
    export async function getFreePort(): Promise<number> {
      return await new Promise((resolve, reject) => {
        const srv = net.createServer();
        srv.unref();
        srv.on("error", reject);
        srv.listen(0, "127.0.0.1", () => {
          const addr = srv.address();
          if (!addr || typeof addr === "string") {
            srv.close(() => reject(new Error("Unable to allocate a free TCP port.")));
            return;
          }
          const port = addr.port;
          srv.close((err) => (err ? reject(err) : resolve(port)));
        });
      });
    }
    
    export function findChromeExecutable(): string | null {
      const override = process.env.WECHAT_DL_CHROME_PATH?.trim();
      if (override && fs.existsSync(override)) return override;
    
      const candidates: string[] = [];
      switch (process.platform) {
        case "darwin":
          candidates.push(
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
            "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
          );
          break;
        case "win32":
          candidates.push(
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
            "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
          );
          break;
        default:
          candidates.push(
            "/usr/bin/google-chrome",
            "/usr/bin/google-chrome-stable",
            "/usr/bin/chromium",
            "/usr/bin/chromium-browser",
            "/snap/bin/chromium",
            "/usr/bin/microsoft-edge"
          );
          break;
      }
    
      for (const p of candidates) {
        if (fs.existsSync(p)) return p;
      }
      return null;
    }
    
    export async function waitForChromeDebugPort(port: number, timeoutMs: number): Promise<string> {
      const start = Date.now();
      while (Date.now() - start < timeoutMs) {
        try {
          const res = await fetchWithTimeout(`http://127.0.0.1:${port}/json/version`, { timeoutMs: 5_000 });
          if (!res.ok) throw new Error(`status=${res.status}`);
          const j = (await res.json()) as { webSocketDebuggerUrl?: string };
          if (j.webSocketDebuggerUrl) return j.webSocketDebuggerUrl;
        } catch {}
        await sleep(200);
      }
      throw new Error("Chrome debug port not ready");
    }
    
    export async function launchChrome(url: string, port: number, headless: boolean = false): Promise<ChildProcess> {
      const chrome = findChromeExecutable();
      if (!chrome) throw new Error("Chrome executable not found. Install Chrome or set WECHAT_DL_CHROME_PATH env.");
      const profileDir = resolveWeChatChromeProfileDir();
      await mkdir(profileDir, { recursive: true });
    
      const args = [
        `--remote-debugging-port=${port}`,
        `--user-data-dir=${profileDir}`,
        "--no-first-run",
        "--no-default-browser-check",
        "--disable-popup-blocking",
      ];
      if (headless) args.push("--headless=new");
      args.push(url);
    
      return spawn(chrome, args, { stdio: "ignore" });
    }
    
    export async function waitForNetworkIdle(cdp: CdpConnection, sessionId: string, timeoutMs: number = NETWORK_IDLE_TIMEOUT_MS): Promise<void> {
      return new Promise((resolve) => {
        let timer: ReturnType<typeof setTimeout> | null = null;
        let pending = 0;
        const cleanup = () => {
          if (timer) clearTimeout(timer);
          cdp.off("Network.requestWillBeSent", onRequest);
          cdp.off("Network.loadingFinished", onFinish);
          cdp.off("Network.loadingFailed", onFinish);
        };
        const done = () => { cleanup(); resolve(); };
        const resetTimer = () => {
          if (timer) clearTimeout(timer);
          timer = setTimeout(done, timeoutMs);
        };
        const onRequest = () => { pending++; resetTimer(); };
        const onFinish = () => { pending = Math.max(0, pending - 1); if (pending <= 2) resetTimer(); };
        cdp.on("Network.requestWillBeSent", onRequest);
        cdp.on("Network.loadingFinished", onFinish);
        cdp.on("Network.loadingFailed", onFinish);
        resetTimer();
      });
    }
    
    export async function waitForPageLoad(cdp: CdpConnection, sessionId: string, timeoutMs: number = 30_000): Promise<void> {
      return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
          cdp.off("Page.loadEventFired", handler);
          resolve();
        }, timeoutMs);
        const handler = () => {
          clearTimeout(timer);
          cdp.off("Page.loadEventFired", handler);
          resolve();
        };
        cdp.on("Page.loadEventFired", handler);
      });
    }
    
    export async function evaluateScript<T>(cdp: CdpConnection, sessionId: string, expression: string, timeoutMs: number = 30_000): Promise<T> {
      const result = await cdp.send<{ result: { value?: T; type?: string; description?: string } }>(
        "Runtime.evaluate",
        { expression, returnByValue: true, awaitPromise: true },
        { sessionId, timeoutMs }
      );
      return result.result.value as T;
    }
    
    export async function autoScroll(cdp: CdpConnection, sessionId: string, steps: number = 8, waitMs: number = 600): Promise<void> {
      let lastHeight = await evaluateScript<number>(cdp, sessionId, "document.body.scrollHeight");
      for (let i = 0; i < steps; i++) {
        await evaluateScript<void>(cdp, sessionId, "window.scrollTo(0, document.body.scrollHeight)");
        await sleep(waitMs);
        const newHeight = await evaluateScript<number>(cdp, sessionId, "document.body.scrollHeight");
        if (newHeight === lastHeight) break;
        lastHeight = newHeight;
      }
      await evaluateScript<void>(cdp, sessionId, "window.scrollTo(0, 0)");
    }
    
    export function killChrome(chrome: ChildProcess): void {
      try { chrome.kill("SIGTERM"); } catch {}
      setTimeout(() => {
        if (!chrome.killed) {
          try { chrome.kill("SIGKILL"); } catch {}
        }
      }, 2_000).unref?.();
    }
    
  • scripts/constants.ts799 Bf60e3be7a29aupstream ↗
    export const DEFAULT_USER_AGENT =
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
    
    export const DEFAULT_TIMEOUT_MS = 30_000;
    export const CDP_CONNECT_TIMEOUT_MS = 15_000;
    export const NETWORK_IDLE_TIMEOUT_MS = 2_000;
    export const POST_LOAD_DELAY_MS = 1_000;
    export const SCROLL_STEP_WAIT_MS = 800;
    export const SCROLL_MAX_STEPS = 15;
    export const IMAGE_DOWNLOAD_TIMEOUT_MS = 15_000;
    export const IMAGE_DOWNLOAD_CONCURRENCY = 3;
    export const BATCH_INTER_ARTICLE_DELAY_MS = 2_000;
    
    // WeChat DOM selectors
    export const WECHAT_CONTENT_SELECTOR = "#js_content";
    export const WECHAT_TITLE_SELECTOR = "#activity-name";
    export const WECHAT_AUTHOR_SELECTOR = "#js_name";
    export const WECHAT_PUBLISH_DATE_SELECTOR = "#publish_time";
    
  • scripts/image-downloader.ts2.7 KB5621923630f7upstream ↗
    import { writeFile, mkdir } from "node:fs/promises";
    import path from "node:path";
    import { DEFAULT_USER_AGENT, IMAGE_DOWNLOAD_CONCURRENCY } from "./constants.js";
    
    function sleep(ms: number): Promise<void> {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    
    function resolveImageExtension(url: string, contentType: string | null): string {
      // Check wx_fmt parameter first (WeChat-specific)
      try {
        const parsed = new URL(url);
        const wxFmt = parsed.searchParams.get("wx_fmt");
        if (wxFmt) {
          if (wxFmt === "jpeg" || wxFmt === "jpg") return "jpg";
          if (wxFmt === "png") return "png";
          if (wxFmt === "gif") return "gif";
          if (wxFmt === "webp") return "webp";
          if (wxFmt === "svg") return "svg";
        }
      } catch {}
    
      // Fallback to content-type
      const ct = contentType?.split(";")[0]?.trim().toLowerCase() ?? "";
      if (ct === "image/jpeg" || ct === "image/jpg") return "jpg";
      if (ct === "image/png") return "png";
      if (ct === "image/gif") return "gif";
      if (ct === "image/webp") return "webp";
      if (ct === "image/svg+xml") return "svg";
    
      return "jpg";
    }
    
    export async function downloadImages(
      imageUrls: string[],
      outputDir: string,
      log?: (msg: string) => void,
    ): Promise<Map<string, string>> {
      const urlMap = new Map<string, string>();
      if (imageUrls.length === 0) return urlMap;
    
      const imgDir = path.join(outputDir, "imgs");
      await mkdir(imgDir, { recursive: true });
    
      for (let i = 0; i < imageUrls.length; i += IMAGE_DOWNLOAD_CONCURRENCY) {
        const batch = imageUrls.slice(i, i + IMAGE_DOWNLOAD_CONCURRENCY);
        const results = await Promise.allSettled(batch.map(async (url, batchIdx) => {
          const globalIdx = i + batchIdx + 1;
          try {
            const response = await fetch(url, {
              headers: {
                "User-Agent": DEFAULT_USER_AGENT,
                "Referer": "https://mp.weixin.qq.com/",
              },
              redirect: "follow",
              signal: AbortSignal.timeout(15_000),
            });
    
            if (!response.ok) {
              log?.(`  Skip image ${globalIdx} (HTTP ${response.status})`);
              return;
            }
    
            const ext = resolveImageExtension(url, response.headers.get("content-type"));
            const fileName = `${String(globalIdx).padStart(3, "0")}.${ext}`;
            const bytes = Buffer.from(await response.arrayBuffer());
            await writeFile(path.join(imgDir, fileName), bytes);
            urlMap.set(url, `imgs/${fileName}`);
          } catch (err) {
            log?.(`  Failed image ${globalIdx}: ${err instanceof Error ? err.message : String(err)}`);
          }
        }));
    
        // Small delay between batches
        if (i + IMAGE_DOWNLOAD_CONCURRENCY < imageUrls.length) {
          await sleep(200);
        }
      }
    
      return urlMap;
    }
    
  • scripts/main.ts16 KBa70dd59a2200upstream ↗
    import { createInterface } from "node:readline";
    import { writeFile, mkdir, access } from "node:fs/promises";
    import fs from "node:fs";
    import path from "node:path";
    import process from "node:process";
    
    import { CdpConnection, getFreePort, launchChrome, waitForChromeDebugPort, waitForNetworkIdle, waitForPageLoad, autoScroll, killChrome } from "./cdp.js";
    import { extractWeChatArticle } from "./wechat-extractor.js";
    import { wechatHtmlToMarkdown, createMarkdownDocument } from "./wechat-to-markdown.js";
    import { downloadImages } from "./image-downloader.js";
    import { parseBatchFile, processBatch } from "./batch.js";
    import { loadApiConfig, listPublishedArticles } from "./wechat-api.js";
    import { searchAccountArticles } from "./wechat-search.js";
    import type { ArticleOutput, WeChatExtractionResult } from "./types.js";
    import {
      DEFAULT_TIMEOUT_MS,
      CDP_CONNECT_TIMEOUT_MS,
      NETWORK_IDLE_TIMEOUT_MS,
      POST_LOAD_DELAY_MS,
      SCROLL_STEP_WAIT_MS,
      SCROLL_MAX_STEPS,
      BATCH_INTER_ARTICLE_DELAY_MS,
    } from "./constants.js";
    
    function sleep(ms: number): Promise<void> {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    
    async function fileExists(filePath: string): Promise<boolean> {
      try { await access(filePath); return true; } catch { return false; }
    }
    
    // --- Args ---
    
    interface Args {
      input: string;
      output: string;
      noImages: boolean;
      wait: boolean;
      timeout: number;
      listOnly: boolean;
      maxArticles: number;
      account: boolean;
      search: string;
    }
    
    function parseArgs(argv: string[]): Args {
      const args: Args = {
        input: "",
        output: "./wechat-articles",
        noImages: false,
        wait: false,
        timeout: DEFAULT_TIMEOUT_MS,
        listOnly: false,
        maxArticles: Infinity,
        account: false,
        search: "",
      };
    
      for (let i = 2; i < argv.length; i++) {
        const arg = argv[i];
        if (arg === "--no-images") args.noImages = true;
        else if (arg === "--wait" || arg === "-w") args.wait = true;
        else if (arg === "--list") args.listOnly = true;
        else if (arg === "--account") args.account = true;
        else if (arg === "--search" || arg === "-s") args.search = argv[++i] || "";
        else if (arg === "-o" || arg === "--output") args.output = argv[++i];
        else if (arg === "--timeout" || arg === "-t") args.timeout = parseInt(argv[++i], 10) || DEFAULT_TIMEOUT_MS;
        else if (arg === "--max" || arg === "-n") args.maxArticles = parseInt(argv[++i], 10) || Infinity;
        else if (!arg.startsWith("-") && !args.input) args.input = arg;
      }
      return args;
    }
    
    function printUsage(): void {
      console.log(`Usage: bun main.ts <url|batch-file> [options]
    
    Arguments:
      <url>                   Single WeChat article URL
      <batch-file.txt>        Text file with one URL per line
    
    Options:
      -o, --output <dir>      Output directory (default: ./wechat-articles/)
      --no-images             Skip image download, keep remote URLs
      --wait                  Wait mode: log in manually, press Enter to capture
      --timeout <ms>          Page load timeout (default: 30000)
      --search, -s <name>     Search & download articles from a public account by name
      --account               Download all articles from your own account (needs API config)
      --list                  List articles only, don't download
      --max, -n <num>         Max articles to download (default: all)
    
    Examples:
      bun main.ts "https://mp.weixin.qq.com/s/xxxx"
      bun main.ts urls.txt -o ./backup/
      bun main.ts --search "时见谈" --max 5
      bun main.ts --search "时见谈" --list
      bun main.ts --account -o ./my-articles/
      bun main.ts --account --list`);
    }
    
    // --- Slug generation ---
    
    function generateSlug(title: string): string {
      // For CJK titles, use first N characters + timestamp
      const cleaned = title
        .replace(/[^\w一-鿿㐀-䶿\s-]/g, "")
        .trim();
    
      if (!cleaned) return formatTimestamp();
    
      // If mostly CJK, keep first 20 chars
      const cjkRatio = (cleaned.match(/[一-鿿㐀-䶿]/g) || []).length / cleaned.length;
      if (cjkRatio > 0.3) {
        return cleaned.slice(0, 20).trim().replace(/\s+/g, "-");
      }
    
      // Latin: kebab-case
      return cleaned
        .toLowerCase()
        .replace(/\s+/g, "-")
        .replace(/-+/g, "-")
        .replace(/^-|-$/g, "")
        .slice(0, 50) || formatTimestamp();
    }
    
    function formatTimestamp(): string {
      const now = new Date();
      const pad = (n: number) => n.toString().padStart(2, "0");
      return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
    }
    
    async function generateOutputPath(outputDir: string, title: string): Promise<string> {
      const slug = generateSlug(title);
      const basePath = path.join(outputDir, `${slug}.md`);
      if (!(await fileExists(basePath))) return basePath;
      return path.join(outputDir, `${slug}-${formatTimestamp()}.md`);
    }
    
    // --- Core: capture single article ---
    
    async function waitForUserSignal(): Promise<void> {
      console.log("Page opened. Press Enter when ready to capture...");
      const rl = createInterface({ input: process.stdin, output: process.stdout });
      await new Promise<void>((resolve) => {
        rl.once("line", () => { rl.close(); resolve(); });
      });
    }
    
    async function captureArticle(
      cdp: CdpConnection,
      sessionId: string,
      url: string,
      args: Args,
    ): Promise<WeChatExtractionResult> {
      // Navigate
      const loadPromise = new Promise<void>((resolve) => {
        const timer = setTimeout(() => {
          cdp.off("Page.lifecycleEvent", handler);
          resolve();
        }, args.timeout);
        const handler = (params: unknown) => {
          const p = params as { name?: string };
          if (p.name === "load" || p.name === "DOMContentLoaded") {
            clearTimeout(timer);
            cdp.off("Page.lifecycleEvent", handler);
            resolve();
          }
        };
        cdp.on("Page.lifecycleEvent", handler);
      });
      await cdp.send("Page.navigate", { url }, { sessionId });
      await loadPromise;
    
      if (args.wait) {
        await waitForUserSignal();
      } else {
        await waitForNetworkIdle(cdp, sessionId, NETWORK_IDLE_TIMEOUT_MS);
        await sleep(POST_LOAD_DELAY_MS);
        await autoScroll(cdp, sessionId, SCROLL_MAX_STEPS, SCROLL_STEP_WAIT_MS);
        await sleep(POST_LOAD_DELAY_MS);
      }
    
      return extractWeChatArticle(cdp, sessionId, url, args.timeout);
    }
    
    async function processOneArticle(
      cdp: CdpConnection,
      sessionId: string,
      url: string,
      args: Args,
    ): Promise<ArticleOutput> {
      const extraction = await captureArticle(cdp, sessionId, url, args);
    
      // Download images
      let imageUrlMap: Map<string, string> | undefined;
      let imageCount = 0;
      const articleDir = path.dirname(await generateOutputPath(args.output, extraction.meta.title));
    
      if (!args.noImages && extraction.imageUrls.length > 0) {
        const outputBase = args.output;
        const slug = generateSlug(extraction.meta.title);
        const imgOutputDir = path.join(outputBase, slug);
        imageUrlMap = await downloadImages(extraction.imageUrls, imgOutputDir, console.log);
        imageCount = imageUrlMap.size;
      }
    
      // Convert to markdown
      const markdownBody = wechatHtmlToMarkdown(extraction.contentHtml, imageUrlMap);
      const document = createMarkdownDocument(extraction.meta, markdownBody);
    
      // Write file
      const outputPath = await generateOutputPath(args.output, extraction.meta.title);
      await mkdir(path.dirname(outputPath), { recursive: true });
      await writeFile(outputPath, document, "utf-8");
    
      return {
        markdownPath: outputPath,
        imageDir: imageUrlMap && imageUrlMap.size > 0 ? path.join(args.output, generateSlug(extraction.meta.title), "imgs") : null,
        imageCount,
        meta: extraction.meta,
      };
    }
    
    // --- Chrome lifecycle ---
    
    async function withChrome<T>(
      initialUrl: string,
      headless: boolean,
      fn: (cdp: CdpConnection, sessionId: string) => Promise<T>,
    ): Promise<T> {
      const port = await getFreePort();
      const chrome = await launchChrome(initialUrl, port, headless);
    
      let cdp: CdpConnection | null = null;
      try {
        const wsUrl = await waitForChromeDebugPort(port, 30_000);
        cdp = await CdpConnection.connect(wsUrl, CDP_CONNECT_TIMEOUT_MS);
    
        const targets = await cdp.send<{ targetInfos: Array<{ targetId: string; type: string; url: string }> }>("Target.getTargets");
        const pageTarget = targets.targetInfos.find(t => t.type === "page");
        if (!pageTarget) throw new Error("No page target found");
    
        const { sessionId } = await cdp.send<{ sessionId: string }>(
          "Target.attachToTarget",
          { targetId: pageTarget.targetId, flatten: true }
        );
        await cdp.send("Network.enable", {}, { sessionId });
        await cdp.send("Page.enable", {}, { sessionId });
    
        return await fn(cdp, sessionId);
      } finally {
        if (cdp) {
          try { await cdp.send("Browser.close", {}, { timeoutMs: 5_000 }); } catch {}
          cdp.close();
        }
        killChrome(chrome);
      }
    }
    
    // --- Main ---
    
    async function main(): Promise<void> {
      const args = parseArgs(process.argv);
    
      // --search mode: search for account by name
      if (args.search) {
        return handleSearchMode(args);
      }
    
      // --account mode
      if (args.account) {
        return handleAccountMode(args);
      }
    
      if (!args.input) {
        printUsage();
        process.exit(1);
      }
    
      // Check if input is a URL or a batch file
      const isUrl = args.input.startsWith("http://") || args.input.startsWith("https://");
      const isBatchFile = !isUrl && fs.existsSync(args.input) && args.input.endsWith(".txt");
    
      if (!isUrl && !isBatchFile) {
        console.error(`Invalid input: ${args.input}`);
        console.error("Provide a WeChat article URL, a .txt batch file, or --account");
        process.exit(1);
      }
    
      await mkdir(args.output, { recursive: true });
    
      if (isUrl) {
        // Single URL mode
        console.log(`Fetching: ${args.input}`);
        const result = await withChrome(args.input, false, async (cdp, sessionId) => {
          return processOneArticle(cdp, sessionId, args.input, args);
        });
        console.log(`\nSaved: ${result.markdownPath}`);
        console.log(`Title: ${result.meta.title}`);
        if (result.imageCount > 0) console.log(`Images: ${result.imageCount}`);
      } else {
        // Batch file mode
        const urls = await parseBatchFile(args.input);
        if (urls.length === 0) {
          console.error("No valid URLs found in batch file.");
          process.exit(1);
        }
        console.log(`Found ${urls.length} URLs in ${args.input}`);
    
        const firstUrl = urls[0];
        await withChrome(firstUrl, false, async (cdp, sessionId) => {
          const result = await processBatch(
            urls,
            async (url, _idx) => {
              if (url !== firstUrl) {
                // Navigate to new URL within same Chrome instance
              }
              return processOneArticle(cdp, sessionId, url, args);
            },
            { delayMs: BATCH_INTER_ARTICLE_DELAY_MS, log: console.log }
          );
    
          console.log(`\n--- Summary ---`);
          console.log(`Succeeded: ${result.succeeded.length}`);
          console.log(`Failed: ${result.failed.length}`);
          if (result.failed.length > 0) {
            console.log("\nFailed URLs:");
            for (const f of result.failed) {
              console.log(`  ${f.url}: ${f.error}`);
            }
          }
        });
      }
    }
    
    async function handleSearchMode(args: Args): Promise<void> {
      const accountName = args.search;
      const max = isFinite(args.maxArticles) ? args.maxArticles : 10;
      const searchUrl = `https://weixin.sogou.com/weixin?type=2&query=${encodeURIComponent(accountName)}&ie=utf8`;
    
      await mkdir(args.output, { recursive: true });
    
      // Launch Chrome directly with the search URL
      const port = await getFreePort();
      const chrome = await launchChrome(searchUrl, port, false);
    
      let cdp: CdpConnection | null = null;
      try {
        const wsUrl = await waitForChromeDebugPort(port, 30_000);
        cdp = await CdpConnection.connect(wsUrl, CDP_CONNECT_TIMEOUT_MS);
    
        // Wait a moment for Chrome to settle
        await sleep(2_000);
    
        const targets = await cdp.send<{ targetInfos: Array<{ targetId: string; type: string; url: string }> }>("Target.getTargets");
        const pageTarget = targets.targetInfos.find(t => t.type === "page");
        if (!pageTarget) throw new Error("No page target found");
    
        const { sessionId } = await cdp.send<{ sessionId: string }>(
          "Target.attachToTarget",
          { targetId: pageTarget.targetId, flatten: true }
        );
        await cdp.send("Network.enable", {}, { sessionId });
        await cdp.send("Page.enable", {}, { sessionId });
    
        // Wait for sogou search page to load
        console.log(`Searching for "${accountName}" on Sogou...`);
        await waitForNetworkIdle(cdp, sessionId, NETWORK_IDLE_TIMEOUT_MS);
        await sleep(2_000);
    
        // Extract article links from search results
        const articles = await searchAccountArticles(cdp, sessionId, accountName, max, console.log);
    
        if (articles.length === 0) {
          console.error(`No articles found for "${accountName}".`);
          process.exit(1);
        }
    
        if (args.listOnly) {
          console.log(`\n--- Articles from "${accountName}" ---`);
          for (let i = 0; i < articles.length; i++) {
            console.log(`${String(i + 1).padStart(3)}. ${articles[i].title}`);
            console.log(`     ${articles[i].url}`);
          }
          return;
        }
    
        console.log(`\nDownloading ${articles.length} articles to ${args.output}/`);
        const urls = articles.map(a => a.url);
    
        const result = await processBatch(
          urls,
          async (url, _idx) => processOneArticle(cdp!, sessionId, url, args),
          { delayMs: BATCH_INTER_ARTICLE_DELAY_MS, log: console.log }
        );
    
        console.log(`\n--- Summary ---`);
        console.log(`Succeeded: ${result.succeeded.length}`);
        console.log(`Failed: ${result.failed.length}`);
        if (result.failed.length > 0) {
          console.log("\nFailed URLs:");
          for (const f of result.failed) {
            console.log(`  ${f.url}: ${f.error}`);
          }
        }
      } finally {
        if (cdp) {
          try { await cdp.send("Browser.close", {}, { timeoutMs: 5_000 }); } catch {}
          cdp.close();
        }
        killChrome(chrome);
      }
    }
    
    async function handleAccountMode(args: Args): Promise<void> {
      const config = loadApiConfig();
      if (!config) {
        console.error("WeChat API credentials not found.");
        console.error("Set WECHAT_APP_ID and WECHAT_APP_SECRET in:");
        console.error("  - .wechat-article-downloader/.env (project level)");
        console.error("  - ~/.wechat-article-downloader/.env (user level)");
        console.error("  - Environment variables");
        process.exit(1);
      }
    
      console.log("Fetching article list from WeChat API...");
      const articles = await listPublishedArticles(config, { maxArticles: args.maxArticles });
      console.log(`Found ${articles.length} published articles.`);
    
      if (articles.length === 0) {
        console.log("No articles found.");
        return;
      }
    
      if (args.listOnly) {
        console.log("\n--- Article List ---");
        for (let i = 0; i < articles.length; i++) {
          const a = articles[i];
          const date = new Date(a.createTime * 1000).toISOString().split("T")[0];
          console.log(`${String(i + 1).padStart(3)}. [${date}] ${a.title}`);
          console.log(`     ${a.url}`);
        }
        return;
      }
    
      const urls = articles.map(a => a.url).filter(Boolean);
      if (urls.length === 0) {
        console.error("No downloadable article URLs found.");
        process.exit(1);
      }
    
      await mkdir(args.output, { recursive: true });
      console.log(`\nDownloading ${urls.length} articles to ${args.output}/`);
    
      await withChrome(urls[0], false, async (cdp, sessionId) => {
        const result = await processBatch(
          urls,
          async (url, _idx) => processOneArticle(cdp, sessionId, url, args),
          { delayMs: BATCH_INTER_ARTICLE_DELAY_MS, log: console.log }
        );
    
        console.log(`\n--- Summary ---`);
        console.log(`Succeeded: ${result.succeeded.length}`);
        console.log(`Failed: ${result.failed.length}`);
        if (result.failed.length > 0) {
          console.log("\nFailed URLs:");
          for (const f of result.failed) {
            console.log(`  ${f.url}: ${f.error}`);
          }
        }
      });
    }
    
    main().catch((err) => {
      console.error("Error:", err instanceof Error ? err.message : String(err));
      process.exit(1);
    });
    
  • scripts/paths.ts807 B90800694301cupstream ↗
    import os from "node:os";
    import path from "node:path";
    import process from "node:process";
    
    const APP_DATA_DIR = "wechat-article-downloader";
    const PROFILE_DIR_NAME = "chrome-profile";
    
    export function resolveUserDataRoot(): string {
      if (process.platform === "win32") {
        return process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming");
      }
      if (process.platform === "darwin") {
        return path.join(os.homedir(), "Library", "Application Support");
      }
      return process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share");
    }
    
    export function resolveWeChatChromeProfileDir(): string {
      const override = process.env.WECHAT_DL_CHROME_PROFILE_DIR?.trim();
      if (override) return path.resolve(override);
      return path.join(resolveUserDataRoot(), APP_DATA_DIR, PROFILE_DIR_NAME);
    }
    
  • scripts/types.ts552 B3dccb0597fceupstream ↗
    export interface WeChatArticleMeta {
      title: string;
      author: string;
      accountName: string;
      publishDate: string;
      sourceUrl: string;
      digest: string;
      coverImageUrl?: string;
    }
    
    export interface WeChatExtractionResult {
      meta: WeChatArticleMeta;
      contentHtml: string;
      imageUrls: string[];
    }
    
    export interface ArticleOutput {
      markdownPath: string;
      imageDir: string | null;
      imageCount: number;
      meta: WeChatArticleMeta;
    }
    
    export interface BatchResult {
      succeeded: ArticleOutput[];
      failed: Array<{ url: string; error: string }>;
    }
    
  • scripts/wechat-api.ts4.2 KBeda79545f0f4upstream ↗
    import fs from "node:fs";
    import path from "node:path";
    import process from "node:process";
    
    const TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    const FREEPUBLISH_URL = "https://api.weixin.qq.com/cgi-bin/freepublish/batchget";
    
    export interface WeChatApiConfig {
      appId: string;
      appSecret: string;
    }
    
    export interface PublishedArticle {
      title: string;
      author: string;
      digest: string;
      url: string;
      thumbUrl: string;
      createTime: number;
    }
    
    function loadEnvFile(envPath: string): Record<string, string> {
      const env: Record<string, string> = {};
      if (!fs.existsSync(envPath)) return env;
    
      const content = fs.readFileSync(envPath, "utf-8");
      for (const line of content.split("\n")) {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith("#")) continue;
        const eqIdx = trimmed.indexOf("=");
        if (eqIdx > 0) {
          const key = trimmed.slice(0, eqIdx).trim();
          let value = trimmed.slice(eqIdx + 1).trim();
          if ((value.startsWith('"') && value.endsWith('"')) ||
              (value.startsWith("'") && value.endsWith("'"))) {
            value = value.slice(1, -1);
          }
          env[key] = value;
        }
      }
      return env;
    }
    
    export function loadApiConfig(): WeChatApiConfig | null {
      // Priority: env vars → project .env → user .env
      const cwdEnv = loadEnvFile(path.join(process.cwd(), ".wechat-article-downloader", ".env"));
      const homeEnv = loadEnvFile(path.join(process.env.HOME || "", ".wechat-article-downloader", ".env"));
    
      const appId = process.env.WECHAT_APP_ID || cwdEnv.WECHAT_APP_ID || homeEnv.WECHAT_APP_ID;
      const appSecret = process.env.WECHAT_APP_SECRET || cwdEnv.WECHAT_APP_SECRET || homeEnv.WECHAT_APP_SECRET;
    
      if (!appId || !appSecret) return null;
      return { appId, appSecret };
    }
    
    async function getAccessToken(config: WeChatApiConfig): Promise<string> {
      const url = `${TOKEN_URL}?grant_type=client_credential&appid=${config.appId}&secret=${config.appSecret}`;
      const res = await fetch(url);
      const data = await res.json() as { access_token?: string; errcode?: number; errmsg?: string };
    
      if (data.errcode && data.errcode !== 0) {
        throw new Error(`WeChat API error ${data.errcode}: ${data.errmsg}`);
      }
      if (!data.access_token) {
        throw new Error("Failed to get access token");
      }
      return data.access_token;
    }
    
    export async function listPublishedArticles(
      config: WeChatApiConfig,
      options: { offset?: number; count?: number; maxArticles?: number } = {}
    ): Promise<PublishedArticle[]> {
      const accessToken = await getAccessToken(config);
      const maxArticles = options.maxArticles ?? Infinity;
      const pageSize = Math.min(options.count ?? 20, 20);
      let offset = options.offset ?? 0;
      const allArticles: PublishedArticle[] = [];
    
      while (allArticles.length < maxArticles) {
        const res = await fetch(`${FREEPUBLISH_URL}?access_token=${accessToken}`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ offset, count: pageSize, no_content: 1 }),
        });
    
        const data = await res.json() as {
          errcode?: number;
          errmsg?: string;
          total_count?: number;
          item_count?: number;
          item?: Array<{
            article_id: string;
            content: {
              news_item: Array<{
                title: string;
                author: string;
                digest: string;
                url: string;
                thumb_url: string;
              }>;
              create_time: number;
            };
          }>;
        };
    
        if (data.errcode && data.errcode !== 0) {
          throw new Error(`WeChat API error ${data.errcode}: ${data.errmsg}`);
        }
    
        const items = data.item ?? [];
        if (items.length === 0) break;
    
        for (const item of items) {
          for (const article of item.content.news_item) {
            allArticles.push({
              title: article.title,
              author: article.author,
              digest: article.digest,
              url: article.url,
              thumbUrl: article.thumb_url,
              createTime: item.content.create_time,
            });
            if (allArticles.length >= maxArticles) break;
          }
          if (allArticles.length >= maxArticles) break;
        }
    
        offset += items.length;
        if ((data.item_count ?? 0) < pageSize) break;
    
        // Rate limit: WeChat API allows ~20 calls/second
        await new Promise(r => setTimeout(r, 200));
      }
    
      return allArticles;
    }
    
  • scripts/wechat-extractor.ts3.6 KB86c9cb6d9d29upstream ↗
    import type { CdpConnection } from "./cdp.js";
    import { evaluateScript } from "./cdp.js";
    import type { WeChatArticleMeta, WeChatExtractionResult } from "./types.js";
    
    const wechatExtractScript = `
    (function() {
      var contentEl = document.querySelector('#js_content');
    
      // Materialize lazy images: WeChat uses data-src instead of src
      if (contentEl) {
        contentEl.querySelectorAll('img[data-src]').forEach(function(img) {
          if (!img.src || img.src === '' || img.src.startsWith('data:')) {
            img.src = img.getAttribute('data-src');
          }
        });
      }
    
      function getText(selector) {
        var el = document.querySelector(selector);
        return el ? el.textContent.trim() : '';
      }
    
      function getMeta(prop) {
        var el = document.querySelector('meta[property="' + prop + '"]')
              || document.querySelector('meta[name="' + prop + '"]');
        return el ? (el.getAttribute('content') || '').trim() : '';
      }
    
      var title = getText('#activity-name') || getMeta('og:title') || document.title || '';
      var author = getText('#js_name') || getMeta('author') || '';
      var publishTime = getText('#publish_time') || '';
      var digest = getMeta('og:description') || getMeta('description') || '';
      var coverUrl = getMeta('og:image') || '';
    
      // Collect image URLs
      var imageUrls = [];
      var seen = {};
      if (contentEl) {
        contentEl.querySelectorAll('img').forEach(function(img) {
          var url = img.getAttribute('data-src') || img.src || '';
          if (url && !url.startsWith('data:') && !seen[url]) {
            seen[url] = true;
            imageUrls.push(url);
          }
        });
      }
    
      // Clean content HTML
      if (contentEl) {
        contentEl.querySelectorAll('script, style, noscript').forEach(function(el) { el.remove(); });
        // Remove tracking pixels and invisible images
        contentEl.querySelectorAll('img[style*="visibility: hidden"], img[style*="display: none"], img[width="0"], img[height="0"]').forEach(function(el) { el.remove(); });
      }
    
      return {
        title: title,
        author: author,
        publishTime: publishTime,
        digest: digest,
        coverUrl: coverUrl,
        contentHtml: contentEl ? contentEl.innerHTML : '',
        imageUrls: imageUrls
      };
    })()
    `;
    
    const materializeLazyImagesScript = `
    (function() {
      var contentEl = document.querySelector('#js_content');
      if (contentEl) {
        contentEl.querySelectorAll('img[data-src]').forEach(function(img) {
          if (!img.src || img.src === '' || img.src.startsWith('data:')) {
            img.src = img.getAttribute('data-src');
          }
        });
      }
    })()
    `;
    
    interface RawExtraction {
      title: string;
      author: string;
      publishTime: string;
      digest: string;
      coverUrl: string;
      contentHtml: string;
      imageUrls: string[];
    }
    
    export async function materializeLazyImages(cdp: CdpConnection, sessionId: string): Promise<void> {
      await evaluateScript<void>(cdp, sessionId, materializeLazyImagesScript);
    }
    
    export async function extractWeChatArticle(
      cdp: CdpConnection,
      sessionId: string,
      sourceUrl: string,
      timeoutMs: number = 30_000
    ): Promise<WeChatExtractionResult> {
      // Second pass: materialize any remaining lazy images after scroll
      await materializeLazyImages(cdp, sessionId);
    
      const raw = await evaluateScript<RawExtraction>(cdp, sessionId, wechatExtractScript, timeoutMs);
    
      if (!raw.contentHtml && !raw.title) {
        throw new Error("Article not found or has been deleted. No content at #js_content.");
      }
    
      return {
        meta: {
          title: raw.title,
          author: raw.author,
          accountName: raw.author,
          publishDate: raw.publishTime,
          sourceUrl,
          digest: raw.digest,
          coverImageUrl: raw.coverUrl || undefined,
        },
        contentHtml: raw.contentHtml,
        imageUrls: raw.imageUrls,
      };
    }
    
  • scripts/wechat-search.ts4.7 KB5b68ac9e1a9fupstream ↗
    import type { CdpConnection } from "./cdp.js";
    import { evaluateScript } from "./cdp.js";
    
    /**
     * Extract WeChat article links from Sogou Weixin search results page.
     * Assumes the page is already loaded at weixin.sogou.com search results.
     */
    
    function sleep(ms: number): Promise<void> {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    
    // Extract article links from Sogou search results page (type=2, article search)
    const extractArticleLinksScript = `
    (function() {
      var links = [];
      var seen = {};
    
      // Method 1: Sogou article search result items (.news-list structure)
      var items = document.querySelectorAll('.news-list li, .news-box li, ul.news-list > li, .txt-box');
      items.forEach(function(item) {
        var a = item.querySelector('h3 a, a[href*="weixin.qq.com"]');
        if (a) {
          var href = a.href || a.getAttribute('href') || '';
          var title = (a.textContent || '').trim().replace(/\\s+/g, ' ');
          // Try to extract account name from the result item
          var accountEl = item.querySelector('.account, .s-p a, .s-p, .tit-s');
          var account = accountEl ? (accountEl.textContent || '').trim() : '';
          if (href && title && title.length > 2 && !seen[title]) {
            seen[title] = true;
            links.push({ url: href, title: title, account: account });
          }
        }
      });
    
      // Method 2: Broader fallback - any link containing mp.weixin.qq.com or sogou redirect
      if (links.length === 0) {
        document.querySelectorAll('a[href]').forEach(function(a) {
          var href = a.href || '';
          var title = (a.textContent || '').trim().replace(/\\s+/g, ' ');
          if (title.length > 4 && !seen[title]) {
            if (href.indexOf('mp.weixin.qq.com') !== -1 ||
                href.indexOf('weixin.sogou.com/link') !== -1) {
              seen[title] = true;
              links.push({ url: href, title: title, account: '' });
            }
          }
        });
      }
    
      // Method 3: Even broader - get all substantial links on the page
      if (links.length === 0) {
        document.querySelectorAll('a[href]').forEach(function(a) {
          var href = a.href || '';
          var title = (a.textContent || '').trim().replace(/\\s+/g, ' ');
          if (title.length > 8 && !seen[title] && href.indexOf('javascript:') === -1 && href.indexOf('#') !== 0) {
            seen[title] = true;
            links.push({ url: href, title: title, account: '' });
          }
        });
      }
    
      return links;
    })()
    `;
    
    // Debug: dump page info
    const debugPageScript = `
    (function() {
      return {
        url: location.href,
        title: document.title,
        linkCount: document.querySelectorAll('a').length,
        bodyLength: (document.body.textContent || '').length,
        hasNewsList: !!document.querySelector('.news-list'),
        hasResults: !!document.querySelector('.results'),
        sampleLinks: Array.from(document.querySelectorAll('a')).slice(0, 10).map(function(a) {
          return { href: (a.href || '').substring(0, 80), text: (a.textContent || '').trim().substring(0, 40) };
        })
      };
    })()
    `;
    
    export interface SearchResult {
      url: string;
      title: string;
      account?: string;
    }
    
    export async function searchAccountArticles(
      cdp: CdpConnection,
      sessionId: string,
      accountName: string,
      maxArticles: number = 5,
      log?: (msg: string) => void,
    ): Promise<SearchResult[]> {
      // Page should already be loaded at sogou search results
      // First, debug what we see on the page
      const debug = await evaluateScript<{
        url: string; title: string; linkCount: number; bodyLength: number;
        hasNewsList: boolean; hasResults: boolean;
        sampleLinks: Array<{ href: string; text: string }>;
      }>(cdp, sessionId, debugPageScript);
    
      log?.(`Page: ${debug.url}`);
      log?.(`Title: ${debug.title}`);
      log?.(`Links: ${debug.linkCount}, Body: ${debug.bodyLength} chars`);
    
      if (debug.bodyLength < 100) {
        log?.(`Page seems empty, waiting more...`);
        await sleep(3_000);
      }
    
      // Extract article links
      let articles = await evaluateScript<SearchResult[]>(cdp, sessionId, extractArticleLinksScript);
    
      // Filter out navigation/noise links
      articles = articles.filter(a =>
        a.title.length > 4 &&
        !a.title.includes("搜狗") &&
        !a.title.includes("登录") &&
        !a.title.includes("首页")
      );
    
      // If account name extracted, prefer articles from the matching account
      const accountMatched = articles.filter(a =>
        a.account && a.account.includes(accountName)
      );
    
      const finalArticles = accountMatched.length > 0 ? accountMatched : articles;
      const result = finalArticles.slice(0, maxArticles);
    
      log?.(`Found ${result.length} articles${accountMatched.length > 0 ? ` (matched account: ${accountName})` : ""}.`);
    
      if (result.length > 0) {
        for (let i = 0; i < result.length; i++) {
          const acctInfo = result[i].account ? ` [${result[i].account}]` : "";
          log?.(`  ${i + 1}. ${result[i].title}${acctInfo}`);
        }
      }
    
      return result;
    }
    
  • scripts/wechat-to-markdown.ts3.4 KB4de7d5f31909upstream ↗
    import TurndownService from "turndown";
    import { gfm } from "turndown-plugin-gfm";
    import type { WeChatArticleMeta } from "./types.js";
    
    function createTurndown(imageUrlMap?: Map<string, string>): TurndownService {
      const turndown = new TurndownService({
        headingStyle: "atx",
        hr: "---",
        bulletListMarker: "-",
        codeBlockStyle: "fenced",
        emDelimiter: "*",
        strongDelimiter: "**",
        linkStyle: "inlined",
      });
    
      turndown.use(gfm);
    
      // Remove noise elements
      turndown.remove(["script", "style", "iframe", "noscript", "template", "svg", "path"]);
    
      // WeChat image rule: prefer data-src, rewrite to local path if available
      turndown.addRule("wechatImage", {
        filter: "img",
        replacement(_content, node) {
          const el = node as HTMLElement;
          const src = el.getAttribute("data-src") || el.getAttribute("src") || "";
          if (!src || src.startsWith("data:")) return "";
          const alt = el.getAttribute("alt") || "";
          const finalUrl = imageUrlMap?.get(src) || src;
          return `\n\n![${alt}](${finalUrl})\n\n`;
        },
      });
    
      // Collapse figure elements
      turndown.addRule("collapseFigure", {
        filter: "figure",
        replacement(content) {
          return `\n\n${content.trim()}\n\n`;
        },
      });
    
      // Drop invisible anchors
      turndown.addRule("dropInvisibleAnchors", {
        filter(node) {
          return node.nodeName === "A" && !(node as Element).textContent?.trim();
        },
        replacement() {
          return "";
        },
      });
    
      // Handle WeChat mpvoice (audio) elements
      turndown.addRule("wechatAudio", {
        filter(node) {
          return node.nodeName === "MPVOICE" || (node.nodeName === "QQMUSIC");
        },
        replacement(_content, node) {
          const el = node as HTMLElement;
          const name = el.getAttribute("name") || el.getAttribute("voice_encode_fileid") || "audio";
          return `\n\n[Audio: ${name}]\n\n`;
        },
      });
    
      return turndown;
    }
    
    function normalizeMarkdown(markdown: string): string {
      return markdown
        .replace(/\r\n/g, "\n")
        .replace(/[ \t]+\n/g, "\n")
        .replace(/\n{3,}/g, "\n\n")
        .trim();
    }
    
    export function wechatHtmlToMarkdown(html: string, imageUrlMap?: Map<string, string>): string {
      if (!html || !html.trim()) return "";
    
      const turndown = createTurndown(imageUrlMap);
      try {
        const markdown = turndown.turndown(html);
        return normalizeMarkdown(markdown);
      } catch {
        return "";
      }
    }
    
    function escapeYaml(value: string): string {
      return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\\n");
    }
    
    export function formatFrontmatter(meta: WeChatArticleMeta): string {
      const lines = ["---"];
      lines.push(`title: "${escapeYaml(meta.title)}"`);
      if (meta.author) lines.push(`author: "${escapeYaml(meta.author)}"`);
      if (meta.accountName && meta.accountName !== meta.author) {
        lines.push(`account: "${escapeYaml(meta.accountName)}"`);
      }
      if (meta.publishDate) lines.push(`date: "${escapeYaml(meta.publishDate)}"`);
      lines.push(`source_url: "${meta.sourceUrl}"`);
      if (meta.digest) lines.push(`description: "${escapeYaml(meta.digest)}"`);
      if (meta.coverImageUrl) lines.push(`cover_image: "${meta.coverImageUrl}"`);
      lines.push(`captured_at: "${new Date().toISOString()}"`);
      lines.push("---");
      return lines.join("\n");
    }
    
    export function createMarkdownDocument(meta: WeChatArticleMeta, markdownBody: string): string {
      const frontmatter = formatFrontmatter(meta);
      const title = meta.title ? `\n\n# ${meta.title}\n\n` : "\n\n";
      return frontmatter + title + markdownBody + "\n";
    }
    
  • references/config/first-time-setup.md1.8 KB0f7906d6916cupstream ↗
    # First-Time Setup
    
    ## Prerequisites
    
    - **Bun** runtime — [bun.sh](https://bun.sh/) or via `npx -y bun`
    - **Google Chrome** or Chromium-based browser
    
    ## Quick Start
    
    No special setup is needed for basic usage. Just run with a WeChat article URL:
    
    ```bash
    bun scripts/main.ts "https://mp.weixin.qq.com/s/xxxx"
    ```
    
    ## Optional Configuration
    
    ### Custom Chrome Path
    
    If Chrome is not in a standard location:
    
    ```bash
    export WECHAT_DL_CHROME_PATH="/path/to/chrome"
    ```
    
    ### WeChat Official Account API (for `--account` mode)
    
    To download all articles from your own Official Account, you need API credentials:
    
    1. Log in to [WeChat Official Platform](https://mp.weixin.qq.com/)
    2. Go to **Settings** → **Developer** → **Basic Configuration**
    3. Get your `AppID` and `AppSecret`
    4. Store them securely:
    
    **Option A**: Environment variables
    ```bash
    export WECHAT_APP_ID=your_app_id
    export WECHAT_APP_SECRET=your_app_secret
    ```
    
    **Option B**: `.env` file (project-level)
    ```bash
    mkdir -p .wechat-article-downloader
    cat > .wechat-article-downloader/.env << 'EOF'
    WECHAT_APP_ID=your_app_id
    WECHAT_APP_SECRET=your_app_secret
    EOF
    ```
    
    **Option C**: `.env` file (user-level, shared across projects)
    ```bash
    mkdir -p ~/.wechat-article-downloader
    cat > ~/.wechat-article-downloader/.env << 'EOF'
    WECHAT_APP_ID=your_app_id
    WECHAT_APP_SECRET=your_app_secret
    EOF
    ```
    
    > **Security**: Never commit `.env` files to git. The `.gitignore` already excludes `*.env`.
    
    ### EXTEND.md Preferences
    
    Create an `EXTEND.md` to customize default behavior:
    
    ```bash
    mkdir -p ~/.wechat-article-downloader
    cat > ~/.wechat-article-downloader/EXTEND.md << 'EOF'
    # Preferences
    
    - default_output: ./wechat-articles
    - download_images: true
    - timeout: 30000
    - max_scroll_steps: 15
    EOF
    ```
    
    See `preferences-schema.md` for all available options.
    
  • references/config/preferences-schema.md1.3 KBb01bd402a753upstream ↗
    # EXTEND.md Preferences Schema
    
    ## Overview
    
    EXTEND.md allows users to customize default behavior without modifying the skill source.
    
    **Lookup order**:
    1. `.wechat-article-downloader/EXTEND.md` (project directory)
    2. `~/.wechat-article-downloader/EXTEND.md` (user home)
    
    CLI arguments always override EXTEND.md settings.
    
    ## Available Options
    
    | Key | Type | Default | Description |
    |-----|------|---------|-------------|
    | `default_output` | string | `./wechat-articles` | Default output directory |
    | `download_images` | boolean | `true` | Download images locally (`false` keeps remote URLs) |
    | `timeout` | number | `30000` | Page load timeout in milliseconds |
    | `max_scroll_steps` | number | `15` | Max scroll steps for lazy image loading |
    | `scroll_wait_ms` | number | `800` | Wait time between scroll steps |
    | `batch_delay_ms` | number | `2000` | Delay between articles in batch mode |
    | `image_concurrency` | number | `3` | Max parallel image downloads |
    
    ## Example EXTEND.md
    
    ```markdown
    # Preferences
    
    - default_output: ./my-wechat-articles
    - download_images: true
    - timeout: 45000
    - max_scroll_steps: 20
    ```
    
    ## Notes
    
    - Keys are case-insensitive
    - Boolean values: `true`/`false`, `yes`/`no`
    - Lines starting with `#` are comments
    - Unknown keys are silently ignored
    
  • .gitignore332 B4b350a162a87upstream ↗
    # Dependencies
    node_modules/
    
    # Environment / Secrets
    *.env
    .env.*
    !.env.example
    
    # User preferences (local customizations)
    .wechat-article-downloader/
    
    # Output directories
    wechat-articles/
    
    # Chrome profile (local only)
    chrome-profile/
    
    # OS files
    .DS_Store
    Thumbs.db
    
    # IDE
    .idea/
    *.iml
    .vscode/
    
    # Build artifacts
    *.tsbuildinfo
    
  • bun.lock782 B5cbe2d666ee3upstream ↗
    {
      "lockfileVersion": 1,
      "configVersion": 1,
      "workspaces": {
        "": {
          "name": "wechat-article-downloader",
          "dependencies": {
            "turndown": "^7.2.0",
            "turndown-plugin-gfm": "^1.0.2",
          },
        },
      },
      "packages": {
        "@mixmark-io/domino": ["@mixmark-io/[email protected]", "", {}, "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw=="],
    
        "turndown": ["[email protected]", "", { "dependencies": { "@mixmark-io/domino": "^2.2.0" } }, "sha512-1F7db8BiExOKxjSMU2b7if62D/XOyQyZbPKq/nUwopfgnHlqXHqQ0lvfUTeUIr1lZJzOPFn43dODyMSIfvWRKQ=="],
    
        "turndown-plugin-gfm": ["[email protected]", "", {}, "sha512-vwz9tfvF7XN/jE0dGoBei3FXWuvll78ohzCZQuOb+ZjWrs3a0XhQVomJEb2Qh4VHTPNRO4GPZh0V7VRbiWwkRg=="],
      }
    }
    
  • CHANGELOG.md1.4 KB43dae327289aupstream ↗
    # Changelog
    
    ## 0.2.0 - 2026-03-08
    
    ### Features
    - Add `--search` mode: find and download articles from any public account via Sogou Weixin Search
    - Add bilingual documentation (README.md + README.zh.md)
    - Add `references/` directory with configuration docs and preferences schema
    - Add CHANGELOG.md / CHANGELOG.zh.md
    
    ### Refactor
    - Remove `baoyu-skills` dependency — fully standalone skill
    - Update SKILL.md to follow baoyu-skills conventions (`${SKILL_DIR}`, `${BUN_X}`, EXTEND.md pattern)
    - Improve .gitignore with comprehensive patterns
    - Update config path: `.baoyu-skills/` → `.wechat-article-downloader/`
    
    ### Fixes
    - Fix `--account` flag not being parsed in CLI args
    - Fix CDP session error when using search mode (launch Chrome with target URL directly)
    
    ## 0.1.0 - 2026-03-07
    
    ### Features
    - Initial release
    - Single article download via Chrome CDP
    - Batch download from URL list file
    - Account-wide download via WeChat Official Platform API
    - WeChat-specific extraction: `#js_content`, `data-src` lazy images, metadata
    - Local image download with URL rewriting to relative paths
    - YAML frontmatter generation (title, author, date, source_url, description)
    - HTML to Markdown conversion with Turndown + GFM plugin
    - WeChat-specific Turndown rules (data-src preference, mpvoice/audio handling)
    - Wait mode for login-required articles
    - Cross-platform Chrome detection (macOS, Windows, Linux)
    
  • CHANGELOG.zh.md1.3 KBf58f89f0d805upstream ↗
    # 更新日志
    
    ## 0.2.0 - 2026-03-08
    
    ### 新功能
    - 新增 `--search` 模式:通过搜狗微信搜索按公众号名查找并下载文章
    - 新增中英双语文档(README.md + README.zh.md)
    - 新增 `references/` 目录,包含配置文档和偏好设置模式
    - 新增 CHANGELOG.md / CHANGELOG.zh.md
    
    ### 重构
    - 移除 `baoyu-skills` 依赖 — 完全独立运行
    - 更新 SKILL.md 遵循 baoyu-skills 规范(`${SKILL_DIR}`、`${BUN_X}`、EXTEND.md 模式)
    - 改进 .gitignore
    - 更新配置路径:`.baoyu-skills/` → `.wechat-article-downloader/`
    
    ### 修复
    - 修复 `--account` 标志未被正确解析的问题
    - 修复搜索模式下 CDP 会话错误(改为直接以目标 URL 启动 Chrome)
    
    ## 0.1.0 - 2026-03-07
    
    ### 新功能
    - 首次发布
    - 通过 Chrome CDP 下载单篇文章
    - 从 URL 列表文件批量下载
    - 通过微信公众平台 API 下载整个账号文章
    - 微信专属提取:`#js_content`、`data-src` 懒加载图片、元数据
    - 本地图片下载,URL 自动重写为相对路径
    - YAML 元数据生成(标题、作者、日期、来源 URL、摘要)
    - HTML 转 Markdown(Turndown + GFM 插件)
    - 微信专属 Turndown 规则(data-src 优先、mpvoice/audio 处理)
    - 等待模式(用于需要登录的文章)
    - 跨平台 Chrome 检测(macOS、Windows、Linux)
    
  • LICENSE1.1 KB1a2a6e8f3cf6upstream ↗
    MIT License
    
    Copyright (c) 2026 Harmless Acceleration
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
    
  • package.json917 B9df879832fbfupstream ↗
    {
      "name": "wechat-article-downloader",
      "version": "0.2.0",
      "description": "Download WeChat Official Account articles to Markdown with local images. Chrome CDP + Sogou Search + WeChat API. Claude Code skill.",
      "author": "Harmless Acceleration <[email protected]>",
      "license": "MIT",
      "repository": {
        "type": "git",
        "url": "https://github.com/acchaacc/wechat-article-downloader"
      },
      "homepage": "https://github.com/acchaacc/wechat-article-downloader",
      "bugs": {
        "url": "https://github.com/acchaacc/wechat-article-downloader/issues"
      },
      "keywords": [
        "wechat",
        "weixin",
        "official-account",
        "article-downloader",
        "markdown",
        "chrome-cdp",
        "sogou-search",
        "wechat-api",
        "claude-code-skill"
      ],
      "scripts": {
        "start": "bun scripts/main.ts"
      },
      "dependencies": {
        "turndown": "^7.2.0",
        "turndown-plugin-gfm": "^1.0.2"
      }
    }
    
  • README.en.md6.5 KBf83b1c3505dbupstream ↗
    # 📰 WeChat Article Downloader
    
    > Download WeChat Official Account (微信公众号) articles to clean Markdown with locally saved images.
    
    [中文](./README.md)
    
    Built as a [Claude Code](https://docs.anthropic.com/en/docs/claude-code) skill — works standalone via CLI or as a 🤖 AI Agent skill.
    
    ## ✨ Features
    
    - 🌐 **Chrome CDP rendering** — Full JavaScript execution, handles lazy-loaded images
    - 📦 **Four download modes** — Single URL / batch file / search by account name / bulk API download
    - 📝 **Markdown output** — YAML frontmatter (title, author, date, source) + clean body
    - 🖼️ **Local images** — Downloads all article images, rewrites URLs to local paths
    - 🔧 **WeChat-specific** — Handles `data-src` lazy loading, `mmbiz.qpic.cn` images, `#js_content` extraction
    - ⚙️ **Configurable** — EXTEND.md preferences, environment variables, CLI options
    
    ## 📋 Prerequisites
    
    - [Bun](https://bun.sh/) runtime (or Node.js with `npx -y bun`)
    - Google Chrome or Chromium
    
    ## 🚀 Quick Start
    
    ### Install dependencies
    
    ```bash
    bun install
    ```
    
    ### Download a single article
    
    ```bash
    bun scripts/main.ts "https://mp.weixin.qq.com/s/YOUR_ARTICLE_ID"
    ```
    
    ### Download with custom output directory
    
    ```bash
    bun scripts/main.ts "https://mp.weixin.qq.com/s/xxxx" -o ./articles/
    ```
    
    ### 🔍 Search and download by account name
    
    ```bash
    # Download latest 5 articles from an account
    bun scripts/main.ts --search "公众号名称" --max 5
    
    # List articles only (no download)
    bun scripts/main.ts --search "公众号名称" --list
    ```
    
    ### 📑 Batch download from URL list
    
    Create a `urls.txt` file (one URL per line, `#` for comments):
    
    ```bash
    bun scripts/main.ts urls.txt -o ./backup/
    ```
    
    ### 🔑 Download all articles from your own account
    
    Requires WeChat Official Account API credentials:
    
    ```bash
    # Set credentials
    export WECHAT_APP_ID=your_app_id
    export WECHAT_APP_SECRET=your_app_secret
    
    # List all articles
    bun scripts/main.ts --account --list
    
    # Download all
    bun scripts/main.ts --account -o ./my-articles/
    
    # Download latest 20
    bun scripts/main.ts --account --max 20
    ```
    
    Or store credentials in `.wechat-article-downloader/.env`:
    
    ```env
    WECHAT_APP_ID=your_app_id
    WECHAT_APP_SECRET=your_app_secret
    ```
    
    ## 📖 CLI Options
    
    | Option | Description |
    |--------|-------------|
    | `<url>` | Single WeChat article URL |
    | `<file.txt>` | Batch file with URLs |
    | `--search, -s <name>` | 🔍 Search & download articles by account name |
    | `--account` | 🔑 Download from your own Official Account via API |
    | `-o, --output <dir>` | 📂 Output directory (default: `./wechat-articles/`) |
    | `--no-images` | 🚫 Skip image download, keep remote URLs |
    | `--wait` | ⏳ Wait mode: log in manually, press Enter to capture |
    | `--timeout <ms>` | ⏱️ Page load timeout (default: 30000) |
    | `--list` | 📋 List articles only, don't download |
    | `--max, -n <num>` | 🔢 Max articles to download |
    
    ## 🔄 Download Modes
    
    | Mode | Trigger | Description |
    |------|---------|-------------|
    | 📄 **Single URL** | Pass a `mp.weixin.qq.com` URL | Download one article via CDP |
    | 📑 **Batch file** | Pass a `.txt` file path | Download all URLs in file sequentially |
    | 🔍 **Search** | `--search "name"` | Find articles via Sogou Weixin Search, then download |
    | 🔑 **Account** | `--account` flag | List + download all via WeChat Official Platform API |
    | ⏳ **Wait** | `--wait` flag | Open Chrome, user logs in, press Enter |
    
    ## 📂 Output Format
    
    ```
    wechat-articles/
      📄 article-title.md          ← Markdown with YAML frontmatter
      📁 article-title/
          📁 imgs/
              🖼️ 001.jpg            ← Downloaded images
              🖼️ 002.png
    ```
    
    Each `.md` file includes:
    
    ```yaml
    ---
    title: "Article Title"
    author: "Author Name"
    date: "2024-01-15"
    source_url: "https://mp.weixin.qq.com/s/xxxx"
    description: "Article summary..."
    captured_at: "2024-01-15T12:00:00.000Z"
    ---
    
    # Article Title
    
    Article content in Markdown...
    
    ![](imgs/001.jpg)
    ```
    
    ## 🤖 Claude Code Skill
    
    ### Install
    
    ```bash
    # Clone to your skills directory
    git clone https://github.com/acchaacc/wechat-article-downloader ~/.claude/skills/wechat-article-downloader
    
    # Or symlink from an existing clone
    ln -s /path/to/wechat-article-downloader ~/.claude/skills/wechat-article-downloader
    ```
    
    ### Trigger keywords
    
    In Claude Code, say:
    
    - 💬 "下载这篇公众号文章 https://mp.weixin.qq.com/s/xxxx"
    - 💬 "保存公众号文章到 Markdown"
    - 💬 "搜索并下载无害加速最近的文章"
    - 💬 "Download this WeChat article"
    - 💬 "Batch download all articles from an account"
    
    ## ⚙️ Configuration
    
    ### EXTEND.md Preferences
    
    Customize defaults via `EXTEND.md` (no source code changes needed):
    
    ```markdown
    # Preferences
    - default_output: ./my-wechat-articles
    - download_images: true
    - timeout: 45000
    ```
    
    **Lookup order**: `.wechat-article-downloader/EXTEND.md` → `~/.wechat-article-downloader/EXTEND.md`
    
    See [preferences schema](./references/config/preferences-schema.md) for all options.
    
    ### Environment Variables
    
    | Variable | Description |
    |----------|-------------|
    | `WECHAT_DL_CHROME_PATH` | Custom Chrome executable path |
    | `WECHAT_DL_CHROME_PROFILE_DIR` | Custom Chrome profile directory |
    | `WECHAT_APP_ID` | WeChat Official Account App ID |
    | `WECHAT_APP_SECRET` | WeChat Official Account App Secret |
    
    ## 🔧 How It Works
    
    ```
    URL → 🌐 Chrome CDP → 📄 Navigate → ⬇️ Scroll (lazy load)
        → 🔍 Extract metadata + HTML → 🖼️ Download images → 📝 Convert to Markdown → 💾 Write file
    ```
    
    1. Launch Chrome via DevTools Protocol
    2. Navigate to the WeChat article URL
    3. Auto-scroll to trigger lazy image loading (`data-src` → `src`)
    4. Extract content and metadata from `#js_content`
    5. Download images from `mmbiz.qpic.cn` with proper Referer headers
    6. Convert HTML to Markdown using Turndown with WeChat-specific rules
    7. Write `.md` file with YAML frontmatter and local image references
    
    ## ❓ Troubleshooting
    
    | Problem | Solution |
    |---------|----------|
    | 🚫 Chrome not found | Install Chrome or set `WECHAT_DL_CHROME_PATH` |
    | ⏱️ Timeout | Increase `--timeout` value |
    | 🔐 Login required | Use `--wait` mode |
    | ❌ API errors | Check `WECHAT_APP_ID` and `WECHAT_APP_SECRET` |
    | 🖼️ Images not loading | Page may need more scroll time |
    | 🗑️ Article deleted | The article has been removed by the author |
    | 🤖 Sogou captcha | Try again later or use direct URLs |
    
    ## 📄 License
    
    [MIT](./LICENSE)
    
    ---
    
    Made with ❤️ by [Harmless Acceleration](https://github.com/acchaacc)
    

Plain-text copy, no login: /skill-bundles/wechat-article-downloader.md

// REPO STATS

2 stars
0 open issues
Last commit: 8mo ago