@wkgeo/cli 2.1.0 → 2.2.1
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/CHANGELOG.md +15 -0
- package/README.md +1 -1
- package/lib/commands/index.mjs +2 -0
- package/lib/commands/siteops.mjs +138 -4
- package/lib/runtime.mjs +78 -47
- package/lib/site-publish.mjs +410 -0
- package/lib/site-spec.mjs +28 -4
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,21 @@
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## 2.2.1 · 2026-11-22
|
|
8
|
+
|
|
9
|
+
- 修 CRLF(Windows)文件上的误报:`site-spec` 的 `extractSection` 归一换行后再比较,未变版块不再被重写;`gen-site-spec` 写盘保留原文件 EOL
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 2.2.0 · 2026-11-22
|
|
14
|
+
|
|
15
|
+
- 新增 `site publish`:把本地 `html/` 打包上传到站点(默认 dry-run,`--confirm` 才发)
|
|
16
|
+
- plan / apply 两段:只上传变更文件,内容未变不重复传
|
|
17
|
+
- prune 保护 `upload/`、`robots.txt`、`.well-known/`,不会被远端清理
|
|
18
|
+
- 站点自有存储与平台存储同批复制,发布后本地产物与线上一致
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
7
22
|
## 2.1.0 · 2026-11-22
|
|
8
23
|
|
|
9
24
|
- 新增 `site build`:把站点静态生成到本地 `html/`(页面引用 `/template/` 模板资产、不复制资产;生成清单可幂等跳过未变页面),产物结构与发布器落桶口径一致
|
package/README.md
CHANGED
|
@@ -108,7 +108,7 @@ cd cli && node scripts/build-exe.mjs --sea # 跑 Node SEA 的离线两步(
|
|
|
108
108
|
|
|
109
109
|
### 版本与升级策略
|
|
110
110
|
|
|
111
|
-
* 当前版本 **`2.
|
|
111
|
+
* 当前版本 **`2.2.1`**(`cli/package.json`,**2026-11-09 已发布到 npm 组织 `@wkgeo`**;1.1.0–1.1.3 是增量补丁,逐版明细见 [`CHANGELOG.md`](./CHANGELOG.md));**`1.0.0`**(2026-10-30)在 0.6.0 之上把后台**整块搬进 CLI** —— 内容 45 / 素材 18 / 发布 16 / 配置类 auth 11 / 站点 7 / 插件 9 / 控制台 8 七批动作全部由自持云函数 `wkgeo-cli-fc` 进程内执行(不再借 `/cms` 会话转发,因而计入 `cli_action_usage`),**`whoami.action_total` 150 → 185**,新增 / 补齐 `assets`、`publish`、`site info`、`plugins`、`config`、`logs`、`overview`、`lang`/`role`/`member` 命令组;上一个版本 **`0.6.0`**(2026-10-28:`/cli` 收口 + `auth` 命令组 + `domain bind` + 域名成交链路);更早的补丁版 **`0.5.1`**(2026-10-26:修 0.5.0 的 `publish --confirm` 轮询崩溃 `ctx.sleep is not a function`)。
|
|
112
112
|
* **本版只加命令、不改契约**:原有命令 / 参数 / `--json` 信封 / 退出码与 0.6.0 完全一致,AI 端继续用 `npx -y @wkgeo/cli@latest` 即可;逐批明细与已知缺口见 [`CHANGELOG.md`](./CHANGELOG.md) 顶部「1.0.0」。
|
|
113
113
|
* **同一个版本号不能覆盖**:改了代码必须 `npm version patch|minor|major` 再发布。
|
|
114
114
|
* AI 端统一用 **`npx -y @wkgeo/cli@latest`** → 每次自动拿最新版;
|
package/lib/commands/index.mjs
CHANGED
|
@@ -70,6 +70,7 @@ import {
|
|
|
70
70
|
previewCommand,
|
|
71
71
|
siteSyncDiffCommand,
|
|
72
72
|
siteBuildCommand,
|
|
73
|
+
sitePublishCommand,
|
|
73
74
|
importV2StartCommand,
|
|
74
75
|
importV2StatusCommand,
|
|
75
76
|
} from './siteops.mjs';
|
|
@@ -318,6 +319,7 @@ export const COMMANDS = [
|
|
|
318
319
|
* 与 `site sync diff` 同属「工作区」这一层:先在本地看 / 先生成,最后才轮到发布。
|
|
319
320
|
*/
|
|
320
321
|
siteBuildCommand,
|
|
322
|
+
sitePublishCommand,
|
|
321
323
|
importV2StartCommand,
|
|
322
324
|
importV2StatusCommand,
|
|
323
325
|
/**
|
package/lib/commands/siteops.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { maskPii, maskPiiDeep, formatTime } from '../format.mjs';
|
|
|
24
24
|
import { PLATFORM_WEB_ORIGIN } from '../hosts.mjs';
|
|
25
25
|
import { openUrlForUser } from '../login.mjs';
|
|
26
26
|
import { diffWorkspace } from '../workspace-sync.mjs';
|
|
27
|
+
import { publishLocalBuild, PUBLISH_LIMITS } from '../site-publish.mjs';
|
|
27
28
|
|
|
28
29
|
/** 表单后台函数(`wkgeo-plugin-contact-form`)认的来源;不给会被 `checkAdminOrigin` 403 */
|
|
29
30
|
const FORM_ORIGIN = PLATFORM_WEB_ORIGIN;
|
|
@@ -467,10 +468,10 @@ export const siteBuildCommand = {
|
|
|
467
468
|
});
|
|
468
469
|
}
|
|
469
470
|
/**
|
|
470
|
-
* ★ 2026-11-22 rev4
|
|
471
|
-
* `publicSitemap` / `pageRender
|
|
472
|
-
*
|
|
473
|
-
*
|
|
471
|
+
* ★ 2026-11-22 rev4 + Key 优先口径:build 调的全是 **CMS 动作**(`cmsMe` /
|
|
472
|
+
* `siteAssetBundle` / `publicSitemap` / `pageRender`)。Key 模式(`wkgeo_sk_…`)只认 Key、
|
|
473
|
+
* **不回落账号登录**:Key 被 CMS 拒时抛 `AUTH_FAILED` / `KEY_SCOPE_DENIED`(去后台重建 Key),
|
|
474
|
+
* 不再提示登录。
|
|
474
475
|
*/
|
|
475
476
|
const credentials = ctx.cmsAuth().creds;
|
|
476
477
|
const payload = await buildStaticSite({
|
|
@@ -541,6 +542,139 @@ export const siteBuildCommand = {
|
|
|
541
542
|
},
|
|
542
543
|
};
|
|
543
544
|
|
|
545
|
+
/* ------------------------------------------------- 本地 html → OSS 上传(task-68) */
|
|
546
|
+
/**
|
|
547
|
+
* `site publish`:把 `<站点目录>/html/` 上传到平台 OSS。
|
|
548
|
+
*
|
|
549
|
+
* 与 `site build` 的分工:build 只生成(只读线上),publish 才写线上(OSS 对象);
|
|
550
|
+
* 默认 **dry-run**(服务端 `mode=plan`,**零写**),`--confirm` 才 `mode=apply`。
|
|
551
|
+
*/
|
|
552
|
+
export const sitePublishCommand = {
|
|
553
|
+
name: 'site publish',
|
|
554
|
+
summary: '把本地 html/ 上传到平台 OSS(默认只对比不写;--confirm 才真传,--prune 才删孤儿)',
|
|
555
|
+
usage:
|
|
556
|
+
'wkgeo site publish [--dir <站点目录>] [--site <域名|站点ID>] [--prune] [--confirm] [--json]',
|
|
557
|
+
args: [],
|
|
558
|
+
flags: {
|
|
559
|
+
...SITE_FLAG,
|
|
560
|
+
dir: {
|
|
561
|
+
type: 'string',
|
|
562
|
+
desc: '站点目录(里面有 html/;默认当前目录。站点目录里有本地站点票时自动用票上传)',
|
|
563
|
+
},
|
|
564
|
+
prune: {
|
|
565
|
+
type: 'boolean',
|
|
566
|
+
desc: '删除「远端有、本次包里没有」的页面/资产(只删本站前缀内,且跳过 upload/ 等保护路径;仅 --confirm 时真删)',
|
|
567
|
+
},
|
|
568
|
+
confirm: { type: 'boolean', desc: '真上传(不加只对比:服务端零写,只回缺失/变更/待删清单)' },
|
|
569
|
+
},
|
|
570
|
+
examples: [
|
|
571
|
+
'wkgeo site publish --dir my-site --site hanyien.com # 只对比(零写)',
|
|
572
|
+
'wkgeo site publish --dir my-site --site hanyien.com --confirm # 真上传',
|
|
573
|
+
'wkgeo site publish --dir my-site --site hanyien.com --prune --confirm # 顺带删孤儿',
|
|
574
|
+
],
|
|
575
|
+
notes: [
|
|
576
|
+
'**本地打包**:`html/**` → tar.gz(路径 = 站内相对路径),由服务端解包校验(拒绝 `..` / 绝对路径 / 符号链接)。',
|
|
577
|
+
'**只传变更**:服务端按远端 ETag 与本地 md5 比对,只 PUT 缺失 + 变更;重复上传幂等。',
|
|
578
|
+
'**不删桶**:`--prune` 也只删 `<站点>/` 前缀内、且不在保护名单(`upload/`、`.well-known/`、`robots.txt`)里的对象。',
|
|
579
|
+
'**未 build**:没有 `html/` 或里面没文件 ⇒ exit 2(`BUILD_MISSING`),先跑 `wkgeo site build`。',
|
|
580
|
+
'**凭据**:站点目录命中本地站点票(`%LOCALAPPDATA%\\wkgeo-ops\\creds`)就用票;否则用 `wkgeo login` 的账号 Key。',
|
|
581
|
+
],
|
|
582
|
+
async run(ctx) {
|
|
583
|
+
const { out } = ctx;
|
|
584
|
+
const dirFlag = ctx.flags.dir === undefined ? '' : String(ctx.flags.dir || '').trim();
|
|
585
|
+
const dir = dirFlag || '.';
|
|
586
|
+
let site = String(ctx.flags.site || '').trim();
|
|
587
|
+
if (!site) {
|
|
588
|
+
/** 没有显式站:能给就用本地选中的站(站点票场景下由票自带站,不需要这一步) */
|
|
589
|
+
try {
|
|
590
|
+
const current = ctx.cmsSite();
|
|
591
|
+
site = current.id || '';
|
|
592
|
+
} catch {
|
|
593
|
+
site = '';
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
const prune = ctx.flags.prune === true;
|
|
597
|
+
const confirm = ctx.flags.confirm === true;
|
|
598
|
+
|
|
599
|
+
const result = await publishLocalBuild({ ctx, dir, site, prune, confirm });
|
|
600
|
+
const body = result.body;
|
|
601
|
+
|
|
602
|
+
if (!out.json) {
|
|
603
|
+
out.head(`本地 html 上传:${result.siteLabel || result.siteId}`);
|
|
604
|
+
out.line(
|
|
605
|
+
` 来源:html/ 共 ${result.pack.files} 个文件(原始 ${result.pack.rawBytes} B → 压缩后 ${result.pack.gzipBytes} B)`,
|
|
606
|
+
);
|
|
607
|
+
if (result.keyPrefix) out.line(` 凭据:站点票(${result.keyPrefix})`);
|
|
608
|
+
out.line(` 远端前缀:${body.prefix}`);
|
|
609
|
+
if (body.mode === 'plan') {
|
|
610
|
+
out.line(
|
|
611
|
+
` 对比:缺失 ${body.missing.length} | 变更 ${body.changed.length} | 远端多余 ${body.deleted.length}` +
|
|
612
|
+
`(${prune ? '会删' : '不删,加 --prune 才删'}) | 待传 ${body.bytes} B`,
|
|
613
|
+
);
|
|
614
|
+
if (body.protectedKept && body.protectedKept.length) {
|
|
615
|
+
out.line(` 保护保留:${body.protectedKept.length} 个(upload/ 等,永不随 prune 删除)`);
|
|
616
|
+
}
|
|
617
|
+
out.line('');
|
|
618
|
+
if (body.missing.length) {
|
|
619
|
+
out.line(' 缺失(将上传):');
|
|
620
|
+
for (const one of body.missing.slice(0, 20)) out.line(` + ${one}`);
|
|
621
|
+
if (body.missing.length > 20) out.line(` … 其余 ${body.missing.length - 20} 个`);
|
|
622
|
+
}
|
|
623
|
+
if (body.changed.length) {
|
|
624
|
+
out.line(' 变更(将覆盖):');
|
|
625
|
+
for (const one of body.changed.slice(0, 20)) out.line(` ~ ${one}`);
|
|
626
|
+
if (body.changed.length > 20) out.line(` … 其余 ${body.changed.length - 20} 个`);
|
|
627
|
+
}
|
|
628
|
+
if (prune && body.deleted.length) {
|
|
629
|
+
out.line(' 将删除(远端多余):');
|
|
630
|
+
for (const one of body.deleted.slice(0, 20)) out.line(` - ${one}`);
|
|
631
|
+
if (body.deleted.length > 20) out.line(` … 其余 ${body.deleted.length - 20} 个`);
|
|
632
|
+
}
|
|
633
|
+
out.info('本命令只对比:服务端一个字节都没写。确认无误后加 `--confirm` 真上传。');
|
|
634
|
+
} else {
|
|
635
|
+
out.line(
|
|
636
|
+
` 结果:上传 ${body.uploaded} | 跳过 ${body.skipped} | 删除 ${body.pruned} | 传输 ${body.bytes} B`,
|
|
637
|
+
);
|
|
638
|
+
if (body.ownStorage) {
|
|
639
|
+
const own = body.ownStorage;
|
|
640
|
+
out.line(
|
|
641
|
+
` 自有存储:${own.ok ? `已复制 ${own.copied} 个` : `失败(复制 ${own.copied} / 失败 ${own.failed})${own.error ? `:${own.error}` : ''}`}`,
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
if (body.errors && body.errors.length) {
|
|
645
|
+
out.line('');
|
|
646
|
+
for (const one of body.errors.slice(0, 20)) out.warn(` ✗ ${one.path} ${one.message}`);
|
|
647
|
+
if (body.errors.length > 20) out.warn(` … 其余 ${body.errors.length - 20} 条`);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
if (body.warnings && body.warnings.length) {
|
|
651
|
+
out.line('');
|
|
652
|
+
for (const w of body.warnings) out.warn(w);
|
|
653
|
+
}
|
|
654
|
+
if (result.pack.gzipBytes > PUBLISH_LIMITS.gatewayBytes) {
|
|
655
|
+
out.warn(
|
|
656
|
+
`包体 ${result.pack.gzipBytes} B 超过网关默认请求体闸门(${PUBLISH_LIMITS.gatewayBytes} B),` +
|
|
657
|
+
'线上可能被 413 挡住:需要调大 GW_MAX_BODY_BYTES 或拆包。',
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
out.line('');
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
if (body.errors && body.errors.length) {
|
|
664
|
+
throw new CliError(`上传完成但 ${body.errors.length} 个文件失败`, {
|
|
665
|
+
kind: 'publish_partial',
|
|
666
|
+
code: 'PUBLISH_PARTIAL',
|
|
667
|
+
exitCode: EXIT.ERROR,
|
|
668
|
+
details: body,
|
|
669
|
+
raw: body,
|
|
670
|
+
hint: '看 errors[]:权限/网络抖动可以重跑(幂等,已成功的会跳过)。',
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
ctx.done(body);
|
|
674
|
+
return body;
|
|
675
|
+
},
|
|
676
|
+
};
|
|
677
|
+
|
|
544
678
|
/* ------------------------------------------------------------------ 导入 v2 */
|
|
545
679
|
|
|
546
680
|
/** `importV2Start` 接受的选项(数值型都是可选的;不传就用后端默认) */
|
package/lib/runtime.mjs
CHANGED
|
@@ -58,21 +58,20 @@ export function okEnvelope(command, data, meta) {
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
/**
|
|
61
|
-
* `wkgeo_sk_…` 是 **API Key /
|
|
62
|
-
*
|
|
63
|
-
* 这里只做形状判断(不验签),目的是**在本地就把误导性 401 变成可照做的错误**。
|
|
61
|
+
* `wkgeo_sk_…` 是 **API Key / 按站短票**的令牌形状(CMS 侧 task-58 起认这类令牌做
|
|
62
|
+
* `templateList / templateGet / templateAssetFiles`)。
|
|
64
63
|
*/
|
|
65
64
|
function isApiKeyToken(token) {
|
|
66
65
|
return /^wkgeo_sk_/i.test(String(token || '').trim());
|
|
67
66
|
}
|
|
68
67
|
|
|
69
68
|
/**
|
|
70
|
-
*
|
|
69
|
+
* 读一个凭据文件,判断它是 **Key** 还是**账号 OAuth**(不发送任何请求)。
|
|
71
70
|
*
|
|
72
|
-
* @returns {{ok:true,creds:object,file:string,kind:'account'}
|
|
73
|
-
* | {ok:false,kind:'missing'|'invalid'|'
|
|
71
|
+
* @returns {{ok:true,creds:object,file:string,kind:'key'|'account'}
|
|
72
|
+
* | {ok:false,kind:'missing'|'invalid'|'expired',file:string,error?:Error}}
|
|
74
73
|
*/
|
|
75
|
-
function
|
|
74
|
+
function readCredentialToken(file, nowFn) {
|
|
76
75
|
if (!file) return { ok: false, kind: 'missing', file: '' };
|
|
77
76
|
let creds = null;
|
|
78
77
|
try {
|
|
@@ -83,7 +82,7 @@ function tryCmsCredentials(file, nowFn) {
|
|
|
83
82
|
if (!creds) return { ok: false, kind: 'missing', file };
|
|
84
83
|
const token = String(creds.access_token || '').trim();
|
|
85
84
|
if (!token) return { ok: false, kind: 'missing', file };
|
|
86
|
-
if (isApiKeyToken(token)) return { ok:
|
|
85
|
+
if (isApiKeyToken(token)) return { ok: true, creds, file, kind: 'key' };
|
|
87
86
|
if (isExpired(creds, { now: nowFn() })) {
|
|
88
87
|
return {
|
|
89
88
|
ok: false,
|
|
@@ -93,15 +92,49 @@ function tryCmsCredentials(file, nowFn) {
|
|
|
93
92
|
kind: 'unauthenticated',
|
|
94
93
|
code: 401,
|
|
95
94
|
exitCode: EXIT.AUTH,
|
|
96
|
-
hint:
|
|
97
|
-
'重新登录一次即可:`wkgeo login`(登录后账号令牌会带上 template / attachment 等新能力;' +
|
|
98
|
-
'面板 Key 模式会沿用本机账号登录态,模板拉取随之恢复)。',
|
|
95
|
+
hint: '重新登录一次即可:`wkgeo login`。',
|
|
99
96
|
}),
|
|
100
97
|
};
|
|
101
98
|
}
|
|
102
99
|
return { ok: true, creds, file, kind: 'account' };
|
|
103
100
|
}
|
|
104
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Key 模式下 CMS 报错的**唯一**正确说法(老板 2026-11-22 硬口径:
|
|
104
|
+
* 「`wkgeo login` 只有 CLI 该有;填了 Key 就不该再要登录,否则就是重复登录」)。
|
|
105
|
+
*
|
|
106
|
+
* 401 ⇒ `AUTH_FAILED`(Key 无效/过期 → 去后台重建 Key);
|
|
107
|
+
* 403 ⇒ `KEY_SCOPE_DENIED`(Key 的权限/站点绑定不够 → 去后台重建 / 换绑站点)。
|
|
108
|
+
* **一律不提示 `wkgeo login`。**
|
|
109
|
+
*/
|
|
110
|
+
function keyCmsCliError(action, err) {
|
|
111
|
+
const raw = String((err && err.message) || err || '未知错误');
|
|
112
|
+
const code = Number(err && err.code);
|
|
113
|
+
const status = Number.isFinite(code) && code >= 400 ? code : err && err.kind === 'cms_auth' ? 401 : 403;
|
|
114
|
+
if (status === 401) {
|
|
115
|
+
return new CliError(
|
|
116
|
+
`CMS 拒绝了这个 Key(HTTP 401):${raw}\n` +
|
|
117
|
+
'Key 模式只认 Key:这个 Key 被 CMS 判为无效或过期 —— 请到后台重新生成 Key(面板「设置 → Key」),把新 Key 填回面板重试。',
|
|
118
|
+
{
|
|
119
|
+
kind: 'key_auth',
|
|
120
|
+
code: 'AUTH_FAILED',
|
|
121
|
+
exitCode: EXIT.AUTH,
|
|
122
|
+
hint: '换 Key / 重建 Key 才是正确的修法(面板「设置 → Key」)。',
|
|
123
|
+
},
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
return new CliError(
|
|
127
|
+
`CMS 拒绝了这个 Key(HTTP ${status}):${raw}\n` +
|
|
128
|
+
'这是 Key 的权限 / 站点绑定问题:请确认这个 Key 属于该站点(或账号下已绑定该站),或到后台重新生成 Key 后再试。',
|
|
129
|
+
{
|
|
130
|
+
kind: 'key_scope',
|
|
131
|
+
code: 'KEY_SCOPE_DENIED',
|
|
132
|
+
exitCode: EXIT.AUTH,
|
|
133
|
+
hint: '问题在 Key 本身(权限范围 / 站点绑定):到后台调整或重建 Key 后重试。',
|
|
134
|
+
},
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
105
138
|
/** 失败信封:**结构化**,带 code / message / hint,让 AI 端能自己决定下一步 */
|
|
106
139
|
export function errorEnvelope(command, err, meta) {
|
|
107
140
|
const env = {
|
|
@@ -539,47 +572,40 @@ export function createRuntime({
|
|
|
539
572
|
return { id: '', label: null, source: 'none' };
|
|
540
573
|
},
|
|
541
574
|
/**
|
|
542
|
-
* 取 **CMS
|
|
575
|
+
* 取 **CMS 管理面**要用的身份。老板 2026-11-22 硬口径:
|
|
576
|
+
* **「`wkgeo login` 只有 CLI 该有;填了 Key 就不该再要登录,否则就是重复登录」**。
|
|
543
577
|
*
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
547
|
-
*
|
|
548
|
-
*
|
|
578
|
+
* 解析顺序(**Key 永远优先,且不回落账号 OAuth**):
|
|
579
|
+
* 1. env `WKGEO_API_KEY`(面板 / 自动化注入的 Key,直接当 Bearer,不落盘)
|
|
580
|
+
* 2. 主凭据 `config.credentialsFile`:是 `wkgeo_sk_…` Key ⇒ **只走 Key**(401/403 由
|
|
581
|
+
* `keyCmsCliError` 翻成 `AUTH_FAILED` / `KEY_SCOPE_DENIED`,不提示登录)
|
|
582
|
+
* 3. 主凭据是**账号 OAuth**(纯 CLI 用户 `wkgeo login` 的场景)⇒ 用它
|
|
583
|
+
* 4. 都没有 ⇒ `cmsCredentialsFile`(纯 CLI 用户的账号登录态)
|
|
549
584
|
*
|
|
550
|
-
*
|
|
551
|
-
*
|
|
552
|
-
* 2. 主凭据 `config.credentialsFile`(本身就是账号登录时,它才是对的)
|
|
553
|
-
* 3. 都没有 / 都是 Key ⇒ 本地抛**可照做**的错误,不把请求发出去换一个误导 401。
|
|
585
|
+
* 为什么不再「Key 401 → 回落账号」:那正是重复登录的来源;CMS 侧 task-58 起已认
|
|
586
|
+
* Key 做模板读动作,回落只会掩盖真正的 Key 问题。
|
|
554
587
|
*
|
|
555
|
-
* @returns {{creds:object, file:string, kind:'account'}}
|
|
588
|
+
* @returns {{creds:object, file:string, kind:'key'|'account'}}
|
|
556
589
|
*/
|
|
557
590
|
cmsAuth() {
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
if (account.ok) return { creds: account.creds, file: account.file, kind: 'account' };
|
|
562
|
-
const primary = primaryFile && primaryFile !== accountFile ? tryCmsCredentials(primaryFile, nowFn) : { ok: false, kind: 'missing', file: '' };
|
|
563
|
-
if (primary.ok) return { creds: primary.creds, file: primary.file, kind: 'account' };
|
|
564
|
-
const apiKeyFile = account.kind === 'api-key' ? account.file : primary.kind === 'api-key' ? primary.file : '';
|
|
565
|
-
if (apiKeyFile) {
|
|
566
|
-
throw new CliError(
|
|
567
|
-
'CMS 管理动作(模板 / 栏目 / 内容等)需要**账号登录令牌**,当前用的是 Key / 站点票:服务端不接受这类令牌(会回 401「OAuth 令牌无效或已过期」)。\n' +
|
|
568
|
-
'处理办法:在这台机器上跑一次 `wkgeo login` 登录账号,然后重试(面板 Key 模式会自动沿用本机账号登录态,不用把账号令牌填进面板)。',
|
|
569
|
-
{
|
|
570
|
-
kind: 'cms_account_required',
|
|
571
|
-
code: 401,
|
|
572
|
-
exitCode: EXIT.AUTH,
|
|
573
|
-
hint:
|
|
574
|
-
'账号令牌默认位置:' + (accountFile || '~/.wkongai/credentials.json') +
|
|
575
|
-
'(可用 WKONGAI_CMS_CREDENTIALS 指定别的路径)。站点 / 内容类动作仍走 Key,不受影响。',
|
|
576
|
-
},
|
|
577
|
-
);
|
|
591
|
+
const envKey = String((env && env.WKGEO_API_KEY) || '').trim();
|
|
592
|
+
if (envKey) {
|
|
593
|
+
return { creds: { access_token: envKey }, file: 'env:WKGEO_API_KEY', kind: 'key' };
|
|
578
594
|
}
|
|
595
|
+
const primaryFile = String((config && config.credentialsFile) || '').trim();
|
|
596
|
+
const accountFile = String((config && config.cmsCredentialsFile) || '').trim();
|
|
597
|
+
const primary = readCredentialToken(primaryFile, nowFn);
|
|
598
|
+
/* ★ Key 优先:主凭据本身就是 Key ⇒ 只走 Key,不看账号文件、不给登录提示 */
|
|
599
|
+
if (primary.ok) return { creds: primary.creds, file: primary.file, kind: primary.kind };
|
|
600
|
+
const account = accountFile && accountFile !== primaryFile
|
|
601
|
+
? readCredentialToken(accountFile, nowFn)
|
|
602
|
+
: { ok: false, kind: 'missing', file: accountFile };
|
|
603
|
+
if (account.ok) return { creds: account.creds, file: account.file, kind: account.kind };
|
|
604
|
+
if (primary.error) throw primary.error;
|
|
579
605
|
if (account.error) throw account.error;
|
|
580
606
|
return {
|
|
581
|
-
creds: requireCredentials(
|
|
582
|
-
file:
|
|
607
|
+
creds: requireCredentials(primaryFile || accountFile, { now: nowFn() }),
|
|
608
|
+
file: primaryFile || accountFile,
|
|
583
609
|
kind: 'account',
|
|
584
610
|
};
|
|
585
611
|
},
|
|
@@ -597,8 +623,8 @@ export function createRuntime({
|
|
|
597
623
|
*/
|
|
598
624
|
cmsCall(action, payload = {}, opts = {}) {
|
|
599
625
|
/**
|
|
600
|
-
* ★ 2026-11-22:CMS
|
|
601
|
-
* Key
|
|
626
|
+
* ★ 2026-11-22:Key 模式只走 Key(CMS task-58 起认 `wkgeo_sk_` 做模板读动作);
|
|
627
|
+
* Key 被拒时由 `keyCmsCliError` 给人话(重建 Key),**不再回落账号 OAuth**。
|
|
602
628
|
*/
|
|
603
629
|
const auth = runtime.cmsAuth();
|
|
604
630
|
let siteId;
|
|
@@ -606,7 +632,12 @@ export function createRuntime({
|
|
|
606
632
|
const site = runtime.cmsSite();
|
|
607
633
|
siteId = site.id || undefined;
|
|
608
634
|
}
|
|
609
|
-
|
|
635
|
+
try {
|
|
636
|
+
return cms.call(action, payload, { token: auth.creds.access_token, siteId });
|
|
637
|
+
} catch (err) {
|
|
638
|
+
if (auth.kind !== 'key') throw err;
|
|
639
|
+
throw keyCmsCliError(action, err);
|
|
640
|
+
}
|
|
610
641
|
},
|
|
611
642
|
/**
|
|
612
643
|
* 调 **内容类自持动作**(`wkgeo-cli-fc` 的 B1 45 条:栏目 / 文章 / 字段 / 关联 /
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `site publish` 的**打包 + 上传**实现(task-68,2026-11-22)。
|
|
3
|
+
*
|
|
4
|
+
* 老板口径:「待发布」是一个**动作** —— 把本地 `<站点目录>\html\` 里 build 出来的整站
|
|
5
|
+
* 上传到平台 OSS(站点有自有存储时服务端再复制过去)。
|
|
6
|
+
*
|
|
7
|
+
* 链路:本地 `html/**` → 零依赖 tar.gz → `POST /site/build-upload?siteId=…&mode=plan|apply&prune=0|1`
|
|
8
|
+
* · 不带 `--confirm` ⇒ `mode=plan`(服务端**零写**,只回 missing/changed/deleted);
|
|
9
|
+
* · 带 `--confirm` ⇒ `mode=apply`(服务端只 PUT 缺失/变更,`--prune` 才删前缀内孤儿)。
|
|
10
|
+
*
|
|
11
|
+
* 约定:
|
|
12
|
+
* · tar 路径 = **站内相对路径**(`index.html` / `syhz/index.html` / `upload/a.png`),
|
|
13
|
+
* 由服务端拼成 `<siteId>/<rel>`,所以这里**不带**站点目录名、不带 `./`;
|
|
14
|
+
* · 文件系统垃圾(`.DS_Store` / `__MACOSX/**` / `._*`)静默跳过(服务端同样会跳过,双保险);
|
|
15
|
+
* · 绝不打印 / 打印到日志:`access_token`(站点票/账号 Key)。只报 keyPrefix。
|
|
16
|
+
*/
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import zlib from 'node:zlib';
|
|
20
|
+
|
|
21
|
+
import { CliError, EXIT, networkError } from './errors.mjs';
|
|
22
|
+
import { listSiteCredentials, sitePathKey, isSiteCredentialExpired } from './site-credentials.mjs';
|
|
23
|
+
import { resolveSiteTarget } from './build.mjs';
|
|
24
|
+
|
|
25
|
+
/** 与上传接口契约一致的上限(服务端同样校验;这里先拦一次,给出"该删什么"的提示) */
|
|
26
|
+
export const PUBLISH_LIMITS = Object.freeze({
|
|
27
|
+
fileBytes: 20 * 1024 * 1024,
|
|
28
|
+
totalBytes: 100 * 1024 * 1024,
|
|
29
|
+
entries: 5000,
|
|
30
|
+
/** 网关默认请求体闸门(GW_MAX_BODY_BYTES 默认 8 MiB)——只用于提醒,不做拒绝 */
|
|
31
|
+
gatewayBytes: 8 * 1024 * 1024,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const SKIP_FILES = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini']);
|
|
35
|
+
|
|
36
|
+
function isSkippedRel(rel) {
|
|
37
|
+
const base = rel.slice(rel.lastIndexOf('/') + 1);
|
|
38
|
+
if (SKIP_FILES.has(base)) return true;
|
|
39
|
+
if (base.startsWith('._')) return true;
|
|
40
|
+
if (rel === '__MACOSX' || rel.startsWith('__MACOSX/')) return true;
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 单段路径白名单(与服务端 `src/build-upload-archive.js` 的 `SAFE_SEGMENT_RE` 同口径) */
|
|
45
|
+
const SAFE_SEGMENT_RE = /^[\p{L}\p{N}\p{M}._~+@()()\-]+$/u;
|
|
46
|
+
|
|
47
|
+
function assertSafeRel(rel) {
|
|
48
|
+
for (const part of rel.split('/')) {
|
|
49
|
+
if (!part || part === '.' || part === '..') {
|
|
50
|
+
throw new CliError(`本地文件名不合法:${rel}`, {
|
|
51
|
+
kind: 'build_bad_path',
|
|
52
|
+
code: 'BAD_PATH',
|
|
53
|
+
hint: '页面/资产文件名里不要有 ".." 或空目录名,重命名后再发布',
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
if (!SAFE_SEGMENT_RE.test(part)) {
|
|
57
|
+
throw new CliError(`本地文件名含不允许的字符:${rel}`, {
|
|
58
|
+
kind: 'build_bad_path',
|
|
59
|
+
code: 'BAD_PATH',
|
|
60
|
+
hint: '文件名只用字母 / 数字 / 中文 / . _ - ~ + @ ( )(),不要用空格、%、#、?、& 等字符',
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 递归列 `html/` 下的文件(返回 `{rel, file, size}`,rel 一律 `/` 分隔) */
|
|
67
|
+
export function listHtmlFiles(htmlDir) {
|
|
68
|
+
const root = path.resolve(htmlDir);
|
|
69
|
+
const out = [];
|
|
70
|
+
const walk = (dirAbs, relPrefix) => {
|
|
71
|
+
const names = fs.readdirSync(dirAbs, { withFileTypes: true });
|
|
72
|
+
names.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
73
|
+
for (const one of names) {
|
|
74
|
+
const abs = path.join(dirAbs, one.name);
|
|
75
|
+
const rel = relPrefix ? `${relPrefix}/${one.name}` : one.name;
|
|
76
|
+
if (one.isDirectory()) {
|
|
77
|
+
if (one.name === '__MACOSX') continue;
|
|
78
|
+
walk(abs, rel);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (!one.isFile()) continue; // 符号链接 / 设备文件一律不要
|
|
82
|
+
if (isSkippedRel(rel)) continue;
|
|
83
|
+
const stat = fs.statSync(abs);
|
|
84
|
+
out.push({ rel, file: abs, size: stat.size });
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
walk(root, '');
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 零依赖 tar writer(ustar):只用得到普通文件 + 目录层级;不写 uid/gid/注释。
|
|
93
|
+
* 头 512 字节 + 数据按 512 对齐 + 结尾两个全 0 块。
|
|
94
|
+
*/
|
|
95
|
+
function writeOctal(buf, offset, length, value) {
|
|
96
|
+
const text = Math.max(0, Math.floor(Number(value) || 0)).toString(8);
|
|
97
|
+
const padded = text.padStart(length - 1, '0').slice(-(length - 1));
|
|
98
|
+
buf.write(padded, offset, length - 1, 'ascii');
|
|
99
|
+
buf[offset + length - 1] = 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function tarHeaderOf(rel, size, mtimeSec) {
|
|
103
|
+
const header = Buffer.alloc(512);
|
|
104
|
+
/** name 字段 100 字节;长路径拆 prefix(155) + name(100)(在 `/` 处切) */
|
|
105
|
+
let namePart = rel;
|
|
106
|
+
let prefixPart = '';
|
|
107
|
+
if (Buffer.byteLength(rel) > 100) {
|
|
108
|
+
let cut = -1;
|
|
109
|
+
const slashPositions = [];
|
|
110
|
+
for (let i = 0; i < rel.length; i += 1) if (rel[i] === '/') slashPositions.push(i);
|
|
111
|
+
for (const pos of slashPositions) {
|
|
112
|
+
const head = rel.slice(0, pos);
|
|
113
|
+
const tail = rel.slice(pos + 1);
|
|
114
|
+
if (Buffer.byteLength(tail) <= 100 && Buffer.byteLength(head) <= 155) {
|
|
115
|
+
cut = pos;
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (cut === -1) {
|
|
120
|
+
throw new CliError(`文件路径太长,无法打包:${rel}`, {
|
|
121
|
+
kind: 'build_bad_path',
|
|
122
|
+
code: 'PATH_TOO_LONG',
|
|
123
|
+
hint: '把目录层级缩短,或给文件换个短一点的名字',
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
prefixPart = rel.slice(0, cut);
|
|
127
|
+
namePart = rel.slice(cut + 1);
|
|
128
|
+
}
|
|
129
|
+
header.write(namePart, 0, 100, 'utf8');
|
|
130
|
+
writeOctal(header, 100, 8, 0o644); // mode
|
|
131
|
+
writeOctal(header, 108, 8, 0); // uid
|
|
132
|
+
writeOctal(header, 116, 8, 0); // gid
|
|
133
|
+
writeOctal(header, 124, 12, size); // size
|
|
134
|
+
writeOctal(header, 136, 12, mtimeSec); // mtime
|
|
135
|
+
header.fill(0x20, 148, 156); // chksum 先填空格
|
|
136
|
+
header.write('0', 156, 1, 'ascii'); // typeflag = 普通文件
|
|
137
|
+
header.write('ustar\0', 257, 6, 'ascii');
|
|
138
|
+
header.write('00', 263, 2, 'ascii');
|
|
139
|
+
if (prefixPart) header.write(prefixPart, 345, 155, 'utf8');
|
|
140
|
+
let sum = 0;
|
|
141
|
+
for (let i = 0; i < 512; i += 1) sum += header[i];
|
|
142
|
+
header.write(sum.toString(8).padStart(6, '0'), 148, 6, 'ascii');
|
|
143
|
+
header[154] = 0;
|
|
144
|
+
header[155] = 0x20;
|
|
145
|
+
return header;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 把 `html/` 打成 tar.gz。
|
|
150
|
+
* @returns {{ok:true, buffer:Buffer, files:number, rawBytes:number, gzipBytes:number, entries:Array<{rel,size}>}}
|
|
151
|
+
*/
|
|
152
|
+
export function packHtmlDirectory(htmlDir, { limits = PUBLISH_LIMITS } = {}) {
|
|
153
|
+
const root = path.resolve(htmlDir);
|
|
154
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
|
|
155
|
+
throw new CliError(`没有找到 html 目录:${root}`, {
|
|
156
|
+
kind: 'build_missing',
|
|
157
|
+
code: 'BUILD_MISSING',
|
|
158
|
+
exitCode: EXIT.USAGE,
|
|
159
|
+
hint: '先在这个站点目录里执行 `wkgeo site build`,生成 html/ 后再发布',
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
const files = listHtmlFiles(root);
|
|
163
|
+
if (!files.length) {
|
|
164
|
+
throw new CliError(`html 目录里没有可发布的文件:${root}`, {
|
|
165
|
+
kind: 'build_missing',
|
|
166
|
+
code: 'BUILD_MISSING',
|
|
167
|
+
exitCode: EXIT.USAGE,
|
|
168
|
+
hint: '先执行 `wkgeo site build`;如果刚 build 过,检查产物是不是在别的目录(--out)',
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
const mtimeSec = Math.floor(Date.now() / 1000);
|
|
172
|
+
const chunks = [];
|
|
173
|
+
let rawBytes = 0;
|
|
174
|
+
for (const one of files) {
|
|
175
|
+
assertSafeRel(one.rel);
|
|
176
|
+
if (one.size > limits.fileBytes) {
|
|
177
|
+
throw new CliError(`单个文件超过上限(${limits.fileBytes} 字节):${one.rel}`, {
|
|
178
|
+
kind: 'build_too_large',
|
|
179
|
+
code: 'FILE_TOO_LARGE',
|
|
180
|
+
hint: '压缩/换掉这个大文件(视频请走素材库或外部链接),再发布',
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
rawBytes += one.size;
|
|
184
|
+
if (rawBytes > limits.totalBytes) {
|
|
185
|
+
throw new CliError(`产物总大小超过上限(${limits.totalBytes} 字节)`, {
|
|
186
|
+
kind: 'build_too_large',
|
|
187
|
+
code: 'ARCHIVE_TOO_LARGE',
|
|
188
|
+
hint: '删掉 html/ 里不需要上传的大文件(临时视频、备份包等)后再发布',
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
if (files.length > limits.entries) {
|
|
192
|
+
throw new CliError(`产物文件数超过上限(${limits.entries} 个)`, {
|
|
193
|
+
kind: 'build_too_large',
|
|
194
|
+
code: 'TOO_MANY_ENTRIES',
|
|
195
|
+
hint: '检查 html/ 里有没有误生成的临时目录',
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const data = fs.readFileSync(one.file);
|
|
199
|
+
const header = tarHeaderOf(one.rel, data.length, mtimeSec);
|
|
200
|
+
chunks.push(header, data);
|
|
201
|
+
const pad = (512 - (data.length % 512)) % 512;
|
|
202
|
+
if (pad) chunks.push(Buffer.alloc(pad));
|
|
203
|
+
}
|
|
204
|
+
chunks.push(Buffer.alloc(1024)); // 结尾两个全 0 块
|
|
205
|
+
const tarBuf = Buffer.concat(chunks);
|
|
206
|
+
let gzipBuf;
|
|
207
|
+
try {
|
|
208
|
+
gzipBuf = zlib.gzipSync(tarBuf, { level: 9 });
|
|
209
|
+
} catch (error) {
|
|
210
|
+
throw new CliError(`打包失败:${String((error && error.message) || error)}`, { kind: 'build', code: 'PACK_FAILED' });
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
ok: true,
|
|
214
|
+
buffer: gzipBuf,
|
|
215
|
+
files: files.length,
|
|
216
|
+
rawBytes,
|
|
217
|
+
gzipBytes: gzipBuf.length,
|
|
218
|
+
entries: files.map((one) => ({ rel: one.rel, size: one.size })),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Windows 下路径大小写不敏感:比较前统一小写 + 去掉末尾斜杠 */
|
|
223
|
+
function dirKeyOf(dir) {
|
|
224
|
+
return sitePathKey(path.resolve(String(dir || ''))).replace(/[\\/]+$/, '').toLowerCase();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* 选这次上传用哪张凭据:
|
|
229
|
+
* ① `--dir` 指向的站点目录命中了本地站点票(`%LOCALAPPDATA%\wkgeo-ops\creds\*.json` 里的 site.dir)
|
|
230
|
+
* ⇒ 用站点票(最常用:老板在站点目录里 publish,不需要 OAuth 登录);
|
|
231
|
+
* ② `--site` 是 uuid 且命中某张票的 siteId/cmsId ⇒ 用那张票;
|
|
232
|
+
* ③ 都没命中 ⇒ 交给 `ctx.cmsAuth()` 的账号 Key(服务端按"本人名下站"校验)。
|
|
233
|
+
*/
|
|
234
|
+
export function pickSiteCredential({ dir = '', siteRef = '', env = process.env, now = Date.now() } = {}) {
|
|
235
|
+
let creds = [];
|
|
236
|
+
try {
|
|
237
|
+
creds = listSiteCredentials({ env, now }) || [];
|
|
238
|
+
} catch {
|
|
239
|
+
creds = [];
|
|
240
|
+
}
|
|
241
|
+
creds = creds.filter((one) => one && !isSiteCredentialExpired(one, { now }));
|
|
242
|
+
const wantDir = dir ? dirKeyOf(dir) : '';
|
|
243
|
+
if (wantDir) {
|
|
244
|
+
const byDir = creds.filter((one) => one.siteDir && dirKeyOf(one.siteDir) === wantDir);
|
|
245
|
+
if (byDir.length) {
|
|
246
|
+
/** 同目录多张票(续期残留):取最晚过期的那张 */
|
|
247
|
+
byDir.sort((a, b) => Number(b.expiresMs || 0) - Number(a.expiresMs || 0));
|
|
248
|
+
return { credential: byDir[0], source: 'dir' };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const ref = String(siteRef || '').trim();
|
|
252
|
+
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ref)) {
|
|
253
|
+
const byId = creds.filter((one) => one.siteId === ref || one.cmsId === ref);
|
|
254
|
+
if (byId.length) {
|
|
255
|
+
byId.sort((a, b) => Number(b.expiresMs || 0) - Number(a.expiresMs || 0));
|
|
256
|
+
return { credential: byId[0], source: 'site-id' };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return { credential: null, source: '' };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 上传一次(plan / apply 同一条链路,只有 query 不同)。
|
|
264
|
+
*
|
|
265
|
+
* @param {object} p
|
|
266
|
+
* @param {Buffer} p.buffer 已打包的 tar.gz
|
|
267
|
+
* @param {string} p.siteId 平台站 id(query 用;服务端也认 cmsId)
|
|
268
|
+
* @param {string} p.base 平台 API 基址(`config.base`,默认 https://api.wkgeo.cn)
|
|
269
|
+
* @param {string} p.token Bearer 凭据(站点票 / 账号 Key);**不打印**
|
|
270
|
+
* @param {'plan'|'apply'} p.mode
|
|
271
|
+
* @param {boolean} p.prune
|
|
272
|
+
* @param {Function} p.fetchImpl
|
|
273
|
+
* @param {string} [p.traceId]
|
|
274
|
+
*/
|
|
275
|
+
export async function postBuildUpload({ buffer, siteId, base, token, mode = 'plan', prune = false, fetchImpl }) {
|
|
276
|
+
const qs = new URLSearchParams({ siteId: String(siteId), mode, prune: prune ? '1' : '0' });
|
|
277
|
+
const url = `${String(base || 'https://api.wkgeo.cn').replace(/\/+$/, '')}/site/build-upload?${qs.toString()}`;
|
|
278
|
+
const headers = {
|
|
279
|
+
authorization: `Bearer ${token}`,
|
|
280
|
+
'content-type': 'application/gzip',
|
|
281
|
+
accept: 'application/json',
|
|
282
|
+
};
|
|
283
|
+
let res;
|
|
284
|
+
try {
|
|
285
|
+
const signal =
|
|
286
|
+
typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
|
|
287
|
+
? AbortSignal.timeout(180000)
|
|
288
|
+
: undefined;
|
|
289
|
+
res = await fetchImpl(url, { method: 'POST', headers, body: buffer, ...(signal ? { signal } : {}) });
|
|
290
|
+
} catch (error) {
|
|
291
|
+
throw networkError(String((error && error.message) || error), { cause: error });
|
|
292
|
+
}
|
|
293
|
+
const status = Number(res && res.status) || 0;
|
|
294
|
+
let text = '';
|
|
295
|
+
try {
|
|
296
|
+
text = await res.text();
|
|
297
|
+
} catch {
|
|
298
|
+
text = '';
|
|
299
|
+
}
|
|
300
|
+
let body = null;
|
|
301
|
+
try {
|
|
302
|
+
body = text ? JSON.parse(text) : null;
|
|
303
|
+
} catch {
|
|
304
|
+
body = null;
|
|
305
|
+
}
|
|
306
|
+
if (!body || typeof body !== 'object') {
|
|
307
|
+
throw new CliError(`上传接口返回了非 JSON(HTTP ${status})`, {
|
|
308
|
+
kind: 'server',
|
|
309
|
+
code: status,
|
|
310
|
+
raw: String(text || '').slice(0, 500),
|
|
311
|
+
hint: '确认网关已下发 /site/build-upload 路由,或稍后重试',
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
if (status < 200 || status >= 300 || body.ok !== true) {
|
|
315
|
+
const message = String(body.message || body.error || `上传接口返回 HTTP ${status}`);
|
|
316
|
+
const code = body.code == null ? status : body.code;
|
|
317
|
+
/** 401 ⇒ 凭据问题(票过期 / Key 错);其余按一般失败,把服务端 code 留着好排查 */
|
|
318
|
+
const authLike = status === 401 || /^KEY_(INVALID|REVOKED|EXPIRED)$/.test(String(code));
|
|
319
|
+
throw new CliError(message, {
|
|
320
|
+
kind: authLike ? 'auth' : 'server',
|
|
321
|
+
code,
|
|
322
|
+
exitCode: authLike ? EXIT.AUTH : EXIT.ERROR,
|
|
323
|
+
raw: body,
|
|
324
|
+
details: body.details || null,
|
|
325
|
+
hint: authLike
|
|
326
|
+
? '站点票可能过期:在站点目录里重新执行 `wkgeo site credential`(或控制台重新生成站点票)后再发布'
|
|
327
|
+
: status === 413
|
|
328
|
+
? '包太大:删掉 html/ 里不需要上传的大文件;网关还有 8 MiB 请求体闸门,超过要调 GW_MAX_BODY_BYTES'
|
|
329
|
+
: status === 403
|
|
330
|
+
? '这个凭据没有该站点的写权限:确认 --site 是票绑定的那个站,或换账号 Key'
|
|
331
|
+
: '把 --json 的输出贴给平台排查',
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
return { status, body };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* 命令主流程:打包 → 解析站点 → plan/apply。
|
|
339
|
+
* 返回服务端 body(已经在内部通过 `ctx.done` 之外的打印由命令负责)。
|
|
340
|
+
*/
|
|
341
|
+
export async function publishLocalBuild({ ctx, dir, site, prune = false, confirm = false }) {
|
|
342
|
+
const htmlDir = path.join(path.resolve(dir), 'html');
|
|
343
|
+
const pack = packHtmlDirectory(htmlDir);
|
|
344
|
+
const credPick = pickSiteCredential({ dir, siteRef: site, env: ctx.env || process.env });
|
|
345
|
+
const credential = credPick.credential;
|
|
346
|
+
const token = credential ? credential.accessToken : null;
|
|
347
|
+
|
|
348
|
+
/** 站点 id:有票就用票里的(服务端会再校验票 ↔ 站),否则按 `--site` 解析 */
|
|
349
|
+
let siteId = '';
|
|
350
|
+
let siteLabel = '';
|
|
351
|
+
if (credential) {
|
|
352
|
+
siteId = String(credential.siteId || credential.cmsId || '');
|
|
353
|
+
siteLabel = String(credential.cmsId || credential.siteId || '');
|
|
354
|
+
} else {
|
|
355
|
+
const credentials = ctx.cmsAuth().creds;
|
|
356
|
+
const resolved = await resolveSiteTarget({
|
|
357
|
+
site: site || '',
|
|
358
|
+
cmsSite: ctx.flags && ctx.flags.cmsSite ? String(ctx.flags.cmsSite) : '',
|
|
359
|
+
config: ctx.config,
|
|
360
|
+
credentials,
|
|
361
|
+
fetchImpl: ctx.fetchImpl,
|
|
362
|
+
});
|
|
363
|
+
siteId = String(resolved.id || '');
|
|
364
|
+
siteLabel = String(resolved.label || '');
|
|
365
|
+
}
|
|
366
|
+
if (!siteId) {
|
|
367
|
+
throw new CliError('没能确定要发布到哪个站点', {
|
|
368
|
+
kind: 'usage',
|
|
369
|
+
code: 'SITE_REQUIRED',
|
|
370
|
+
exitCode: EXIT.USAGE,
|
|
371
|
+
hint: '用 `--site <域名|站点uuid>` 指定站点,或在站点目录里用站点票发布',
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
let bearer = token;
|
|
376
|
+
if (!bearer) {
|
|
377
|
+
const auth = ctx.cmsAuth();
|
|
378
|
+
bearer = auth && auth.creds && auth.creds.access_token ? auth.creds.access_token : '';
|
|
379
|
+
}
|
|
380
|
+
if (!bearer) {
|
|
381
|
+
throw new CliError('没有可用的凭据', {
|
|
382
|
+
kind: 'auth',
|
|
383
|
+
code: 'NO_CREDENTIAL',
|
|
384
|
+
exitCode: EXIT.AUTH,
|
|
385
|
+
hint: '在站点目录里生成站点票,或先 `wkgeo login` 用账号 Key 发布',
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const mode = confirm ? 'apply' : 'plan';
|
|
390
|
+
const { status, body } = await postBuildUpload({
|
|
391
|
+
buffer: pack.buffer,
|
|
392
|
+
siteId,
|
|
393
|
+
base: ctx.config.base,
|
|
394
|
+
token: bearer,
|
|
395
|
+
mode,
|
|
396
|
+
prune,
|
|
397
|
+
fetchImpl: ctx.fetchImpl,
|
|
398
|
+
});
|
|
399
|
+
return {
|
|
400
|
+
status,
|
|
401
|
+
body,
|
|
402
|
+
pack,
|
|
403
|
+
siteId,
|
|
404
|
+
siteLabel,
|
|
405
|
+
credentialSource: credPick.source,
|
|
406
|
+
keyPrefix: credential ? credential.keyPrefix || '' : '',
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export default { packHtmlDirectory, postBuildUpload, publishLocalBuild, pickSiteCredential, listHtmlFiles, PUBLISH_LIMITS };
|
package/lib/site-spec.mjs
CHANGED
|
@@ -131,6 +131,9 @@ export function extractSection(markdown, begin, end, what = '规范段落') {
|
|
|
131
131
|
}
|
|
132
132
|
const body = text
|
|
133
133
|
.slice(start + begin.length, stop)
|
|
134
|
+
/* 切出来的正文一律 CRLF → LF:下游(init 写盘 / 生成器)都按 LF 拼块,
|
|
135
|
+
只有在真正落盘时才按目标文件换行风格转换(见 withEol) */
|
|
136
|
+
.replace(/\r\n/g, '\n')
|
|
134
137
|
.replace(/^\r?\n/, '')
|
|
135
138
|
.replace(/\s+$/, '');
|
|
136
139
|
if (!body.trim()) {
|
|
@@ -202,14 +205,31 @@ export function resolveAgentFiles(value) {
|
|
|
202
205
|
return out;
|
|
203
206
|
}
|
|
204
207
|
|
|
208
|
+
/**
|
|
209
|
+
* 统一换行符:`\r\n` → `\n`(null / undefined 原样返回,方便"文件不存在"也走同一套比较)。
|
|
210
|
+
*
|
|
211
|
+
* 为什么必须归一:仓库在 Windows(`core.autocrlf=true`)下检出的文件是 CRLF,git 里存的却是 LF。
|
|
212
|
+
* 「内容有没有变」如果按字节比,会把"只是平台换行不同"误判成 drift / replaced,
|
|
213
|
+
* 于是每次重跑都重写一遍(幂等失效)。所以**读取 / 比较 / 判断 unchanged 一律先归一**;
|
|
214
|
+
* 写盘仍保留目标文件原来的换行风格(见 `eolOf` / `withEol`)。
|
|
215
|
+
*
|
|
216
|
+
* @param {string|null|undefined} text
|
|
217
|
+
* @returns {string|null|undefined}
|
|
218
|
+
*/
|
|
219
|
+
export function normalizeEol(text) {
|
|
220
|
+
if (text === null || text === undefined) return text;
|
|
221
|
+
return String(text).replace(/\r\n/g, '\n');
|
|
222
|
+
}
|
|
223
|
+
|
|
205
224
|
/** 现有文件用的换行符(Windows 项目里多半是 CRLF,插入段跟着走,别混出两种) */
|
|
206
225
|
function eolOf(text) {
|
|
207
226
|
return String(text || '').includes('\r\n') ? '\r\n' : '\n';
|
|
208
227
|
}
|
|
209
228
|
|
|
210
|
-
/** 把块里的 `\n`
|
|
229
|
+
/** 把块里的 `\n` 换成目标换行符(先归一,避免源块自带 CRLF 时叠成 `\r\r\n`) */
|
|
211
230
|
function withEol(block, eol) {
|
|
212
|
-
|
|
231
|
+
const lf = normalizeEol(block);
|
|
232
|
+
return eol === '\n' ? lf : lf.split('\n').join(eol);
|
|
213
233
|
}
|
|
214
234
|
|
|
215
235
|
/**
|
|
@@ -226,7 +246,8 @@ function withEol(block, eol) {
|
|
|
226
246
|
* @returns {{content:string, action:'created'|'replaced'|'appended'|'unchanged'}}
|
|
227
247
|
*/
|
|
228
248
|
export function upsertBriefBlock(existing, brief) {
|
|
229
|
-
|
|
249
|
+
/* brief 可能来自 CRLF 检出的主源(或调用方直接传 CRLF),先归一成 LF,保证块结构可预测 */
|
|
250
|
+
const body = normalizeEol(String(brief || '')).replace(/\s+$/, '');
|
|
230
251
|
const block = `${BLOCK_BEGIN}\n${body}\n${BLOCK_END}`;
|
|
231
252
|
if (existing === null || existing === undefined || !String(existing).trim()) {
|
|
232
253
|
const content = `${block}\n`;
|
|
@@ -240,7 +261,10 @@ export function upsertBriefBlock(existing, brief) {
|
|
|
240
261
|
if (start !== -1 && end !== -1) {
|
|
241
262
|
const after = text.slice(end + BLOCK_END.length);
|
|
242
263
|
const next = text.slice(0, start) + marker + after;
|
|
243
|
-
return { content: next, action:
|
|
264
|
+
if (next === text) return { content: next, action: 'unchanged' };
|
|
265
|
+
/* 只差换行风格(比如 Linux 写的 LF 到 Windows 被检出成 CRLF)⇒ 语义没变,不写盘 */
|
|
266
|
+
if (normalizeEol(next) === normalizeEol(text)) return { content: next, action: 'unchanged' };
|
|
267
|
+
return { content: next, action: 'replaced' };
|
|
244
268
|
}
|
|
245
269
|
/* 没有我们的标记 ⇒ 追加到末尾;文件末尾没换行就先补一个,段间留一个空行 */
|
|
246
270
|
const base = text.endsWith('\n') ? text : text + eol;
|