release-spec.mjs
25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#!/usr/bin/env node
/**
* 发布清单模式(release:spec)—— 「开发者写清单,ops 照单执行」。
*
* pnpm release:spec --spec 1.3.0 [选项]
* pnpm release:spec --latest # 自动取 releases/ 下版本号最大的清单
*
* 与 release:affected(git 自动反查)的区别:本命令「不比对 git」。
* WHAT 由开发者显式写进 releases/<version>.json,ops 只按清单执行,命令固定、不用判断范围。
*
* 清单格式(releases/1.3.0.json):
* {
* "version": "1.3.0", // 可选;缺省取文件名
* "apps": ["system", "store"], // 要发的子系统(必须存在于 workspace)
* "host": false, // 主壳是否要重发(进 /mfe/host/<version>/,站点根只写指针)
* "note": "门店分页修复", // 备注(仅展示 / 历史留存)
* "uploadCmd": "..." // 可选;不写则用 --upload-cmd 或 MFE_UPLOAD_CMD
* }
*
* 旧清单随 git 提交天然留存为发布历史,比从 git diff 反推更准(声明意图 vs 推断)。
*
* 安全护栏:--verify 会在发版前跑一次 git 反查,若清单与 git 实际改动对不上【仅告警、不阻断】,
* 用于防漏写。不做校验时零额外 git 操作,最快最干净。
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { scanWorkspace, collectChangedFiles, computeAffected } from './release-affected.mjs';
import { deployHost, hostRelOf } from './host-deploy.mjs';
import { writeBuildInfo, manifestVersionOf } from './build-info.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const SPECS_DIR = path.join(ROOT, 'releases');
/** 日志前缀。release:all 复用本文件的 runRelease 时改成自己的标签,日志才不会互相串。 */
let TAG = 'release:spec';
function die(message) {
console.error(`\n[${TAG}] ✗ ${message}\n`);
process.exit(1);
}
function info(message) {
console.log(`[${TAG}] ${message}`);
}
function parseArgs(argv) {
const flags = new Set(['dry-run', 'force', 'no-force', 'help', 'skip-build', 'verify', 'latest']);
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === '--') continue; // 容忍 pnpm 把 -- 透传给脚本
if (!token.startsWith('--')) throw new Error(`无法识别的参数:${token}`);
const eq = token.indexOf('=');
const key = eq > 0 ? token.slice(2, eq) : token.slice(2);
if (flags.has(key)) {
out[key] = true;
continue;
}
const value = eq > 0 ? token.slice(eq + 1) : argv[++i];
if (value === undefined || value.startsWith('--')) throw new Error(`参数 --${key} 缺少取值`);
out[key] = value;
}
return out;
}
function listSpecFiles() {
if (!fs.existsSync(SPECS_DIR)) return [];
return fs
.readdirSync(SPECS_DIR)
.filter((f) => f.endsWith('.json'))
.map((f) => ({ file: f, version: f.replace(/\.json$/, '') }));
}
function cmpVersion(a, b) {
const pa = String(a).split('.');
const pb = String(b).split('.');
const n = Math.max(pa.length, pb.length);
for (let i = 0; i < n; i += 1) {
const na = parseInt(pa[i] ?? '0', 10) || 0;
const nb = parseInt(pb[i] ?? '0', 10) || 0;
if (na !== nb) return na - nb;
}
return 0;
}
function loadSpec(args, microAppNames, shellName) {
const specs = listSpecFiles();
let fileName;
if (args.latest) {
if (specs.length === 0) die('releases/ 下没有任何清单文件,无法 --latest。');
fileName = specs.sort((a, b) => cmpVersion(a.version, b.version)).pop().file;
} else {
const v = args.spec;
if (!v) die('缺少 --spec <版本> 或 --latest。用 --help 查看用法。');
fileName = v.endsWith('.json') ? v : `${v}.json`;
if (!fs.existsSync(path.join(SPECS_DIR, fileName))) {
die(
`找不到清单文件 releases/${fileName}。可用:${specs.map((s) => s.file).join(', ') || '(无)'}`,
);
}
}
const full = path.join(SPECS_DIR, fileName);
let raw;
try {
raw = JSON.parse(fs.readFileSync(full, 'utf8'));
} catch (e) {
die(`清单 ${fileName} 不是合法 JSON:${e.message}`);
}
const version = raw.version ?? fileName.replace(/\.json$/, '');
if (!version || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(version) || version.includes('..')) {
die(`清单版本号 "${version}" 非法:只允许字母数字 . _ -,且不得含 ".."`);
}
const apps = Array.isArray(raw.apps) ? raw.apps : [];
for (const a of apps) {
if (!microAppNames.includes(a)) {
die(`清单包含未知子系统 "${a}"。可用:${microAppNames.join(', ') || '(无)'}`);
}
}
const host = Boolean(raw.host);
if (host && !shellName) die('清单 host=true 但未找到主壳包(apps/web/shell)。');
return { version, apps, host, note: raw.note ?? '', uploadCmd: raw.uploadCmd, file: fileName };
}
/** 交叉校验:清单与 git 实际改动对不上时返回告警列表(不阻断)。 */
function verifySpec(spec, base, workspace) {
const changed = collectChangedFiles(base);
const aff = computeAffected(changed, workspace);
const warnings = [];
for (const a of aff.affectedApps) {
if (!spec.apps.includes(a))
warnings.push(`git 显示子系统 [${a}] 有改动,但清单未包含 → 可能漏发`);
}
for (const a of spec.apps) {
if (!aff.affectedApps.includes(a))
warnings.push(`清单包含 [${a}],但 git 未见其改动 → 可能已发过或故意重建`);
}
if (aff.hostAffected && !spec.host)
warnings.push('git 显示主壳(host)受影响,但清单 host=false → 主壳可能漏发');
if (!aff.hostAffected && spec.host)
warnings.push('清单 host=true,但 git 未见主壳改动 → 可能无需重发主壳');
return warnings;
}
function printHelp() {
console.log(`
release:spec —— 发布清单模式(开发者写清单,ops 照单执行,不比对 git)
用法:
pnpm release:spec --spec <版本> [选项]
pnpm release:spec --latest 自动取 releases/ 下版本号最大的清单
选项:
--spec <版本> 清单文件名(releases/<版本>.json),可省略 .json
--latest 取 releases/ 下版本号最大的清单
--base <ref> --verify 用的 git 基线,默认 origin/master
--verify 发版前跑 git 反查交叉校验,清单与实改不符【仅告警不阻断】
--public-base <u> 子应用产物公网基址(透传给 release.mjs)
--out <dir> 产物目录,默认 dist(或 MFE_OUT_DIR)。它镜像部署根、
**每次发布重建**,只装本次要覆盖的文件,整棵树覆盖进部署目录即生效。
--state <dir> manifest 累积状态目录,默认 .release-state(或 MFE_STATE_DIR)
--upload-cmd <cmd> 上传钩子;{dir} 即产物根、{file} 是产物清单。也可用 MFE_UPLOAD_CMD。
推荐两阶段(清单最后落地):
"rsync -a --exclude='manifest.json' {dir}/ /srv/www/ && rsync -a {file} /srv/www/mfe/manifest.json"
--force 允许覆盖已发布过的同名版本目录
--skip-build 跳过构建,直接复用已有 dist(CI 已构建场景)
--dry-run 只打印将执行的动作,不构建、不落盘、不上传
--help 显示本帮助
清单格式(releases/1.3.0.json):
{
"version": "1.3.0", // 可选,缺省取文件名
"apps": ["system", "store"], // 要发的子系统
"host": false, // 主壳是否重发(进 mfe/host/<version>/,站点根只写指针)
"note": "门店分页修复", // 备注
"uploadCmd": "..." // 可选,覆盖环境变量
}
旧清单随 git 提交即发布历史;ops 固定跑本命令即可,无需判断发哪个。
`);
}
function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (e) {
die(e.message);
}
if (args.help) {
printHelp();
return;
}
const workspace = scanWorkspace();
const shellName = [...workspace.pkgs.values()].find((p) => p.isShell)?.name;
const microAppNames = [...workspace.pkgs.values()]
.filter((p) => p.isMicroApp)
.map((p) => p.microAppName);
const spec = loadSpec(args, microAppNames, shellName);
const base = args.base ?? 'origin/master';
if (args.verify) {
const warnings = verifySpec(spec, base, workspace);
if (warnings.length) {
console.log('\n[release:spec] ⚠ --verify 交叉校验告警(不阻断):');
for (const w of warnings) console.log(` - ${w}`);
console.log('');
} else {
info('--verify 通过:清单与 git 实际改动一致。');
}
}
return runRelease(spec, args, { workspace, shellName });
}
/**
* 按一份「已解析好的清单」发版 —— 单一实现,两个入口共用:
* - release:spec:清单来自 releases/<version>.json(明确写了发哪几个)
* - release:all :清单是现场算出来的全量(所有子系统 + 主壳)
*
* 抽出来是为了不让「发版流程」存在第二份实现。任何一处漏改(清空时机、
* --no-clean 传递、主壳落点、上传模板变量)都会变成两条行为分叉的路径。
*
* @param {{version: string, apps: string[], host: boolean, file?: string, note?: string, uploadCmd?: string, remoteManifest?: string}} spec
* @param {Record<string, any>} args 解析后的命令行参数;额外支持 args.tag 覆盖日志前缀
*/
/**
* 增量发版的清单基线检查:本次没发的 app 条目从哪来?
* - remoteManifest 已配置 → 以线上清单为准(真源,跨机器一致);
* - 本机 .release-state 有累积清单 → 用它(本机缓存,同事机器上可能没有);
* - 两处都没有 → 拦截。全量发版(apps 覆盖全部子系统)不拦,它不依赖基线。
*/
export function assertBaseline({ tag, apps, allApps, remoteManifest, stateDir }) {
const isPartial = apps.length < allApps.length;
if (!isPartial) return;
if (remoteManifest) return;
const stateFile = path.join(stateDir, 'manifest.json');
let hasLocal = false;
if (fs.existsSync(stateFile)) {
try {
const st = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
hasLocal = Boolean(st.subapps && Object.keys(st.subapps).length > 0);
} catch {
/* 坏文件按无基线处理,release.mjs 读到时会自己报更具体的错 */
}
}
if (hasLocal) {
info(
`⚠ 增量基线来自本机 ${path.relative(ROOT, stateFile)}(仅本机有效)。` +
'跨机器协作请配置 MFE_REMOTE_MANIFEST 或清单字段 remoteManifest,以线上清单为真源。',
);
return;
}
console.error(
`\n[${tag}] ✗ 增量发版(只发 ${apps.join(', ')})缺少清单基线。\n` +
` 本次没发的子系统条目必须来自基线,否则发出去的 mfe/manifest.json 只包含\n` +
` ${apps.join(', ')} —— 线上其它子系统(${allApps.filter((a) => !apps.includes(a)).join(', ') || '其它'})\n` +
` 的条目会被整份抹掉,页面直接白屏。\n\n` +
` 出路(任选一):\n` +
` 1. 指向线上清单后重跑(推荐,多机协作必配):\n` +
` 设环境变量 MFE_REMOTE_MANIFEST=http://<部署机>/mfe/manifest.json\n` +
` 或在清单 releases/<版本>.json 里加 "remoteManifest" 字段\n` +
` 2. 先跑一次全量(pnpm release:ops 走全量清单 / pnpm release:all),本机就有基线了。\n`,
);
process.exit(1);
}
function runRelease(spec, args, ctx = {}) {
TAG = args.tag ?? 'release:spec';
// workspace 只在这里用来定位主壳;调用方已经扫过就直接传进来,避免重复读 package.json
const workspace = ctx.workspace ?? scanWorkspace();
const shellName = ctx.shellName ?? [...workspace.pkgs.values()].find((p) => p.isShell)?.name;
const isWin = process.platform === 'win32';
const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm';
const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? 'dist');
const stateDir = args.state ?? process.env.MFE_STATE_DIR;
const publicBase = args['public-base'];
const out = args.out;
/**
* force 语义:
* - --latest(ops 零参数自动取最新清单)默认允许就地重建 —— 它的语义就是
* 「把最新声明的那版整套重打一遍」,与 release:all 一致。否则 ops 用同一条
* 固定命令跑第二次就会被本机发布记录拦住,违背「ops 只跑固定命令」的约定。
* - 显式 --spec <版本> 保留不可变保护(重发历史版本应当三思)。
* - 两者都可用 --no-force 关闭。
* 「已发布」的判定本身以线上清单为真源(见 release.mjs),本机记录只是兜底。
*/
const autoForce = Boolean(args.latest) && !args['no-force'];
const force = args['no-force'] ? false : Boolean(args.force) || autoForce;
const skipBuild = Boolean(args['skip-build']);
const uploadCmd = args['upload-cmd'] ?? spec.uploadCmd ?? process.env.MFE_UPLOAD_CMD;
/**
* 线上清单地址,三级来源:CLI > 清单字段 remoteManifest > 环境变量。
* 清单字段最省事:清单入库后,任何同事拿到它都自动带上正确地址,
* 不依赖每台机器各自配 env。
*/
const remoteManifest =
args['remote-manifest'] ?? spec.remoteManifest ?? process.env.MFE_REMOTE_MANIFEST;
const dryRun = Boolean(args['dry-run']);
/**
* 主壳的落点:/mfe/host/<version>/,与子应用的 /mfe/<app>/<version>/ 同构。
*
* 为什么不摊在站点根:站点根是唯一会被**原地覆盖**的地方。摊开时一次发布要逐个
* 覆盖 index.html 和一批 assets,在「HTML 已落地、JS 还没到」的几百毫秒里,线上
* 是新页面配旧资产 → 白屏 404,且窗口不可观测。版本化之后资产是整目录新增(原子),
* 站点根只覆盖 index.html 一个文件(单文件 rename 级原子),混合态消失。
* 顺带把「旧主壳 assets 散在根目录、覆盖式部署永不删除」这个坑一起收了。
*/
const hostVersion = spec.hostVersion ?? spec.version;
const hostRel = `mfe/host/${hostVersion}/`;
const hostBase = `/${hostRel}`;
if (spec.apps.length === 0 && !spec.host) {
die('清单里既没有子系统也没有 host,没有可发布的内容。');
}
// no-header:调用方(release:all)自己已经打过一份更贴场景的总览,这里不再重复一遍
if (!args['no-header']) {
console.log(`\n[${TAG}] ==== 发版计划 ====`);
console.log(` 来源 : ${spec.file ?? '(全量,现场扫描 workspace)'}`);
console.log(` 版本 : ${spec.version}`);
console.log(` 子系统 : ${spec.apps.length ? spec.apps.join(', ') : '(无)'}`);
console.log(` 主壳(host) : ${spec.host ? `是(${shellName})` : '否'}`);
if (spec.note) console.log(` 备注 : ${spec.note}`);
if (remoteManifest)
console.log(` 线上清单 : ${remoteManifest}(增量合并 + 已发布判定以线上为准)`);
console.log('');
}
if (dryRun) {
console.log(`[${TAG}] --dry-run:以下动作不会执行。`);
console.log(` 0. 重建产物目录 ${path.relative(ROOT, outRoot)}/(只装本次要覆盖的文件)`);
let step = 1;
for (const [i, app] of spec.apps.entries()) {
const cmd = [
'node scripts/release/release.mjs',
`--app ${app}`,
`--version ${spec.version}`,
publicBase ? `--public-base ${publicBase}` : '',
out ? `--out ${out}` : '',
stateDir ? `--state ${stateDir}` : '',
force ? '--force' : '',
skipBuild ? '--skip-build' : '',
i > 0 ? '--no-clean' : '',
]
.filter(Boolean)
.join(' ');
console.log(` ${step}. ${cmd}`);
step += 1;
}
if (spec.host) {
console.log(
` ${step}. 主壳 ${shellName} 构建(SHELL_BASE=${hostBase})→ 整目录落 ${hostRel},根 index.html 只写指针`,
);
step += 1;
}
console.log(
` ${step}. 一次性上传({dir}=${outRoot} 覆盖部署根):${uploadCmd ?? '(未配置,仅产出入参)'}`,
);
console.log('');
process.exit(0);
}
// ---- 增量发版前必须确认能拼出**完整**清单 ----
// mfe/manifest.json 是全量快照:本次没发的 app 条目全靠基线(线上清单或本机累积
// 状态)带过来。两处都没有时发出去的清单只剩本次 apps —— 线上其它子系统被整份
// 抹掉,直接白屏。这比「少发一个包」严重得多,所以宁可拦下。
assertBaseline({
tag: TAG,
apps: spec.apps,
allApps: [...workspace.pkgs.values()].filter((p) => p.isMicroApp).map((p) => p.microAppName),
remoteManifest,
stateDir: path.resolve(ROOT, stateDir ?? process.env.MFE_STATE_DIR ?? '.release-state'),
});
// ---- 逐个发版子系统 ----
// 产物目录由**第一个**子应用负责清空(release.mjs 在构建与资源校验都过了才清),
// 后续一律 --no-clean 共用同一份产物树 —— 否则后一个会把前一个的产物删掉。
for (const [i, app] of spec.apps.entries()) {
info(`发版子系统 ${app}(${spec.version})...`);
const cmd = ['node', 'scripts/release/release.mjs', '--app', app, '--version', spec.appVersions?.[app] ?? spec.version];
// 整批要发的应用一并保护:后续子进程重新合并线上清单时,不得把前面已发的条目
// 按线上旧值覆盖回去(否则最终清单里前面的发布凭空消失,版本目录白传)。
if (spec.apps.length) cmd.push('--keep-local', spec.apps.join(','));
if (publicBase) cmd.push('--public-base', publicBase);
if (out) cmd.push('--out', out);
if (stateDir) cmd.push('--state', stateDir);
if (force) cmd.push('--force');
if (skipBuild) cmd.push('--skip-build');
if (remoteManifest) cmd.push('--remote-manifest', remoteManifest);
if (i > 0) cmd.push('--no-clean');
cmd.push('--quiet'); // 子进程的三段 banner 是纯噪音,总览由本层打印
const res = spawnSync(cmd[0], cmd.slice(1), { cwd: ROOT, stdio: 'inherit' });
if (res.status !== 0) die(`子系统 ${app} 发版失败(exit ${res.status}),已中止,未执行上传。`);
}
// 只发主壳时没有子应用负责清空,这里补一次(产物根只装主壳产物)。
if (spec.apps.length === 0) {
fs.rmSync(outRoot, { recursive: true, force: true });
fs.mkdirSync(outRoot, { recursive: true });
info(`产物目录已重建:${path.relative(ROOT, outRoot)}/`);
}
// ---- 主壳(host)→ /mfe/host/<version>/,站点根只放一个指针 index.html ----
// 实现抽在 host-deploy.mjs:release:affected 走同一条链路,避免两处行为分叉。
if (spec.host) {
deployHost({
root: ROOT,
outRoot,
version: hostVersion,
shellName,
workspace: workspace.pkgs,
skipBuild,
pnpmBin,
isWin,
info,
die,
});
}
// host 版本写回状态,作为 versionDiff 的「线上 host 版本」真源(远程清单不存 host,故用本地 state)
if (spec.host && !dryRun) {
const stFile = path.join(
path.resolve(ROOT, stateDir ?? process.env.MFE_STATE_DIR ?? '.release-state'),
'manifest.json',
);
let st = {};
try {
st = JSON.parse(fs.readFileSync(stFile, 'utf8'));
} catch {
/* 无则新建 */
}
st.host = { version: hostVersion, url: `/${hostRel}` };
if (!st.subapps) st.subapps = {};
fs.mkdirSync(path.dirname(stFile), { recursive: true });
fs.writeFileSync(stFile, `${JSON.stringify(st, null, 2)}\n`, 'utf8');
}
// 主壳未列入清单 → 产物根不会有它的文件(目录已重建),无需额外清理
// ---- 构建指纹:产物离开构建机后,这是唯一的溯源凭据 ----
const manifestFile = path.join(outRoot, 'mfe', 'manifest.json');
// 把 host 版本写进「要 rsync 上线的那份清单」。远程清单原先只有 subapps,
// versionDiff 读不到主壳线上版本 → 每次都判定主壳要重建;本机 .release-state 是
// gitignored 缓存、ops 干净检出时拿不到,所以真源必须是随部署上线的这份清单。
if (!dryRun) {
try {
const stFile = path.join(
path.resolve(ROOT, stateDir ?? process.env.MFE_STATE_DIR ?? '.release-state'),
'manifest.json',
);
let st = {};
try {
st = JSON.parse(fs.readFileSync(stFile, 'utf8'));
} catch {
/* 无 state:首次全量时由下面补最小字段 */
}
let m = {};
try {
m = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
} catch {
/* 只发主壳时 release.mjs 没跑,产物里还没有清单,这里补一份全量快照 */
}
if (!m.subapps || typeof m.subapps !== 'object') m.subapps = st.subapps ?? {};
if (st.host?.version) m.host = st.host;
if (!m.version) m.version = spec.version;
if (!m.updatedAt) m.updatedAt = new Date().toISOString();
fs.mkdirSync(path.dirname(manifestFile), { recursive: true });
fs.writeFileSync(manifestFile, `${JSON.stringify(m, null, 2)}\n`, 'utf8');
} catch (e) {
info(`⚠ 无法把 host 版本写进产物清单:${e.message}(下次发版可能重建主壳)`);
}
}
const buildInfo = writeBuildInfo({
root: ROOT,
outRoot,
releaseVersion: spec.version,
apps: spec.apps,
hostRel: spec.host ? hostRelOf(hostVersion) : null,
manifestVersion: manifestVersionOf(manifestFile),
source: TAG,
});
info(
`构建指纹:${path.relative(ROOT, path.join(outRoot, 'BUILD_INFO.json'))}` +
(buildInfo.git
? `(${buildInfo.git.shortSha}${buildInfo.git.dirty ? '+dirty' : ''} @ ${buildInfo.git.branch})`
: '(无 git 信息)'),
);
// ---- 上传前最后一道校验:产物清单必须真的包含本次所有发布 ----
// mfe/manifest.json 是「整份覆盖」上线。任意一个条目被线上旧值回滚、或干脆缺失,
// 结果都是「版本目录传上去了,清单却没指向它」/「其它子系统白屏」。宁可拦下不传。
if (!dryRun) {
let snapshot = null;
try {
snapshot = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
} catch {
/* 下面统一报错 */
}
if (!snapshot || !snapshot.subapps) {
die(`产物里没有可用的 ${path.relative(ROOT, manifestFile)},已中止上传(清单整份覆盖上线,不能没有)。`);
}
const rolledBack = spec.apps.filter(
(a) => snapshot.subapps[a]?.version !== (spec.appVersions?.[a] ?? spec.version),
);
if (rolledBack.length) {
die(
`产物清单未正确包含本次发布:${rolledBack.join(', ')}(清单里仍是 ${rolledBack
.map((a) => `${a}=${snapshot.subapps[a]?.version ?? '(缺)'}`)
.join(', ')})。\n` +
' 已中止:这份清单上传后线上会退回旧版本。请检查 --remote-manifest 是否指向正确的环境清单。',
);
}
const missing = [...workspace.pkgs.values()]
.filter((p) => p.isMicroApp)
.map((p) => p.microAppName)
.filter((n) => !snapshot.subapps[n]?.url);
if (missing.length) {
die(
`产物清单缺少子系统条目:${missing.join(', ')} —— 整份覆盖上线会让它们白屏。\n` +
' 请确认该环境已全量部署过,且 /mfe/manifest.json 可访问(作为合并基线)。',
);
}
}
// ---- 一次性上传:产物是一棵镜像部署根的树,{dir} 一个变量覆盖过去 ----
if (uploadCmd) {
const template = String(uploadCmd);
if (!/\{dir\}/.test(template)) {
info('⚠ 上传钩子未包含 {dir}:产物是镜像部署根的一棵树,一个 {dir} 覆盖过去即可。');
}
const cmd = template
.replaceAll('{dir}', outRoot)
.replaceAll('{target}', outRoot)
.replaceAll('{remote}', '')
.replaceAll('{host}', outRoot) // 兼容旧钩子:主壳已落在产物根
.replaceAll('{file}', manifestFile);
info(`执行一次性上传钩子:${cmd}`);
const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true });
if (res.status !== 0)
die(
`上传失败(exit ${res.status})。各子系统与 host 已落盘到 ${outRoot},远端尚未生效。\n` +
' 线上 mfe/manifest.json 未被本次发布覆盖 → 基线仍是失败前的版本,直接重跑本命令即可自动重发;\n' +
' 不需要改 package.json 版本号。用两阶段上传钩子时,清单本就是最后一步、不会抢跑。',
);
}
console.log(`\n[${TAG}] ==== 完成 ====`);
console.log(
` 已发版子系统: ${spec.apps.length ? spec.apps.join(', ') : '(无)'} @ ${spec.version}`,
);
if (spec.host)
console.log(` 主壳(host) : ${shellName} → ${hostRel}(站点根 index.html 是指针)`);
console.log(
` 产物 : ${path.relative(ROOT, outRoot)}/ 只含本次内容,覆盖进部署根即生效;未出现的模块保持线上老版本。`,
);
console.log(
' 发布生效:浏览器必须【整页刷新】;manifest.json 与 host index.html 建议 no-cache。',
);
console.log('');
}
// 直接运行时执行 main;被 import 时只导出纯函数(便于复用 / 测试)
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main();
}
export { loadSpec, verifySpec, cmpVersion, listSpecFiles, runRelease };