@wkgeo/cli 1.1.5 → 2.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.
@@ -1,1013 +1,438 @@
1
- /**
2
- * 站点运营类命令(0.5.0 新增):
3
- *
4
- * * `wkgeo plugins list|toggle` 插件开关(`/cms/pluginList` / `/cms/pluginToggle`)
5
- * * `wkgeo forms list|entries` 表单与提交记录(`/form/formList` / `/form/formEntryList`)
6
- * * `wkgeo domain inspection` 域名巡检(`/cli` 的 `cmsSiteDomainInspectionList`,只读)
7
- * * `wkgeo preview <path>` 拼预览地址(零后端)
8
- * * `wkgeo import-v2 start|status` 导入老网站 v2(默认 dry-run)
9
- *
10
- * 共同约定:
11
- * * 站点一律走 `ctx.cmsSite()`(`--site` > `WKONGAI_SITE` > `site use`),没站点就报用法错误;
12
- * * 所有"人产出的数据"(表单提交、域名巡检里的客户信息)**默认脱敏**,要原文得加 `--raw --confirm`;
13
- * * 写操作默认 dry-run,`--confirm` 才真发。
14
- */
15
-
16
- import { camel } from '../args.mjs';
17
- import { CliError, EXIT, UsageError } from '../errors.mjs';
18
- import { maskPii, maskPiiDeep, formatTime } from '../format.mjs';
19
- import { PLATFORM_WEB_ORIGIN } from '../hosts.mjs';
20
- import { openUrlForUser } from '../login.mjs';
21
-
22
- /** 表单后台函数(`wkgeo-plugin-contact-form`)认的来源;不给会被 `checkAdminOrigin` 403 */
23
- const FORM_ORIGIN = PLATFORM_WEB_ORIGIN;
24
-
25
- const SITE_FLAG = {
26
- site: { type: 'string', desc: '站点 ID(默认用 `wkgeo site use` 选中的站点,可用 WKONGAI_SITE 覆盖)' },
27
- };
28
-
29
- /** 站点必须显式(表单/发布这类写操作不接受"随便哪个站") */
30
- function needSite(ctx, what) {
31
- const site = ctx.cmsSite();
32
- if (!site.id) {
33
- throw new UsageError(`${what}需要指定站点`, {
34
- hint: '先 `wkgeo site use <站点ID>` 选站,或加 `--site <站点ID>`。',
35
- });
36
- }
37
- return site;
38
- }
39
-
40
- function rowsOf(data) {
41
- if (Array.isArray(data)) return data;
42
- if (data && Array.isArray(data.rows)) return data.rows;
43
- if (data && Array.isArray(data.list)) return data.list;
44
- if (data && Array.isArray(data.plugins)) return data.plugins;
45
- return [];
46
- }
47
-
48
- /* ------------------------------------------------------------------ 表单 */
49
-
50
- /**
51
- * 表单后台动作只认 CMS 后台 Cookie(`cms_session`)+ Origin 白名单,**不认 Bearer**。
52
- * 这里把 401/403 翻成一句人话,而不是把后端原文甩给用户 —— 但也**不假装成功**。
53
- */
54
- function formCall(ctx, action, payload) {
55
- return ctx
56
- .callData(action, payload, {
57
- prefix: 'form',
58
- headers: { Origin: FORM_ORIGIN, 'x-cms-site': ctx.cmsSite().id },
59
- })
60
- .catch((err) => {
61
- const kind = String((err && err.kind) || '');
62
- if (kind === 'cms_auth' || kind === 'unauthenticated' || kind === 'forbidden' || kind === 'expired') {
63
- throw new CliError('表单后台接口(/form)目前只认 CMS 后台登录态,CLI 的授权令牌还调不通', {
64
- kind: 'form_backend_gap',
65
- exitCode: EXIT.AUTH,
66
- hint:
67
- '这是后端缺口(插件函数未接 Bearer 桥),不是你的权限问题:' +
68
- '现在请在 CMS 后台「表单」页查看;后端补上 Bearer 桥后 `wkgeo forms` 会自动可用。',
69
- });
70
- }
71
- throw err;
72
- });
73
- }
74
-
75
- function formSummary(form) {
76
- const fields = Array.isArray(form.fields) ? form.fields : (form.schema && form.schema.fields) || [];
77
- return Array.isArray(fields) ? fields : [];
78
- }
79
-
80
- export const formsListCommand = {
81
- name: 'forms list',
82
- summary: '列本站表单(字段数、提交数、未读数)',
83
- usage: 'wkgeo forms list [--site <站点ID>] [--json]',
84
- args: [],
85
- flags: { ...SITE_FLAG },
86
- examples: ['wkgeo forms list', 'wkgeo forms list --json'],
87
- notes: [
88
- '表单结构(字段名/类型/是否必填)不含客户数据,可以放心看。',
89
- '提交记录里会有手机号/邮箱/IP —— `wkgeo forms entries` 默认全部脱敏。',
90
- ],
91
- async run(ctx) {
92
- const { out } = ctx;
93
- const site = needSite(ctx, 'forms');
94
- const data = (await formCall(ctx, 'formList', {})) || {};
95
- const forms = rowsOf(data);
96
- const payload = {
97
- site_id: site.id,
98
- total: forms.length,
99
- unread_total: data.unreadTotal || 0,
100
- embed_base: data.embedBase || '',
101
- forms: forms.map((f) => ({
102
- id: f.id,
103
- key: f.key,
104
- name: f.name,
105
- status: f.status || '',
106
- fields: formSummary(f).map((one) => ({ key: one.key, label: one.label, type: one.type, required: one.required === true })),
107
- entry_count: f.entryCount || 0,
108
- unread_count: f.unreadCount || 0,
109
- })),
110
- };
111
- if (!out.json) {
112
- out.head(`表单(站点 ${site.id})`);
113
- out.table(
114
- [
115
- { title: '名称', key: 'name', width: 22 },
116
- { title: 'key', key: 'key', width: 20 },
117
- { title: '字段', key: 'fields', width: 6 },
118
- { title: '提交', key: 'entries', width: 6 },
119
- { title: '未读', key: 'unread', width: 6 },
120
- ],
121
- payload.forms.map((f) => ({
122
- name: f.name,
123
- key: f.key,
124
- fields: f.fields.length,
125
- entries: f.entry_count,
126
- unread: f.unread_count,
127
- })),
128
- );
129
- out.info(`未读合计 ${payload.unread_total};看提交:\`wkgeo forms entries --form <id>\``);
130
- }
131
- ctx.done(payload);
132
- return payload;
133
- },
134
- };
135
-
136
- export const formsEntriesCommand = {
137
- name: 'forms entries',
138
- summary: '看表单提交记录(默认脱敏:手机号/邮箱/IP/UA 都不出原文)',
139
- usage:
140
- 'wkgeo forms entries [--form <表单ID>] [--status new|read] [--keyword <词>] [--page <n>] [--page-size <n>] [--raw --confirm]',
141
- args: [],
142
- flags: {
143
- ...SITE_FLAG,
144
- form: { type: 'string', desc: '只看某个表单(表单 ID)' },
145
- status: { type: 'string', desc: 'new 未读 / read 已读' },
146
- keyword: { type: 'string', desc: '关键词(后端按字段值模糊匹配)' },
147
- page: { type: 'string', desc: '页码(从 1 开始)' },
148
- 'page-size': { type: 'string', desc: '每页条数(1..100,默认 20)' },
149
- raw: { type: 'boolean', desc: '输出原文(**必须同时加 --confirm**,否则不执行)' },
150
- confirm: { type: 'boolean', desc: '配合 --raw 确认"我确实要看客户原文"' },
151
- },
152
- examples: [
153
- 'wkgeo forms entries',
154
- 'wkgeo forms entries --form <表单ID> --status new --page-size 50',
155
- 'wkgeo forms entries --raw --confirm --form <表单ID> # 真要看原文',
156
- ],
157
- notes: [
158
- '**默认脱敏**:手机 `138****1234`、邮箱 `zh***@e***.com`、IP 只留前三段、UA 只报长度。',
159
- '`--raw` 必须再给 `--confirm`:不给就报用法错误(防止手滑把客户隐私打到终端/日志)。',
160
- '记录里有 client_ip / user_agent 字段,脱敏后仍会显示"有值",但看不到原文。',
161
- ],
162
- async run(ctx) {
163
- const { out } = ctx;
164
- const site = needSite(ctx, 'forms entries');
165
- const raw = ctx.flags.raw === true;
166
- if (raw && ctx.flags.confirm !== true) {
167
- throw new UsageError('--raw 会输出客户原文,必须再加 --confirm', {
168
- hint: '确认要看原文:`wkgeo forms entries --raw --confirm`(输出的内容可能含手机号/邮箱/IP,别贴到公开地方)',
169
- });
170
- }
171
-
172
- const page = Number(ctx.flags.page || 1);
173
- const pageSize = Number(ctx.flags.pageSize || 20);
174
- if (!Number.isFinite(page) || page < 1) throw new UsageError('--page 必须是 ≥1 的整数');
175
- if (!Number.isFinite(pageSize) || pageSize < 1 || pageSize > 100) throw new UsageError('--page-size 必须是 1..100 的整数');
176
-
177
- const body = { page, pageSize };
178
- if (ctx.flags.form) body.formId = String(ctx.flags.form);
179
- if (ctx.flags.status) body.status = String(ctx.flags.status);
180
- if (ctx.flags.keyword) body.keyword = String(ctx.flags.keyword);
181
-
182
- const data = (await formCall(ctx, 'formEntryList', body)) || {};
183
- const rows = rowsOf(data);
184
-
185
- const shown = rows.map((one) => {
186
- const values = Array.isArray(one.values) ? one.values : [];
187
- const entry = {
188
- id: one.id,
189
- form_id: one.formId,
190
- form_name: one.formName,
191
- status: one.status,
192
- created_at: one.createdAt,
193
- client_ip: one.clientIp || '',
194
- user_agent: one.userAgent || '',
195
- values: values.map((v) => ({ key: v.key, label: v.label, value: v.value === undefined || v.value === null ? '' : String(v.value) })),
196
- };
197
- return raw ? entry : maskPiiDeep(entry, { scrubStrings: true });
198
- });
199
-
200
- const payload = {
201
- site_id: site.id,
202
- page: data.page || page,
203
- page_size: data.pageSize || pageSize,
204
- total: data.total || 0,
205
- unread_total: data.unreadTotal || 0,
206
- redacted: !raw,
207
- entries: shown,
208
- };
209
-
210
- if (!out.json) {
211
- out.head(`表单提交(站点 ${site.id},第 ${payload.page} 页,共 ${payload.total} 条${payload.unread_total ? `,未读 ${payload.unread_total}` : ''})`);
212
- if (!shown.length) {
213
- out.line(' (这一页没有记录)');
214
- }
215
- for (const one of shown) {
216
- out.line('');
217
- out.line(` #${one.id} ${one.form_name || ''} | ${one.status || ''} | ${one.created_at || ''}`);
218
- for (const v of one.values) {
219
- out.line(` ${v.label || v.key}:${v.value}`);
220
- }
221
- if (one.client_ip) out.line(` IP:${one.client_ip}`);
222
- }
223
- if (payload.redacted) {
224
- out.line('');
225
- out.info('以上已脱敏(手机/邮箱/IP/UA)。需要原文:`--raw --confirm`。');
226
- } else {
227
- out.warn('⚠️ 这是**未脱敏原文**:别贴进公开 issue / 群聊 / 提交到仓库。');
228
- }
229
- }
230
- ctx.done(payload);
231
- return payload;
232
- },
233
- };
234
-
235
- /* ------------------------------------------------------------------ 域名巡检 */
236
-
237
- export const domainInspectionCommand = {
238
- name: 'domain inspection',
239
- summary: '看域名巡检结果(只读;需要系统管理员权限)',
240
- usage: 'wkgeo domain inspection [--keyword <词>] [--status pending|resolved|verified|failed|timeout] [--page <n>] [--page-size <n>] [--scope all] [--site <站点ID>]',
241
- args: [],
242
- flags: {
243
- ...SITE_FLAG,
244
- keyword: { type: 'string', desc: '按域名/站点名过滤' },
245
- status: { type: 'string', desc: 'pending 待解析 / resolved 已解析 / verified 已验证 / failed 失败 / timeout 超时' },
246
- page: { type: 'string', desc: '页码(从 1 开始)' },
247
- 'page-size': { type: 'string', desc: '每页条数(1..100,默认 20)' },
248
- scope: { type: 'string', desc: 'all = 全平台(仅平台管理员可用;默认只看自己的站)' },
249
- },
250
- examples: [
251
- 'wkgeo domain inspection',
252
- 'wkgeo domain inspection --status failed',
253
- 'wkgeo domain inspection --scope all --page-size 100',
254
- 'wkgeo domain inspection --site a9c743ed-7db7-4156-b7ef-eb6bf6065163',
255
- ],
256
- notes: [
257
- '后端动作 `cmsSiteDomainInspectionList` 的权限是「系统管理」:普通账号会回 403,这里给一句人话,不抛堆栈。',
258
- '`--status verified` = 域名已经解析到我们的 CDN 且证书就绪。',
259
- '`--scope all` 只有平台管理员能用;其他人传了会被后端拒(403)。',
260
- '**多站账号必须带 `--site`**:动作走 `/cli` 自持通道时站点只从 `body.siteId` 认(B4 起不再用 `x-cms-site` 头),不带就回「缺少 siteId」。',
261
- ],
262
- async run(ctx) {
263
- const { out } = ctx;
264
- const page = Number(ctx.flags.page || 1);
265
- const pageSize = Number(ctx.flags.pageSize || 20);
266
- if (!Number.isFinite(page) || page < 1) throw new UsageError('--page 必须是 ≥1 的整数');
267
- if (!Number.isFinite(pageSize) || pageSize < 1 || pageSize > 100) throw new UsageError('--page-size 必须是 1..100 的整数');
268
-
269
- const body = { page, pageSize };
270
- if (ctx.flags.keyword) body.keyword = String(ctx.flags.keyword);
271
- if (ctx.flags.status) body.status = String(ctx.flags.status);
272
- if (ctx.flags.scope) body.scope = String(ctx.flags.scope);
273
-
274
- let data;
275
- try {
276
- data = (await ctx.siteCoreCall('cmsSiteDomainInspectionList', body)) || {};
277
- } catch (err) {
278
- const kind = String((err && err.kind) || '');
279
- const denied = (err && err.exitCode === 3) || kind === 'cms_policy' || kind === 'cms_scope' || kind === 'forbidden' || kind === 'cms_readonly';
280
- if (!denied) throw err;
281
- throw new CliError('域名巡检需要「系统管理员」权限,当前账号没有', {
282
- kind: 'domain_inspection_forbidden',
283
- exitCode: EXIT.AUTH,
284
- hint: '让站点/平台的系统管理员在 CMS 后台「系统管理 → 域名巡检」看,或请他给你加「系统管理」权限后再跑这条命令。',
285
- });
286
- }
287
-
288
- const rows = rowsOf(data);
289
- const payload = {
290
- total: data.total || rows.length,
291
- rows_count: rows.length,
292
- page: data.page || page,
293
- page_size: data.pageSize || pageSize,
294
- scope: data.scope || (ctx.flags.scope ? String(ctx.flags.scope) : 'site'),
295
- domain: rows.map((one) => ({
296
- domain: one.domain || one.host || '',
297
- site_name: one.siteName || one.site_name || '',
298
- status: one.status || '',
299
- resolved_at: one.resolvedAt || one.resolved_at || '',
300
- checked_at: one.checkedAt || one.checked_at || '',
301
- message: maskPii(String(one.message || '')),
302
- })),
303
- };
304
-
305
- if (!out.json) {
306
- out.head(`域名巡检(${payload.scope === 'all' ? '全平台' : '本站'},共 ${payload.total} 条)`);
307
- if (!payload.domain.length) {
308
- out.line(' (没有记录:还没绑过自有域名,或都没进巡检队列)');
309
- } else {
310
- out.table(
311
- [
312
- { title: '域名', key: 'domain', width: 32 },
313
- { title: '站点', key: 'site_name', width: 16 },
314
- { title: '状态', key: 'status', width: 10 },
315
- { title: '检查时间', key: 'checked_at', width: 20 },
316
- ],
317
- payload.domain,
318
- );
319
- }
320
- }
321
- ctx.done(payload);
322
- return payload;
323
- },
324
- };
325
-
326
- /* ------------------------------------------------------------------ 域名(只读) */
327
-
328
- /**
329
- * ★ task-9(0.5.2 未发布):域名只读命令。
330
- *
331
- * 只做了**读**:`status` / `records` / `dns` / `check` / `remind`。
332
- * `domain bind` / `domain unbind`(真实绑定/解绑)故意没有 —— 权限模型(谁能绑、谁来批)
333
- * 还没拍板,现在加进去就是给普通账号一条"改线上解析"的路。
334
- * `domain repair` 也还没有:等后端 B2 的修复动作上线(`printShortDomain` 里那段 TODO)。
335
- */
336
-
337
- /** DNS 记录的三态(后端 `ok` 是 true / false / null) */
338
- function dnsStateLabel(ok) {
339
- if (ok === true) return '已生效';
340
- if (ok === false) return '未生效';
341
- return '未知';
342
- }
343
-
344
- /** 开通状态人话(未知值原样返回,别编) */
345
- const PROVISION_LABEL = {
346
- none: '未开始',
347
- pending: '待开通',
348
- provisioning: '开通中',
349
- active: '已开通',
350
- failed: '失败',
351
- released: '已释放',
352
- };
353
-
354
- function provisionLabel(state) {
355
- const key = String(state || '');
356
- return PROVISION_LABEL[key] || (key || '未知');
357
- }
358
-
359
- /** `siteDomainCheck` 的 reason → 人话(后端只回枚举,不回占用方) */
360
- const CHECK_REASON_LABEL = {
361
- self: '你自己的站已经在用',
362
- taken: '已被别人占用',
363
- platform_owned: '平台保留域名',
364
- invalid: '格式不合法',
365
- };
366
-
367
- /**
368
- * 「域名开通通道暂不可用」的统一人话(2026-10-28 task-12)。
369
- *
370
- * 触发条件是**上游** `wkgeo-domain` 的内部通道没开(部署侧
371
- * `DOMAIN_INTERNAL_CHANNEL_ENABLED` 目前仍是 false),`wkgeo-cli-fc` 会把上游 503 归一成
372
- * 「域名服务暂时不可用,请稍后重试或联系客服(本次未计入每日额度,可直接重试)」。
373
- * CLI 这一层**不许假装成功**:明说没写入、可重试,并按业务失败退出(exit 1)。
374
- */
375
- const BIND_CHANNEL_UNAVAILABLE = '域名开通通道暂不可用(平台侧未开),本次未写入,可直接重试';
376
-
377
- /**
378
- * `domain bind` —— 给站点绑定自有域名。
379
- *
380
- * ## 为什么这条命令一直缺
381
- * 2026-10-28 之前 OAuth 令牌调 `provisionSiteDomain` 一律 403(`action-risk.js` 的会员自助策略),
382
- * 要绑域只能走超管后台。`wkgeo-cli-fc` 上线后有了**原生动作 `cliProvisionSiteDomain`**
383
- * (CLI 自己的函数接、代执行 domain 的内部开通编排,免 428 短信二次验证)⇒ CLI 才有入口。
384
- *
385
- * ## 为什么 unbind / repair 没有对应命令(重要,别"顺手补上")
386
- * `/cli` 的动作面里**没有**解绑 / 修复的等价动作:
387
- * · 解绑:只有 `releaseSiteDomain`,走 OAuth 时照样 428(要短信二次验证)且动作面未收录;
388
- * · 修复:`retrySiteProvision` 在 `DOMAIN_ACTIONS` 里,但语义是"重跑一次开通",
389
- * 与"修复"不是一回事,CLI 不另造命令 —— 等价做法就是**再跑一次 `domain bind`**
390
- * (后端幂等:同站同域重复调用会复用记录、不重置状态)。
391
- */
392
- export const domainBindCommand = {
393
- name: 'domain bind',
394
- summary: '给站点绑定自有域名(原生动作 cliProvisionSiteDomain;未开通时明说可重试,不假装成功)',
395
- usage: 'wkgeo domain bind <域名> [--site <站点ID>] [--json]',
396
- args: [{ name: 'domain', required: true, desc: '要绑定的自有域名,如 www.example.com(不带 http:// 与路径)' }],
397
- flags: { ...SITE_FLAG },
398
- examples: [
399
- 'wkgeo domain bind www.example.com --site <站点ID>',
400
- 'wkgeo domain bind www.example.com --site <站点ID> --json',
401
- ],
402
- notes: [
403
- '后端动作 `cliProvisionSiteDomain`:CLI 自己的函数接,代执行 `wkgeo-domain` 的内部开通编排(免 OAuth 的 428 短信二次验证)。',
404
- '渠道依赖:该内部通道由部署侧开关 `DOMAIN_INTERNAL_CHANNEL_ENABLED` 控制。**没开时上游回 503** ⇒ CLI 打印「域名开通通道暂不可用(平台侧未开),本次未写入,可直接重试」并按失败退出,绝不假装成功。',
405
- '成功只是"受理开通":`provision_state` 通常是 provisioning,进度用 `wkgeo domain status` 看;要客户自己去域名商加的解析用 `wkgeo domain dns`。',
406
- '平台自有域名(wkgeo.com / wkgeo.com.cn 等)会被平台侧 403 挡住;站点已绑了**别的**域名时回 409 —— 换域名要先去会员中心解绑(短信二次验证,CLI 不支持)。',
407
- '**没有** `domain unbind` / `domain repair`:`/cli` 动作面没有等价动作(解绑只有 `releaseSiteDomain`,OAuth 下 428)。重试开通 = 再跑一次 `domain bind`(幂等)。',
408
- ],
409
- async run(ctx) {
410
- const { out } = ctx;
411
- const domain = String((ctx.positional && ctx.positional.domain) || '')
412
- .trim()
413
- .toLowerCase()
414
- .replace(/\.$/, '');
415
- if (!domain) {
416
- throw new UsageError('缺少域名:wkgeo domain bind <域名> --site <站点ID>', {
417
- hint: '例:wkgeo domain bind www.example.com --site <站点ID>',
418
- });
419
- }
420
- if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/.test(domain)) {
421
- throw new UsageError(`域名形状不合法:${domain}`, {
422
- hint: '只填域名本身(如 www.example.com),不要带 http:// / 路径 / 空格。',
423
- });
424
- }
425
- const site = needSite(ctx, 'domain bind');
426
-
427
- let data;
428
- try {
429
- data = (await ctx.callData('cliProvisionSiteDomain', { id: site.id, domain })) || {};
430
- } catch (err) {
431
- const code = Number(err && err.code);
432
- const body = (err && err.raw && err.raw.body) || {};
433
- const bodyData = body.data || {};
434
- const reason = String(bodyData.code || '');
435
-
436
- /** 503 = 上游域名通道没开(或真故障):说清"没写入 + 可重试",exit 1 */
437
- if (code === 503) {
438
- throw new CliError(BIND_CHANNEL_UNAVAILABLE, {
439
- kind: 'domain_channel_unavailable',
440
- code: 503,
441
- exitCode: EXIT.ERROR,
442
- hint: `服务端原文:${(err && err.message) || '域名服务暂时不可用'}。本次没有写入任何东西;平台开通后直接重跑同一条命令即可。`,
443
- raw: err && err.raw,
444
- });
445
- }
446
- if (code === 403) {
447
- const owned = reason === 'platform_owned_domain';
448
- throw new CliError((err && err.message) || '绑域被拒绝(403)', {
449
- kind: owned ? 'platform_owned_domain' : 'domain_bind_forbidden',
450
- code: 403,
451
- exitCode: EXIT.AUTH,
452
- hint: owned
453
- ? '平台自有域名只有超管后台能配;请换自己的域名(如你买的 example.com)。'
454
- : '只有站点归属人(owner)能绑定域名:确认 `--site` 是你自己的站(`wkgeo sites list` 查)。',
455
- raw: err && err.raw,
456
- });
457
- }
458
- if (code === 409 || reason === 'domain_already_bound') {
459
- throw new CliError(
460
- `站点已绑定了另一个域名(${bodyData.current_domain || '未知'}),本次未改动`,
461
- {
462
- kind: 'domain_already_bound',
463
- code: 409,
464
- exitCode: EXIT.ERROR,
465
- hint: '换域名要先在会员中心解绑(短信二次验证,CLI 不支持),解绑后再跑一次 `wkgeo domain bind`。',
466
- raw: err && err.raw,
467
- },
468
- );
469
- }
470
- /** 429 / 401 / 其它:保留原错误(exit 4 / 3 / 1 的语义由 errors.mjs 定) */
471
- throw err;
472
- }
473
-
474
- const payload = { ...data, site_id: data.site_id || site.id, domain: data.domain || domain };
475
-
476
- if (!out.json) {
477
- out.head(`绑定域名:${payload.domain} → 站点 ${payload.site_id}`);
478
- out.line(
479
- ` 开通状态:${provisionLabel(payload.provision_state)}${payload.provision_step ? `(步骤:${payload.provision_step})` : ''}${
480
- payload.idempotent ? ' [幂等命中,本次未重复执行]' : ''
481
- }`,
482
- );
483
- if (payload.esa_record_id) out.line(` ESA 记录:${payload.esa_record_id}`);
484
- if (payload.cname_target) out.line(` CNAME 目标:${payload.cname_target}`);
485
- if (payload.check_status) out.line(` 校验状态:${payload.check_status}`);
486
- if (payload.verify_code) out.line(` TXT 验证值:${payload.verify_code}`);
487
- if (payload.verify_host) out.line(` TXT 主机记录:${payload.verify_host}`);
488
- if (payload.dns_auto) {
489
- out.line(` 自动解析:${String(payload.dns_auto.status || JSON.stringify(payload.dns_auto))}`);
490
- }
491
- if (payload.note) out.info(` ${payload.note}`);
492
- out.ok('已受理域名开通(进度:`wkgeo domain status`;要加的解析:`wkgeo domain dns`)');
493
- }
494
- ctx.done(payload);
495
- return payload;
496
- },
497
- };
498
-
499
- export const domainStatusCommand = {
500
- name: 'domain status',
501
- summary: '看站点域名开通到哪一步(只读:解析 / 证书 / ESA / 失败原因)',
502
- usage: 'wkgeo domain status [--site <站点ID>] [--json]',
503
- args: [],
504
- flags: { ...SITE_FLAG },
505
- examples: ['wkgeo domain status', 'wkgeo domain status --site <站点ID>'],
506
- notes: [
507
- '后端动作 `getSiteProvisionStatus`:`provision_state` = none 未开始 / provisioning 开通中 / active 已开通 / failed 失败;卡住看 `provision_step` 和 `last_error`。',
508
- '`customer_todo` 有值 = **要你自己去域名商加的解析**(TXT 验证 + CNAME 接入);不想读 JSON 就用 `wkgeo domain dns` 看现成清单。',
509
- '`--site` 不填时用 `wkgeo site use` 选中的站(或环境变量 WKONGAI_SITE)。',
510
- ],
511
- async run(ctx) {
512
- const { out } = ctx;
513
- const id = needSite(ctx, 'domain status').id;
514
- const data = (await ctx.callData('getSiteProvisionStatus', { id })) || {};
515
- const payload = { ...data, site_id: data.site_id || id };
516
-
517
- if (!out.json) {
518
- out.head(`域名开通状态:${payload.site_id}`);
519
- out.line(` 自有域名:${payload.custom_domain || '未绑定'}`);
520
- out.line(
521
- ` 开通状态:${provisionLabel(payload.provision_state)}${payload.provision_step ? `(步骤:${payload.provision_step})` : ''}`,
522
- );
523
- if (payload.esa_site_id) {
524
- out.line(` ESA 站点:${payload.esa_site_id}${payload.esa_status ? `(${payload.esa_status})` : ''}`);
525
- }
526
- out.line(` 证书:${payload.cert_status || '未申请'}${payload.cert_not_after ? `(到期 ${formatTime(payload.cert_not_after)})` : ''}`);
527
- if (payload.offline_reason) out.warn(`已下线原因:${payload.offline_reason}`);
528
- if (payload.last_error) {
529
- out.warn(`最近错误:${payload.last_error}${payload.last_error_at ? `(${formatTime(payload.last_error_at)})` : ''}`);
530
- }
531
- out.line(
532
- ` 开通尝试:${payload.provision_attempts || 0} 次${payload.next_check_at ? ` · 下次检查:${formatTime(payload.next_check_at)}` : ''}`,
533
- );
534
- if (payload.verified_at) out.line(` 已验证:${formatTime(payload.verified_at)}`);
535
- if (payload.activated_at) out.line(` 已激活:${formatTime(payload.activated_at)}`);
536
-
537
- const todo = payload.customer_todo || null;
538
- if (todo) {
539
- /** TXT 是"证明域名是你的",CNAME 是"把访问接过来",两条都得加 */
540
- const list = [todo.txt, todo.cname].filter(Boolean);
541
- out.head(' 要你在域名商自己加的解析');
542
- if (list.length) {
543
- out.table(
544
- [
545
- { title: '主机记录', key: 'rr', width: 24 },
546
- { title: '类型', key: 'type', width: 8 },
547
- { title: '记录值', key: 'value', width: 48 },
548
- ],
549
- list.map((one) => ({
550
- rr: one.name_hint || one.name || '',
551
- type: one.record_type || one.type || '',
552
- value: one.value || '',
553
- })),
554
- );
555
- }
556
- const all = Array.isArray(todo.domains) ? todo.domains.filter(Boolean) : [];
557
- if (all.length > 1) {
558
- out.line(` (一共 ${all.length} 个域名要各加一遍:${all.map((one) => one.domain).filter(Boolean).join('、')})`);
559
- }
560
- if (todo.icp_required) out.warn('该域名要先完成 ICP 备案才能开通;备案下来后再跑一次 `wkgeo domain status`。');
561
- out.info(' → 现成清单:`wkgeo domain dns`');
562
- } else if (!payload.custom_domain) {
563
- out.info(' → 还没有自有域名:先 `wkgeo sites create --domain <域名> --channel platform` 登记(只登记,不触发解析/证书)。');
564
- }
565
-
566
- const log = Array.isArray(payload.provision_log) ? payload.provision_log.slice(-5) : [];
567
- if (log.length) {
568
- out.head(' 最近开通日志');
569
- for (const one of log) out.line(` · ${typeof one === 'string' ? one : JSON.stringify(one)}`);
570
- }
571
- }
572
- ctx.done(payload);
573
- return payload;
574
- },
575
- };
576
-
577
- export const domainRecordsCommand = {
578
- name: 'domain records',
579
- summary: '看站点已登记域名的解析 / 证书 / ESA 明细(只读)',
580
- usage: 'wkgeo domain records [--site <站点ID>] [--json]',
581
- args: [],
582
- flags: { ...SITE_FLAG },
583
- examples: ['wkgeo domain records', 'wkgeo domain records --site <站点ID> --json'],
584
- notes: [
585
- '后端动作 `siteDomainRecords`:每个域名的 TXT 验证 / CNAME 接入各自带 `ok`(true 已生效 / false 未生效 / null 未知)。',
586
- '短域(`*.wkgeo.com.cn`)不走这张表,所以这里只列你自己登记的域名。',
587
- '只想抄要加的解析?用 `wkgeo domain dns`(同一份数据,换成一张照抄表)。',
588
- ],
589
- async run(ctx) {
590
- const { out } = ctx;
591
- const id = needSite(ctx, 'domain records').id;
592
- const data = (await ctx.callData('siteDomainRecords', { id })) || {};
593
- const domains = Array.isArray(data.domains) ? data.domains : [];
594
- const payload = { ...data, site_id: data.site_id || id, domains };
595
-
596
- if (!out.json) {
597
- out.head(`域名解析记录:${payload.site_id}${payload.custom_domain ? `(${payload.custom_domain})` : ''}`);
598
- out.line(
599
- ` 开通状态:${provisionLabel(payload.provision_state)}${data.legacy_fallback ? ' · 旧数据兜底' : ''}${
600
- payload.synced_at ? ` · 同步于 ${formatTime(payload.synced_at)}` : ''
601
- }`,
602
- );
603
- if (!domains.length) {
604
- out.line(` ${data.hint || '绑定域名后在这里显示解析记录'}`);
605
- } else {
606
- out.table(
607
- [
608
- { title: '域名', key: 'hostname', width: 32 },
609
- { title: '类型', key: 'kind', width: 10 },
610
- { title: '验证', key: 'verify', width: 12 },
611
- { title: 'TXT', key: 'txt', width: 8 },
612
- { title: 'CNAME', key: 'cname', width: 8 },
613
- { title: '证书', key: 'cert', width: 10 },
614
- ],
615
- domains.map((one) => ({
616
- hostname: one.hostname || '',
617
- kind: one.kind || '',
618
- verify: one.verify_status || '',
619
- txt: dnsStateLabel(one.dns_txt && one.dns_txt.ok),
620
- cname: dnsStateLabel(one.dns_cname && one.dns_cname.ok),
621
- cert: (one.cert && one.cert.status) || '',
622
- })),
623
- );
624
- for (const one of domains) {
625
- if (one.last_error) out.warn(` ${one.hostname || '(未命名)'}:${one.last_error}`);
626
- }
627
- }
628
- }
629
- ctx.done(payload);
630
- return payload;
631
- },
632
- };
633
-
634
- export const domainDnsCommand = {
635
- name: 'domain dns',
636
- summary: '把「要你自己去域名商加的解析」打成可照抄清单(只读)',
637
- usage: 'wkgeo domain dns [--site <站点ID>] [--json]',
638
- args: [],
639
- flags: { ...SITE_FLAG },
640
- examples: ['wkgeo domain dns', 'wkgeo domain dns --site <站点ID>'],
641
- notes: [
642
- '数据源同 `domain records`(`siteDomainRecords`),但只留 **RR / 类型 / 记录值 / 状态** 四列,照着抄到域名商。',
643
- 'CLI **不会**替你加 DNS(也不碰你的域名商账号):加完等几分钟,再跑 `wkgeo domain status` 看验证 / 证书。',
644
- '`主机记录` 一列是相对值(`@` / `www` 这种),不要连域名一起抄进去,各家面板口径略有差别。',
645
- ],
646
- async run(ctx) {
647
- const { out } = ctx;
648
- const id = needSite(ctx, 'domain dns').id;
649
- const data = (await ctx.callData('siteDomainRecords', { id })) || {};
650
- const domains = Array.isArray(data.domains) ? data.domains : [];
651
- const records = [];
652
- const seen = new Set();
653
- for (const one of domains) {
654
- for (const [dns, type] of [
655
- [one.dns_txt, 'TXT'],
656
- [one.dns_cname, 'CNAME'],
657
- ]) {
658
- if (!dns) continue;
659
- const row = {
660
- rr: dns.name_hint || dns.name || '',
661
- type: dns.record_type || dns.type || type,
662
- value: dns.value || '',
663
- state: dnsStateLabel(dns.ok),
664
- hostname: one.hostname || '',
665
- };
666
- /** 多个域名可能共用一条(比如 apex 与 www 各一条,但不该重复) */
667
- const key = `${row.rr}|${row.type}|${row.value}`;
668
- if (seen.has(key)) continue;
669
- seen.add(key);
670
- records.push(row);
671
- }
672
- }
673
- const payload = {
674
- site_id: data.site_id || id,
675
- custom_domain: data.custom_domain || null,
676
- provision_state: data.provision_state || null,
677
- synced_at: data.synced_at || null,
678
- records,
679
- hint: records.length ? null : data.hint || '绑定域名后这里会列出要加的解析记录',
680
- };
681
-
682
- if (!out.json) {
683
- out.head('要你在域名商自己加的解析(照抄 Value 那列)');
684
- if (!records.length) {
685
- out.line(` ${payload.hint}`);
686
- out.info(' → 还没有自有域名?先登记:`wkgeo sites create --domain <域名> --channel platform`(只登记,不触发解析)。');
687
- } else {
688
- out.table(
689
- [
690
- { title: '主机记录 (RR)', key: 'rr', width: 26 },
691
- { title: '类型', key: 'type', width: 8 },
692
- { title: '记录值 (Value)', key: 'value', width: 52 },
693
- { title: '状态', key: 'state', width: 10 },
694
- ],
695
- records,
696
- );
697
- out.info(' → 加完 DNS 等 5~10 分钟,再跑 `wkgeo domain status` 看验证 / 证书是否通过。');
698
- out.info(' → CLI 不会替你加 DNS,也不会碰你的域名商账号。');
699
- }
700
- }
701
- ctx.done(payload);
702
- return payload;
703
- },
704
- };
705
-
706
- export const domainCheckCommand = {
707
- name: 'domain check',
708
- summary: '查域名还能不能注册(只读;一次最多 10 个)',
709
- usage: 'wkgeo domain check <域名…>',
710
- args: [{ name: 'domains', required: true, variadic: true, desc: '一个或多个域名(com / cn 这种,不带 http:// 与路径)' }],
711
- flags: {},
712
- examples: ['wkgeo domain check example.com', 'wkgeo domain check a.com b.cn c.net'],
713
- notes: [
714
- '后端动作 `siteDomainCheck`:只看**能不能注册**,不回占用方是谁(隐私)。',
715
- '`available` = true 可注册 / false 不可用(看 reason:已被占用、平台保留、格式不合法)/ null 没查出来。',
716
- '限流 30 次/分;超了会回 429(CLI 退出码 4)。',
717
- '域名**购买**不在 CLI 里(见 README 的「暂缓」说明),这里只做可用性查询。',
718
- ],
719
- async run(ctx) {
720
- const { out } = ctx;
721
- const input = (Array.isArray(ctx.positional.domains) ? ctx.positional.domains : [])
722
- .map((one) => String(one || '').trim())
723
- .filter(Boolean);
724
- if (!input.length) {
725
- throw new UsageError('至少给一个域名:wkgeo domain check <域名…>', { hint: '例:wkgeo domain check example.com' });
726
- }
727
- if (input.length > 10) {
728
- throw new UsageError(`一次最多查 10 个域名(收到 ${input.length} 个)`, { hint: '分几次跑,别把限流打满。' });
729
- }
730
- const data = (await ctx.callData('siteDomainCheck', { domains: input })) || {};
731
- const items = Array.isArray(data.items) ? data.items : [];
732
- const payload = { checked: input.length, items };
733
-
734
- if (!out.json) {
735
- out.head(`域名可用性(${input.length} 个)`);
736
- for (const one of items) {
737
- const domain = one.domain || one.normalized || '';
738
- const reason = CHECK_REASON_LABEL[String(one.reason || '')] || null;
739
- let verdict;
740
- if (one.available === true) verdict = '可注册';
741
- else if (one.available === false) verdict = reason ? `不可用(${reason})` : '不可用';
742
- else verdict = '没查出来(稍后重试)';
743
- out.line(` ${domain} → ${verdict}`);
744
- }
745
- if (items.length < input.length) out.info(' (服务端只回了部分结果,没回的可能是格式不支持)');
746
- }
747
- ctx.done(payload);
748
- return payload;
749
- },
750
- };
751
-
752
- export const domainRemindCommand = {
753
- name: 'domain remind',
754
- summary: '看哪些域名快到期(只读;需要平台管理员权限)',
755
- usage: 'wkgeo domain remind [--limit <n>]',
756
- args: [],
757
- flags: { limit: { type: 'string', desc: '最多看几条(1..200,默认 50)' } },
758
- examples: ['wkgeo domain remind', 'wkgeo domain remind --limit 200'],
759
- notes: [
760
- '后端动作 `getSiteDomainReminders`:按 30 / 7 / 1 天三档提醒。',
761
- '权限是**平台管理员**:普通账号会回 403,这里给一句人话(退出码 3),不抛堆栈。',
762
- '后端没开提醒表时会回 `{processed:0, skipped:true}`,CLI 显示「没有需要提醒的域名」。',
763
- ],
764
- async run(ctx) {
765
- const { out } = ctx;
766
- const raw = ctx.flags.limit === undefined ? 50 : Number(ctx.flags.limit);
767
- if (!Number.isInteger(raw) || raw < 1 || raw > 200) {
768
- throw new UsageError('--limit 必须是 1..200 的整数');
769
- }
770
- let data;
771
- try {
772
- data = (await ctx.callData('getSiteDomainReminders', { limit: raw })) || {};
773
- } catch (err) {
774
- const kind = String((err && err.kind) || '');
775
- const denied =
776
- (err && err.exitCode === 3) || (err && err.code === 403) || kind === 'forbidden' || kind === 'cms_policy' || kind === 'cms_scope';
777
- if (!denied) throw err;
778
- throw new CliError('域名到期提醒需要「平台管理员」权限,当前账号没有', {
779
- kind: 'domain_remind_forbidden',
780
- exitCode: EXIT.AUTH,
781
- hint: '让平台管理员跑 `wkgeo domain remind --limit 200`,或到超管后台看域名到期提醒。',
782
- });
783
- }
784
- const reminders = Array.isArray(data.reminders) ? data.reminders : [];
785
- const payload = { ...data, reminders, count: reminders.length };
786
-
787
- if (!out.json) {
788
- out.head(`域名到期提醒(${reminders.length} 个${data.tiers ? `;分档 ${data.tiers.join('/')} 天` : ''})`);
789
- if (!reminders.length) {
790
- out.line(` ${data.skipped ? '(后端没有开启到期提醒表:没有需要提醒的域名)' : '(没有 30 / 7 / 1 天内到期的域名)'}`);
791
- } else {
792
- out.table(
793
- [
794
- { title: '域名', key: 'hostname', width: 34 },
795
- { title: '站点 ID', key: 'site_id', width: 38 },
796
- { title: '到期时间', key: 'expires_at', width: 20 },
797
- { title: '剩余天数', key: 'days_left', width: 10 },
798
- { title: '档位', key: 'tier', width: 6 },
799
- ],
800
- reminders.map((one) => ({
801
- hostname: one.hostname || '',
802
- site_id: one.site_id || '',
803
- expires_at: one.expires_at ? formatTime(one.expires_at) : '',
804
- days_left: one.days_left === undefined || one.days_left === null ? '' : String(one.days_left),
805
- tier: one.tier === undefined || one.tier === null ? '' : String(one.tier),
806
- })),
807
- );
808
- }
809
- }
810
- ctx.done(payload);
811
- return payload;
812
- },
813
- };
814
-
815
- /* ------------------------------------------------------------------ 预览 */
816
-
817
- export const previewCommand = {
818
- name: 'preview',
819
- summary: '拼一个预览地址(走 CMS 预览通道,不需要发布)',
820
- usage: 'wkgeo preview <路径> [--site <站点ID>] [--open]',
821
- args: [{ name: 'path', required: true, desc: '站内路径,如 /about/ 或 news/2026/' }],
822
- flags: {
823
- ...SITE_FLAG,
824
- open: { type: 'boolean', desc: '用系统默认浏览器打开(非 TTY 环境会自动跳过)' },
825
- },
826
- examples: ['wkgeo preview /about/', 'wkgeo preview news/2026/ --site <站点ID> --open'],
827
- notes: [
828
- `地址形如 \`${PLATFORM_WEB_ORIGIN}/cms/preview/<站点ID>/<路径>\`,走预览通道:**看的是草稿态**,不影响线上。`,
829
- '零后端调用:只拼字符串,不产生任何写操作。',
830
- '`--open` 用的是系统默认浏览器;CI / 非交互环境会自动跳过(不会卡住)。',
831
- ],
832
- async run(ctx) {
833
- const { out } = ctx;
834
- const site = needSite(ctx, 'preview');
835
- let rel = String(ctx.positional.path || '').trim();
836
- if (!rel) throw new UsageError('请给出要预览的站内路径');
837
- rel = rel.replace(/^https?:\/\/[^/]+/i, '');
838
- rel = rel.replace(/^\/+/, '');
839
-
840
- const url = `${PLATFORM_WEB_ORIGIN}/cms/preview/${site.id}/${rel}`;
841
- const payload = { site_id: site.id, path: `/${rel}`, url };
842
-
843
- if (!out.json) {
844
- out.ok(url);
845
- out.info('预览通道看的是草稿态;要上线还得 `wkgeo publish --confirm`。');
846
- }
847
- if (ctx.flags.open) {
848
- const res = await openUrlForUser(url, {
849
- deps: {
850
- openBrowser: ctx.openBrowser,
851
- platform: ctx.platform,
852
- spawnImpl: ctx.spawnImpl,
853
- verbose: ctx.flags.verbose,
854
- isTTY: ctx.isTTY,
855
- json: ctx.out.json,
856
- forceOpen: true,
857
- env: ctx.env,
858
- },
859
- });
860
- payload.opened = Boolean(res && res.opened);
861
- if (!out.json) {
862
- if (res && res.opened) out.info('已用默认浏览器打开。');
863
- else out.info('没有可用的图形浏览器,地址已打印在上面,手动打开即可。');
864
- }
865
- }
866
- ctx.done(payload);
867
- return payload;
868
- },
869
- };
870
-
871
- /* ------------------------------------------------------------------ 导入 v2 */
872
-
873
- /** `importV2Start` 接受的选项(数值型都是可选的;不传就用后端默认) */
874
- const IMPORT_V2_OPTIONS = [
875
- ['list-limit', 'listLimit', 'num'],
876
- ['news-limit', 'newsLimit', 'num'],
877
- ['other-list-limit', 'otherListLimit', 'num'],
878
- ['max-pages', 'maxPages', 'num'],
879
- ['verify-rounds', 'verifyRounds', 'num'],
880
- ['structure-rounds', 'structureRounds', 'num'],
881
- ['structure-batch-size', 'structureBatchSize', 'num'],
882
- ['structure-concurrency', 'structureConcurrency', 'num'],
883
- ['search', 'search', 'bool'],
884
- ['overwrite', 'overwrite', 'bool'],
885
- ['auto-repair', 'autoRepair', 'bool'],
886
- ];
887
-
888
- export const importV2StartCommand = {
889
- name: 'import-v2 start',
890
- summary: '从老网站导入内容(默认 dry-run;`--confirm` 才真的提交任务)',
891
- usage: 'wkgeo import-v2 start --url <老站地址> [--confirm] [--site <站点ID>] [选项…]',
892
- args: [],
893
- flags: {
894
- ...SITE_FLAG,
895
- url: { type: 'string', required: true, desc: '老站首页地址(http/https)' },
896
- confirm: { type: 'boolean', desc: '真提交(不加只打印计划)' },
897
- search: { type: 'boolean', desc: '导入后顺便配好站内搜索(默认开;关掉用 --no-search)' },
898
- overwrite: { type: 'boolean', desc: '已存在同路径内容时覆盖(默认不覆盖)' },
899
- 'max-pages': { type: 'string', desc: '最多抓多少页(保护老站与预算)' },
900
- 'list-limit': { type: 'string', desc: '每个列表页最多收多少条' },
901
- 'news-limit': { type: 'string', desc: '新闻/资讯类最多收多少条' },
902
- 'other-list-limit': { type: 'string', desc: '其它列表类最多收多少条' },
903
- },
904
- examples: [
905
- 'wkgeo import-v2 start --url https://old-site.example.com/ # dry-run',
906
- 'wkgeo import-v2 start --url https://old-site.example.com/ --confirm # 真提交',
907
- 'wkgeo import-v2 start --url https://old-site.example.com/ --max-pages 200 --confirm',
908
- ],
909
- notes: [
910
- '不加 `--confirm` 是 **dry-run**:只打印将提交什么,**不发任何写请求**。',
911
- '真提交后立刻返回 `runId`,抓取在后台跑;用 `wkgeo import-v2 status --run <runId>` 看进度。',
912
- '需要「导入」写权限(canWrite);后端没部署 v2 导入时会回"未知动作",那是服务端缺动作。',
913
- ],
914
- async run(ctx) {
915
- const { out } = ctx;
916
- const site = needSite(ctx, 'import-v2');
917
- const url = String(ctx.flags.url || '').trim();
918
- if (!url) throw new UsageError('请用 --url 给出老站地址');
919
- if (!/^https?:\/\//i.test(url)) throw new UsageError('--url 只支持 http/https 地址');
920
-
921
- const options = {};
922
- for (const [flagKey, bodyKey, kind] of IMPORT_V2_OPTIONS) {
923
- const value = ctx.flags[camel(flagKey)];
924
- if (value === undefined) continue;
925
- if (kind === 'num') {
926
- const n = Number(value);
927
- if (!Number.isFinite(n) || n <= 0) throw new UsageError(`--${flagKey} 必须是正数`);
928
- options[bodyKey] = n;
929
- } else {
930
- options[bodyKey] = value === true;
931
- }
932
- }
933
-
934
- if (ctx.flags.confirm !== true) {
935
- const payload = { site_id: site.id, action: 'dry_run', confirmed: false, url, options };
936
- if (!out.json) {
937
- out.head('导入 v2 计划(dry-run,未提交任何任务)');
938
- out.line(` 站点:${site.id}`);
939
- out.line(` 老站:${url}`);
940
- const keys = Object.keys(options);
941
- out.line(` 选项:${keys.length ? keys.map((k) => `${k}=${options[k]}`).join(' ') : '(全部用后端默认)'}`);
942
- out.line('');
943
- out.line(' 确认无误就加 `--confirm`:任务会在后台抓取老站结构与内容。');
944
- }
945
- ctx.done(payload);
946
- return payload;
947
- }
948
-
949
- const started = (await ctx.cmsCall('importV2Start', { url, ...options })) || {};
950
- const payload = {
951
- site_id: site.id,
952
- action: 'start',
953
- confirmed: true,
954
- run_id: started.runId || '',
955
- status: started.status || '',
956
- total_stages: started.totalStages || 0,
957
- dispatched: started.dispatched === true,
958
- dispatch_via: started.dispatchVia || '',
959
- timings: started.timings || null,
960
- url,
961
- options,
962
- };
963
- if (!out.json) {
964
- if (payload.dispatched) out.ok(`导入任务已提交:${payload.run_id}(共 ${payload.total_stages} 个阶段,后台跑着)`);
965
- else out.warn(`任务已建但**没派发出去**:${payload.run_id}(状态 ${payload.status});请找后端看派发配置。`);
966
- out.info(`看进度:wkgeo import-v2 status --run ${payload.run_id}`);
967
- }
968
- ctx.done(payload);
969
- return payload;
970
- },
971
- };
972
-
973
- export const importV2StatusCommand = {
974
- name: 'import-v2 status',
975
- summary: '看导入 v2 任务的进度(只读)',
976
- usage: 'wkgeo import-v2 status --run <任务ID> [--site <站点ID>] [--json]',
977
- args: [],
978
- flags: {
979
- ...SITE_FLAG,
980
- run: { type: 'string', required: true, desc: '任务 ID(`import-v2 start --confirm` 回的那个 runId)' },
981
- },
982
- examples: ['wkgeo import-v2 status --run <runId>', 'wkgeo import-v2 status --run <runId> --json'],
983
- notes: [
984
- '后端 `importV2Get` **必须带 runId**(没有"最新一次"的退路):不给就报用法错误。',
985
- '返回里有 stage/status/进度、素材汇总、预览地址与自检结果(原样透出,不裁剪)。',
986
- ],
987
- async run(ctx) {
988
- const { out } = ctx;
989
- const site = needSite(ctx, 'import-v2 status');
990
- const runId = String(ctx.flags.run || '').trim();
991
- if (!runId) throw new UsageError('请用 --run 给出任务 ID', { hint: 'runId 在 `import-v2 start --confirm` 的回执里。' });
992
-
993
- const res = (await ctx.cmsCall('importV2Get', { runId })) || {};
994
- const run = res.run || {};
995
- const payload = { site_id: site.id, run_id: runId, run };
996
- if (!out.json) {
997
- out.head(`导入任务 ${runId}`);
998
- const known = ['status', 'stage', 'message', 'error', 'totalStages', 'doneStages', 'startedAt', 'finishedAt', 'previewUrl'];
999
- for (const key of known) {
1000
- if (run[key] !== undefined && run[key] !== null && run[key] !== '') out.line(` ${key}: ${run[key]}`);
1001
- }
1002
- if (run.summary && typeof run.summary === 'object') {
1003
- const parts = Object.entries(run.summary)
1004
- .filter(([, v]) => v === null || ['string', 'number', 'boolean'].includes(typeof v))
1005
- .map(([k, v]) => `${k}=${v}`);
1006
- if (parts.length) out.line(` summary: ${parts.join(' ')}`);
1007
- }
1008
- out.info('(完整结构用 --json 看;这里只挑人最关心的几项。)');
1009
- }
1010
- ctx.done(payload);
1011
- return payload;
1012
- },
1013
- };
1
+ /**
2
+ * 站点运营类命令(0.5.0 新增):
3
+ *
4
+ * ★ 2026-11-19 task-1250(老板:CLI 只做 CMS 内容管理,跟域名没有关系,不在那里操作):
5
+ * 本文件原有的 7 条域名命令(inspection / bind / status / records / dns / check / remind)
6
+ * 与域名状态标签表、绑域通道文案**已全部删除** —— 域名到 wkgeo-domain / 超管后台 / 会员中心操作。
7
+ *
8
+ * * `wkgeo plugins list|toggle` 插件开关(`/cms/pluginList` / `/cms/pluginToggle`)
9
+ * * `wkgeo forms list|entries` 表单与提交记录(`/form/formList` / `/form/formEntryList`)
10
+ * * `wkgeo preview <path>` 拼预览地址(零后端)
11
+ * * `wkgeo import-v2 start|status` 导入老网站 v2(默认 dry-run)
12
+ *
13
+ * 共同约定:
14
+ * * 站点一律走 `ctx.cmsSite()`(`--site` > `WKONGAI_SITE` > `site use`),没站点就报用法错误;
15
+ * * 所有"人产出的数据"(表单提交里的客户信息)**默认脱敏**,要原文得加 `--raw --confirm`;
16
+ * * 写操作默认 dry-run,`--confirm` 才真发。
17
+ */
18
+
19
+ import { camel } from '../args.mjs';
20
+ import { CliError, EXIT, UsageError } from '../errors.mjs';
21
+ import { maskPii, maskPiiDeep, formatTime } from '../format.mjs';
22
+ import { PLATFORM_WEB_ORIGIN } from '../hosts.mjs';
23
+ import { openUrlForUser } from '../login.mjs';
24
+
25
+ /** 表单后台函数(`wkgeo-plugin-contact-form`)认的来源;不给会被 `checkAdminOrigin` 403 */
26
+ const FORM_ORIGIN = PLATFORM_WEB_ORIGIN;
27
+
28
+ const SITE_FLAG = {
29
+ site: { type: 'string', desc: '站点 ID(默认用 `wkgeo site use` 选中的站点,可用 WKONGAI_SITE 覆盖)' },
30
+ };
31
+
32
+ /** 站点必须显式(表单/发布这类写操作不接受"随便哪个站") */
33
+ function needSite(ctx, what) {
34
+ const site = ctx.cmsSite();
35
+ if (!site.id) {
36
+ throw new UsageError(`${what}需要指定站点`, {
37
+ hint: '先 `wkgeo site use <站点ID>` 选站,或加 `--site <站点ID>`。',
38
+ });
39
+ }
40
+ return site;
41
+ }
42
+
43
+ function rowsOf(data) {
44
+ if (Array.isArray(data)) return data;
45
+ if (data && Array.isArray(data.rows)) return data.rows;
46
+ if (data && Array.isArray(data.list)) return data.list;
47
+ if (data && Array.isArray(data.plugins)) return data.plugins;
48
+ return [];
49
+ }
50
+
51
+ /* ------------------------------------------------------------------ 表单 */
52
+
53
+ /**
54
+ * 表单后台动作只认 CMS 后台 Cookie(`cms_session`)+ Origin 白名单,**不认 Bearer**。
55
+ * 这里把 401/403 翻成一句人话,而不是把后端原文甩给用户 —— 但也**不假装成功**。
56
+ */
57
+ function formCall(ctx, action, payload) {
58
+ return ctx
59
+ .callData(action, payload, {
60
+ prefix: 'form',
61
+ headers: { Origin: FORM_ORIGIN, 'x-cms-site': ctx.cmsSite().id },
62
+ })
63
+ .catch((err) => {
64
+ const kind = String((err && err.kind) || '');
65
+ if (kind === 'cms_auth' || kind === 'unauthenticated' || kind === 'forbidden' || kind === 'expired') {
66
+ throw new CliError('表单后台接口(/form)目前只认 CMS 后台登录态,CLI 的授权令牌还调不通', {
67
+ kind: 'form_backend_gap',
68
+ exitCode: EXIT.AUTH,
69
+ hint:
70
+ '这是后端缺口(插件函数未接 Bearer 桥),不是你的权限问题:' +
71
+ '现在请在 CMS 后台「表单」页查看;后端补上 Bearer 桥后 `wkgeo forms` 会自动可用。',
72
+ });
73
+ }
74
+ throw err;
75
+ });
76
+ }
77
+
78
+ function formSummary(form) {
79
+ const fields = Array.isArray(form.fields) ? form.fields : (form.schema && form.schema.fields) || [];
80
+ return Array.isArray(fields) ? fields : [];
81
+ }
82
+
83
+ export const formsListCommand = {
84
+ name: 'forms list',
85
+ summary: '列本站表单(字段数、提交数、未读数)',
86
+ usage: 'wkgeo forms list [--site <站点ID>] [--json]',
87
+ args: [],
88
+ flags: { ...SITE_FLAG },
89
+ examples: ['wkgeo forms list', 'wkgeo forms list --json'],
90
+ notes: [
91
+ '表单结构(字段名/类型/是否必填)不含客户数据,可以放心看。',
92
+ '提交记录里会有手机号/邮箱/IP —— `wkgeo forms entries` 默认全部脱敏。',
93
+ ],
94
+ async run(ctx) {
95
+ const { out } = ctx;
96
+ const site = needSite(ctx, 'forms');
97
+ const data = (await formCall(ctx, 'formList', {})) || {};
98
+ const forms = rowsOf(data);
99
+ const payload = {
100
+ site_id: site.id,
101
+ total: forms.length,
102
+ unread_total: data.unreadTotal || 0,
103
+ embed_base: data.embedBase || '',
104
+ forms: forms.map((f) => ({
105
+ id: f.id,
106
+ key: f.key,
107
+ name: f.name,
108
+ status: f.status || '',
109
+ fields: formSummary(f).map((one) => ({ key: one.key, label: one.label, type: one.type, required: one.required === true })),
110
+ entry_count: f.entryCount || 0,
111
+ unread_count: f.unreadCount || 0,
112
+ })),
113
+ };
114
+ if (!out.json) {
115
+ out.head(`表单(站点 ${site.id})`);
116
+ out.table(
117
+ [
118
+ { title: '名称', key: 'name', width: 22 },
119
+ { title: 'key', key: 'key', width: 20 },
120
+ { title: '字段', key: 'fields', width: 6 },
121
+ { title: '提交', key: 'entries', width: 6 },
122
+ { title: '未读', key: 'unread', width: 6 },
123
+ ],
124
+ payload.forms.map((f) => ({
125
+ name: f.name,
126
+ key: f.key,
127
+ fields: f.fields.length,
128
+ entries: f.entry_count,
129
+ unread: f.unread_count,
130
+ })),
131
+ );
132
+ out.info(`未读合计 ${payload.unread_total};看提交:\`wkgeo forms entries --form <id>\``);
133
+ }
134
+ ctx.done(payload);
135
+ return payload;
136
+ },
137
+ };
138
+
139
+ export const formsEntriesCommand = {
140
+ name: 'forms entries',
141
+ summary: '看表单提交记录(默认脱敏:手机号/邮箱/IP/UA 都不出原文)',
142
+ usage:
143
+ 'wkgeo forms entries [--form <表单ID>] [--status new|read] [--keyword <词>] [--page <n>] [--page-size <n>] [--raw --confirm]',
144
+ args: [],
145
+ flags: {
146
+ ...SITE_FLAG,
147
+ form: { type: 'string', desc: '只看某个表单(表单 ID)' },
148
+ status: { type: 'string', desc: 'new 未读 / read 已读' },
149
+ keyword: { type: 'string', desc: '关键词(后端按字段值模糊匹配)' },
150
+ page: { type: 'string', desc: '页码(从 1 开始)' },
151
+ 'page-size': { type: 'string', desc: '每页条数(1..100,默认 20)' },
152
+ raw: { type: 'boolean', desc: '输出原文(**必须同时加 --confirm**,否则不执行)' },
153
+ confirm: { type: 'boolean', desc: '配合 --raw 确认"我确实要看客户原文"' },
154
+ },
155
+ examples: [
156
+ 'wkgeo forms entries',
157
+ 'wkgeo forms entries --form <表单ID> --status new --page-size 50',
158
+ 'wkgeo forms entries --raw --confirm --form <表单ID> # 真要看原文',
159
+ ],
160
+ notes: [
161
+ '**默认脱敏**:手机 `138****1234`、邮箱 `zh***@e***.com`、IP 只留前三段、UA 只报长度。',
162
+ '`--raw` 必须再给 `--confirm`:不给就报用法错误(防止手滑把客户隐私打到终端/日志)。',
163
+ '记录里有 client_ip / user_agent 字段,脱敏后仍会显示"有值",但看不到原文。',
164
+ ],
165
+ async run(ctx) {
166
+ const { out } = ctx;
167
+ const site = needSite(ctx, 'forms entries');
168
+ const raw = ctx.flags.raw === true;
169
+ if (raw && ctx.flags.confirm !== true) {
170
+ throw new UsageError('--raw 会输出客户原文,必须再加 --confirm', {
171
+ hint: '确认要看原文:`wkgeo forms entries --raw --confirm`(输出的内容可能含手机号/邮箱/IP,别贴到公开地方)',
172
+ });
173
+ }
174
+
175
+ const page = Number(ctx.flags.page || 1);
176
+ const pageSize = Number(ctx.flags.pageSize || 20);
177
+ if (!Number.isFinite(page) || page < 1) throw new UsageError('--page 必须是 ≥1 的整数');
178
+ if (!Number.isFinite(pageSize) || pageSize < 1 || pageSize > 100) throw new UsageError('--page-size 必须是 1..100 的整数');
179
+
180
+ const body = { page, pageSize };
181
+ if (ctx.flags.form) body.formId = String(ctx.flags.form);
182
+ if (ctx.flags.status) body.status = String(ctx.flags.status);
183
+ if (ctx.flags.keyword) body.keyword = String(ctx.flags.keyword);
184
+
185
+ const data = (await formCall(ctx, 'formEntryList', body)) || {};
186
+ const rows = rowsOf(data);
187
+
188
+ const shown = rows.map((one) => {
189
+ const values = Array.isArray(one.values) ? one.values : [];
190
+ const entry = {
191
+ id: one.id,
192
+ form_id: one.formId,
193
+ form_name: one.formName,
194
+ status: one.status,
195
+ created_at: one.createdAt,
196
+ client_ip: one.clientIp || '',
197
+ user_agent: one.userAgent || '',
198
+ values: values.map((v) => ({ key: v.key, label: v.label, value: v.value === undefined || v.value === null ? '' : String(v.value) })),
199
+ };
200
+ return raw ? entry : maskPiiDeep(entry, { scrubStrings: true });
201
+ });
202
+
203
+ const payload = {
204
+ site_id: site.id,
205
+ page: data.page || page,
206
+ page_size: data.pageSize || pageSize,
207
+ total: data.total || 0,
208
+ unread_total: data.unreadTotal || 0,
209
+ redacted: !raw,
210
+ entries: shown,
211
+ };
212
+
213
+ if (!out.json) {
214
+ out.head(`表单提交(站点 ${site.id},第 ${payload.page} 页,共 ${payload.total} 条${payload.unread_total ? `,未读 ${payload.unread_total}` : ''})`);
215
+ if (!shown.length) {
216
+ out.line(' (这一页没有记录)');
217
+ }
218
+ for (const one of shown) {
219
+ out.line('');
220
+ out.line(` #${one.id} ${one.form_name || ''} | ${one.status || ''} | ${one.created_at || ''}`);
221
+ for (const v of one.values) {
222
+ out.line(` ${v.label || v.key}:${v.value}`);
223
+ }
224
+ if (one.client_ip) out.line(` IP:${one.client_ip}`);
225
+ }
226
+ if (payload.redacted) {
227
+ out.line('');
228
+ out.info('以上已脱敏(手机/邮箱/IP/UA)。需要原文:`--raw --confirm`。');
229
+ } else {
230
+ out.warn('⚠️ 这是**未脱敏原文**:别贴进公开 issue / 群聊 / 提交到仓库。');
231
+ }
232
+ }
233
+ ctx.done(payload);
234
+ return payload;
235
+ },
236
+ };
237
+
238
+ /* ------------------------------------------------------------------ 域名(只读) */
239
+
240
+ /* ------------------------------------------------------------------ 预览 */
241
+
242
+ export const previewCommand = {
243
+ name: 'preview',
244
+ summary: '拼一个预览地址(走 CMS 预览通道,不需要发布)',
245
+ usage: 'wkgeo preview <路径> [--site <站点ID>] [--open]',
246
+ args: [{ name: 'path', required: true, desc: '站内路径,如 /about/ 或 news/2026/' }],
247
+ flags: {
248
+ ...SITE_FLAG,
249
+ open: { type: 'boolean', desc: '用系统默认浏览器打开(非 TTY 环境会自动跳过)' },
250
+ },
251
+ examples: ['wkgeo preview /about/', 'wkgeo preview news/2026/ --site <站点ID> --open'],
252
+ notes: [
253
+ `地址形如 \`${PLATFORM_WEB_ORIGIN}/cms/preview/<站点ID>/<路径>\`,走预览通道:**看的是草稿态**,不影响线上。`,
254
+ '零后端调用:只拼字符串,不产生任何写操作。',
255
+ '`--open` 用的是系统默认浏览器;CI / 非交互环境会自动跳过(不会卡住)。',
256
+ ],
257
+ async run(ctx) {
258
+ const { out } = ctx;
259
+ const site = needSite(ctx, 'preview');
260
+ let rel = String(ctx.positional.path || '').trim();
261
+ if (!rel) throw new UsageError('请给出要预览的站内路径');
262
+ rel = rel.replace(/^https?:\/\/[^/]+/i, '');
263
+ rel = rel.replace(/^\/+/, '');
264
+
265
+ const url = `${PLATFORM_WEB_ORIGIN}/cms/preview/${site.id}/${rel}`;
266
+ const payload = { site_id: site.id, path: `/${rel}`, url };
267
+
268
+ if (!out.json) {
269
+ out.ok(url);
270
+ out.info('预览通道看的是草稿态;要上线还得 `wkgeo publish --confirm`。');
271
+ }
272
+ if (ctx.flags.open) {
273
+ const res = await openUrlForUser(url, {
274
+ deps: {
275
+ openBrowser: ctx.openBrowser,
276
+ platform: ctx.platform,
277
+ spawnImpl: ctx.spawnImpl,
278
+ verbose: ctx.flags.verbose,
279
+ isTTY: ctx.isTTY,
280
+ json: ctx.out.json,
281
+ forceOpen: true,
282
+ env: ctx.env,
283
+ },
284
+ });
285
+ payload.opened = Boolean(res && res.opened);
286
+ if (!out.json) {
287
+ if (res && res.opened) out.info('已用默认浏览器打开。');
288
+ else out.info('没有可用的图形浏览器,地址已打印在上面,手动打开即可。');
289
+ }
290
+ }
291
+ ctx.done(payload);
292
+ return payload;
293
+ },
294
+ };
295
+
296
+ /* ------------------------------------------------------------------ 导入 v2 */
297
+
298
+ /** `importV2Start` 接受的选项(数值型都是可选的;不传就用后端默认) */
299
+ const IMPORT_V2_OPTIONS = [
300
+ ['list-limit', 'listLimit', 'num'],
301
+ ['news-limit', 'newsLimit', 'num'],
302
+ ['other-list-limit', 'otherListLimit', 'num'],
303
+ ['max-pages', 'maxPages', 'num'],
304
+ ['verify-rounds', 'verifyRounds', 'num'],
305
+ ['structure-rounds', 'structureRounds', 'num'],
306
+ ['structure-batch-size', 'structureBatchSize', 'num'],
307
+ ['structure-concurrency', 'structureConcurrency', 'num'],
308
+ ['search', 'search', 'bool'],
309
+ ['overwrite', 'overwrite', 'bool'],
310
+ ['auto-repair', 'autoRepair', 'bool'],
311
+ ];
312
+
313
+ export const importV2StartCommand = {
314
+ name: 'import-v2 start',
315
+ summary: '从老网站导入内容(默认 dry-run;`--confirm` 才真的提交任务)',
316
+ usage: 'wkgeo import-v2 start --url <老站地址> [--confirm] [--site <站点ID>] [选项…]',
317
+ args: [],
318
+ flags: {
319
+ ...SITE_FLAG,
320
+ url: { type: 'string', required: true, desc: '老站首页地址(http/https)' },
321
+ confirm: { type: 'boolean', desc: '真提交(不加只打印计划)' },
322
+ search: { type: 'boolean', desc: '导入后顺便配好站内搜索(默认开;关掉用 --no-search)' },
323
+ overwrite: { type: 'boolean', desc: '已存在同路径内容时覆盖(默认不覆盖)' },
324
+ 'max-pages': { type: 'string', desc: '最多抓多少页(保护老站与预算)' },
325
+ 'list-limit': { type: 'string', desc: '每个列表页最多收多少条' },
326
+ 'news-limit': { type: 'string', desc: '新闻/资讯类最多收多少条' },
327
+ 'other-list-limit': { type: 'string', desc: '其它列表类最多收多少条' },
328
+ },
329
+ examples: [
330
+ 'wkgeo import-v2 start --url https://old-site.example.com/ # dry-run',
331
+ 'wkgeo import-v2 start --url https://old-site.example.com/ --confirm # 真提交',
332
+ 'wkgeo import-v2 start --url https://old-site.example.com/ --max-pages 200 --confirm',
333
+ ],
334
+ notes: [
335
+ '不加 `--confirm` 是 **dry-run**:只打印将提交什么,**不发任何写请求**。',
336
+ '真提交后立刻返回 `runId`,抓取在后台跑;用 `wkgeo import-v2 status --run <runId>` 看进度。',
337
+ '需要「导入」写权限(canWrite);后端没部署 v2 导入时会回"未知动作",那是服务端缺动作。',
338
+ ],
339
+ async run(ctx) {
340
+ const { out } = ctx;
341
+ const site = needSite(ctx, 'import-v2');
342
+ const url = String(ctx.flags.url || '').trim();
343
+ if (!url) throw new UsageError('请用 --url 给出老站地址');
344
+ if (!/^https?:\/\//i.test(url)) throw new UsageError('--url 只支持 http/https 地址');
345
+
346
+ const options = {};
347
+ for (const [flagKey, bodyKey, kind] of IMPORT_V2_OPTIONS) {
348
+ const value = ctx.flags[camel(flagKey)];
349
+ if (value === undefined) continue;
350
+ if (kind === 'num') {
351
+ const n = Number(value);
352
+ if (!Number.isFinite(n) || n <= 0) throw new UsageError(`--${flagKey} 必须是正数`);
353
+ options[bodyKey] = n;
354
+ } else {
355
+ options[bodyKey] = value === true;
356
+ }
357
+ }
358
+
359
+ if (ctx.flags.confirm !== true) {
360
+ const payload = { site_id: site.id, action: 'dry_run', confirmed: false, url, options };
361
+ if (!out.json) {
362
+ out.head('导入 v2 计划(dry-run,未提交任何任务)');
363
+ out.line(` 站点:${site.id}`);
364
+ out.line(` 老站:${url}`);
365
+ const keys = Object.keys(options);
366
+ out.line(` 选项:${keys.length ? keys.map((k) => `${k}=${options[k]}`).join(' ') : '(全部用后端默认)'}`);
367
+ out.line('');
368
+ out.line(' 确认无误就加 `--confirm`:任务会在后台抓取老站结构与内容。');
369
+ }
370
+ ctx.done(payload);
371
+ return payload;
372
+ }
373
+
374
+ const started = (await ctx.cmsCall('importV2Start', { url, ...options })) || {};
375
+ const payload = {
376
+ site_id: site.id,
377
+ action: 'start',
378
+ confirmed: true,
379
+ run_id: started.runId || '',
380
+ status: started.status || '',
381
+ total_stages: started.totalStages || 0,
382
+ dispatched: started.dispatched === true,
383
+ dispatch_via: started.dispatchVia || '',
384
+ timings: started.timings || null,
385
+ url,
386
+ options,
387
+ };
388
+ if (!out.json) {
389
+ if (payload.dispatched) out.ok(`导入任务已提交:${payload.run_id}(共 ${payload.total_stages} 个阶段,后台跑着)`);
390
+ else out.warn(`任务已建但**没派发出去**:${payload.run_id}(状态 ${payload.status});请找后端看派发配置。`);
391
+ out.info(`看进度:wkgeo import-v2 status --run ${payload.run_id}`);
392
+ }
393
+ ctx.done(payload);
394
+ return payload;
395
+ },
396
+ };
397
+
398
+ export const importV2StatusCommand = {
399
+ name: 'import-v2 status',
400
+ summary: '看导入 v2 任务的进度(只读)',
401
+ usage: 'wkgeo import-v2 status --run <任务ID> [--site <站点ID>] [--json]',
402
+ args: [],
403
+ flags: {
404
+ ...SITE_FLAG,
405
+ run: { type: 'string', required: true, desc: '任务 ID(`import-v2 start --confirm` 回的那个 runId)' },
406
+ },
407
+ examples: ['wkgeo import-v2 status --run <runId>', 'wkgeo import-v2 status --run <runId> --json'],
408
+ notes: [
409
+ '后端 `importV2Get` **必须带 runId**(没有"最新一次"的退路):不给就报用法错误。',
410
+ '返回里有 stage/status/进度、素材汇总、预览地址与自检结果(原样透出,不裁剪)。',
411
+ ],
412
+ async run(ctx) {
413
+ const { out } = ctx;
414
+ const site = needSite(ctx, 'import-v2 status');
415
+ const runId = String(ctx.flags.run || '').trim();
416
+ if (!runId) throw new UsageError('请用 --run 给出任务 ID', { hint: 'runId 在 `import-v2 start --confirm` 的回执里。' });
417
+
418
+ const res = (await ctx.cmsCall('importV2Get', { runId })) || {};
419
+ const run = res.run || {};
420
+ const payload = { site_id: site.id, run_id: runId, run };
421
+ if (!out.json) {
422
+ out.head(`导入任务 ${runId}`);
423
+ const known = ['status', 'stage', 'message', 'error', 'totalStages', 'doneStages', 'startedAt', 'finishedAt', 'previewUrl'];
424
+ for (const key of known) {
425
+ if (run[key] !== undefined && run[key] !== null && run[key] !== '') out.line(` ${key}: ${run[key]}`);
426
+ }
427
+ if (run.summary && typeof run.summary === 'object') {
428
+ const parts = Object.entries(run.summary)
429
+ .filter(([, v]) => v === null || ['string', 'number', 'boolean'].includes(typeof v))
430
+ .map(([k, v]) => `${k}=${v}`);
431
+ if (parts.length) out.line(` summary: ${parts.join(' ')}`);
432
+ }
433
+ out.info('(完整结构用 --json 看;这里只挑人最关心的几项。)');
434
+ }
435
+ ctx.done(payload);
436
+ return payload;
437
+ },
438
+ };