@sovovs/bycli 2.1.11 → 2.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ import crawler from '@sovovs/wechat-article-crawler';
2
+ import { ArgumentError, AuthRequiredError, CommandExecutionError } from '@sovovs/bycli/errors';
3
+
4
+ const {
5
+ CrawlerError,
6
+ collectArticles,
7
+ createWechatApi,
8
+ isTrustedWechatArticleUrl,
9
+ saveArticles,
10
+ } = crawler;
11
+
12
+ export {
13
+ CrawlerError,
14
+ collectArticles,
15
+ createWechatApi,
16
+ isTrustedWechatArticleUrl,
17
+ saveArticles,
18
+ };
19
+
20
+ export async function callCrawler(operation) {
21
+ try {
22
+ return await operation();
23
+ } catch (error) {
24
+ if (!(error instanceof CrawlerError)) throw error;
25
+
26
+ if (error.code === 'INVALID_ARGUMENT') {
27
+ throw new ArgumentError(error.message);
28
+ }
29
+ if (error.code === 'AUTH_REQUIRED') {
30
+ throw new AuthRequiredError('mp.weixin.qq.com', error.message);
31
+ }
32
+ throw new CommandExecutionError(error.message);
33
+ }
34
+ }
@@ -1,8 +1,7 @@
1
1
  import { ArgumentError, EmptyResultError } from '@sovovs/bycli/errors';
2
2
  import { cli, Strategy } from '@sovovs/bycli/registry';
3
3
  import { readEnvironmentCredentials, resolveBrowserCredentials } from './_wechat/auth-session.js';
4
- import { collectArticles } from './_wechat/article-service.js';
5
- import { createWechatApi } from './_wechat/wechat-api.js';
4
+ import { callCrawler, collectArticles, createWechatApi } from './_wechat/crawler-runtime.js';
6
5
  import { readAuthSource } from './_wechat/args.js';
7
6
 
8
7
  const DOMAIN = 'mp.weixin.qq.com';
