pi-wechat-session-hub 0.1.1 → 0.1.4

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,281 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 发布前检查与发布后校验。
4
+ *
5
+ * 0.1.0 曾因 2FA 触发 npm staged publishing, packument 的 readme 与
6
+ * readmeFilename 落成空字符串, 导致包进不了 npm search 索引, pi.dev/packages
7
+ * 也查不到。本脚本把这条教训固化成两步检查:
8
+ *
9
+ * node scripts/release-preflight.mjs 发布前检查(不需要网络写权限)
10
+ * node scripts/release-preflight.mjs --verify 发布后校验 registry 元数据
11
+ */
12
+ import { execFileSync } from "node:child_process";
13
+ import { readFileSync } from "node:fs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { dirname, join } from "node:path";
16
+
17
+ const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
18
+ const REGISTRY = "https://registry.npmjs.org";
19
+
20
+ /** 打包后必须存在的文件, 缺任意一个都说明 files 配置有问题。 */
21
+ const REQUIRED_FILES = [
22
+ "package.json",
23
+ "README.md",
24
+ "CHANGELOG.md",
25
+ "LICENSE",
26
+ "extensions/wechat-session-hub.ts",
27
+ "extensions/daemon-entry.mjs",
28
+ "src/runtime/gateway-daemon.ts",
29
+ ];
30
+
31
+ const failures = [];
32
+ const notes = [];
33
+
34
+ /**
35
+ * 记录一条失败原因。
36
+ *
37
+ * @param {string} message 失败说明。
38
+ * @returns {void}
39
+ */
40
+ function fail(message) {
41
+ failures.push(message);
42
+ }
43
+
44
+ /**
45
+ * 记录一条提示信息。
46
+ *
47
+ * @param {string} message 提示说明。
48
+ * @returns {void}
49
+ */
50
+ function note(message) {
51
+ notes.push(message);
52
+ }
53
+
54
+ /**
55
+ * 读取本地 package.json。
56
+ *
57
+ * @returns {Record<string, unknown>} 解析后的清单对象。
58
+ */
59
+ function readManifest() {
60
+ return JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8"));
61
+ }
62
+
63
+ /**
64
+ * 请求 registry 的 packument, 不存在时返回 undefined。
65
+ *
66
+ * @param {string} name 包名。
67
+ * @returns {Promise<Record<string, unknown> | undefined>} packument 或 undefined。
68
+ */
69
+ async function fetchPackument(name) {
70
+ const response = await fetch(`${REGISTRY}/${encodeURIComponent(name)}`, {
71
+ headers: { "user-agent": "pi-wechat-session-hub-release-check" },
72
+ });
73
+ if (response.status === 404) {
74
+ return undefined;
75
+ }
76
+ if (!response.ok) {
77
+ throw new Error(`registry 返回 ${response.status}`);
78
+ }
79
+ return await response.json();
80
+ }
81
+
82
+ /**
83
+ * 执行发布前检查。
84
+ *
85
+ * @returns {Promise<void>} 检查完成后返回。
86
+ */
87
+ async function runPreflight() {
88
+ const manifest = readManifest();
89
+ const { name, version, keywords, files, dependencies, pi } = manifest;
90
+
91
+ if (!Array.isArray(keywords) || !keywords.includes("pi-package")) {
92
+ fail("keywords 缺少 pi-package, 包不会出现在 pi.dev/packages");
93
+ }
94
+ if (!pi || !Array.isArray(pi.extensions) || pi.extensions.length === 0) {
95
+ fail("package.json 缺少 pi.extensions 清单");
96
+ }
97
+ if (!dependencies || !dependencies.jiti) {
98
+ fail("dependencies 缺少 jiti, npm 安装后 daemon 启动垫片会加载失败");
99
+ }
100
+ if (!Array.isArray(files) || !files.includes("CHANGELOG.md")) {
101
+ note("files 未包含 CHANGELOG.md, 更新日志不会进入 tarball");
102
+ }
103
+
104
+ const packed = JSON.parse(
105
+ execFileSync(process.platform === "win32" ? "npm.cmd" : "npm", ["pack", "--dry-run", "--json"], {
106
+ cwd: PACKAGE_ROOT,
107
+ encoding: "utf8",
108
+ stdio: ["ignore", "pipe", "pipe"],
109
+ shell: process.platform === "win32",
110
+ }),
111
+ )[0];
112
+ const packedPaths = new Set(packed.files.map((entry) => entry.path));
113
+ for (const required of REQUIRED_FILES) {
114
+ if (!packedPaths.has(required)) {
115
+ fail(`tarball 缺少 ${required}`);
116
+ }
117
+ }
118
+ note(`tarball 含 ${packed.entryCount} 个文件, ${(packed.size / 1024).toFixed(1)} KiB`);
119
+
120
+ const packument = await fetchPackument(name);
121
+ if (!packument) {
122
+ note(`${name} 在 registry 上尚不存在, 本次为首次发布`);
123
+ } else {
124
+ const published = packument.versions?.[version];
125
+ if (published) {
126
+ fail(`版本 ${version} 已存在于 registry, 请先提升版本号`);
127
+ }
128
+ const latest = packument["dist-tags"]?.latest;
129
+ note(`registry 当前 latest 为 ${latest}, 本地待发布 ${version}`);
130
+ }
131
+
132
+ report();
133
+ }
134
+
135
+ /**
136
+ * 发布后校验 registry 元数据, 重点验证 0.1.0 踩过的 readme 空值问题。
137
+ *
138
+ * @returns {Promise<void>} 校验完成后返回。
139
+ */
140
+ async function runVerify() {
141
+ const manifest = readManifest();
142
+ const { name, version } = manifest;
143
+
144
+ const packument = await fetchPackument(name);
145
+ if (!packument) {
146
+ fail(`${name} 在 registry 上不存在`);
147
+ report();
148
+ return;
149
+ }
150
+
151
+ const published = packument.versions?.[version];
152
+ if (!published) {
153
+ const rawVersions = Object.keys(packument.versions ?? {});
154
+ if (rawVersions.includes("0.0.0-stage") || packument["dist-tags"]?.latest !== version) {
155
+ fail(`registry 上暂时看不到 ${version}: npm 可能正在做发布后安全扫描(网页显示 Validating), 稍等几分钟后重试`);
156
+ } else {
157
+ fail(`registry 上找不到 ${version}, 发布可能尚未生效`);
158
+ }
159
+ report();
160
+ return;
161
+ }
162
+
163
+ // 版本级 readme 在正常发布的包里也常为空, 真正影响搜索索引的是顶层 readme,
164
+ // 因此只在顶层也为空时判失败, 避免误报。
165
+ const packumentReadme = typeof packument.readme === "string" ? packument.readme : "";
166
+ const versionReadme = typeof published.readme === "string" ? published.readme : "";
167
+ if (packumentReadme.trim().length === 0) {
168
+ fail("顶层 readme 为空, 该包可能无法进入 npm search 索引(0.1.0 的同款问题)");
169
+ } else {
170
+ const versionNote = versionReadme.trim().length === 0 ? "(版本级为空属正常)" : "";
171
+ note(`顶层 readme ${packumentReadme.length} 字符, 版本级 readme ${versionReadme.length} 字符${versionNote}`);
172
+ }
173
+
174
+ const latest = packument["dist-tags"]?.latest;
175
+ if (latest !== version) {
176
+ fail(`dist-tags.latest 是 ${latest}, 与本地版本 ${version} 不一致`);
177
+ } else {
178
+ note(`dist-tags.latest = ${version}`);
179
+ }
180
+
181
+ const searchHit = await checkNpmSearch(name).catch((error) => {
182
+ note(`npm search 检查跳过: ${error instanceof Error ? error.message : String(error)}`);
183
+ return undefined;
184
+ });
185
+ if (searchHit === true) {
186
+ note("npm search 已能检索到该包");
187
+ } else if (searchHit === false) {
188
+ note("npm search 暂未收录, 索引有延迟, 通常几分钟到数小时");
189
+ }
190
+
191
+ const galleryHit = await checkGallery(name).catch((error) => {
192
+ note(`pi.dev/packages 检查跳过: ${error instanceof Error ? error.message : String(error)}`);
193
+ return undefined;
194
+ });
195
+ if (galleryHit === true) {
196
+ note("pi.dev/packages 已能搜到该包");
197
+ } else if (galleryHit === false) {
198
+ note("pi.dev/packages 暂未收录, 站点有自己的索引缓存, 需要等待刷新");
199
+ }
200
+
201
+ report();
202
+ }
203
+
204
+ /**
205
+ * 查询 npm search 是否已收录该包。
206
+ *
207
+ * @param {string} name 包名。
208
+ * @returns {Promise<boolean>} 已收录返回 true, 未收录返回 false。
209
+ */
210
+ async function checkNpmSearch(name) {
211
+ const response = await fetchWithTimeout(
212
+ `${REGISTRY}/-/v1/search?text=${encodeURIComponent(`${name} keywords:pi-package`)}&size=20`,
213
+ );
214
+ if (!response.ok) {
215
+ throw new Error(`search 接口返回 ${response.status}`);
216
+ }
217
+ const result = await response.json();
218
+ return Boolean(result.objects?.some((item) => item.package?.name === name));
219
+ }
220
+
221
+ /**
222
+ * 查询 pi.dev 包画廊是否已收录该包。
223
+ *
224
+ * @param {string} name 包名。
225
+ * @returns {Promise<boolean>} 已收录返回 true, 未收录返回 false。
226
+ */
227
+ async function checkGallery(name) {
228
+ const response = await fetchWithTimeout(`https://pi.dev/packages?name=${encodeURIComponent(name)}`);
229
+ if (!response.ok) {
230
+ throw new Error(`pi.dev 返回 ${response.status}`);
231
+ }
232
+ const html = await response.text();
233
+ return html.includes(name);
234
+ }
235
+
236
+ /**
237
+ * 带超时的 fetch。
238
+ *
239
+ * 外部站点(尤其是经 Cloudflare 的 pi.dev)在网络受限时可能长时间不响应,
240
+ * 必须显式限时, 否则会拖住整个校验流程。
241
+ *
242
+ * @param {string} url 请求地址。
243
+ * @returns {Promise<Response>} 响应对象。
244
+ */
245
+ async function fetchWithTimeout(url) {
246
+ const controller = new AbortController();
247
+ const timer = setTimeout(() => controller.abort(), 15000);
248
+ try {
249
+ return await fetch(url, {
250
+ headers: { "user-agent": "pi-wechat-session-hub-release-check" },
251
+ signal: controller.signal,
252
+ });
253
+ } finally {
254
+ clearTimeout(timer);
255
+ }
256
+ }
257
+
258
+ /**
259
+ * 输出结果并按失败情况设置退出码。
260
+ *
261
+ * @returns {void}
262
+ */
263
+ function report() {
264
+ for (const message of notes) {
265
+ console.log(` · ${message}`);
266
+ }
267
+ if (failures.length === 0) {
268
+ console.log("\n检查通过");
269
+ return;
270
+ }
271
+ console.error("");
272
+ for (const message of failures) {
273
+ console.error(` ✗ ${message}`);
274
+ }
275
+ console.error(`\n${failures.length} 项检查未通过`);
276
+ process.exitCode = 1;
277
+ }
278
+
279
+ const isVerify = process.argv.includes("--verify");
280
+ console.log(isVerify ? "发布后校验" : "发布前检查");
281
+ await (isVerify ? runVerify() : runPreflight());
@@ -6,11 +6,12 @@ export type GatewayCommand =
6
6
  | { kind: "status" }
