@wechatsync/cli 1.0.0
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.
- package/README.md +117 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +926 -0
- package/package.json +49 -0
package/README.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# @wechatsync/cli
|
|
2
|
+
|
|
3
|
+
命令行同步文章到多个内容平台。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @wechatsync/cli
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## 快速开始
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
# 同步文章到知乎和掘金
|
|
15
|
+
wechatsync sync article.md --platforms zhihu,juejin
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
首次使用会提示安装 Chrome 扩展 - 访问 https://wechatsync.com/#install 安装。
|
|
19
|
+
|
|
20
|
+
## 命令
|
|
21
|
+
|
|
22
|
+
### sync - 同步文章
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
# 基本用法
|
|
26
|
+
wechatsync sync article.md -p zhihu,juejin
|
|
27
|
+
|
|
28
|
+
# 指定标题
|
|
29
|
+
wechatsync sync article.md -t "我的文章" -p zhihu
|
|
30
|
+
|
|
31
|
+
# 添加封面
|
|
32
|
+
wechatsync sync article.md -p juejin --cover https://example.com/cover.jpg
|
|
33
|
+
|
|
34
|
+
# 预览(不实际同步)
|
|
35
|
+
wechatsync sync article.md --dry-run
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### platforms - 查看平台
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# 列出所有平台
|
|
42
|
+
wechatsync platforms
|
|
43
|
+
|
|
44
|
+
# 显示登录状态
|
|
45
|
+
wechatsync platforms --auth
|
|
46
|
+
wechatsync ls -a
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### auth - 检查登录
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# 检查所有平台
|
|
53
|
+
wechatsync auth
|
|
54
|
+
|
|
55
|
+
# 检查单个平台
|
|
56
|
+
wechatsync auth zhihu
|
|
57
|
+
|
|
58
|
+
# 强制刷新
|
|
59
|
+
wechatsync auth --refresh
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### extract - 提取文章
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
# 从浏览器当前页面提取
|
|
66
|
+
wechatsync extract
|
|
67
|
+
|
|
68
|
+
# 保存到文件
|
|
69
|
+
wechatsync extract -o article.md
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## 工作原理
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
┌──────────────┐ WebSocket ┌───────────────────┐
|
|
76
|
+
│ wechatsync │◄─────────────────►│ Chrome Extension │
|
|
77
|
+
│ (CLI) │ port 9527 │ (同步助手) │
|
|
78
|
+
└──────────────┘ └───────────────────┘
|
|
79
|
+
│
|
|
80
|
+
▼
|
|
81
|
+
┌───────────────────┐
|
|
82
|
+
│ 目标平台 API │
|
|
83
|
+
│ (知乎/掘金/...) │
|
|
84
|
+
└───────────────────┘
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
CLI 启动后监听 WebSocket 端口,等待 Chrome 扩展连接。
|
|
88
|
+
扩展连接后,CLI 通过 WebSocket 发送请求,扩展执行实际的平台 API 调用。
|
|
89
|
+
|
|
90
|
+
## 支持的平台
|
|
91
|
+
|
|
92
|
+
知乎、掘金、简书、头条、微博、B站、百家号、CSDN、语雀、豆瓣、搜狐、雪球、微信公众号、人人都是产品经理、大鱼号、一点资讯、51CTO、搜狐焦点、慕课网、开源中国、思否、博客园
|
|
93
|
+
|
|
94
|
+
## 环境变量
|
|
95
|
+
|
|
96
|
+
| 变量 | 说明 | 默认值 |
|
|
97
|
+
|------|------|--------|
|
|
98
|
+
| `SYNC_WS_PORT` | WebSocket 端口 | 9527 |
|
|
99
|
+
| `WECHATSYNC_TOKEN` | 安全验证 token | - |
|
|
100
|
+
|
|
101
|
+
## Claude Code 集成
|
|
102
|
+
|
|
103
|
+
安装 Skill 插件:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
/plugin marketplace add wechatsync/Wechatsync
|
|
107
|
+
/plugin install wechatsync
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
然后在 Claude Code 中可以直接说:
|
|
111
|
+
- "把这篇文章同步到掘金"
|
|
112
|
+
- "帮我看看哪些平台已登录"
|
|
113
|
+
- "从浏览器提取当前文章"
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
+
mod
|
|
24
|
+
));
|
|
25
|
+
|
|
26
|
+
// src/index.ts
|
|
27
|
+
var import_commander = require("commander");
|
|
28
|
+
var import_chalk = __toESM(require("chalk"));
|
|
29
|
+
var import_ora = __toESM(require("ora"));
|
|
30
|
+
var import_open = __toESM(require("open"));
|
|
31
|
+
var import_fs = __toESM(require("fs"));
|
|
32
|
+
var import_path = __toESM(require("path"));
|
|
33
|
+
|
|
34
|
+
// ../mcp-server/dist/exports.js
|
|
35
|
+
var import_ws = __toESM(require("ws"), 1);
|
|
36
|
+
var import_http = __toESM(require("http"), 1);
|
|
37
|
+
var WsModule = import_ws.default;
|
|
38
|
+
var WebSocketServer = WsModule.WebSocketServer || WsModule.Server || WsModule.default?.WebSocketServer || WsModule.default?.Server;
|
|
39
|
+
var WS_OPEN = 1;
|
|
40
|
+
var ExtensionBridge = class {
|
|
41
|
+
constructor(port = 9527, options) {
|
|
42
|
+
this.port = port;
|
|
43
|
+
this.silent = options?.silent ?? false;
|
|
44
|
+
if (!this.silent) {
|
|
45
|
+
if (this.token) {
|
|
46
|
+
console.error("[Bridge] Token authentication enabled");
|
|
47
|
+
} else {
|
|
48
|
+
console.error("[Bridge] Warning: MCP_TOKEN not set, requests may be rejected by extension");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
wss = null;
|
|
53
|
+
httpServer = null;
|
|
54
|
+
client = null;
|
|
55
|
+
isServerMode = false;
|
|
56
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
57
|
+
requestTimeout = 36e4;
|
|
58
|
+
// 6 minutes (图片多时需要更长时间)
|
|
59
|
+
connectionResolvers = [];
|
|
60
|
+
// 安全验证 token(从环境变量读取,优先使用 WECHATSYNC_TOKEN)
|
|
61
|
+
token = process.env.WECHATSYNC_TOKEN || process.env.MCP_TOKEN || "";
|
|
62
|
+
// 是否静默模式(CLI 使用时不输出日志)
|
|
63
|
+
silent = false;
|
|
64
|
+
/**
|
|
65
|
+
* 启动服务 - 自动选择服务器模式或客户端模式
|
|
66
|
+
*/
|
|
67
|
+
async start() {
|
|
68
|
+
try {
|
|
69
|
+
await this.startServer();
|
|
70
|
+
this.isServerMode = true;
|
|
71
|
+
if (!this.silent) console.error(`[Bridge] Running as PRIMARY (WebSocket: ${this.port}, HTTP: ${this.port + 1})`);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error.code === "EADDRINUSE") {
|
|
74
|
+
this.isServerMode = false;
|
|
75
|
+
if (!this.silent) console.error(`[Bridge] Running as SECONDARY (forwarding to localhost:${this.port + 1})`);
|
|
76
|
+
} else {
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* 启动 WebSocket 服务器 + HTTP API
|
|
83
|
+
*/
|
|
84
|
+
startServer() {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
try {
|
|
87
|
+
this.wss = new WebSocketServer({ port: this.port });
|
|
88
|
+
this.wss.on("listening", () => {
|
|
89
|
+
if (!this.silent) console.error(`[Bridge] WebSocket server listening on port ${this.port}`);
|
|
90
|
+
this.startHttpApi().then(resolve).catch(reject);
|
|
91
|
+
});
|
|
92
|
+
this.wss.on("connection", (ws) => {
|
|
93
|
+
if (!this.silent) console.error("[Bridge] Extension connected");
|
|
94
|
+
this.client = ws;
|
|
95
|
+
for (const resolver of this.connectionResolvers) {
|
|
96
|
+
resolver();
|
|
97
|
+
}
|
|
98
|
+
this.connectionResolvers = [];
|
|
99
|
+
ws.on("message", (data) => {
|
|
100
|
+
this.handleMessage(data.toString());
|
|
101
|
+
});
|
|
102
|
+
ws.on("close", () => {
|
|
103
|
+
if (!this.silent) console.error("[Bridge] Extension disconnected");
|
|
104
|
+
this.client = null;
|
|
105
|
+
});
|
|
106
|
+
ws.on("error", (error) => {
|
|
107
|
+
if (!this.silent) console.error("[Bridge] WebSocket error:", error);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
this.wss.on("error", (error) => {
|
|
111
|
+
reject(error);
|
|
112
|
+
});
|
|
113
|
+
} catch (error) {
|
|
114
|
+
reject(error);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* 启动 HTTP API 服务器(供其他 MCP 实例调用)
|
|
120
|
+
*/
|
|
121
|
+
startHttpApi() {
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
this.httpServer = import_http.default.createServer(async (req, res) => {
|
|
124
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
125
|
+
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
|
126
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
127
|
+
if (req.method === "OPTIONS") {
|
|
128
|
+
res.writeHead(200);
|
|
129
|
+
res.end();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (req.method === "GET" && req.url === "/status") {
|
|
133
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
134
|
+
res.end(JSON.stringify({
|
|
135
|
+
connected: this.isConnected(),
|
|
136
|
+
mode: "primary"
|
|
137
|
+
}));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (req.method === "POST" && req.url === "/request") {
|
|
141
|
+
let body = "";
|
|
142
|
+
req.on("data", (chunk) => body += chunk);
|
|
143
|
+
req.on("end", async () => {
|
|
144
|
+
try {
|
|
145
|
+
const { method, params } = JSON.parse(body);
|
|
146
|
+
const result = await this.requestInternal(method, params);
|
|
147
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
148
|
+
res.end(JSON.stringify({ result }));
|
|
149
|
+
} catch (error) {
|
|
150
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
151
|
+
res.end(JSON.stringify({ error: error.message }));
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
res.writeHead(404);
|
|
157
|
+
res.end("Not found");
|
|
158
|
+
});
|
|
159
|
+
const httpPort = this.port + 1;
|
|
160
|
+
this.httpServer.listen(httpPort, () => {
|
|
161
|
+
if (!this.silent) console.error(`[Bridge] HTTP API listening on port ${httpPort}`);
|
|
162
|
+
resolve();
|
|
163
|
+
});
|
|
164
|
+
this.httpServer.on("error", reject);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* 停止服务器
|
|
169
|
+
*/
|
|
170
|
+
stop() {
|
|
171
|
+
if (this.wss) {
|
|
172
|
+
this.wss.close();
|
|
173
|
+
this.wss = null;
|
|
174
|
+
}
|
|
175
|
+
if (this.httpServer) {
|
|
176
|
+
this.httpServer.close();
|
|
177
|
+
this.httpServer = null;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 检查 Extension 是否已连接
|
|
182
|
+
*/
|
|
183
|
+
isConnected() {
|
|
184
|
+
if (this.isServerMode) {
|
|
185
|
+
return this.client !== null && this.client.readyState === WS_OPEN;
|
|
186
|
+
} else {
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* 等待 Extension 连接
|
|
192
|
+
*/
|
|
193
|
+
waitForConnection(timeoutMs = 6e4) {
|
|
194
|
+
if (this.isConnected()) {
|
|
195
|
+
return Promise.resolve();
|
|
196
|
+
}
|
|
197
|
+
return new Promise((resolve, reject) => {
|
|
198
|
+
const timeout = setTimeout(() => {
|
|
199
|
+
const index = this.connectionResolvers.indexOf(resolve);
|
|
200
|
+
if (index > -1) {
|
|
201
|
+
this.connectionResolvers.splice(index, 1);
|
|
202
|
+
}
|
|
203
|
+
reject(new Error("timeout"));
|
|
204
|
+
}, timeoutMs);
|
|
205
|
+
this.connectionResolvers.push(() => {
|
|
206
|
+
clearTimeout(timeout);
|
|
207
|
+
resolve();
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* 检查 Primary 实例健康状态(Secondary 模式用)
|
|
213
|
+
*/
|
|
214
|
+
async checkPrimaryHealth() {
|
|
215
|
+
return new Promise((resolve) => {
|
|
216
|
+
const options = {
|
|
217
|
+
hostname: "localhost",
|
|
218
|
+
port: this.port + 1,
|
|
219
|
+
path: "/status",
|
|
220
|
+
method: "GET",
|
|
221
|
+
timeout: 3e3
|
|
222
|
+
};
|
|
223
|
+
const req = import_http.default.request(options, (res) => {
|
|
224
|
+
let body = "";
|
|
225
|
+
res.on("data", (chunk) => body += chunk);
|
|
226
|
+
res.on("end", () => {
|
|
227
|
+
try {
|
|
228
|
+
const status = JSON.parse(body);
|
|
229
|
+
resolve({ connected: status.connected });
|
|
230
|
+
} catch {
|
|
231
|
+
resolve({ connected: false, error: "Invalid response from primary" });
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
req.on("error", (error) => {
|
|
236
|
+
resolve({ connected: false, error: `Primary not reachable: ${error.message}` });
|
|
237
|
+
});
|
|
238
|
+
req.on("timeout", () => {
|
|
239
|
+
req.destroy();
|
|
240
|
+
resolve({ connected: false, error: "Primary health check timeout" });
|
|
241
|
+
});
|
|
242
|
+
req.end();
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* 发送请求到 Extension 并等待响应
|
|
247
|
+
*/
|
|
248
|
+
async request(method, params) {
|
|
249
|
+
if (this.isServerMode) {
|
|
250
|
+
return this.requestInternal(method, params);
|
|
251
|
+
} else {
|
|
252
|
+
const health = await this.checkPrimaryHealth();
|
|
253
|
+
if (!health.connected) {
|
|
254
|
+
throw new Error(
|
|
255
|
+
health.error || "Primary MCP instance not available. Please ensure only one Claude Code session is using MCP."
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
return this.requestViaHttp(method, params);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* 直接通过 WebSocket 发送请求(服务器模式)
|
|
263
|
+
*/
|
|
264
|
+
async requestInternal(method, params) {
|
|
265
|
+
if (!this.client || this.client.readyState !== WS_OPEN) {
|
|
266
|
+
throw new Error("Extension not connected. Please ensure the Chrome extension is running.");
|
|
267
|
+
}
|
|
268
|
+
const id = this.generateId();
|
|
269
|
+
const message = {
|
|
270
|
+
id,
|
|
271
|
+
method,
|
|
272
|
+
token: this.token,
|
|
273
|
+
// 发送 token 供插件端验证
|
|
274
|
+
params
|
|
275
|
+
};
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const timeout = setTimeout(() => {
|
|
278
|
+
this.pendingRequests.delete(id);
|
|
279
|
+
reject(new Error(`Request timeout: ${method}`));
|
|
280
|
+
}, this.requestTimeout);
|
|
281
|
+
this.pendingRequests.set(id, { resolve, reject, timeout });
|
|
282
|
+
this.client.send(JSON.stringify(message));
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* 通过 HTTP API 转发请求(客户端模式)
|
|
287
|
+
*/
|
|
288
|
+
requestViaHttp(method, params) {
|
|
289
|
+
return new Promise((resolve, reject) => {
|
|
290
|
+
const data = JSON.stringify({ method, params });
|
|
291
|
+
const options = {
|
|
292
|
+
hostname: "localhost",
|
|
293
|
+
port: this.port + 1,
|
|
294
|
+
path: "/request",
|
|
295
|
+
method: "POST",
|
|
296
|
+
headers: {
|
|
297
|
+
"Content-Type": "application/json",
|
|
298
|
+
"Content-Length": Buffer.byteLength(data)
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
const req = import_http.default.request(options, (res) => {
|
|
302
|
+
let body = "";
|
|
303
|
+
res.on("data", (chunk) => body += chunk);
|
|
304
|
+
res.on("end", () => {
|
|
305
|
+
try {
|
|
306
|
+
const response = JSON.parse(body);
|
|
307
|
+
if (response.error) {
|
|
308
|
+
reject(new Error(response.error));
|
|
309
|
+
} else {
|
|
310
|
+
resolve(response.result);
|
|
311
|
+
}
|
|
312
|
+
} catch (error) {
|
|
313
|
+
reject(new Error("Failed to parse response"));
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
req.on("error", (error) => {
|
|
318
|
+
const hint = error.message.includes("ECONNREFUSED") ? " (Is the primary MCP server running?)" : "";
|
|
319
|
+
reject(new Error(`Failed to connect to primary MCP instance: ${error.message}${hint}`));
|
|
320
|
+
});
|
|
321
|
+
req.setTimeout(this.requestTimeout, () => {
|
|
322
|
+
req.destroy();
|
|
323
|
+
reject(new Error(`Request timeout: ${method}`));
|
|
324
|
+
});
|
|
325
|
+
req.write(data);
|
|
326
|
+
req.end();
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* 处理来自 Extension 的消息
|
|
331
|
+
*/
|
|
332
|
+
handleMessage(data) {
|
|
333
|
+
try {
|
|
334
|
+
const message = JSON.parse(data);
|
|
335
|
+
const pending = this.pendingRequests.get(message.id);
|
|
336
|
+
if (!pending) {
|
|
337
|
+
console.error("[Bridge] Unknown response id:", message.id);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
clearTimeout(pending.timeout);
|
|
341
|
+
this.pendingRequests.delete(message.id);
|
|
342
|
+
if (message.error) {
|
|
343
|
+
pending.reject(new Error(message.error.message));
|
|
344
|
+
} else {
|
|
345
|
+
pending.resolve(message.result);
|
|
346
|
+
}
|
|
347
|
+
} catch (error) {
|
|
348
|
+
console.error("[Bridge] Failed to parse message:", error);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* 生成唯一 ID
|
|
353
|
+
*/
|
|
354
|
+
generateId() {
|
|
355
|
+
return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
356
|
+
}
|
|
357
|
+
// 分片上传配置
|
|
358
|
+
CHUNK_SIZE = 512 * 1024;
|
|
359
|
+
// 512KB per chunk
|
|
360
|
+
CHUNK_THRESHOLD = 1024 * 1024;
|
|
361
|
+
// 1MB threshold for chunking
|
|
362
|
+
/**
|
|
363
|
+
* 分片上传图片
|
|
364
|
+
* 大于 1MB 的图片会自动分片上传
|
|
365
|
+
*/
|
|
366
|
+
async uploadImageChunked(imageData, mimeType, platform = "weibo") {
|
|
367
|
+
if (imageData.length < this.CHUNK_THRESHOLD) {
|
|
368
|
+
return this.request("uploadImage", { imageData, mimeType, platform });
|
|
369
|
+
}
|
|
370
|
+
const uploadId = this.generateId();
|
|
371
|
+
const chunks = [];
|
|
372
|
+
for (let i = 0; i < imageData.length; i += this.CHUNK_SIZE) {
|
|
373
|
+
chunks.push(imageData.slice(i, i + this.CHUNK_SIZE));
|
|
374
|
+
}
|
|
375
|
+
console.error(`[Bridge] Chunked upload: ${chunks.length} chunks, total size: ${imageData.length}`);
|
|
376
|
+
await this.request("uploadImage:start", {
|
|
377
|
+
uploadId,
|
|
378
|
+
totalChunks: chunks.length,
|
|
379
|
+
mimeType,
|
|
380
|
+
platform
|
|
381
|
+
});
|
|
382
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
383
|
+
await this.request("uploadImage:chunk", {
|
|
384
|
+
uploadId,
|
|
385
|
+
chunkIndex: i,
|
|
386
|
+
data: chunks[i]
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
const result = await this.request("uploadImage:complete", {
|
|
390
|
+
uploadId
|
|
391
|
+
});
|
|
392
|
+
return result;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
// src/index.ts
|
|
397
|
+
var WS_PORT = parseInt(process.env.SYNC_WS_PORT || "9527", 10);
|
|
398
|
+
var WEBSITE_URL = "https://www.wechatsync.com";
|
|
399
|
+
var EXTENSION_URL = "https://www.wechatsync.com/#install";
|
|
400
|
+
var GITHUB_URL = "https://github.com/wechatsync/Wechatsync";
|
|
401
|
+
var program = new import_commander.Command();
|
|
402
|
+
var connectionTimeout = 3e4;
|
|
403
|
+
program.name("wechatsync").description("\u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E2A\u5185\u5BB9\u5E73\u53F0 (\u77E5\u4E4E\u3001\u6398\u91D1\u3001CSDN \u7B49)").version("1.0.0").option("--timeout <ms>", "\u7B49\u5F85 Extension \u8FDE\u63A5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09", "30000").hook("preAction", (thisCommand) => {
|
|
404
|
+
const opts = thisCommand.opts();
|
|
405
|
+
if (opts.timeout) {
|
|
406
|
+
connectionTimeout = parseInt(opts.timeout);
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
function showInstallGuide() {
|
|
410
|
+
console.log();
|
|
411
|
+
console.log(import_chalk.default.bgYellow.black(" \u9700\u8981\u5B89\u88C5 Chrome \u6269\u5C55 "));
|
|
412
|
+
console.log();
|
|
413
|
+
console.log("WechatSync CLI \u9700\u8981\u914D\u5408 Chrome \u6269\u5C55\u4F7F\u7528\u3002");
|
|
414
|
+
console.log("\u6269\u5C55\u8D1F\u8D23\u5904\u7406\u5404\u5E73\u53F0\u7684\u767B\u5F55\u72B6\u6001\u548C API \u8C03\u7528\u3002");
|
|
415
|
+
console.log();
|
|
416
|
+
console.log(import_chalk.default.bold("\u5B89\u88C5\u6B65\u9AA4:"));
|
|
417
|
+
console.log();
|
|
418
|
+
console.log(` 1. \u8BBF\u95EE\u5B98\u7F51\u5B89\u88C5\u6269\u5C55:`);
|
|
419
|
+
console.log(` ${import_chalk.default.cyan(EXTENSION_URL)}`);
|
|
420
|
+
console.log();
|
|
421
|
+
console.log(` 2. \u5728\u6269\u5C55\u8BBE\u7F6E\u4E2D\u542F\u7528 ${import_chalk.default.cyan("MCP \u8FDE\u63A5")}\uFF0C\u83B7\u53D6 Token`);
|
|
422
|
+
console.log();
|
|
423
|
+
console.log(` 3. \u914D\u7F6E\u73AF\u5883\u53D8\u91CF:`);
|
|
424
|
+
console.log(` ${import_chalk.default.cyan('export WECHATSYNC_TOKEN="\u4F60\u7684token"')}`);
|
|
425
|
+
console.log();
|
|
426
|
+
console.log(` 4. \u5728\u5404\u5E73\u53F0 (\u77E5\u4E4E\u3001\u6398\u91D1\u7B49) \u767B\u5F55\u4F60\u7684\u8D26\u53F7`);
|
|
427
|
+
console.log();
|
|
428
|
+
console.log(` 5. \u91CD\u65B0\u8FD0\u884C\u6B64\u547D\u4EE4`);
|
|
429
|
+
console.log();
|
|
430
|
+
console.log(import_chalk.default.gray(`\u5B98\u7F51: ${WEBSITE_URL}`));
|
|
431
|
+
console.log(import_chalk.default.gray(`GitHub: ${GITHUB_URL}`));
|
|
432
|
+
console.log();
|
|
433
|
+
}
|
|
434
|
+
async function promptOpenInstallPage() {
|
|
435
|
+
const readline = await import("readline");
|
|
436
|
+
const rl = readline.createInterface({
|
|
437
|
+
input: process.stdin,
|
|
438
|
+
output: process.stdout
|
|
439
|
+
});
|
|
440
|
+
return new Promise((resolve) => {
|
|
441
|
+
rl.question(import_chalk.default.yellow("\u662F\u5426\u6253\u5F00\u6269\u5C55\u5B89\u88C5\u9875\u9762? (y/N) "), async (answer) => {
|
|
442
|
+
rl.close();
|
|
443
|
+
if (answer.toLowerCase() === "y") {
|
|
444
|
+
console.log(import_chalk.default.gray("\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668..."));
|
|
445
|
+
await (0, import_open.default)(EXTENSION_URL);
|
|
446
|
+
}
|
|
447
|
+
resolve();
|
|
448
|
+
});
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
var MIME_TYPES = {
|
|
452
|
+
".png": "image/png",
|
|
453
|
+
".jpg": "image/jpeg",
|
|
454
|
+
".jpeg": "image/jpeg",
|
|
455
|
+
".gif": "image/gif",
|
|
456
|
+
".webp": "image/webp",
|
|
457
|
+
".svg": "image/svg+xml",
|
|
458
|
+
".bmp": "image/bmp"
|
|
459
|
+
};
|
|
460
|
+
function findLocalImages(content, basePath) {
|
|
461
|
+
const images = [];
|
|
462
|
+
const seen = /* @__PURE__ */ new Set();
|
|
463
|
+
const mdImageRegex = /!\[[^\]]*\]\(([^)]+)\)/g;
|
|
464
|
+
let match;
|
|
465
|
+
while ((match = mdImageRegex.exec(content)) !== null) {
|
|
466
|
+
const imgPath = match[1].trim();
|
|
467
|
+
if (imgPath.startsWith("http://") || imgPath.startsWith("https://") || imgPath.startsWith("data:")) {
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (!seen.has(imgPath)) {
|
|
471
|
+
seen.add(imgPath);
|
|
472
|
+
images.push({
|
|
473
|
+
originalRef: match[0],
|
|
474
|
+
localPath: imgPath,
|
|
475
|
+
absolutePath: import_path.default.resolve(basePath, imgPath)
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const htmlImageRegex = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
|
|
480
|
+
while ((match = htmlImageRegex.exec(content)) !== null) {
|
|
481
|
+
const imgPath = match[1].trim();
|
|
482
|
+
if (imgPath.startsWith("http://") || imgPath.startsWith("https://") || imgPath.startsWith("data:")) {
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
if (!seen.has(imgPath)) {
|
|
486
|
+
seen.add(imgPath);
|
|
487
|
+
images.push({
|
|
488
|
+
originalRef: match[0],
|
|
489
|
+
localPath: imgPath,
|
|
490
|
+
absolutePath: import_path.default.resolve(basePath, imgPath)
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return images;
|
|
495
|
+
}
|
|
496
|
+
function readImageAsBase64(imagePath) {
|
|
497
|
+
if (!import_fs.default.existsSync(imagePath)) {
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
500
|
+
const ext = import_path.default.extname(imagePath).toLowerCase();
|
|
501
|
+
const mimeType = MIME_TYPES[ext];
|
|
502
|
+
if (!mimeType) {
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
const buffer = import_fs.default.readFileSync(imagePath);
|
|
506
|
+
return {
|
|
507
|
+
data: buffer.toString("base64"),
|
|
508
|
+
mimeType
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
async function processLocalImages(content, basePath, bridge, platform = "weibo") {
|
|
512
|
+
const images = findLocalImages(content, basePath);
|
|
513
|
+
if (images.length === 0) {
|
|
514
|
+
return { content, uploadedCount: 0, failedCount: 0 };
|
|
515
|
+
}
|
|
516
|
+
let processedContent = content;
|
|
517
|
+
let uploadedCount = 0;
|
|
518
|
+
let failedCount = 0;
|
|
519
|
+
for (const img of images) {
|
|
520
|
+
const imageData = readImageAsBase64(img.absolutePath);
|
|
521
|
+
if (!imageData) {
|
|
522
|
+
console.log(import_chalk.default.yellow(` \u26A0 \u8DF3\u8FC7: ${img.localPath} (\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u683C\u5F0F\u4E0D\u652F\u6301)`));
|
|
523
|
+
failedCount++;
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
try {
|
|
527
|
+
const result = await bridge.uploadImageChunked(imageData.data, imageData.mimeType, platform);
|
|
528
|
+
if (img.originalRef.startsWith("![")) {
|
|
529
|
+
const newRef = img.originalRef.replace(img.localPath, result.url);
|
|
530
|
+
processedContent = processedContent.replace(img.originalRef, newRef);
|
|
531
|
+
} else {
|
|
532
|
+
const newRef = img.originalRef.replace(img.localPath, result.url);
|
|
533
|
+
processedContent = processedContent.replace(img.originalRef, newRef);
|
|
534
|
+
}
|
|
535
|
+
console.log(import_chalk.default.green(` \u2713 \u4E0A\u4F20: ${img.localPath}`));
|
|
536
|
+
uploadedCount++;
|
|
537
|
+
} catch (error) {
|
|
538
|
+
console.log(import_chalk.default.red(` \u2717 \u5931\u8D25: ${img.localPath} - ${error.message}`));
|
|
539
|
+
failedCount++;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return { content: processedContent, uploadedCount, failedCount };
|
|
543
|
+
}
|
|
544
|
+
function parseFileContent(filePath) {
|
|
545
|
+
const content = import_fs.default.readFileSync(filePath, "utf-8");
|
|
546
|
+
const ext = import_path.default.extname(filePath).toLowerCase();
|
|
547
|
+
if (ext === ".md" || ext === ".markdown") {
|
|
548
|
+
return parseMarkdown(content);
|
|
549
|
+
} else if (ext === ".html" || ext === ".htm") {
|
|
550
|
+
return parseHtml(content);
|
|
551
|
+
} else {
|
|
552
|
+
return {
|
|
553
|
+
title: import_path.default.basename(filePath, ext),
|
|
554
|
+
content,
|
|
555
|
+
format: "markdown"
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
function parseMarkdown(content) {
|
|
560
|
+
let title = null;
|
|
561
|
+
let body = content;
|
|
562
|
+
const yamlMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
|
|
563
|
+
if (yamlMatch) {
|
|
564
|
+
const frontMatter = yamlMatch[1];
|
|
565
|
+
const titleMatch = frontMatter.match(/^title:\s*["']?(.+?)["']?\s*$/m);
|
|
566
|
+
if (titleMatch) {
|
|
567
|
+
title = titleMatch[1].trim();
|
|
568
|
+
}
|
|
569
|
+
body = content.slice(yamlMatch[0].length);
|
|
570
|
+
}
|
|
571
|
+
if (!title) {
|
|
572
|
+
const h1Match = body.match(/^#\s+(.+)$/m);
|
|
573
|
+
if (h1Match) {
|
|
574
|
+
title = h1Match[1].trim();
|
|
575
|
+
body = body.replace(/^#\s+.+\n+/, "");
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
body = body.trim();
|
|
579
|
+
if (!body) {
|
|
580
|
+
body = content;
|
|
581
|
+
}
|
|
582
|
+
return {
|
|
583
|
+
title,
|
|
584
|
+
content: body,
|
|
585
|
+
format: "markdown"
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
function parseHtml(content) {
|
|
589
|
+
let title = null;
|
|
590
|
+
const titleMatch = content.match(/<title[^>]*>([^<]+)<\/title>/i);
|
|
591
|
+
if (titleMatch) {
|
|
592
|
+
title = titleMatch[1].trim();
|
|
593
|
+
}
|
|
594
|
+
if (!title) {
|
|
595
|
+
const h1Match = content.match(/<h1[^>]*>([^<]+)<\/h1>/i);
|
|
596
|
+
if (h1Match) {
|
|
597
|
+
title = h1Match[1].trim();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
let body = content;
|
|
601
|
+
const bodyMatch = content.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
|
|
602
|
+
if (bodyMatch) {
|
|
603
|
+
body = bodyMatch[1].trim();
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
title,
|
|
607
|
+
content: body,
|
|
608
|
+
format: "html"
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
function markdownToHtml(markdown) {
|
|
612
|
+
let html = markdown;
|
|
613
|
+
html = html.replace(/```(\w*)\n([\s\S]*?)```/g, "<pre><code>$2</code></pre>");
|
|
614
|
+
html = html.replace(/`([^`]+)`/g, "<code>$1</code>");
|
|
615
|
+
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" />');
|
|
616
|
+
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
|
|
617
|
+
html = html.replace(/^######\s+(.+)$/gm, "<h6>$1</h6>");
|
|
618
|
+
html = html.replace(/^#####\s+(.+)$/gm, "<h5>$1</h5>");
|
|
619
|
+
html = html.replace(/^####\s+(.+)$/gm, "<h4>$1</h4>");
|
|
620
|
+
html = html.replace(/^###\s+(.+)$/gm, "<h3>$1</h3>");
|
|
621
|
+
html = html.replace(/^##\s+(.+)$/gm, "<h2>$1</h2>");
|
|
622
|
+
html = html.replace(/^#\s+(.+)$/gm, "<h1>$1</h1>");
|
|
623
|
+
html = html.replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>");
|
|
624
|
+
html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
|
|
625
|
+
html = html.replace(/\*(.+?)\*/g, "<em>$1</em>");
|
|
626
|
+
html = html.replace(/^\s*[-*+]\s+(.+)$/gm, "<li>$1</li>");
|
|
627
|
+
html = html.replace(/(<li>.*<\/li>\n?)+/g, "<ul>$&</ul>");
|
|
628
|
+
html = html.replace(/^\s*\d+\.\s+(.+)$/gm, "<li>$1</li>");
|
|
629
|
+
html = html.replace(/^>\s+(.+)$/gm, "<blockquote>$1</blockquote>");
|
|
630
|
+
html = html.replace(/^---+$/gm, "<hr />");
|
|
631
|
+
html = html.replace(/^(?!<[a-z])((?:[^\n]+\n?)+)/gm, (match) => {
|
|
632
|
+
const trimmed = match.trim();
|
|
633
|
+
if (trimmed && !trimmed.startsWith("<")) {
|
|
634
|
+
return `<p>${trimmed}</p>
|
|
635
|
+
`;
|
|
636
|
+
}
|
|
637
|
+
return match;
|
|
638
|
+
});
|
|
639
|
+
return html;
|
|
640
|
+
}
|
|
641
|
+
async function createBridge() {
|
|
642
|
+
const bridge = new ExtensionBridge(WS_PORT, { silent: true });
|
|
643
|
+
const timeout = connectionTimeout;
|
|
644
|
+
const spinner = (0, import_ora.default)("\u542F\u52A8\u670D\u52A1...").start();
|
|
645
|
+
try {
|
|
646
|
+
await bridge.start();
|
|
647
|
+
spinner.text = "\u7B49\u5F85 Chrome Extension \u8FDE\u63A5...";
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (error.code === "EADDRINUSE") {
|
|
650
|
+
spinner.fail(`\u7AEF\u53E3 ${WS_PORT} \u5DF2\u88AB\u5360\u7528`);
|
|
651
|
+
console.log(import_chalk.default.gray("\u53EF\u80FD\u5DF2\u6709\u5176\u4ED6 wechatsync \u5B9E\u4F8B\u5728\u8FD0\u884C"));
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
throw error;
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
await bridge.waitForConnection(timeout);
|
|
658
|
+
spinner.succeed("Chrome Extension \u5DF2\u8FDE\u63A5");
|
|
659
|
+
return bridge;
|
|
660
|
+
} catch {
|
|
661
|
+
spinner.stop();
|
|
662
|
+
showInstallGuide();
|
|
663
|
+
await promptOpenInstallPage();
|
|
664
|
+
bridge.stop();
|
|
665
|
+
return null;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
program.command("sync <file>").description("\u540C\u6B65 Markdown/HTML \u6587\u4EF6\u5230\u5E73\u53F0").option("-p, --platforms <platforms>", "\u76EE\u6807\u5E73\u53F0\uFF0C\u9017\u53F7\u5206\u9694", "zhihu,juejin").option("-t, --title <title>", "\u6587\u7AE0\u6807\u9898\uFF08\u9ED8\u8BA4\u4ECE\u6587\u4EF6\u63D0\u53D6\uFF09").option("--cover <url>", "\u5C01\u9762\u56FE URL \u6216\u672C\u5730\u8DEF\u5F84").option("--dry-run", "\u4EC5\u663E\u793A\u5C06\u8981\u6267\u884C\u7684\u64CD\u4F5C\uFF0C\u4E0D\u5B9E\u9645\u540C\u6B65").action(async (file, options) => {
|
|
669
|
+
const filePath = import_path.default.resolve(file);
|
|
670
|
+
if (!import_fs.default.existsSync(filePath)) {
|
|
671
|
+
console.error(import_chalk.default.red(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`));
|
|
672
|
+
process.exit(1);
|
|
673
|
+
}
|
|
674
|
+
const parsed = parseFileContent(filePath);
|
|
675
|
+
const title = options.title || parsed.title;
|
|
676
|
+
if (!title) {
|
|
677
|
+
console.error(import_chalk.default.red("\u65E0\u6CD5\u4ECE\u6587\u4EF6\u63D0\u53D6\u6807\u9898\uFF0C\u8BF7\u4F7F\u7528 --title \u6307\u5B9A"));
|
|
678
|
+
console.log(import_chalk.default.gray("\u63D0\u793A: Markdown \u6587\u4EF6\u9700\u8981\u5305\u542B # \u6807\u9898 \u6216 YAML front matter"));
|
|
679
|
+
process.exit(1);
|
|
680
|
+
}
|
|
681
|
+
let cover = options.cover;
|
|
682
|
+
if (cover && !cover.startsWith("http") && !cover.startsWith("data:")) {
|
|
683
|
+
const coverPath = import_path.default.resolve(cover);
|
|
684
|
+
if (import_fs.default.existsSync(coverPath)) {
|
|
685
|
+
const coverBuffer = import_fs.default.readFileSync(coverPath);
|
|
686
|
+
const ext = import_path.default.extname(coverPath).toLowerCase();
|
|
687
|
+
const mimeTypes = {
|
|
688
|
+
".png": "image/png",
|
|
689
|
+
".jpg": "image/jpeg",
|
|
690
|
+
".jpeg": "image/jpeg",
|
|
691
|
+
".gif": "image/gif",
|
|
692
|
+
".webp": "image/webp"
|
|
693
|
+
};
|
|
694
|
+
const mimeType = mimeTypes[ext] || "image/png";
|
|
695
|
+
cover = `data:${mimeType};base64,${coverBuffer.toString("base64")}`;
|
|
696
|
+
} else {
|
|
697
|
+
console.error(import_chalk.default.red(`\u5C01\u9762\u56FE\u6587\u4EF6\u4E0D\u5B58\u5728: ${coverPath}`));
|
|
698
|
+
process.exit(1);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const platforms = options.platforms.split(",").map((p) => p.trim().toLowerCase());
|
|
702
|
+
const markdown = parsed.format === "markdown" ? parsed.content : void 0;
|
|
703
|
+
const html = parsed.format === "html" ? parsed.content : markdownToHtml(parsed.content);
|
|
704
|
+
console.log();
|
|
705
|
+
console.log(import_chalk.default.bold("\u540C\u6B65\u4FE1\u606F:"));
|
|
706
|
+
console.log(` \u6587\u4EF6: ${import_chalk.default.cyan(import_path.default.basename(filePath))}`);
|
|
707
|
+
console.log(` \u6807\u9898: ${import_chalk.default.cyan(title)}`);
|
|
708
|
+
console.log(` \u683C\u5F0F: ${import_chalk.default.cyan(parsed.format)}`);
|
|
709
|
+
console.log(` \u5E73\u53F0: ${import_chalk.default.cyan(platforms.join(", "))}`);
|
|
710
|
+
console.log(` \u5185\u5BB9: ${import_chalk.default.gray(parsed.content.length + " \u5B57\u7B26")}`);
|
|
711
|
+
if (cover) {
|
|
712
|
+
console.log(` \u5C01\u9762: ${import_chalk.default.cyan(cover.startsWith("data:") ? "(\u672C\u5730\u56FE\u7247)" : cover)}`);
|
|
713
|
+
}
|
|
714
|
+
console.log();
|
|
715
|
+
if (options.dryRun) {
|
|
716
|
+
console.log(import_chalk.default.yellow("(dry-run \u6A21\u5F0F\uFF0C\u4E0D\u5B9E\u9645\u540C\u6B65)"));
|
|
717
|
+
console.log();
|
|
718
|
+
console.log(import_chalk.default.bold("\u5185\u5BB9\u9884\u89C8:"));
|
|
719
|
+
console.log(import_chalk.default.gray(parsed.content.slice(0, 300) + (parsed.content.length > 300 ? "..." : "")));
|
|
720
|
+
process.exit(0);
|
|
721
|
+
}
|
|
722
|
+
const bridge = await createBridge();
|
|
723
|
+
if (!bridge) {
|
|
724
|
+
process.exit(1);
|
|
725
|
+
}
|
|
726
|
+
const fileDir = import_path.default.dirname(filePath);
|
|
727
|
+
const localImages = findLocalImages(parsed.content, fileDir);
|
|
728
|
+
let processedMarkdown = markdown;
|
|
729
|
+
let processedHtml = html;
|
|
730
|
+
if (localImages.length > 0) {
|
|
731
|
+
const imageHost = platforms[0];
|
|
732
|
+
console.log(import_chalk.default.bold(`\u53D1\u73B0 ${localImages.length} \u5F20\u672C\u5730\u56FE\u7247\uFF0C\u4E0A\u4F20\u5230 ${imageHost}...`));
|
|
733
|
+
console.log();
|
|
734
|
+
const imageResult = await processLocalImages(parsed.content, fileDir, bridge, imageHost);
|
|
735
|
+
if (imageResult.uploadedCount > 0) {
|
|
736
|
+
if (parsed.format === "markdown") {
|
|
737
|
+
processedMarkdown = imageResult.content;
|
|
738
|
+
processedHtml = markdownToHtml(imageResult.content);
|
|
739
|
+
} else {
|
|
740
|
+
processedHtml = imageResult.content;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
console.log();
|
|
744
|
+
console.log(
|
|
745
|
+
`\u56FE\u7247\u4E0A\u4F20\u5B8C\u6210: ${import_chalk.default.green(imageResult.uploadedCount + " \u6210\u529F")}, ${import_chalk.default.red(imageResult.failedCount + " \u5931\u8D25")}`
|
|
746
|
+
);
|
|
747
|
+
if (platforms.length > 1) {
|
|
748
|
+
console.log(import_chalk.default.gray(`(\u5176\u4ED6\u5E73\u53F0\u5C06\u4ECE ${imageHost} \u56FE\u5E8A\u8F6C\u5B58)`));
|
|
749
|
+
}
|
|
750
|
+
console.log();
|
|
751
|
+
}
|
|
752
|
+
const syncSpinner = (0, import_ora.default)("\u6B63\u5728\u540C\u6B65...").start();
|
|
753
|
+
try {
|
|
754
|
+
const response = await bridge.request("syncArticle", {
|
|
755
|
+
platforms,
|
|
756
|
+
article: {
|
|
757
|
+
title,
|
|
758
|
+
markdown: processedMarkdown,
|
|
759
|
+
content: processedHtml,
|
|
760
|
+
cover
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
const results = response.results || [];
|
|
764
|
+
syncSpinner.stop();
|
|
765
|
+
console.log();
|
|
766
|
+
console.log(import_chalk.default.bold("\u540C\u6B65\u7ED3\u679C:"));
|
|
767
|
+
console.log();
|
|
768
|
+
for (const result of results) {
|
|
769
|
+
if (result.success) {
|
|
770
|
+
console.log(
|
|
771
|
+
import_chalk.default.green(" \u2713"),
|
|
772
|
+
import_chalk.default.bold(result.platform),
|
|
773
|
+
result.draftOnly ? import_chalk.default.gray("(\u8349\u7A3F)") : ""
|
|
774
|
+
);
|
|
775
|
+
if (result.postUrl) {
|
|
776
|
+
console.log(` ${import_chalk.default.cyan(result.postUrl)}`);
|
|
777
|
+
}
|
|
778
|
+
} else {
|
|
779
|
+
console.log(import_chalk.default.red(" \u2717"), import_chalk.default.bold(result.platform));
|
|
780
|
+
console.log(` ${import_chalk.default.red(result.error || "\u672A\u77E5\u9519\u8BEF")}`);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const successCount = results.filter((r) => r.success).length;
|
|
784
|
+
console.log();
|
|
785
|
+
console.log(
|
|
786
|
+
`\u540C\u6B65\u5B8C\u6210: ${import_chalk.default.green(successCount + " \u6210\u529F")}, ${import_chalk.default.red(results.length - successCount + " \u5931\u8D25")}`
|
|
787
|
+
);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
syncSpinner.fail("\u540C\u6B65\u5931\u8D25");
|
|
790
|
+
console.error(import_chalk.default.red(error.message));
|
|
791
|
+
} finally {
|
|
792
|
+
bridge.stop();
|
|
793
|
+
process.exit(0);
|
|
794
|
+
}
|
|
795
|
+
});
|
|
796
|
+
program.command("platforms").alias("ls").description("\u5217\u51FA\u6240\u6709\u652F\u6301\u7684\u5E73\u53F0").option("-a, --auth", "\u540C\u65F6\u663E\u793A\u767B\u5F55\u72B6\u6001").action(async (options) => {
|
|
797
|
+
const bridge = await createBridge();
|
|
798
|
+
if (!bridge) {
|
|
799
|
+
process.exit(1);
|
|
800
|
+
}
|
|
801
|
+
const spinner = (0, import_ora.default)("\u83B7\u53D6\u5E73\u53F0\u5217\u8868...").start();
|
|
802
|
+
try {
|
|
803
|
+
const platforms = await bridge.request("listPlatforms", {
|
|
804
|
+
forceRefresh: options.auth
|
|
805
|
+
});
|
|
806
|
+
spinner.stop();
|
|
807
|
+
console.log();
|
|
808
|
+
console.log(import_chalk.default.bold(`\u652F\u6301\u7684\u5E73\u53F0 (${platforms.length}):`));
|
|
809
|
+
console.log();
|
|
810
|
+
for (const p of platforms) {
|
|
811
|
+
const status = options.auth ? p.isAuthenticated ? import_chalk.default.green("\u2713 \u5DF2\u767B\u5F55") : import_chalk.default.red("\u2717 \u672A\u767B\u5F55") : "";
|
|
812
|
+
const username = p.username ? import_chalk.default.gray(`(${p.username})`) : "";
|
|
813
|
+
console.log(` ${import_chalk.default.cyan(p.id.padEnd(15))} ${p.name.padEnd(10)} ${status} ${username}`);
|
|
814
|
+
}
|
|
815
|
+
console.log();
|
|
816
|
+
} catch (error) {
|
|
817
|
+
spinner.fail("\u83B7\u53D6\u5931\u8D25");
|
|
818
|
+
console.error(import_chalk.default.red(error.message));
|
|
819
|
+
} finally {
|
|
820
|
+
bridge.stop();
|
|
821
|
+
process.exit(0);
|
|
822
|
+
}
|
|
823
|
+
});
|
|
824
|
+
program.command("auth [platform]").description("\u68C0\u67E5\u5E73\u53F0\u767B\u5F55\u72B6\u6001").option("-r, --refresh", "\u5F3A\u5236\u5237\u65B0\u72B6\u6001").action(async (platform, options) => {
|
|
825
|
+
const bridge = await createBridge();
|
|
826
|
+
if (!bridge) {
|
|
827
|
+
process.exit(1);
|
|
828
|
+
}
|
|
829
|
+
const spinner = (0, import_ora.default)("\u68C0\u67E5\u767B\u5F55\u72B6\u6001...").start();
|
|
830
|
+
try {
|
|
831
|
+
if (platform) {
|
|
832
|
+
const result = await bridge.request("checkAuth", {
|
|
833
|
+
platform
|
|
834
|
+
});
|
|
835
|
+
spinner.stop();
|
|
836
|
+
console.log();
|
|
837
|
+
if (result.isAuthenticated) {
|
|
838
|
+
console.log(import_chalk.default.green(`\u2713 ${result.name} \u5DF2\u767B\u5F55`));
|
|
839
|
+
if (result.username) {
|
|
840
|
+
console.log(` \u7528\u6237: ${import_chalk.default.cyan(result.username)}`);
|
|
841
|
+
}
|
|
842
|
+
} else {
|
|
843
|
+
console.log(import_chalk.default.red(`\u2717 ${result.name} \u672A\u767B\u5F55`));
|
|
844
|
+
if (result.error) {
|
|
845
|
+
console.log(` \u9519\u8BEF: ${import_chalk.default.gray(result.error)}`);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
} else {
|
|
849
|
+
const platforms = await bridge.request("listPlatforms", {
|
|
850
|
+
forceRefresh: options.refresh
|
|
851
|
+
});
|
|
852
|
+
spinner.stop();
|
|
853
|
+
const authenticated = platforms.filter((p) => p.isAuthenticated);
|
|
854
|
+
const unauthenticated = platforms.filter((p) => !p.isAuthenticated);
|
|
855
|
+
console.log();
|
|
856
|
+
console.log(import_chalk.default.bold("\u767B\u5F55\u72B6\u6001:"));
|
|
857
|
+
console.log();
|
|
858
|
+
if (authenticated.length > 0) {
|
|
859
|
+
console.log(import_chalk.default.green(`\u5DF2\u767B\u5F55 (${authenticated.length}):`));
|
|
860
|
+
for (const p of authenticated) {
|
|
861
|
+
const username = p.username ? import_chalk.default.gray(`(${p.username})`) : "";
|
|
862
|
+
console.log(` ${import_chalk.default.cyan(p.id.padEnd(15))} ${p.name} ${username}`);
|
|
863
|
+
}
|
|
864
|
+
console.log();
|
|
865
|
+
}
|
|
866
|
+
if (unauthenticated.length > 0) {
|
|
867
|
+
console.log(import_chalk.default.red(`\u672A\u767B\u5F55 (${unauthenticated.length}):`));
|
|
868
|
+
for (const p of unauthenticated) {
|
|
869
|
+
console.log(` ${import_chalk.default.gray(p.id.padEnd(15))} ${p.name}`);
|
|
870
|
+
}
|
|
871
|
+
console.log();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
} catch (error) {
|
|
875
|
+
spinner.fail("\u68C0\u67E5\u5931\u8D25");
|
|
876
|
+
console.error(import_chalk.default.red(error.message));
|
|
877
|
+
} finally {
|
|
878
|
+
bridge.stop();
|
|
879
|
+
process.exit(0);
|
|
880
|
+
}
|
|
881
|
+
});
|
|
882
|
+
program.command("extract").description("\u4ECE\u5F53\u524D\u6D4F\u89C8\u5668\u9875\u9762\u63D0\u53D6\u6587\u7AE0").option("-o, --output <file>", "\u8F93\u51FA\u5230\u6587\u4EF6").action(async (options) => {
|
|
883
|
+
const bridge = await createBridge();
|
|
884
|
+
if (!bridge) {
|
|
885
|
+
process.exit(1);
|
|
886
|
+
}
|
|
887
|
+
const spinner = (0, import_ora.default)("\u63D0\u53D6\u6587\u7AE0...").start();
|
|
888
|
+
try {
|
|
889
|
+
const article = await bridge.request("extractArticle");
|
|
890
|
+
spinner.stop();
|
|
891
|
+
if (options.output) {
|
|
892
|
+
const outputPath = import_path.default.resolve(options.output);
|
|
893
|
+
const content = article.markdown || article.content;
|
|
894
|
+
const output = `# ${article.title}
|
|
895
|
+
|
|
896
|
+
${content}`;
|
|
897
|
+
import_fs.default.writeFileSync(outputPath, output, "utf-8");
|
|
898
|
+
console.log(import_chalk.default.green(`\u2713 \u5DF2\u4FDD\u5B58\u5230: ${outputPath}`));
|
|
899
|
+
} else {
|
|
900
|
+
console.log();
|
|
901
|
+
console.log(import_chalk.default.bold("\u6807\u9898:"), article.title);
|
|
902
|
+
console.log();
|
|
903
|
+
console.log(import_chalk.default.bold("\u5185\u5BB9\u9884\u89C8:"));
|
|
904
|
+
const preview = (article.markdown || article.content).slice(0, 500);
|
|
905
|
+
console.log(import_chalk.default.gray(preview + (preview.length >= 500 ? "..." : "")));
|
|
906
|
+
}
|
|
907
|
+
} catch (error) {
|
|
908
|
+
spinner.fail("\u63D0\u53D6\u5931\u8D25");
|
|
909
|
+
console.error(import_chalk.default.red(error.message));
|
|
910
|
+
} finally {
|
|
911
|
+
bridge.stop();
|
|
912
|
+
process.exit(0);
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
if (process.argv.length <= 2) {
|
|
916
|
+
console.log();
|
|
917
|
+
console.log(import_chalk.default.bold("WechatSync CLI") + " - \u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E2A\u5185\u5BB9\u5E73\u53F0");
|
|
918
|
+
console.log();
|
|
919
|
+
console.log(`\u5B98\u7F51: ${import_chalk.default.cyan(WEBSITE_URL)}`);
|
|
920
|
+
console.log();
|
|
921
|
+
console.log("\u652F\u6301\u7684\u5E73\u53F0: \u77E5\u4E4E\u3001\u6398\u91D1\u3001CSDN\u3001\u5934\u6761\u3001\u5FAE\u535A\u3001B\u7AD9\u3001\u7B80\u4E66 \u7B49 20+ \u5E73\u53F0");
|
|
922
|
+
console.log();
|
|
923
|
+
program.outputHelp();
|
|
924
|
+
process.exit(0);
|
|
925
|
+
}
|
|
926
|
+
program.parse();
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@wechatsync/cli",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "WechatSync CLI - 命令行同步文章到多个平台",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"bin": {
|
|
7
|
+
"wechatsync": "./dist/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsup",
|
|
14
|
+
"dev": "tsup --watch",
|
|
15
|
+
"start": "node dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"wechat",
|
|
19
|
+
"sync",
|
|
20
|
+
"markdown",
|
|
21
|
+
"zhihu",
|
|
22
|
+
"juejin",
|
|
23
|
+
"csdn",
|
|
24
|
+
"publish",
|
|
25
|
+
"article",
|
|
26
|
+
"claude",
|
|
27
|
+
"ai"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/wechatsync/Wechatsync"
|
|
32
|
+
},
|
|
33
|
+
"author": "fun",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"commander": "^12.1.0",
|
|
37
|
+
"chalk": "^5.3.0",
|
|
38
|
+
"ora": "^8.0.1",
|
|
39
|
+
"open": "^10.1.0",
|
|
40
|
+
"ws": "^8.18.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@wechatsync/mcp-server": "workspace:*",
|
|
44
|
+
"@types/node": "^22.10.2",
|
|
45
|
+
"@types/ws": "^8.5.13",
|
|
46
|
+
"tsup": "^8.5.1",
|
|
47
|
+
"typescript": "^5.7.2"
|
|
48
|
+
}
|
|
49
|
+
}
|