@@ -24,8 +23,10 @@ export const articlesCommand = cli({
24
23
  const authSource = readAuthSource(args);
25
24
  const credentials = authSource === 'env'
26
25
  ? readEnvironmentCredentials(false) : await resolveBrowserCredentials(page);
27
- const { fetchPage } = createWechatApi(credentials);
28
- const { articles } = await collectArticles({ fakeid, fetchPage, limit: args.limit, maxPages: args['max-pages'] });
26
+ const { articles } = await callCrawler(async () => {
27
+ const { fetchPage } = createWechatApi(credentials);
28
+ return collectArticles({ fakeid, fetchPage, limit: args.limit, maxPages: args['max-pages'] });
29
+ });
29
30
  if (articles.length === 0) throw new EmptyResultError('weixin articles', `No published articles were found for ${fakeid}.`);
30
31
  return articles.map(article => ({
31
32
  title: article.title, author: article.author || null, digest: article.digest || null,
@@ -2,10 +2,11 @@ import { ArgumentError, AuthRequiredError, CommandExecutionError } from '@sovovs
2
2
  import { MAX_WECHAT_HTML_BYTES } from '@sovovs/bycli/download/wechat-article';
3
3
  import { cli, Strategy } from '@sovovs/bycli/registry';
4
4
  import { readEnvironmentCredentials, resolveBrowserCredentials } from './_wechat/auth-session.js';
5
- import { collectArticles, isTrustedWechatArticleUrl } from './_wechat/article-service.js';
6
- import { saveArticles } from './_wechat/save-service.js';
7
- import { createWechatApi } from './_wechat/wechat-api.js';
5
+ import {
6
+ callCrawler, collectArticles, createWechatApi, isTrustedWechatArticleUrl, saveArticles,
7
+ } from './_wechat/crawler-runtime.js';
8
8
  import { readAuthSource } from './_wechat/args.js';
9
+ import { wechatArticleToMarkdown } from './_wechat/markdown.js';
9
10
 
10
11
  const DOMAIN = 'mp.weixin.qq.com';
11
12
  const browserRequired = args => readAuthSource(args) === 'browser';
@@ -165,12 +166,18 @@ export const saveArticlesCommand = cli({
165
166
  const authSource = readAuthSource(args);
166
167
  const credentials = authSource === 'env'
167
168
  ? readEnvironmentCredentials(false) : await resolveBrowserCredentials(page);
168
- const { fetchPage } = createWechatApi(credentials);
169
- const { articles } = await collectArticles({ fakeid, fetchPage, limit: args.limit, maxPages: args['max-pages'] });
170
169
  const articleHtmlDownloader = createArticleHtmlDownloader({ authSource, page });
171
- const rows = await saveArticles({
172
- articles, accountName: String(args.name ?? '').trim(),
173
- outputDir: args.output ?? './weixin-articles', fetchArticleHtml: articleHtmlDownloader,
170
+ const rows = await callCrawler(async () => {
171
+ const { fetchPage } = createWechatApi(credentials);
172
+ const { articles } = await collectArticles({ fakeid, fetchPage, limit: args.limit, maxPages: args['max-pages'] });
173
+ return saveArticles({
174
+ articles, accountName: String(args.name ?? '').trim(),
175
+ outputDir: args.output ?? './weixin-articles', fetchArticleHtml: articleHtmlDownloader,
176
+ buildMarkdown: (article, html) => wechatArticleToMarkdown({
177
+ html, title: article.title, accountName: String(args.name ?? '').trim(), author: article.author,
178
+ publishedAt: article.publishedAt, digest: article.digest, url: article.url,
179
+ }), existingFilePolicy: 'suffix',
180
+ });
174
181
  });
175
182
  return rows.map(row => ({
176
183
  title: row.title, status: row.status, stage: row.stage || null, path: row.saved || null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sovovs/bycli",
3
- "version": "2.1.11",
3
+ "version": "2.1.12",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -90,6 +90,7 @@
90
90
  "dependencies": {
91
91
  "@mozilla/readability": "^0.6.0",
92
92
  "@sovovs/bycli-recorder-core": "^0.1.0",
93
+ "@sovovs/wechat-article-crawler": "^1.1.0",
93
94
  "cli-table3": "^0.6.5",
94
95
  "commander": "^14.0.3",
95
96
  "js-yaml": "^4.1.0",
@@ -3,6 +3,7 @@ import { execFileSync } from 'node:child_process';
3
3
  import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { dirname, join, resolve } from 'node:path';
6
+ import { createRequire } from 'node:module';
6
7
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
8
 
8
9
  const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -58,8 +59,24 @@ try {
58
59
  project, 'node_modules/@sovovs/bycli/package.json',
59
60
  ), 'utf8'));
60
61
  assert.equal(mainManifest.dependencies?.['@sovovs/bycli-recorder-core'], '^0.1.0');
62
+ assert.equal(mainManifest.dependencies?.['@sovovs/wechat-article-crawler'], '^1.1.0');
61
63
 
62
64
  const coreDirectory = join(project, 'node_modules/@sovovs/bycli-recorder-core');
65
+ const crawlerDirectoryInstalled = join(project, 'node_modules/@sovovs/wechat-article-crawler');
66
+ const crawlerManifest = JSON.parse(readFileSync(
67
+ join(crawlerDirectoryInstalled, 'package.json'), 'utf8',
68
+ ));
69
+ assert.equal(crawlerManifest.version, '1.1.2');
70
+ const projectRequire = createRequire(join(project, 'package.json'));
71
+ const crawlerEntry = projectRequire.resolve('@sovovs/wechat-article-crawler');
72
+ const crawlerModule = await import(pathToFileURL(crawlerEntry).href);
73
+ const crawlerApi = crawlerModule.default ?? crawlerModule;
74
+ for (const name of [
75
+ 'CrawlerError', 'createWechatApi', 'collectArticles',
76
+ 'isTrustedWechatArticleUrl', 'saveArticles',
77
+ ]) {
78
+ assert.ok(crawlerApi[name], `crawler root API missing ${name}`);
79
+ }
63
80
  const recorderEntry = join(
64
81
  project, 'node_modules/@sovovs/bycli/dist/src/browser/analyze.js',
65
82
  );
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env bash
2
+ # 录制三端管理脚本
3
+ # daemon : 浏览器底座(19825),由 bycli 管理;扩展连这口
4
+ # be : Recorder Local Service(19826),同源托管真实工作台 UI(dashboard/dist)
5
+ # web : Umi dev server(8000),mock 模式,仅前端开发用(无真实录制)
6
+ #
7
+ # 用法:
8
+ # scripts/recorder.sh start [daemon|be|all] # 默认=真实录制环境(daemon+be,自动停 mock)
9
+ # scripts/recorder.sh start --mock # 仅此参数才起 mock 前端(web :8000,假数据)
10
+ # scripts/recorder.sh stop [daemon|be|web|all]
11
+ # scripts/recorder.sh restart [daemon|be|vnc|all] # restart all=daemon+be(不含 mock);改了 .env/dist 后用;vnc=删旧容器换新镜像
12
+ # scripts/recorder.sh status # 看三端
13
+ # scripts/recorder.sh build [core|be|ui|ext|all] # 重建 dist(改源码后;all 含扩展,需手动重载)
14
+ #
15
+ # 真实录制(带 LLM)启动:scripts/recorder.sh start → 打开 http://127.0.0.1:19826/workbench
16
+ #
17
+ # embedded_iframe 录制模式(P2,公开站页内嵌入;**本机默认开**):起 be 默认带 flag——
18
+ # EMBEDDED=0 scripts/recorder.sh start # 显式关闭页内嵌入模式
19
+ # IFRAME_FRAME_SRC=https://juejin.cn scripts/recorder.sh restart be # 只放该 origin(hardened)
20
+ # inline env 经 `env VAR=…` 注入,优先级高于 --env-file(.env 不覆盖已存在的 process env)。
21
+ #
22
+ # vnc 录制模式(容器内 Chromium+扩展+daemon,noVNC 投画面;**本机默认开**,需 podman + 镜像):
23
+ # scripts/recorder.sh build vnc # 构建容器镜像 bycli-verify:latest(需先 build ext + npm run build)
24
+ # scripts/recorder.sh restart vnc # 重启镜像:删旧容器(bycli-vnc),be 下次 bind 用新镜像重建(改镜像后用)
25
+ # VNC=0 scripts/recorder.sh restart be # 显式关闭 vnc 模式
26
+ # 选 VNC 模式后 be 自动 podman run 起容器、前端 iframe 投 noVNC 画面;录的数据走容器网关→be→合成链。
27
+ set -uo pipefail
28
+
29
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
30
+ RUN="$ROOT/.recorder-run"; mkdir -p "$RUN"
31
+ DAEMON_PORT=19825; BE_PORT=19826; WEB_PORT=8000
32
+
33
+ port_pid() { lsof -ti "tcp:$1" -sTCP:LISTEN 2>/dev/null | head -1; }
34
+ alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; }
35
+
36
+ # ───────────────────────── daemon(交给 bycli 管) ─────────────────────────
37
+ need_bycli() { command -v bycli >/dev/null || { echo "✗ bycli 不在 PATH(在仓库根 npm link)"; return 1; }; }
38
+ daemon_start() { need_bycli || return 1; bycli daemon start 2>&1 | tail -1; }
39
+ daemon_stop() { need_bycli && { bycli daemon stop 2>&1 | tail -1; } || true; }
40
+ daemon_restart() { need_bycli || return 1; bycli daemon restart 2>&1 | tail -1; }
41
+ daemon_status() { local p; p="$(port_pid $DAEMON_PORT)"; [ -n "$p" ] && echo "● daemon RUNNING :$DAEMON_PORT pid=$p" || echo "○ daemon stopped :$DAEMON_PORT"; }
42
+
43
+ # ───────────────────────── vnc(podman 容器,be 自动编排) ────────────────
44
+ # 容器名与 vncOrchestrator.ts 保持一致(BYCLI_VNC_CONTAINER 覆盖,默认 bycli-vnc)。
45
+ VNC_CONTAINER="${BYCLI_VNC_CONTAINER:-bycli-vnc}"
46
+ VNC_IMAGE="${BYCLI_VNC_IMAGE:-bycli-verify:latest}"
47
+ need_podman() { command -v podman >/dev/null || { echo "✗ podman 不在 PATH(VNC 模式需 podman)"; return 1; }; }
48
+ # 重启镜像:删旧容器,be 下次 bind 时用当前镜像重建(build vnc 换镜像后调用)。
49
+ vnc_restart() {
50
+ need_podman || return 1
51
+ [ -n "$(podman images -q "$VNC_IMAGE" 2>/dev/null)" ] || { echo "✗ 镜像 $VNC_IMAGE 不存在 → scripts/recorder.sh build vnc"; return 1; }
52
+ if [ -n "$(podman ps -aq -f "name=^${VNC_CONTAINER}$" 2>/dev/null)" ]; then
53
+ podman rm -f "$VNC_CONTAINER" >/dev/null 2>&1 && echo "✓ 已删旧容器 $VNC_CONTAINER(be 下次 bind 用新镜像 $VNC_IMAGE 重建)"
54
+ else
55
+ echo "○ 容器 $VNC_CONTAINER 未运行(be 下次 bind 会用新镜像 $VNC_IMAGE 新建)"
56
+ fi
57
+ }
58
+ vnc_stop() {
59
+ need_podman || return 1
60
+ if [ -n "$(podman ps -aq -f "name=^${VNC_CONTAINER}$" 2>/dev/null)" ]; then
61
+ podman rm -f "$VNC_CONTAINER" >/dev/null 2>&1 && echo "✓ vnc 容器 $VNC_CONTAINER 已删"
62
+ else echo "○ vnc 容器未运行"; fi
63
+ }
64
+ vnc_status() {
65
+ command -v podman >/dev/null || { echo "○ vnc (podman 未装)"; return; }
66
+ local st; st="$(podman inspect "$VNC_CONTAINER" --format '{{.State.Status}}' 2>/dev/null)"
67
+ [ -n "$st" ] && echo "● vnc $st container=$VNC_CONTAINER image=$VNC_IMAGE" || echo "○ vnc no container ($VNC_CONTAINER)"
68
+ }
69
+
70
+ # ───────────────────────── be(node 进程,PID 文件) ──────────────────────
71
+ be_start() {
72
+ [ -f "$ROOT/dashboard-be/dist/server.js" ] || { echo "✗ be 未构建 → scripts/recorder.sh build be"; return 1; }
73
+ [ -f "$ROOT/dashboard-be/.env" ] || { echo "✗ 缺 dashboard-be/.env → cp dashboard-be/.env.example dashboard-be/.env 并填值"; return 1; }
74
+ [ -d "$ROOT/dashboard/dist" ] || echo "⚠ dashboard/dist 不存在,be 将 API-only(无 UI)→ scripts/recorder.sh build ui"
75
+ if [ -n "$(port_pid $BE_PORT)" ]; then echo "● be 已在 :$BE_PORT(先 stop/restart)"; return 0; fi
76
+ # embedded_iframe 模式(P2):EMBEDDED=1 → 注入 flag 开 frame-src + 前端模式选项。
77
+ # 经 `env VAR=…` 内联注入,优先级高于 --env-file(.env 不覆盖已存在的 process env)。
78
+ # 三种录制模式默认全开(本机录制工作台);显式 EMBEDDED=0 / VNC=0 可单独关。
79
+ # 注:只在本机 be 启动注入,不动 recorder-core 的 fail-closed 发布默认(全局 CSP 安全底线不变)。
80
+ local envv=()
81
+ if [ "${EMBEDDED:-1}" = 1 ]; then
82
+ envv+=(FEATURE_EMBEDDED_IFRAME_RECORDING=1)
83
+ [ -n "${IFRAME_FRAME_SRC:-}" ] && envv+=("RECORDER_IFRAME_FRAME_SRC=$IFRAME_FRAME_SRC")
84
+ echo " ⚙ embedded_iframe 模式 ON${IFRAME_FRAME_SRC:+(frame-src=$IFRAME_FRAME_SRC)}"
85
+ fi
86
+ if [ "${VNC:-1}" = 1 ]; then
87
+ envv+=(FEATURE_VNC_RECORDING=1)
88
+ echo " ⚙ vnc 容器模式 ON(be 自动 podman run bycli-verify:latest;需先 build vnc)"
89
+ fi
90
+ ( cd "$ROOT" && nohup env ${envv[@]+"${envv[@]}"} node --env-file=dashboard-be/.env dashboard-be/dist/server.js >"$RUN/be.log" 2>&1 & echo $! >"$RUN/be.pid" )
91
+ sleep 1; be_status; echo " 日志: $RUN/be.log"
92
+ }
93
+ be_stop() {
94
+ # 端口权威:pid 文件 + 实际占 19826 的进程都杀(防重复实例残留)
95
+ local stopped=0 pf; pf="$(cat "$RUN/be.pid" 2>/dev/null)"
96
+ for pid in "$pf" "$(port_pid $BE_PORT)"; do
97
+ if alive "$pid"; then kill "$pid" 2>/dev/null; echo "✓ be 已停(pid=$pid)"; stopped=1; fi
98
+ done
99
+ [ "$stopped" = 0 ] && echo "○ be 未运行"
100
+ rm -f "$RUN/be.pid"
101
+ }
102
+ be_restart() { be_stop; sleep 1; be_start; }
103
+ be_status() { local p; p="$(port_pid $BE_PORT)"; [ -n "$p" ] && echo "● be RUNNING http://127.0.0.1:$BE_PORT/workbench pid=$p" || echo "○ be stopped :$BE_PORT"; }
104
+
105
+ # ───────────────────────── web(Umi dev,mock) ───────────────────────────
106
+ web_start() {
107
+ if [ -n "$(port_pid $WEB_PORT)" ]; then echo "● web 已在 :$WEB_PORT"; return 0; fi
108
+ ( cd "$ROOT/dashboard" && nohup npm run dev >"$RUN/web.log" 2>&1 & echo $! >"$RUN/web.pid" )
109
+ echo "✓ web 启动中(mock,http://127.0.0.1:$WEB_PORT) 日志: $RUN/web.log"
110
+ }
111
+ web_stop() {
112
+ local pid; pid="$(cat "$RUN/web.pid" 2>/dev/null)"; [ -z "$pid" ] && pid="$(port_pid $WEB_PORT)"
113
+ if alive "$pid"; then pkill -P "$pid" 2>/dev/null; kill "$pid" 2>/dev/null; echo "✓ web 已停"; else echo "○ web 未运行"; fi
114
+ rm -f "$RUN/web.pid"
115
+ }
116
+ web_restart() { web_stop; sleep 1; web_start; }
117
+ web_status() { local p; p="$(port_pid $WEB_PORT)"; [ -n "$p" ] && echo "● web RUNNING http://127.0.0.1:$WEB_PORT (mock) pid=$p" || echo "○ web stopped :$WEB_PORT (mock dev)"; }
118
+
119
+ # ───────────────────────── build ────────────────────────────────────────
120
+ do_build() {
121
+ case "${1:-all}" in
122
+ core) npm --prefix "$ROOT/packages/recorder-core" run build ;;
123
+ be) npm --prefix "$ROOT/dashboard-be" run build ;;
124
+ ui) ( cd "$ROOT/dashboard" && npm run build ) ;;
125
+ ext) ( cd "$ROOT/extension" && npm run build ) ;;
126
+ vnc) # VNC 录制模式容器镜像(Chromium+扩展+daemon+x11vnc+websockify+网关);be 起容器时复用 bycli-verify:latest。
127
+ command -v podman >/dev/null || { echo "✗ podman 不在 PATH(VNC 模式需 podman)"; return 1; }
128
+ [ -f "$ROOT/extension/dist/background.js" ] || { echo "✗ 扩展未构建 → scripts/recorder.sh build ext"; return 1; }
129
+ [ -f "$ROOT/dist/src/daemon.js" ] || { echo "✗ dist 未构建 → npm run build"; return 1; }
130
+ echo "▶ 构建 VNC 容器镜像 bycli-verify:latest(首次装 chromium 较慢)…"
131
+ ( cd "$ROOT" && podman build -f podman-verify/Dockerfile -t bycli-verify:latest . ) ;;
132
+ all) npm --prefix "$ROOT/packages/recorder-core" run build \
133
+ && npm --prefix "$ROOT/dashboard-be" run build \
134
+ && ( cd "$ROOT/dashboard" && npm run build ) \
135
+ && ( cd "$ROOT/extension" && npm run build ) \
136
+ && echo "↻ 扩展已重建 → chrome://extensions 重载 byCLI(确认版本号刷新)" ;;
137
+ *) echo "build: core|be|ui|ext|vnc|all"; return 1 ;;
138
+ esac
139
+ }
140
+
141
+ # ───────────────────────── dispatch ─────────────────────────────────────
142
+ action="${1:-}"; shift || true
143
+ case "$action" in
144
+ start)
145
+ # mock 仅在显式 --mock 时启动;其余参数视作服务名
146
+ mock=0; svcs=()
147
+ for a in "$@"; do if [ "$a" = "--mock" ]; then mock=1; else svcs+=("$a"); fi; done
148
+ if [ "$mock" = 1 ]; then
149
+ echo "▶ 启动【mock 前端】(web :$WEB_PORT,假数据,无真实录制)"
150
+ web_start
151
+ elif [ ${#svcs[@]} -eq 0 ]; then
152
+ # 默认 = 真实录制环境:停掉 mock web(防 :8000 误测)→ 起 daemon + be
153
+ echo "▶ 启动【真实录制环境】(daemon + be);mock web 若在跑将被停掉以免混淆"
154
+ [ -n "$(port_pid $WEB_PORT)" ] && web_stop
155
+ daemon_start; be_start
156
+ echo; echo "✅ 真实录制 → http://127.0.0.1:$BE_PORT/workbench(mock 需 start --mock)"
157
+ else
158
+ [ "${svcs[0]}" = "all" ] && svcs=(daemon be)
159
+ for t in "${svcs[@]}"; do
160
+ case "$t" in
161
+ daemon|be) "${t}_start" ;;
162
+ web) echo "✗ web 是 mock,请用:scripts/recorder.sh start --mock" ;;
163
+ *) echo "未知服务: $t(daemon|be|all,mock 用 --mock)" ;;
164
+ esac
165
+ done
166
+ fi ;;
167
+ stop|restart)
168
+ # all 语义:restart 只起真实环境(daemon+be,不复活 mock,与 start 默认一致);
169
+ # stop 则全停(含 mock web,teardown)。mock 启停一律显式 web/--mock。
170
+ if [ $# -eq 0 ]; then targets=(daemon be)
171
+ elif [ "${1:-}" = all ]; then
172
+ [ "$action" = stop ] && targets=(daemon be web) || targets=(daemon be)
173
+ else targets=("$@"); fi
174
+ [ "$action" = stop ] && targets=($(printf '%s\n' "${targets[@]}" | tail -r 2>/dev/null || printf '%s\n' "${targets[@]}"))
175
+ for t in "${targets[@]}"; do
176
+ case "$t" in daemon|be|web|vnc) "${t}_${action}" ;; *) echo "未知服务: $t(daemon|be|web|vnc|all)";; esac
177
+ done ;;
178
+ status)
179
+ daemon_status; be_status; web_status; vnc_status ;;
180
+ build)
181
+ do_build "${1:-all}" ;;
182
+ ""|-h|--help|help)
183
+ awk 'NR>1 && /^#/{sub(/^# ?/,"");print;next} NR>1{exit}' "${BASH_SOURCE[0]}" ;;
184
+ *)
185
+ echo "未知命令: $action(start|stop|restart|status|build)"; exit 1 ;;
186
+ esac
@@ -1,124 +0,0 @@
1
- import { ArgumentError, CommandExecutionError } from '@sovovs/bycli/errors';
2
-
3
- export const MAX_PAGES = 100;
4
- export const MAX_PAGE_SIZE = 10;
5
- export const MAX_ARTICLES = 1000;
6
-
7
- export function isTrustedWechatArticleUrl(value) {
8
- try {
9
- const url = new URL(value);
10
- return url.protocol === 'https:'
11
- && url.hostname === 'mp.weixin.qq.com'
12
- && url.port === ''
13
- && url.username === ''
14
- && url.password === ''
15
- && (url.pathname === '/s' || url.pathname.startsWith('/s/'));
16
- } catch {
17
- return false;
18
- }
19
- }
20
-
21
- /** @param {any} article */
22
- export function isUsableArticle(article) {
23
- return Boolean(article)
24
- && article.isDeleted !== true
25
- && typeof article.url === 'string'
26
- && isTrustedWechatArticleUrl(article.url)
27
- && !article.url.includes('tempkey=');
28
- }
29
-
30
- function canonicalUrl(value) {
31
- try {
32
- const url = new URL(value);
33
- url.hash = '';
34
- return url.href;
35
- } catch {
36
- return value;
37
- }
38
- }
39
-
40
- function publicArticle(article) {
41
- return {
42
- title: typeof article.title === 'string' ? article.title : '',
43
- url: article.url,
44
- publishedAt: typeof article.publishedAt === 'string' ? article.publishedAt : null,
45
- digest: typeof article.digest === 'string' ? article.digest : '',
46
- author: typeof article.author === 'string' ? article.author : '',
47
- };
48
- }
49
-
50
- /**
51
- * @param {{fakeid:string,fetchPage:(input:{fakeid:string,begin:number,count:number})=>Promise<any>,limit?:number,maxPages?:number,pageSize?:number}} options
52
- */
53
- export async function collectArticles({ fakeid, fetchPage, limit, maxPages, pageSize = 10 }) {
54
- for (const [name, value, maximum] of [
55
- ['pageSize', pageSize, MAX_PAGE_SIZE],
56
- ['limit', limit, MAX_ARTICLES],
57
- ['maxPages', maxPages, MAX_PAGES],
58
- ]) {
59
- if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {
60
- throw new ArgumentError(`${name} must be a positive safe integer`);
61
- }
62
- if (value !== undefined && value > maximum) {
63
- throw new ArgumentError(`${name} must not exceed ${maximum}`);
64
- }
65
- }
66
- const pageLimit = maxPages ?? MAX_PAGES;
67
- const articleLimit = limit ?? MAX_ARTICLES;
68
- const articles = [];
69
- const seen = new Set();
70
- let totalFromApi = 0;
71
- let scanned = 0;
72
- let invalid = 0;
73
- let duplicates = 0;
74
- let pages = 0;
75
- let begin = 0;
76
-
77
- while (true) {
78
- const page = await fetchPage({ fakeid, begin, count: pageSize });
79
- pages += 1;
80
- const pageTotal = page?.total === undefined ? 0 : page.total;
81
- if (!Number.isSafeInteger(pageTotal) || pageTotal < 0) {
82
- throw new CommandExecutionError('WeChat article history returned invalid total metadata');
83
- }
84
- if (pages === 1) totalFromApi = pageTotal;
85
- const rawArticles = Array.isArray(page?.articles) ? page.articles : [];
86
- const publishItemCount = page?.publishItemCount === undefined ? 0 : page.publishItemCount;
87
- if (!Number.isSafeInteger(publishItemCount) || publishItemCount < 0) {
88
- throw new CommandExecutionError('WeChat article history returned invalid publish-item metadata');
89
- }
90
-
91
- for (const article of rawArticles) {
92
- scanned += 1;
93
- if (!isUsableArticle(article)) {
94
- invalid += 1;
95
- continue;
96
- }
97
- const canonical = canonicalUrl(article.url);
98
- if (seen.has(canonical)) {
99
- duplicates += 1;
100
- continue;
101
- }
102
- seen.add(canonical);
103
- articles.push(publicArticle(article));
104
- if (articles.length >= articleLimit) break;
105
- }
106
-
107
- const reachedLimit = articles.length >= articleLimit;
108
- const reachedMaxPages = pages >= pageLimit;
109
- const reachedEnd = publishItemCount === 0
110
- || publishItemCount < pageSize
111
- || (totalFromApi > 0 && begin + publishItemCount >= totalFromApi);
112
- if (reachedLimit || reachedMaxPages || reachedEnd) break;
113
- const nextBegin = begin + pageSize;
114
- if (!Number.isSafeInteger(nextBegin) || nextBegin <= begin) {
115
- throw new CommandExecutionError('WeChat article pagination could not advance safely');
116
- }
117
- begin = nextBegin;
118
- }
119
-
120
- return {
121
- articles,
122
- summary: { totalFromApi, scanned, valid: articles.length, invalid, duplicates, pages },
123
- };
124
- }
@@ -1,176 +0,0 @@
1
- import * as defaultFs from 'node:fs';
2
- import path from 'node:path';
3
- import { ArgumentError, AuthRequiredError, CommandExecutionError } from '@sovovs/bycli/errors';
4
- import { cleanMarkdownFilename, wechatArticleToMarkdown } from './markdown.js';
5
-
6
- export const MAX_FILENAME_ATTEMPTS = 100;
7
-
8
- function commandError(action, error) {
9
- return new CommandExecutionError(`Failed to ${action}: ${error instanceof Error ? error.message : String(error)}`);
10
- }
11
-
12
- function assertInside(root, target) {
13
- const relative = path.relative(root, target);
14
- if (relative === '' || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
15
- throw new CommandExecutionError('Refusing to save an article outside the output directory');
16
- }
17
- }
18
-
19
- function sameIdentity(left, right) {
20
- return left.dev === right.dev && left.ino === right.ino;
21
- }
22
-
23
- function assertResolvedPathComponents(root, fsImpl) {
24
- const parsed = path.parse(root);
25
- let current = parsed.root;
26
- for (const part of root.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
27
- current = path.join(current, part);
28
- const stat = fsImpl.lstatSync(current);
29
- if (stat.isSymbolicLink?.()) throw new CommandExecutionError('Refusing to save through a symbolic link');
30
- }
31
- }
32
-
33
- function assertRootIdentity(root, rootFd, rootIdentity, fsImpl) {
34
- assertResolvedPathComponents(root, fsImpl);
35
- const pathStat = fsImpl.lstatSync(root);
36
- const fdStat = fsImpl.fstatSync(rootFd);
37
- if (!pathStat.isDirectory?.() || !fdStat.isDirectory?.()
38
- || !sameIdentity(pathStat, rootIdentity) || !sameIdentity(fdStat, rootIdentity)) {
39
- throw new CommandExecutionError('Output directory identity changed during save');
40
- }
41
- }
42
-
43
- function cleanupOpenedTarget(target, openedStat, fsImpl) {
44
- try {
45
- const current = fsImpl.lstatSync(target);
46
- if (sameIdentity(current, openedStat) && !current.isSymbolicLink?.()) fsImpl.unlinkSync(target);
47
- } catch {
48
- // Fail closed; cleanup is best effort after identity mismatch.
49
- }
50
- }
51
-
52
- function writeExclusive(root, rootFd, rootIdentity, target, markdown, fsImpl) {
53
- const noFollow = defaultFs.constants.O_NOFOLLOW;
54
- if (typeof noFollow !== 'number') {
55
- throw new CommandExecutionError('Secure article saving is unavailable: O_NOFOLLOW is unsupported');
56
- }
57
- // The opened root fd plus its dev/ino is the authorization capability.
58
- // Path checks detect namespace replacement, but cannot and need not prevent
59
- // a same-privilege process from renaming that already-authorized inode.
60
- assertRootIdentity(root, rootFd, rootIdentity, fsImpl);
61
- let fd;
62
- let openedStat;
63
- try {
64
- fd = fsImpl.openSync(target,
65
- defaultFs.constants.O_CREAT | defaultFs.constants.O_EXCL | defaultFs.constants.O_WRONLY | noFollow,
66
- 0o600);
67
- // Once open succeeds, this fd remains bound to that inode; later renames
68
- // or symlink swaps cannot redirect its writes into a replacement root.
69
- openedStat = fsImpl.fstatSync(fd);
70
- if (!openedStat.isFile?.() || openedStat.isSymbolicLink?.()) {
71
- throw new CommandExecutionError('Refusing to write a non-regular article target');
72
- }
73
- assertRootIdentity(root, rootFd, rootIdentity, fsImpl);
74
- const body = Buffer.from(markdown, 'utf8');
75
- let offset = 0;
76
- while (offset < body.length) {
77
- const written = fsImpl.writeSync(fd, body, offset, body.length - offset);
78
- if (!Number.isInteger(written) || written <= 0) throw new CommandExecutionError('Failed to write article bytes');
79
- offset += written;
80
- }
81
- fsImpl.fsyncSync?.(fd);
82
- assertRootIdentity(root, rootFd, rootIdentity, fsImpl);
83
- } catch (error) {
84
- if (openedStat) cleanupOpenedTarget(target, openedStat, fsImpl);
85
- throw error;
86
- } finally {
87
- if (fd !== undefined) fsImpl.closeSync(fd);
88
- }
89
- }
90
-
91
- export async function saveArticles({ articles, accountName, outputDir, fetchArticleHtml, buildMarkdown = wechatArticleToMarkdown, fsImpl = defaultFs }) {
92
- if (!Array.isArray(articles) || articles.length > 1000) {
93
- throw new ArgumentError('articles must be an array of at most 1000 items');
94
- }
95
- const requestedRoot = path.resolve(outputDir);
96
- try { fsImpl.mkdirSync(requestedRoot, { recursive: true }); } catch (error) { throw commandError('create output directory', error); }
97
- let root;
98
- try { root = fsImpl.realpathSync(requestedRoot); } catch (error) { throw commandError('resolve output directory', error); }
99
- let rootFd;
100
- let rootIdentity;
101
- try {
102
- assertResolvedPathComponents(root, fsImpl);
103
- rootIdentity = fsImpl.lstatSync(root);
104
- if (!rootIdentity.isDirectory?.() || rootIdentity.isSymbolicLink?.()) throw new Error('not a directory');
105
- rootFd = fsImpl.openSync(root, defaultFs.constants.O_RDONLY);
106
- const openedRoot = fsImpl.fstatSync(rootFd);
107
- if (!openedRoot.isDirectory?.() || !sameIdentity(openedRoot, rootIdentity)) {
108
- throw new CommandExecutionError('Output directory identity changed during secure open');
109
- }
110
- assertRootIdentity(root, rootFd, rootIdentity, fsImpl);
111
- } catch (error) {
112
- if (rootFd !== undefined) fsImpl.closeSync(rootFd);
113
- if (error instanceof CommandExecutionError) throw error;
114
- throw commandError('secure output directory', error);
115
- }
116
- const reserved = new Set();
117
- const rows = [];
118
-
119
- try {
120
- for (const article of articles) {
121
- let articleHtml;
122
- try {
123
- articleHtml = await fetchArticleHtml(article);
124
- } catch (error) {
125
- if (error instanceof AuthRequiredError) throw error;
126
- rows.push({ title: article.title || '', url: article.url || '', status: 'failed', stage: 'download', saved: '', error: 'article download failed' });
127
- continue;
128
- }
129
- let markdown;
130
- try {
131
- markdown = buildMarkdown({ html: articleHtml, title: article.title, accountName,
132
- author: article.author, publishedAt: article.publishedAt, digest: article.digest, url: article.url });
133
- } catch {
134
- rows.push({ title: article.title || '', url: article.url || '', status: 'failed', stage: 'download', saved: '', error: 'invalid article content' });
135
- continue;
136
- }
137
-
138
- let suffix = 1;
139
- let target;
140
- while (suffix <= MAX_FILENAME_ATTEMPTS) {
141
- const suffixText = suffix === 1 ? '' : `-${suffix}`;
142
- const name = `${cleanMarkdownFilename(article.title, 100, suffixText)}${suffixText}`;
143
- target = path.resolve(root, `${name}.md`);
144
- assertInside(root, target);
145
- if (reserved.has(target)) { suffix += 1; continue; }
146
- try {
147
- const stat = fsImpl.lstatSync(target);
148
- if (stat.isSymbolicLink?.()) throw new CommandExecutionError('Refusing to overwrite a symbolic link');
149
- suffix += 1;
150
- continue;
151
- } catch (error) {
152
- if (error instanceof CommandExecutionError) throw error;
153
- if (error?.code !== 'ENOENT') throw commandError('inspect article target', error);
154
- }
155
- try {
156
- writeExclusive(root, rootFd, rootIdentity, target, markdown, fsImpl);
157
- reserved.add(target);
158
- break;
159
- } catch (error) {
160
- if (error?.code === 'EEXIST') {
161
- suffix += 1;
162
- continue;
163
- }
164
- throw commandError('write article Markdown', error);
165
- }
166
- }
167
- if (suffix > MAX_FILENAME_ATTEMPTS) {
168
- throw new CommandExecutionError(`Failed to reserve an article filename after ${MAX_FILENAME_ATTEMPTS} attempts`);
169
- }
170
- rows.push({ title: article.title || '', url: article.url || '', status: 'saved', stage: null, saved: target, error: '' });
171
- }
172
- } finally {
173
- fsImpl.closeSync(rootFd);
174
- }
175
- return rows;
176
- }
@@ -1,133 +0,0 @@
1
- import { AuthRequiredError, CommandExecutionError } from '@sovovs/bycli/errors';
2
- import { buildSecretSet, redactText } from './redact.js';
3
-
4
- const DOMAIN = 'mp.weixin.qq.com';
5
- const ENDPOINT = `https://${DOMAIN}/cgi-bin/appmsgpublish`;
6
-
7
- function normalizedMessage(value) {
8
- return String(value ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
9
- }
10
-
11
- function commandError(message) {
12
- return new CommandExecutionError(redactText(message, []));
13
- }
14
-
15
- function parseNestedJson(value, label) {
16
- if (typeof value !== 'string') return value;
17
- try {
18
- return JSON.parse(value);
19
- } catch (error) {
20
- const detail = error instanceof Error ? error.message : String(error);
21
- throw commandError(`WeChat ${label} is malformed: ${detail}`);
22
- }
23
- }
24
-
25
- /** @param {unknown} data */
26
- export function parsePublishData(data) {
27
- if (!data || typeof data !== 'object') {
28
- throw new CommandExecutionError('WeChat article history returned an unreadable response');
29
- }
30
- const response = /** @type {Record<string, any>} */ (data);
31
- const ret = response.base_resp?.ret;
32
- const message = response.base_resp?.err_msg ?? response.base_resp?.err_msg_en ?? '';
33
- if (ret === 200013 && normalizedMessage(message) === 'invalid credential') {
34
- throw new AuthRequiredError(DOMAIN, 'WeChat article-history credentials have expired');
35
- }
36
- if (ret !== undefined && ret !== 0) {
37
- throw new CommandExecutionError(`WeChat article history failed (ret=${String(ret)})`);
38
- }
39
- if (response.publish_page === undefined || response.publish_page === null || response.publish_page === '') {
40
- return { total: 0, publishItemCount: 0, articles: [] };
41
- }
42
- const page = parseNestedJson(response.publish_page, 'publish_page');
43
- if (!page || typeof page !== 'object' || !Array.isArray(page.publish_list)) {
44
- throw new CommandExecutionError('WeChat article history returned an invalid publish page');
45
- }
46
- const total = page.total_count === undefined ? 0 : page.total_count;
47
- if (!Number.isSafeInteger(total) || total < 0) {
48
- throw new CommandExecutionError('WeChat article history returned invalid total metadata');
49
- }
50
- const articles = [];
51
- for (const item of page.publish_list) {
52
- const info = parseNestedJson(item?.publish_info ?? {}, 'publish_info');
53
- if (!info || typeof info !== 'object' || !Array.isArray(info.appmsg_info)) {
54
- throw new CommandExecutionError('WeChat article history returned invalid publish information');
55
- }
56
- const timestamp = info.sent_info?.time ?? info.publish_info?.create_time ?? 0;
57
- let publishedAt = null;
58
- if (timestamp !== 0) {
59
- if (typeof timestamp !== 'number' || !Number.isFinite(timestamp) || timestamp <= 0) {
60
- throw new CommandExecutionError('WeChat article history returned an invalid publish timestamp');
61
- }
62
- const date = new Date(timestamp * 1000);
63
- if (!Number.isFinite(date.getTime())) {
64
- throw new CommandExecutionError('WeChat article history returned an invalid publish timestamp');
65
- }
66
- publishedAt = date.toISOString();
67
- }
68
- for (const messageItem of info.appmsg_info) {
69
- const article = messageItem && typeof messageItem === 'object' ? messageItem : {};
70
- articles.push({
71
- title: typeof article.title === 'string' ? article.title : '',
72
- url: typeof article.content_url === 'string' ? article.content_url : '',
73
- isDeleted: article.is_deleted === true,
74
- timestamp,
75
- publishedAt,
76
- digest: typeof article.digest === 'string' ? article.digest : '',
77
- author: typeof article.author === 'string' ? article.author : '',
78
- });
79
- }
80
- }
81
- return {
82
- total,
83
- publishItemCount: page.publish_list.length,
84
- articles,
85
- };
86
- }
87
-
88
- export function requestHeaders(cookie, token) {
89
- return {
90
- Accept: 'application/json, text/javascript, */*; q=0.01',
91
- Cookie: cookie,
92
- Origin: `https://${DOMAIN}`,
93
- Referer: `https://${DOMAIN}/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&token=${encodeURIComponent(token)}&lang=zh_CN`,
94
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/143 Safari/537.36',
95
- 'X-Requested-With': 'XMLHttpRequest',
96
- };
97
- }
98
-
99
- /**
100
- * @param {{token:string,cookie:string,timeoutMs?:number,fetchImpl?:typeof fetch}} options
101
- */
102
- export function createWechatApi({ token, cookie, timeoutMs = 30_000, fetchImpl = fetch }) {
103
- const headers = requestHeaders(cookie, token);
104
- const secrets = buildSecretSet({ token, cookie });
105
-
106
- return {
107
- async fetchPage({ fakeid, begin = 0, count = 10 }) {
108
- const query = new URLSearchParams({
109
- sub: 'list', begin: String(begin), count: String(count), fakeid, token,
110
- lang: 'zh_CN', f: 'json', ajax: '1',
111
- });
112
- try {
113
- const response = await fetchImpl(`${ENDPOINT}?${query}`, {
114
- headers,
115
- signal: AbortSignal.timeout(timeoutMs),
116
- });
117
- if (!response.ok) {
118
- throw new CommandExecutionError(`WeChat article history request failed: HTTP ${response.status} ${response.statusText ?? ''}`.trim());
119
- }
120
- return parsePublishData(await response.json());
121
- } catch (error) {
122
- if (error instanceof AuthRequiredError && error.domain === DOMAIN) throw error;
123
- const message = error instanceof Error ? error.message : String(error);
124
- const hint = error && typeof error === 'object' && 'hint' in error && typeof error.hint === 'string'
125
- ? error.hint : undefined;
126
- throw new CommandExecutionError(
127
- `WeChat article history request failed: ${redactText(message, secrets)}`,
128
- hint ? redactText(hint, secrets) : undefined,
129
- );
130
- }
131
- },
132
- };
133
- }