7
7
  | { kind: "projects"; arguments: string }
8
8
  | { kind: "new"; mode?: RuntimeMode; projectAlias?: string; name?: string }
9
- | { kind: "sessions"; projectAlias?: string; state: "default" | "active" | "saved" | "pending" | "all"; page: number }
9
+ | { kind: "sessions"; projectAlias?: string; state: "default" | "active" | "saved" | "pending" | "all" }
10
10
  | { kind: "resume"; selector: string }
11
11
  | { kind: "last"; selector?: string }
12
12
  | { kind: "stop"; selector?: string }
13
13
  | { kind: "retry"; messageId: string; confirmed: boolean }
14
+ | { kind: "watch"; all: boolean }
14
15
  | { kind: "prompt"; text: string };
15
16
 
16
17
  /**
@@ -91,6 +92,9 @@ export function parseGatewayCommand(text: string): GatewayCommand {
91
92
  ...(arguments_[0] ? { selector: arguments_[0] } : {}),
92
93
  };
93
94
  }
95
+ if (commandName === "watch") {
96
+ return parseWatchCommand(arguments_);
97
+ }
94
98
  if (commandName === "retry") {
95
99
  if (
96
100
  arguments_.length < 1 ||
@@ -112,6 +116,24 @@ export function parseGatewayCommand(text: string): GatewayCommand {
112
116
  );
113
117
  }
114
118
 
119
+ /**
120
+ * 解析 /watch 参数。
121
+ *
122
+ * 不带参数时只展示运行中与异常会话; 带 --all 时展示全部。
123
+ *
124
+ * @param arguments_ 去掉命令名后的 token 列表。
125
+ * @returns watch 参数。
126
+ */
127
+ function parseWatchCommand(arguments_: string[]): GatewayCommand {
128
+ if (arguments_.length === 0) {
129
+ return { kind: "watch", all: false };
130
+ }
131
+ if (arguments_.length === 1 && arguments_[0] === "--all") {
132
+ return { kind: "watch", all: true };
133
+ }
134
+ throw usageError();
135
+ }
136
+
115
137
  /**
116
138
  * 解析 /new 参数。
117
139
  *
@@ -144,14 +166,9 @@ function parseNewCommand(arguments_: string[]): GatewayCommand {
144
166
  * @returns session 列表过滤参数。
145
167
  */
146
168
  function parseSessionsCommand(arguments_: string[]): GatewayCommand {
147
- const options = readOptions(arguments_, ["project", "state", "page"]);
169
+ const options = readOptions(arguments_, ["project", "state"]);
148
170
  const projectAlias = options.get("project");
149
171
  const state = options.get("state") ?? "active";
150
- const pageText = options.get("page") ?? "1";
151
- const page = Number(pageText);
152
- if (!Number.isInteger(page) || page < 1) {
153
- throw new GatewayCommandParseError("page 必须是大于 0 的整数。");
154
- }
155
172
  if (
156
173
  state !== "default" &&
157
174
  state !== "active" &&
@@ -165,7 +182,6 @@ function parseSessionsCommand(arguments_: string[]): GatewayCommand {
165
182
  kind: "sessions",
166
183
  ...(projectAlias ? { projectAlias } : {}),
167
184
  state,
168
- page,
169
185
  };
170
186
  }
171
187
 
@@ -279,7 +295,7 @@ function extractRawArguments(input: string): string {
279
295
  }
280
296
 
281
297
  const GATEWAY_COMMAND_USAGE =
282
- "用法: /new [--mode background|ui] [--project <alias>] [--name <名称>] | /sessions [--project <alias>] [--state active|saved|pending|all] [--page <n>] | /resume <会话索引|名称> | /last [会话索引|名称] | /stop [会话索引|名称] | /retry <message-id> --confirm | /status | /projects | /help";
298
+ "用法: /new [--mode background|ui] [--project <alias>] [--name <名称>] | /sessions [--project <alias>] [--state active|saved|pending|all] | /watch [--all] | /resume <会话索引|名称> | /last [会话索引|名称] | /stop [会话索引|名称] | /retry <message-id> --confirm | /status | /projects | /help";
283
299
 
284
300
  /**
285
301
  * 创建统一格式的 command usage 错误。