Commit 79844005 by liimin

feat: 发布链路改造 —— 主壳版本化、一条命令、线上清单为真源

产物结构:
- 主壳进 /mfe/host/<ver>/ 版本目录(createShellConfig 新增 SHELL_BASE base,turbo globalEnv 同步),
  站点根只覆盖一个指针 index.html,消掉覆盖式部署的白屏窗口
- 产物目录 .release → dist(镜像部署根、每次重建);.release-state 降级为本机缓存
- 产物根新增 BUILD_INFO.json 构建指纹(sha/分支/时间/node,dirty 标记)

ops 一条命令(release:ops,零参数、永不卡住):
- 三层兜底:有清单走清单模式 / 无清单有 tag 走 git 分析 / 都没有走全量
- 清单模式 --latest 默认允许就地重打(幂等),显式 --spec 保留不可变保护
- 预览类参数跨模式自动剥离,不再因 --no-serve 之类报错

线上清单为真源:
- 「已发布」判定优先查线上 manifest,本机 published 仅兜底并明示跨机器局限
- 增量发版无基线时拦截(assertBaseline),防止把线上其它子系统条目整份抹掉
- 清单支持 remoteManifest 字段(CLI > 清单 > env 三级),多机协作共用判定与基线
- mergeRemoteManifest 兼容全新机器:状态文件不存在不再崩

周边:
- release:all 一条命令全量打包 + 自检 + 预览;release:preview 独立起预览(站点根=产物目录)
- release-verify 新增主壳入口 chunk 探测,按需加载的 404 chunk 不再漏检
- release:prune 旧版本清理,默认只报告,--apply --yes 双开关
- host 部署实现收敛到 host-deploy.mjs,spec/affected 共用(含 base 前缀校验)
- shell 生产环境变量 .env.production 入库;.vscode 预览根指向 dist
- DEPLOY.md 全面更新:nginx 配置、主壳版本化、预览站点根、状态模型、三层兜底
1 parent c37bb880
...@@ -3,8 +3,8 @@ dist/ ...@@ -3,8 +3,8 @@ dist/
.turbo/ .turbo/
.tmp/ .tmp/
coverage/ coverage/
# 发版脚本产出的待上传目录(版本化产物 + manifest.json) # 发版产物与 manifest 累积状态(每次发布重建,镜像部署根)
.release/ .release-state/
*.log *.log
# 环境变量(可含密钥兜底值) # 环境变量(可含密钥兜底值)
...@@ -25,3 +25,4 @@ Thumbs.db ...@@ -25,3 +25,4 @@ Thumbs.db
# WorkBuddy 内部状态(项目记忆/工具数据,非源码) # WorkBuddy 内部状态(项目记忆/工具数据,非源码)
.workbuddy/ .workbuddy/
temp/
{
"liveServer.settings.root": "/.release"
}
# ---------------------------------------------------------------------------
# 生产构建配置(这个文件入库 —— 它不是密钥,是部署契约)
#
# 为什么需要它:.env 被 .gitignore 排除,CI 上可能根本不存在。
# 生产构建(vite build,mode=production)会依次加载 .env → .env.production,
# 后者覆盖前者;而 process.env 里的同名变量优先级最高,CI 可以继续用环境变量覆盖。
#
# 只写「错了会静默坏掉、且与本机无关」的项。后端地址这类跟环境走的不要写死。
# ---------------------------------------------------------------------------
# 运行时子应用清单。主壳启动时 fetch 它,拿到每个子应用的真实版本目录。
# 不配的后果链:loadRuntimeManifest() 第一句就 return → entryOf() 回落到
# package.json 的 uj.entry(http://localhost:5174/)→ 生产环境判定为无效入口 →
# 主壳能开、菜单能点,点任何业务模块都是「未找到子应用入口」。静态站配得再对也没用。
# 该 URL 必须响应 Cache-Control: no-cache,否则浏览器缓存会把发布卡住。
VITE_MANIFEST_URL=/mfe/manifest.json
# 后端 context-path。缺省为空(请求直接打 /api/...),生产会对不上真实网关。
# 与 .env 里的开发值一致:生产访问站点根就打 /youjia/...,签名 canonical 第 2 行也用它。
# 若某环境网关前缀不同,用 CI 环境变量覆盖本行即可(process.env 优先级更高)。
VITE_API_CONTEXT_PATH=/youjia
# 签名链路。代码里默认就是 true(只有显式 'false' 才关闭),写出来是为了防止
# 某次误加 VITE_SIGN_ENABLED=false 的本地 .env 被带进生产构建。
VITE_SIGN_ENABLED=true
VITE_SIGN_DEBUG=false
...@@ -15,13 +15,117 @@ pnpm release -- --app system --version 1.2.0 ...@@ -15,13 +15,117 @@ pnpm release -- --app system --version 1.2.0
## 0. 一次性前置(每个环境只做一次) ## 0. 一次性前置(每个环境只做一次)
| 项 | 位置 | 说明 | | 项 | 位置 | 说明 |
| ----------- | --------------------------- | ----------------------------------------------------------------- | | ------------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 主壳 `.env` | `apps/web/shell/.env` | 从 `.env.example` 复制,设 `VITE_MANIFEST_URL=/mfe/manifest.json` | | 主壳 `.env` | `apps/web/shell/.env` | 本地开发配置(不入库)。生产用 `.env.production`(**已入库**),它固化 `VITE_MANIFEST_URL=/mfe/manifest.json` |
| 签名密钥 | `apps/web/shell/keys/*.pem` | 从旧仓拷贝,不入库;只有主壳需要 | | 签名密钥 | `apps/web/shell/keys/*.pem` | 从旧仓拷贝,不入库;只有主壳需要 |
| 静态站目录 | 站点根(host 在根,`/mfe/` 在子目录) | host 的 `index.html`/`assets/` 放到站点根;`.release/mfe/` 对齐到 `/mfe/`。上传见 §2.2 | | 静态站目录 | 站点根(host 在根,`/mfe/` 在子目录) | host 的 `index.html`/`assets/` 放到站点根;`dist/mfe/` 对齐到 `/mfe/`。上传见 §2.2 |
| 静态站 nginx | 站点根 | 两条**互斥**的回落规则,见 §0.1;漏配会让子应用静默白屏 |
| 清单缓存头 | `/mfe/manifest.json` | **必须 `Cache-Control: no-cache`**,否则浏览器缓存会把发布卡住 | | 清单缓存头 | `/mfe/manifest.json` | **必须 `Cache-Control: no-cache`**,否则浏览器缓存会把发布卡住 |
> `VITE_MANIFEST_URL` 是构建期注入主壳的。主壳只在**首次部署**时构建一次;之后发子应用不再碰它。 > `VITE_MANIFEST_URL` 是构建期注入主壳的。主壳只在**首次部署**时构建一次;之后发子应用不再碰它。
> 它必须进 `apps/web/shell/.env.production`(而不是只写在本地 `.env`):`.env` 被 `.gitignore` 排除,CI 上根本不存在,
> 不配的后果是主壳产物里搜不到清单地址 → 启动时不拉清单 → 每个业务模块都显示「未找到子应用入口」。
### 0.1 静态站配置(nginx)
产物是纯静态文件,但要正确跑起来需要两条**互斥**的回落规则。**最容易漏的是第二条**:
```nginx
server {
listen 443 ssl;
server_name console.example.com;
root /var/www/console; # dist/ 的覆盖目标
# 入口类必须 no-cache,否则发布被浏览器缓存在旧版本
location = /mfe/manifest.json { add_header Cache-Control "no-cache"; try_files $uri =404; }
location = /index.html { add_header Cache-Control "no-cache"; }
# 主壳与子应用的版本目录:只按真实文件返回,缺文件就是 404,绝不回落到主壳。
# 少了这一条,缺失的 js 会返回主壳 index.html(200 + text/html),
# 浏览器报 Unexpected token '<',而 nginx 日志里没有任何错误记录。
# 目录名带版本号、文件名带 hash,内容永不变化,可以放心长缓存。
location ^~ /mfe/ {
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri $uri/ =404;
}
# 主壳 SPA:刷新 /system/role 时磁盘上没有这个文件,必须回落到 index.html
location / { try_files $uri $uri/ /index.html; }
}
```
`^~` 是关键:它让 `/mfe/` 前缀不再落到下面那条 SPA 回落里。上面那条 `location = /mfe/manifest.json` 是精确匹配、优先级高于 `^~`,所以清单仍然是 no-cache(**这条别删**,否则清单被长缓存,发布等于没发)。
对象存储 / CDN 的等价配置:索引文档设为 `index.html`,并**关闭**站点级「404 重写为 index.html」;
若业务上必须开,把 `/mfe/*` 显式排除。
---
## 0.2 首次部署 / 本地看完整效果:一条命令
```bash
pnpm release:all
```
范围**不用写清单**——现场扫 `apps/web/subapps/*` 得到全部子系统,加上主壳,一次打完:
```
dist/
├── index.html 指针文件:只指向 mfe/host/<ver>/(站点根唯一被覆盖的文件)
├── BUILD_INFO.json 构建指纹:commit sha / 分支 / 时间 / node 版本
└── mfe/
├── manifest.json 全量清单
├── host/1.0.0/ 主壳(版本化,与子应用同构)
├── store/1.0.0/
└── system/1.0.0/
```
主壳也进了版本目录,站点根只留一个 449 字节的 `index.html` 指过去。这是为了消掉覆盖式部署的**白屏窗口**:以前根目录要逐个覆盖 `index.html` 和一批 `assets/`,在「HTML 已落地、JS 还没到」的几百毫秒里,线上是新页面配旧资产,404 且不可观测。现在资产整目录新增(原子),根目录只覆盖一个文件(`rsync` 也是写临时文件再 rename),没有混合态。
打完会自动做两件事:**自检**(清单可达、每个模块的 `index.html` 与资源真的 200)和**起本地预览**(默认 `http://127.0.0.1:4180/`,自动开浏览器)。预览用的是内置静态服务,行为对齐上面那段 nginx(`/mfe/` 缺文件就是 404,主壳走 SPA 回落)——所以本地点得开,上线也点得开。
| 想要 | 命令 |
| ---------------------------------- | ---------------------------------- |
| 全量打包 + 预览 | `pnpm release:all` |
| 只打包,不上预览(CI / 交给运维) | `pnpm release:all --no-serve` |
| 产物已在,只起预览 | `pnpm release:preview` |
| 换版本号 | `pnpm release:all --version 1.1.0` |
| 跳过构建,只重打包(复现布局问题) | `pnpm release:all --skip-build` |
| 换预览端口 | `pnpm release:all --port 5180` |
三个入口的分工,别混:
| 命令 | 「发哪几个」从哪来 | 典型场景 |
| ----------------------- | ------------------------------- | ---------------------------- |
| `pnpm release:all` | 现场扫描 workspace(全量) | 首次部署、本地看完整效果 |
| `pnpm release:spec` | `releases/<v>.json`(显式声明) | 增量发版,线上保留老版本目录 |
| `pnpm release:affected` | git 反查(只发改过的) | CI 自动发版 |
> `release:all` 默认允许同版本就地重建(全量包的语义就是「把这个版本整套重打一遍」)。要恢复不可变保护加 `--no-force`。
> 预览能不能登录,取决于后端是否放行 `http://127.0.0.1:4180` 的 CORS:主壳产物里内嵌了构建机 `.env` 的 `VITE_API_TARGET`(本机是 `http://192.168.3.197:8788`),浏览器会直连它。被 CORS 挡住时用 `--port 5173` 对齐 dev 的 origin,或让后端临时放行。
### 0.2.1 预览打不开?先看站点根对不对
典型报错长这样:
```
Refused to apply style from '.../mfe/host/1.0.0/assets/index-xxx.css' because
its MIME type ('text/html') is not a supported stylesheet MIME type
GET .../mfe/host/1.0.0/assets/index-xxx.js net::ERR_ABORTED 404
```
**这不是产物坏了,是服务器站点根设错。** 产物里所有资源都是**绝对路径**(`/mfe/host/<ver>/assets/...`),只有「站点根 = 产物目录」时才解析得对。VS Code Live Server 默认以工作区根为站点根,于是 `/mfe/...` 被找成 `<仓库>/mfe/...` —— 不存在 → 404,而它把 404 渲染成 HTML 返回,浏览器就报 MIME 不匹配。
| 姿势 | 结果 |
| ------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `pnpm release:all` | ✅ 打包完自动起预览,行为对齐 nginx(推荐) |
| `pnpm release:preview` | ✅ 产物已在,只起服务;`-- --port 5180` 换端口 |
| Live Server 从 `dist/` 启动 | ⚠️ 能用:仓库已带 `.vscode/settings.json` 把根设为 `/dist`。但没有 SPA 回落,刷新 `/system/role` 会 404 |
| Live Server 从仓库根启动 | ❌ 就是上面那个报错 |
| 双击 `index.html`(`file://`) | ❌ ES module 跨 origin 被拦,且绝对路径解析到磁盘根 |
> 上线同理:nginx 的 `root` 必须指向产物树**本身**(里面有 `index.html` 和 `mfe/`),不能指向它的父目录。
--- ---
...@@ -30,10 +134,10 @@ pnpm release -- --app system --version 1.2.0 ...@@ -30,10 +134,10 @@ pnpm release -- --app system --version 1.2.0
### 步骤 1 · 判断改动范围 ### 步骤 1 · 判断改动范围
| 你改了什么 | 要发什么 | | 你改了什么 | 要发什么 |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| 只有 `apps/web/subapps/system/**` | **只发 system**,host 与 store 都不动 | | 只有 `apps/web/subapps/system/**` | **只发 system**,host 与 store 都不动 |
| `packages/ui` / `platform-sdk` / `biz` / `design-tokens` / `contracts` | **system 和 store 都要重建重发**(每个子应用各自打一份这些源码);这些也是主壳的依赖,**主壳会被 `release:affected` 一并重建部署**,见 §2.2 | | `packages/ui` / `platform-sdk` / `biz` / `design-tokens` / `contracts` | **system 和 store 都要重建重发**(每个子应用各自打一份这些源码);这些也是主壳的依赖,**主壳会被 `release:affected` 一并重建部署**,见 §2.2 |
| `packages/platform-core` / `apps/web/shell/**` | 主壳(host) 变了 → `release:affected` 自动构建主壳并部署到站点根,**不再需要手动 `deploy:shell`** | | `packages/platform-core` / `apps/web/shell/**` | 主壳(host) 变了 → `release:affected` 自动构建主壳、落到 `mfe/host/<ver>/` 并更新站点根指针,**不再需要手动 `deploy:shell`** |
| `packages/vite-config` / `turbo.json` / `pnpm-workspace.yaml` | 所有 app 重建(含主壳) | | `packages/vite-config` / `turbo.json` / `pnpm-workspace.yaml` | 所有 app 重建(含主壳) |
### 步骤 2 · 本地校验 ### 步骤 2 · 本地校验
...@@ -54,23 +158,24 @@ pnpm release -- --app system --version 1.2.0 ...@@ -54,23 +158,24 @@ pnpm release -- --app system --version 1.2.0
| # | 动作 | 为什么 | | # | 动作 | 为什么 |
| --- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | --- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | `SUBAPP_BASE=/mfe/system/1.2.0/ pnpm --filter @uj/web-system build` | **Vite 的 `base` 是构建期固定的**。不注入的话产物里是 `/assets/xxx.js`,放进版本目录后 404,症状是「清单生效了、子应用白屏且零报错」 | | 1 | `SUBAPP_BASE=/mfe/system/1.2.0/ pnpm --filter @uj/web-system build` | **Vite 的 `base` 是构建期固定的**。不注入的话产物里是 `/assets/xxx.js`,放进版本目录后 404,症状是「清单生效了、子应用白屏且零报错」 |
| 2 | 产物复制到 `.release/mfe/system/1.2.0/` | 版本目录**不可变**,已存在则拒绝覆盖(回滚依赖旧目录还在) | | 2 | 产物复制到 `dist/mfe/system/1.2.0/` | 版本目录在**线上**不可变(回滚依赖旧目录还在);本地产物目录每次重建,不积累历史 |
| 3 | 校验 `index.html` 里所有资源引用都带 `/mfe/system/1.2.0/` 前缀 | 自动拦住上一条的漏配,不用等线上发现 | | 3 | 校验 `index.html` 里所有资源引用都带 `/mfe/system/1.2.0/` 前缀 | 自动拦住上一条的漏配,不用等线上发现 |
| 4 | 增量更新 `.release/mfe/manifest.json`,只改 `subapps.system` | `store` 条目原样保留 | | 4 | 更新 manifest 累积状态(`.release-state/manifest.json`) | 只改 `subapps.system`,`store` 条目原样保留;产物里那份是本次快照 |
产物形态: 产物形态 —— **镜像部署根,只装本次要覆盖的文件**:
``` ```
.release/ dist/ ← 每次发布重建,运维整棵树覆盖进部署目录即可
├── index.html ← 主壳:仅在本次改到 host 时出现(部署到站点根)
├── assets/ ← 主壳资源
└── mfe/ └── mfe/
├── manifest.json ← 每次发布覆盖,no-cache ├── manifest.json ← 本次快照,覆盖后必须 no-cache
├── system/ └── system/
│ ├── 1.2.0/ ← 本次新增 └── 1.2.0/ ← 本次发的子系统
│ └── 1.1.9/ ← 旧版本保留,回滚用
└── store/
└── 2.0.0/
``` ```
线下的历史版本(`/mfe/system/1.1.9/`)**不在本地产物里**,它在服务器上原地留着,回滚就是改清单指回去。所以「覆盖」对两类东西语义不同:主壳原地替换,子应用是新增版本目录 + 清单改指向。
演练(不构建、不落盘): 演练(不构建、不落盘):
```bash ```bash
...@@ -85,13 +190,23 @@ pnpm release -- --app system --version 1.2.0 --public-base https://cdn.example.c ...@@ -85,13 +190,23 @@ pnpm release -- --app system --version 1.2.0 --public-base https://cdn.example.c
### 步骤 4 · 上传 ### 步骤 4 · 上传
把 `.release/` 的内容同步到站点根(得到 `/mfe/manifest.json` 与 `/mfe/system/1.2.0/`): 把 `dist/` 整棵树覆盖进部署根 —— 它已经是部署根的剪影,不需要挑目录:
```bash ```bash
# 示例:同源静态目录 # 示例:同源静态目录(产物根 = 站点根,mfe/ 与 index.html 一起覆盖)
rsync -a .release/mfe/ /var/www/console/mfe/ rsync -a dist/ /var/www/console/
``` ```
未出现在本次产物里的模块(比如这次只发 system 时的 `mfe/store/`)**不会被动到**,线上保持老版本。
> ⚠️ **绝对不要加 `--delete`,也不要用「先清空部署目录再拷」的方式。**
>
> 本次产物只装本次内容 —— `mfe/store/1.0.0/`、`mfe/system/1.0.0/` 这些**旧版本目录必须原样留在线上**。
> 因为随产物一起传上去的 `manifest.json` 是**全量快照**:它会同时写着本次发的那条和其它应用的现有版本。
> 一旦旧目录被删,清单就指向不存在的目录 —— 所有业务模块直接 404,而且回滚也没得回(旧目录已经没了)。
>
> 这条是「增量产物」这套设计唯一的致命操作。合并语义用 `rsync -a`(默认)或 `aws s3 sync`(默认不删)。
或让脚本代跑(`MFE_UPLOAD_CMD` 环境变量等价): 或让脚本代跑(`MFE_UPLOAD_CMD` 环境变量等价):
```bash ```bash
...@@ -99,14 +214,31 @@ pnpm release -- --app system --version 1.2.0 \ ...@@ -99,14 +214,31 @@ pnpm release -- --app system --version 1.2.0 \
--upload-cmd "aws s3 sync {dir} s3://my-bucket/ --cache-control 'max-age=31536000' " --upload-cmd "aws s3 sync {dir} s3://my-bucket/ --cache-control 'max-age=31536000' "
``` ```
模板变量:`{dir}`=待上传根 `.release/`(**含 manifest**)、`{target}`=单个版本目录、`{remote}`=`mfe/system/1.2.0/`、`{file}`=`manifest.json` 路径。 模板变量:`{dir}`=待上传根 `dist/`(**含 manifest**)、`{target}`=单个版本目录、`{remote}`=`mfe/system/1.2.0/`、`{file}`=`manifest.json` 路径。
> ⚠️ **上传钩子必须覆盖 `manifest.json`**。只传版本目录的话,旧清单仍指向旧版本,发布等于没发。脚本发现钩子既不含 `{dir}` 也不含 `{file}` 时会告警。 > ⚠️ **上传钩子必须覆盖 `manifest.json`**。只传版本目录的话,旧清单仍指向旧版本,发布等于没发。脚本发现钩子既不含 `{dir}` 也不含 `{file}` 时会告警。
> 清单文件单独设 `no-cache`;版本目录里的带 hash 资源可以长缓存。 > 清单文件单独设 `no-cache`;版本目录里的带 hash 资源可以长缓存。
### 步骤 5 · 冒烟(不能省) ### 步骤 5 · 冒烟(不能省)
用**构建产物**起静态服务(不要用 Vite dev server)逐路由验: 先跑机器自检,跑不过就不用人工看了:
```bash
# 传完之后验线上
pnpm release:verify -- --base https://console.example.com
# 或者传之前先验本地产物(内置静态服务,不需要先上传)
pnpm release:verify -- --serve dist
```
它按清单逐个验:版本目录能否取到 `index.html`、`index.html` 里的资源前缀是否与清单 url 一致
(不一致 = 白屏且零报错)、每个资源真的可访问、主壳产物里有没有清单地址。
**拿到 HTML 却当资源**(nginx 漏配 `^~ /mfe/` 的典型症状)也会被单独报出来。任一失败退出码非 0,可直接接进 CI。
本地模式下「清单里有、产物里没有」只算警告 —— 那是正常的:本次没发那个应用,线上旧目录保留着。
另外 `--app store` 可以只验单个模块。
然后再用构建产物起的站(不要用 Vite dev server)人工过这几条:
- `/system/role`、`/system/user` 首屏正常; - `/system/role`、`/system/user` 首屏正常;
- 子应用调 `props.request` 不报 10011(签名链路仍在主壳); - 子应用调 `props.request` 不报 10011(签名链路仍在主壳);
...@@ -148,7 +280,7 @@ createRouter() → collectRouteDefs() → 构建期 SUBAPPS ∪ 运行时 manife ...@@ -148,7 +280,7 @@ createRouter() → collectRouteDefs() → 构建期 SUBAPPS ∪ 运行时 manife
1. 在 `apps/web/subapps/<name>/` 建子应用,`package.json` 的 `name` 必须是 `@uj/web-<name>`(可选 `uj.route` 覆写路由首段、开发期 `uj.entry`)。 1. 在 `apps/web/subapps/<name>/` 建子应用,`package.json` 的 `name` 必须是 `@uj/web-<name>`(可选 `uj.route` 覆写路由首段、开发期 `uj.entry`)。
2. `pnpm gen:tsconfig` 重新生成 tsconfig(已改为动态扫描目录,无需手改脚本)。 2. `pnpm gen:tsconfig` 重新生成 tsconfig(已改为动态扫描目录,无需手改脚本)。
3. `pnpm release -- --app <name> --version 1.0.0` 产出版本目录并把条目写进 `manifest.json`,上传 `.release/`。 3. `pnpm release -- --app <name> --version 1.0.0` 产出版本目录并把条目写进 `manifest.json`,上传 `dist/`。
4. **后端菜单树**(`/system/menu/tree/current`)给该子系统配菜单节点与权限 `resource`;接口未就绪时补 `packages/biz/src/config/menu.json` 兜底。新图标名在 `BasicLayout.tsx` 的 `iconMap` 登记(不登记只回落默认图标并 DEV 告警)。 4. **后端菜单树**(`/system/menu/tree/current`)给该子系统配菜单节点与权限 `resource`;接口未就绪时补 `packages/biz/src/config/menu.json` 兜底。新图标名在 `BasicLayout.tsx` 的 `iconMap` 登记(不登记只回落默认图标并 DEV 告警)。
然后用户**整页刷新**即可访问 `/<name>/...`,host 全程不用重建。 然后用户**整页刷新**即可访问 `/<name>/...`,host 全程不用重建。
...@@ -163,21 +295,50 @@ createRouter() → collectRouteDefs() → 构建期 SUBAPPS ∪ 运行时 manife ...@@ -163,21 +295,50 @@ createRouter() → collectRouteDefs() → 构建期 SUBAPPS ∪ 运行时 manife
### 2.2 主壳(host) 自动发版(一句话版) ### 2.2 主壳(host) 自动发版(一句话版)
主壳和子应用的部署形态不同:子应用走 `/mfe/<app>/<version>/` **不可变版本目录**,主壳是入口应用、走**站点根**、整包替换。**改了主壳(或它的真实依赖)时,不必再手动跑 `deploy:shell`**——`release:affected` 会一并处理: 主壳和子应用现在是**同构**的:都走 `/mfe/<name>/<version>/` 不可变版本目录,区别只在站点根多了一个指向主壳的 `index.html` 指针。**改了主壳(或它的真实依赖)时,不必再手动跑 `deploy:shell`**——`release:affected` 会一并处理:
- 触发条件(按真实依赖图,与子应用同一套判定):`apps/web/shell/**` 自身改动、`packages/platform-core` / `contracts` / `ui` / `biz` / `design-tokens`(主壳依赖的共享包)、或根构建配置任一变动 → 主壳重建。只改某个子应用(如只改 `system`)→ 主壳**不**重建。 - 触发条件(按真实依赖图,与子应用同一套判定):`apps/web/shell/**` 自身改动、`packages/platform-core` / `contracts` / `ui` / `biz` / `design-tokens`(主壳依赖的共享包)、或根构建配置任一变动 → 主壳重建。只改某个子应用(如只改 `system`)→ 主壳**不**重建。
- 主壳构建产物暂存到 `<out>/_host/`,与子应用的 `<out>/mfe/` 分开,避免互相污染。 - 产物落两处:实体进 `<out>/mfe/host/<version>/`,站点根写一个指向它的 `index.html`。上传仍然只有一段:
- 上传时需**两段同步**(主壳在根、子应用在 `/mfe/`):
```bash ```bash
# MFE_UPLOAD_CMD 写成两段(一次性,配置一次即可) # 一次性配置,之后每次发布都用同一条
pnpm release:affected --version 1.3.0 \ pnpm release:affected --version 1.3.0 \
--upload-cmd "aws s3 sync {dir}/mfe s3://bucket/mfe/ && aws s3 sync {host} s3://bucket/ --cache-control 'no-cache'" --upload-cmd "rsync -a {dir}/ /var/www/console/"
```
`{dir}` = `<out>`,即站点根镜像。本次没改主壳时产物根不会有 `index.html`,覆盖过去不会动线上旧主壳;`{host}` 仍可用但已等于 `{dir}`,仅为兼容旧钩子保留。
为什么值得多一层目录:
| 摊在站点根(旧) | 进版本目录(现在) |
| ------------------------------------------------------------------------- | --------------------------------------------------------------- |
| 覆盖 `index.html` + 一批 `assets/`,中间存在「新 HTML 配旧 JS」的白屏窗口 | 资产整目录新增,根目录只覆盖一个文件 |
| 旧 assets 散在根上,hash 文件名让人不敢删,只能越堆越多 | 回收单位是「一个版本目录」,`pnpm release:prune` 可枚举、可预演 |
| 想对比线上跑的是哪版主壳,只能看 hash 猜 | 直接看 `/mfe/host/<ver>/`,还有 `BUILD_INFO.json` 记着 commit |
> 代价:主壳构建也要带 `SHELL_BASE=/mfe/host/<version>/`(发布脚本自动注入,`turbo.json` 的 `globalEnv` 已声明,否则换版本号会命中旧缓存)。`--skip-build` 复用旧 dist 时会被 base 校验拦住,这是有意的。
主壳回滚 = 把站点根 `index.html` 换回指向旧版本目录(旧目录还在就只是一次文件覆盖,不用重新构建):
```bash
cp /var/www/console/mfe/host/1.2.0/index.html /var/www/console/index.html
``` ```
`{dir}`=`<out>`(含 `mfe/`),`{host}`=`<out>/_host`(主壳)。`release:affected` 在 host 未受影响时会清掉 `_host`,所以第二段同步是空操作、不会把旧主壳误传到线上。 ### 2.3 并发发版:清单是全局单点
`mfe/manifest.json` 是一份**全量**清单,同时管着所有子系统。两个 CI job 并发跑(A 发 store、B 发 system),后上传的那份会整份覆盖前一份,先发的条目凭空消失——线上退回旧 URL,而且没有任何报错。
配一个线上清单地址就能把窗口收到最小:
```bash
pnpm release -- --app system --version 1.2.0 \
--remote-manifest https://console.example.com/mfe/manifest.json
# 或一次性设环境变量 MFE_REMOTE_MANIFEST
```
> 主壳**不做版本化**(它是入口,URL 固定)。回滚主壳 = 切回旧 commit 重新构建主壳再部署;子应用回滚仍只改 `manifest.json`(§3)。主壳 `index.html` 同样建议 `no-cache`,否则浏览器缓存会把主壳发布卡住。 发布前先 GET 一次线上真实清单做合并基线:本次要发的 app 用本地条目,**其它 app 以线上为准**(本地那份可能是几小时前的,用它覆盖回去等于静默回滚别人的发布)。拉取失败只告警不阻断——首次部署线上还没有清单,不该被卡住。
这不能彻底消除竞态(真正的原子性需要服务端 CAS),但把冲突窗口从「整个构建过程」压缩到「上传的那几秒」,且后发的一定包含先发的。要完全避免就在 CI 层串行(GitLab 的 `resource_group` / GitHub Actions 的 `concurrency`),这是成本最低的正确解。
--- ---
...@@ -189,7 +350,11 @@ pnpm release:affected --version 1.3.0 \ ...@@ -189,7 +350,11 @@ pnpm release:affected --version 1.3.0 \
pnpm release -- --app system --version 1.1.9 --switch-only pnpm release -- --app system --version 1.1.9 --switch-only
``` ```
然后照常上传 `.release/mfe/manifest.json`(`--switch-only` 也会执行上传钩子),用户整页刷新即回到旧版本。前提是**旧版本目录没被删**——所以版本目录必须不可变、发布脚本默认拒绝覆盖。 然后照常上传 `dist/mfe/manifest.json`(`--switch-only` 也会执行上传钩子),用户整页刷新即回到旧版本。前提是**旧版本目录没被删**——所以版本目录必须不可变、发布脚本默认拒绝重复发布同名版本。
「已发布过哪些版本」的判定,**真源是线上清单**(配置了 `MFE_REMOTE_MANIFEST` / 清单字段 `remoteManifest` 且拉取成功时,直接查线上 `subapps.<app>`);本地 `.release-state/manifest.json` 的 `published` 只是拉不到线上时的兜底 —— 它是**本机记录**,同事的机器上没有,所以跨机器协作**必须**配置线上清单地址(多机共用同一判定 + 增量合并基线)。全量打包入口(`release:all`、清单模式 `--latest`)默认允许就地重建,不会因此被拦。
`.release-state` 同时充当增量发版的清单基线缓存:发增量时若既没有线上清单、本机也没有累积状态,脚本会**直接拦截**(此时拼不出完整 manifest,发出去会把线上其它子系统的条目整份抹掉)。这个目录丢了不会丢数据(重新跑一次全量即可重建),但别当临时文件随手清;CI 里建议用固定缓存目录(`MFE_STATE_DIR`)。
灰度同理:部署系统按租户/账号返回不同内容的 `manifest.json`,同一套产物可以只放给部分用户。 灰度同理:部署系统按租户/账号返回不同内容的 `manifest.json`,同一套产物可以只放给部分用户。
...@@ -208,15 +373,15 @@ pnpm release -- --app system --version 1.1.9 --switch-only ...@@ -208,15 +373,15 @@ pnpm release -- --app system --version 1.1.9 --switch-only
| 变量 | 用途 | | 变量 | 用途 |
| ----------------- | ------------------------------------------------------------------------ | | ----------------- | ------------------------------------------------------------------------ |
| `MFE_PUBLIC_BASE` | 产物对外根地址;留空 = 同源 `/mfe/...`,跨域填 `https://cdn.example.com` | | `MFE_PUBLIC_BASE` | 产物对外根地址;留空 = 同源 `/mfe/...`,跨域填 `https://cdn.example.com` |
| `MFE_UPLOAD_CMD` | 上传钩子,留空则只产出 `.release/` 作为 artifacts,由下游流水线上传 | | `MFE_UPLOAD_CMD` | 上传钩子,留空则只产出 `dist/` 作为 artifacts,由下游流水线上传 |
`deploy:shell` 已由 `release:affected` 自动覆盖:主壳受影响时它会一并构建主壳并暂存到 `{host}`,与子应用一次性上传(见 §2.2)。CI 里把 `deploy:shell` 那一段删掉即可,不要再单独部署主壳。 `deploy:shell` 已由 `release:affected` 自动覆盖:主壳受影响时它会一并构建主壳、落到产物根,与子应用一次性上传(见 §2.2)。CI 里把 `deploy:shell` 那一段删掉即可,不要再单独部署主壳。
--- ---
## 5. 六个坑(都是会静默出错的那种) ## 5. 六个坑(都是会静默出错的那种)
1. **`base` 没随版本目录走** → 资源 404、白屏零报错。`SUBAPP_BASE` 已列入 `turbo.json` 的 `globalEnv`:turbo 只把声明过的 env 纳入任务 hash,漏了的话换版本号重建会命中旧缓存,产物还指上一个目录。`release.mjs` 步骤 3 会再兜一层。 1. **`base` 没随版本目录走** → 资源 404、白屏零报错。`SUBAPP_BASE`(子应用)与 `SHELL_BASE`(主壳)都已列入 `turbo.json` 的 `globalEnv`:turbo 只把声明过的 env 纳入任务 hash,漏了的话换版本号重建会命中旧缓存,产物还指上一个目录。`release.mjs` 与 `host-deploy.mjs` 会再兜一层——`--skip-build` 复用旧 dist 时直接报错,不会让你把上一版的主壳搬进新版本目录。
2. **清单被缓存** → 改了清单但用户拿到旧的。`manifest.json` 必须 `Cache-Control: no-cache`;版本目录里的 hash 资源反而应该长缓存。 2. **清单被缓存** → 改了清单但用户拿到旧的。`manifest.json` 必须 `Cache-Control: no-cache`;版本目录里的 hash 资源反而应该长缓存。
3. **只传产物没传清单** → 发布不生效。见步骤 4 的警告。 3. **只传产物没传清单** → 发布不生效。见步骤 4 的警告。
4. **改了共享包却只发 system** → store 里仍是旧版 `@uj/ui` / `platform-sdk`,两个子应用行为漂移。wujie 下依赖**不共享**,每个子应用各打一份,所以共享包变更要重建全部下游。**别手工判断范围**,用 `pnpm release:affected --base origin/master --version <ver>`:它按 git diff → 归属包 → 真实依赖闭包自动算出该发哪些,只构建这些子应用,并一次性更新清单与上传。注意级联是精确的(改只被 shell 依赖的 `platform-core` 不会动任何子应用),而根构建配置改动会保守地全量重发。同时主壳若受影响也会一并重建部署(§2.2),无需手动 `deploy:shell`。若改用 §7 的 `release:spec` 显式清单,发什么由你写、不会出现「自动全发」,但反过来要小心**漏写**——用 `--verify` 兜底。 4. **改了共享包却只发 system** → store 里仍是旧版 `@uj/ui` / `platform-sdk`,两个子应用行为漂移。wujie 下依赖**不共享**,每个子应用各打一份,所以共享包变更要重建全部下游。**别手工判断范围**,用 `pnpm release:affected --base origin/master --version <ver>`:它按 git diff → 归属包 → 真实依赖闭包自动算出该发哪些,只构建这些子应用,并一次性更新清单与上传。注意级联是精确的(改只被 shell 依赖的 `platform-core` 不会动任何子应用),而根构建配置改动会保守地全量重发。同时主壳若受影响也会一并重建部署(§2.2),无需手动 `deploy:shell`。若改用 §7 的 `release:spec` 显式清单,发什么由你写、不会出现「自动全发」,但反过来要小心**漏写**——用 `--verify` 兜底。
...@@ -228,19 +393,25 @@ pnpm release -- --app system --version 1.1.9 --switch-only ...@@ -228,19 +393,25 @@ pnpm release -- --app system --version 1.1.9 --switch-only
## 6. 命令速查 ## 6. 命令速查
| 场景 | 命令 | | 场景 | 命令 |
| --------------- | ------------------------------------------------------------------------------------ | | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **全量打包 + 本地预览(首次部署)** | `pnpm release:all`(所有子系统 + 主壳 → `dist/` → 自检 → 起 4180 预览) |
| 全量打包但不预览 | `pnpm release:all --no-serve` |
| 产物已在,只起预览(站点根 = `dist`) | `pnpm release:preview`(换端口 `-- --port 5180`,换目录 `-- --dir <dir>`) |
| 演练发版 | `pnpm release -- --app system --version 1.2.0 --dry-run` | | 演练发版 | `pnpm release -- --app system --version 1.2.0 --dry-run` |
| 正式发 system | `pnpm release -- --app system --version 1.2.0` | | 正式发 system | `pnpm release -- --app system --version 1.2.0` |
| 发到 CDN | `pnpm release -- --app system --version 1.2.0 --public-base https://cdn.example.com` | | 发到 CDN | `pnpm release -- --app system --version 1.2.0 --public-base https://cdn.example.com` |
| 复用已构建 dist | `pnpm release -- --app system --version 1.2.0 --skip-build` | | 复用已构建 dist | `pnpm release -- --app system --version 1.2.0 --skip-build` |
| 回滚 / 灰度切换 | `pnpm release -- --app system --version 1.1.9 --switch-only` | | 回滚 / 灰度切换 | `pnpm release -- --app system --version 1.1.9 --switch-only` |
| 查看全部参数 | `pnpm release -- --help` | | 查看全部参数 | `pnpm release -- --help` |
| **ops 唯一命令(推荐,零参数、永远不变)** | `pnpm release:run` —— 有清单走清单模式(自动取最新版本)、无清单自动取最新 git tag 兜底,版本与模式全由命令内部解析,ops 不填任何参数 | | **ops 唯一命令(推荐,零参数、永远不变)** | `pnpm release:run` —— 三层自动兜底:有清单走清单模式(取最新版)、无清单但有 tag 走 git 分析、连 tag 都没有(首次部署)走全量。版本与模式全由命令内部解析,ops 不填任何参数 |
| ops 带上传(一次性配置,平时用 `MFE_UPLOAD_CMD` 环境变量) | `pnpm release:run --upload-cmd "aws s3 sync {dir}/mfe s3://bucket/mfe/ && aws s3 sync {host} s3://bucket/"` | | ops 带上传(一次性配置,平时用 `MFE_UPLOAD_CMD` 环境变量) | `pnpm release:run --upload-cmd "rsync -a {dir}/ /var/www/console/"` |
| 开发者生成清单(人工核实,可选) | `pnpm release:gen --version 1.3.0` | | 开发者生成清单(人工核实,可选) | `pnpm release:gen --version 1.3.0` |
| 开发者显式清单发版(release:run 的底层,一般不用直跑) | `pnpm release:spec --spec 1.3.0` 或 `pnpm release:spec --latest` | | 开发者显式清单发版(release:run 的底层,一般不用直跑) | `pnpm release:spec --spec 1.3.0` 或 `pnpm release:spec --latest` |
| 自动 git 反查发版(release:run 的底层,一般不用直跑) | `pnpm release:affected --version 1.3.0`(无清单时的兜底实现) | | 自动 git 反查发版(release:run 的底层,一般不用直跑) | `pnpm release:affected --version 1.3.0`(无清单时的兜底实现) |
| 清单 + git 交叉校验(防漏发,挂在 run 后可选) | `pnpm release:run --verify`(等价于 `release:spec --spec <最新> --verify`) | | 清单 + git 交叉校验(防漏发,挂在 run 后可选) | `pnpm release:run --verify`(等价于 `release:spec --spec <最新> --verify`) |
| 并发发版保护(拉线上清单做合并基线) | `--remote-manifest <线上清单 URL>`,或设 `MFE_REMOTE_MANIFEST` |
| 清理旧版本目录(默认只报告) | `pnpm release:prune -- --dir /var/www/console` |
| 真删旧版本(保留最近 3 个 + 在线版本) | `pnpm release:prune -- --dir /var/www/console --apply --yes` |
| 开发期起全站 | `pnpm dev`(一条命令起三个 server,只访问 5173) | | 开发期起全站 | `pnpm dev`(一条命令起三个 server,只访问 5173) |
--- ---
...@@ -271,7 +442,7 @@ pnpm release:spec --spec 1.3.0 ...@@ -271,7 +442,7 @@ pnpm release:spec --spec 1.3.0
pnpm release:spec --latest pnpm release:spec --latest
``` ```
脚本读清单 → 逐个 `release.mjs` → `host:true` 时构建主壳部署到站点根 → 跑上传钩子(`{dir}` / `{host}` / `{file}` 占位同 §2.2)。未知子系统名、清单缺失等会在启动阶段直接报错,不会发一半。 脚本读清单 → 逐个 `release.mjs` → `host:true` 时构建主壳、落到产物根 → 跑上传钩子(`{dir}` 即产物根,`{host}`/`{file}` 占位见 §2.2)。未知子系统名、清单缺失等会在启动阶段直接报错,不会发一半。
### 安全护栏 --verify(推荐) ### 安全护栏 --verify(推荐)
...@@ -311,15 +482,25 @@ pnpm release:spec --spec 1.3.0 ...@@ -311,15 +482,25 @@ pnpm release:spec --spec 1.3.0
``` ```
生成的清单示例(节选): 生成的清单示例(节选):
```json ```json
{ {
"version": "1.3.0", "version": "1.3.0",
"apps": ["store", "system"], "apps": ["store", "system"],
"host": true, "host": true,
"changes": { "changes": {
"store": { "trigger": "cascade: @uj/contracts + root-full-rebuild", "files": ["packages/contracts/src/subapp.ts", "scripts/release/release.mjs", "..."] }, "store": {
"system": { "trigger": "cascade: @uj/contracts + root-full-rebuild", "files": ["packages/contracts/src/subapp.ts", "scripts/release/release.mjs", "..."] }, "trigger": "cascade: @uj/contracts + root-full-rebuild",
"host": { "trigger": "direct + cascade: @uj/contracts + root-full-rebuild", "files": ["apps/web/shell/src/router.tsx", "packages/contracts/src/subapp.ts", "..."] } "files": ["packages/contracts/src/subapp.ts", "scripts/release/release.mjs", "..."]
},
"system": {
"trigger": "cascade: @uj/contracts + root-full-rebuild",
"files": ["packages/contracts/src/subapp.ts", "scripts/release/release.mjs", "..."]
},
"host": {
"trigger": "direct + cascade: @uj/contracts + root-full-rebuild",
"files": ["apps/web/shell/src/router.tsx", "packages/contracts/src/subapp.ts", "..."]
}
}, },
"note": "695747d feat: ...;另有 3 个未提交文件(尚未 commit,本次会被一并发掉,建议先 git commit 再发布)", "note": "695747d feat: ...;另有 3 个未提交文件(尚未 commit,本次会被一并发掉,建议先 git commit 再发布)",
"_generated": true, "_generated": true,
...@@ -327,6 +508,7 @@ pnpm release:spec --spec 1.3.0 ...@@ -327,6 +508,7 @@ pnpm release:spec --spec 1.3.0
"_base": "origin/master" "_base": "origin/master"
} }
``` ```
> `changes` 是给**人工 review** 看的「每个模块对应哪些改动」,不参与实际发版;`release:spec` 只读 `version/apps/host`。手写清单不需要这个字段。 > `changes` 是给**人工 review** 看的「每个模块对应哪些改动」,不参与实际发版;`release:spec` 只读 `version/apps/host`。手写清单不需要这个字段。
> ⚠ 若改动文件处于「已移动但未提交」的中间态(如刚把脚本搬家),git 会同时算到旧路径(已提交)与新路径(未提交),`changes.files` 会出现重复条目;**提交后再重新 gen 一次即可消除**。 > ⚠ 若改动文件处于「已移动但未提交」的中间态(如刚把脚本搬家),git 会同时算到旧路径(已提交)与新路径(未提交),`changes.files` 会出现重复条目;**提交后再重新 gen 一次即可消除**。
...@@ -343,14 +525,16 @@ pnpm release:run ...@@ -343,14 +525,16 @@ pnpm release:run
# 等价别名: pnpm release:ops # 等价别名: pnpm release:ops
``` ```
- **版本号 ops 不接触**。命令内部自动解析: - **版本号 ops 不接触**。命令内部按**三层兜底**自动解析,任何仓库状态都能发,永不卡住:
- `releases/` 下**有清单** → 取版本号最大的那份(清单模式,不比对 git)。 - `releases/` 下**有清单** → 取版本号最大的那份(清单模式,不比对 git)。
- `releases/` 下**无清单**(开发者忘了 `release:gen`) → 取**最新 git tag** 作为版本(自动模式兜底),照样能发。 - **无清单、有 git tag** → 取**最新 tag** 作为版本,git 分析只发改动的(自动模式兜底)。
- 模式由命令自身依据「清单文件在不在」决定,ops 不判: - **无清单、无 tag**(典型是首次部署,仓库刚建还没人 gen 过)→ **全量模式**:扫描 workspace 全部子系统 + 主壳一次打齐(等价 `release:all`)。
- 模式由命令自身依据仓库状态决定,ops 不判:
- `releases/<版本>.json` 存在 → 清单模式(等价于 `release:spec --latest`,不比对 git)。 - `releases/<版本>.json` 存在 → 清单模式(等价于 `release:spec --latest`,不比对 git)。
- 不存在 → 自动模式(等价于 `release:affected --version <最新tag>`,git 分析兜底)。 - 不存在但有 tag → 自动模式(等价于 `release:affected --version <最新tag>`)。
- 都没有 → 全量模式(等价于 `release:all`,产物含全部子系统 + 主壳,可直面「第一次部署」)。
- 上传目标由 **`MFE_UPLOAD_CMD` 环境变量**一次性配置(或清单内的 `uploadCmd` 字段),不属于 ops 每次要改的参数。 - 上传目标由 **`MFE_UPLOAD_CMD` 环境变量**一次性配置(或清单内的 `uploadCmd` 字段),不属于 ops 每次要改的参数。
`release:run` 只做「模式分发 + 版本解析」,不重复实现发版逻辑;其余 `--base` / `--public-base` / `--out` / `--upload-cmd` / `--force` / `--skip-build` / `--dry-run` / `--verify` 全部透传给子脚本(ops 一般也不改)。其余 `release:affected` / `release:spec` 仍可直接调用(如需要单独 `--latest` 或调试)。 `release:run` 只做「模式分发 + 版本解析」,不重复实现发版逻辑;其余 `--base` / `--public-base` / `--out` / `--upload-cmd` / `--force` / `--skip-build` / `--dry-run` / `--verify` 全部透传给子脚本(ops 一般也不改)。预览类参数(`--no-serve` / `--port` / `--no-open`)仅全量模式有效,其他模式会自动剥离并提示,不会因此报错。其余 `release:affected` / `release:spec` 仍可直接调用(如需要单独 `--latest` 或调试)。
> 开发者侧若想显式指定版本(而非自动取最新),仍可 `pnpm release:run --version 1.3.0` 覆盖;但 ops 流程无需此参数。 > 开发者侧若想显式指定版本(而非自动取最新),仍可 `pnpm release:run --version 1.3.0` 覆盖;但 ops 流程无需此参数。
...@@ -31,7 +31,11 @@ ...@@ -31,7 +31,11 @@
"release:gen": "node scripts/release/release-gen.mjs", "release:gen": "node scripts/release/release-gen.mjs",
"release:spec": "node scripts/release/release-spec.mjs", "release:spec": "node scripts/release/release-spec.mjs",
"release:run": "node scripts/release/release-run.mjs", "release:run": "node scripts/release/release-run.mjs",
"release:all": "node scripts/release/release-all.mjs",
"release:ops": "node scripts/release/release-run.mjs", "release:ops": "node scripts/release/release-run.mjs",
"release:verify": "node scripts/release/release-verify.mjs",
"release:preview": "node scripts/release/static-server.mjs",
"release:prune": "node scripts/release/release-prune.mjs",
"sync": "node scripts/sync-from-uj-store.mjs", "sync": "node scripts/sync-from-uj-store.mjs",
"gen:tsconfig": "node scripts/gen-tsconfig.mjs", "gen:tsconfig": "node scripts/gen-tsconfig.mjs",
"verify": "node scripts/check-boundaries.mjs && node scripts/reconcile.mjs && pnpm typecheck && pnpm lint && pnpm lint:all && pnpm format:check", "verify": "node scripts/check-boundaries.mjs && node scripts/reconcile.mjs && pnpm typecheck && pnpm lint && pnpm lint:all && pnpm format:check",
......
...@@ -3,4 +3,5 @@ import type { UserConfig } from 'vite'; ...@@ -3,4 +3,5 @@ import type { UserConfig } from 'vite';
export declare function createShellConfig(options: { export declare function createShellConfig(options: {
appDir: string; appDir: string;
port: number; port: number;
base?: string;
}): UserConfig; }): UserConfig;
...@@ -18,9 +18,18 @@ const KEY_MODULES = { ...@@ -18,9 +18,18 @@ const KEY_MODULES = {
* platform-core 的 backend-resolver.ts 推导,dev server 不再挂 /api 代理, * platform-core 的 backend-resolver.ts 推导,dev server 不再挂 /api 代理,
* 因此本工厂只负责 PEM 注入与 .env/keys 热重启,无需 target / proxy 配置。 * 因此本工厂只负责 PEM 注入与 .env/keys 热重启,无需 target / proxy 配置。
* *
* @param {{ appDir: string, port: number }} options * base 与发版结构强相关:主壳产物不再摊在站点根,而是进 /mfe/host/<version>/ 这
* 个不可变目录,站点根的 index.html 只留一个指过去的「指针文件」。这样一次发布需要
* 覆盖的文件从「index.html + 一整批 assets」缩到「一个 index.html」,资产是整体新增
* 的目录,不会出现「新 HTML 配旧 JS」的白屏窗口。
* 发布脚本在 build 前注入 SHELL_BASE=/mfe/host/<version>/;dev 期不设,仍是 '/'。
*
* ⚠️ SHELL_BASE 必须列进 turbo.json 的 globalEnv:turbo 只把声明过的 env 纳入任务
* hash,否则换版本号重建会命中旧缓存,产物 base 还指上一个目录(与 SUBAPP_BASE 同理)。
*
* @param {{ appDir: string, port: number, base?: string }} options
*/ */
export function createShellConfig({ appDir, port }) { export function createShellConfig({ appDir, port, base = process.env.SHELL_BASE || '/' }) {
const keysDir = path.join(appDir, 'keys'); const keysDir = path.join(appDir, 'keys');
const keys = Object.fromEntries( const keys = Object.fromEntries(
Object.entries(KEY_MODULES).map(([id, { file }]) => { Object.entries(KEY_MODULES).map(([id, { file }]) => {
...@@ -79,6 +88,7 @@ export function createShellConfig({ appDir, port }) { ...@@ -79,6 +88,7 @@ export function createShellConfig({ appDir, port }) {
}; };
return { return {
base,
plugins: [react(), virtualKeys, reload], plugins: [react(), virtualKeys, reload],
resolve: { alias: createAliases({ appDir, kind: 'shell' }) }, resolve: { alias: createAliases({ appDir, kind: 'shell' }) },
server: { server: {
......
/**
* 构建指纹 —— 「线上跑的到底是哪个 commit?」
*
* 没有这个文件时,排查线上问题只能靠比对产物里某个 js 的 hash 去猜,或者去问
* 「刚才谁发的」。产物一旦离开构建机就断了溯源链,而部署根是覆盖式写入、不留历史。
*
* 落点:产物根 BUILD_INFO.json(随产物一起上传,运维和排障都看得到)。
* 内容刻意只放「定位版本需要的最小集合」,不放依赖清单 —— 那是 lock 文件的事。
*
* ⚠ 它会公开可访问(静态站的根目录没有鉴权)。里面没有密钥,但有 commit sha 与分支名;
* 若不希望公开,可在 nginx 里 `location = /BUILD_INFO.json { deny all; }`,
* 或上传时排除该文件(此时本文件只作为本地产物留痕)。
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
/** 读 git 元信息。不在 git 仓库里(CI 的浅检出、打好的 tar 包)就返回 null,不阻断发布。 */
function gitInfo(root) {
const run = (args) => {
const r = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
return r.status === 0 ? String(r.stdout).trim() : '';
};
const sha = run(['rev-parse', 'HEAD']);
if (!sha) return null;
return {
sha,
shortSha: sha.slice(0, 7),
branch: run(['rev-parse', '--abbrev-ref', 'HEAD']) || '(detached)',
// 有未提交改动时标出来:这类产物无法用 sha 完整还原,排障时是关键信息
dirty: run(['status', '--porcelain']).length > 0,
};
}
/**
* @param {object} o
* @param {string} o.root 仓库根(读 git 用)
* @param {string} o.outRoot 产物根(写文件用)
* @param {string} odistVersion 本次发布版本号
* @param {string[]} o.apps 本次发版的子系统
* @param {string|null} o.hostRel 主壳版本目录相对路径,未发主壳传 null
* @param {string|null} [o.manifestVersion] 产物清单里的 version 字段
* @param {string} [o.source] 发布入口(release:spec / release:all / release:affected / release)
* @returns {object} 写入的内容
*/
export function writeBuildInfo(o) {
const { root, outRoot, releaseVersion, apps, hostRel, manifestVersion, source } = o;
const info = {
releaseVersion,
builtAt: new Date().toISOString(),
source: source ?? null,
apps: [...apps].sort(),
host: hostRel ?? null,
manifestVersion: manifestVersion ?? null,
git: gitInfo(root),
node: process.version,
platform: `${process.platform}-${process.arch}`,
};
fs.mkdirSync(outRoot, { recursive: true });
fs.writeFileSync(
path.join(outRoot, 'BUILD_INFO.json'),
`${JSON.stringify(info, null, 2)}\n`,
'utf8',
);
return info;
}
/** 读产物里的清单 version(清单缺失或损坏时返回 null,不影响发布)。 */
export function manifestVersionOf(manifestFile) {
try {
return JSON.parse(fs.readFileSync(manifestFile, 'utf8')).version ?? null;
} catch {
return null;
}
}
/**
* 主壳(host)部署 —— 全仓唯一实现,release:spec 与 release:affected 共用。
*
* 为什么不各写一份:这条链路踩一次坑,两边必须同时修,否则「spec 发版正常、
* affected 发版白屏」。历史上清空时机、--no-clean 传递、主壳落点都已经分叉过一次。
*
* ── 落点:/mfe/host/<version>/,站点根只留一个指针 index.html ──────────────
* 站点根是整站唯一会被**原地覆盖**的地方。以前主壳 dist 直接摊在根上,一次发布要
* 逐个覆盖 index.html 和一批 assets;在「HTML 已落地、JS 还没到」的几百毫秒里,
* 线上是新页面配旧资产 → 白屏 404,而且这个窗口不可观测、不可复现。
*
* 版本化之后:
* - 资产进 /mfe/host/<version>/,整目录新增,天然原子;
* - 站点根只覆盖 index.html 一个文件,rsync/cp 都是「写临时文件再 rename」;
* - 旧主壳的 assets 不再散落在根目录,删一个版本就是删一个目录(见 release-prune)。
*
* 代价:主壳也要按版本号构建(SHELL_BASE 注入),所以 turbo 的 globalEnv 必须声明它,
* 否则换版本号会命中旧缓存,产物还指向上一个目录 —— 与 SUBAPP_BASE 同一类坑。
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
/** 主壳版本目录的部署相对路径(含末尾斜杠,可直接当 URL 前缀)。 */
export function hostRelOf(version) {
return `mfe/host/${version}/`;
}
/**
* 主壳产物的 base 校验 —— 与 release.mjs 里子应用那道同源,防同一类事故:
* 产物资源指向 /assets/xxx.js,而实际部署在 /mfe/host/1.0.0/assets/xxx.js,白屏零报错。
* --skip-build 复用旧 dist 时尤其必查(旧 dist 的 base 指向上一个版本目录)。
*/
export function assertShellBase(distDir, hostBase, die) {
const html = fs.readFileSync(path.join(distDir, 'index.html'), 'utf8');
const refs = [...html.matchAll(/\b(?:src|href)="([^"]+)"/g)]
.map((m) => m[1])
.filter((u) => !/^(?:data:|blob:|#)/.test(u));
if (refs.length === 0) return 0;
const bad = refs.filter((u) => {
if (/^https?:\/\//u.test(u)) return !u.includes(hostBase);
if (u.startsWith('/')) return !u.startsWith(hostBase);
return false; // 相对路径由页面自身位置解析,不会脱离版本目录
});
if (bad.length) {
die(
`主壳产物有 ${bad.length} 个资源路径未对齐 ${hostBase}:\n` +
bad
.slice(0, 5)
.map((u) => ` ${u}`)
.join('\n') +
'\n 部署到版本目录后会 404。构建时必须带 SHELL_BASE,且确认 turbo 未命中旧缓存。',
);
}
return refs.length;
}
/**
* 构建主壳并把产物摆到版本目录 + 站点根指针。
*
* @param {object} o
* @param {string} o.root 仓库根
* @param {string} o.outRoot 产物根(部署根镜像)
* @param {string} o.version 本次发布版本号
* @param {string} o.shellName 主壳包名(@uj/web-shell)
* @param {Map<string, any>} o.workspace scanWorkspace() 的 pkgs
* @param {boolean} o.skipBuild 复用已有 dist
* @param {string} o.pnpmBin pnpm 可执行名
* @param {boolean} o.isWin Windows 判定
* @param {(m: string) => void} o.info
* @param {(m: string) => never} o.die
* @returns {{ hostRel: string, fileCount: number }}
*/
export function deployHost(o) {
const { root, outRoot, version, shellName, workspace, skipBuild, pnpmBin, isWin, info, die } = o;
if (!shellName) die('未找到主壳包(apps/web/shell),无法部署 host。');
const shellMeta = workspace.get(shellName);
if (!shellMeta) die(`workspace 里没有 ${shellName},无法部署 host。`);
const shellDist = path.join(root, shellMeta.dir, 'dist');
const hostRel = hostRelOf(version);
const hostBase = `/${hostRel}`;
info(`构建主壳 ${shellName}(SHELL_BASE=${hostBase})...`);
if (skipBuild) {
if (!fs.existsSync(path.join(shellDist, 'index.html'))) {
die(
`--skip-build 但找不到 ${path.relative(root, shellDist)}/index.html;先构建或去掉 --skip-build。`,
);
}
} else {
const bres = spawnSync(pnpmBin, ['--filter', shellName, 'build'], {
cwd: root,
stdio: 'inherit',
shell: isWin,
env: { ...process.env, SHELL_BASE: hostBase },
});
if (bres.error) die(`启动 pnpm 失败:${bres.error.message}`);
if (bres.status !== 0) die(`主壳构建失败(exit ${bres.status}),未执行上传。`);
}
const refCount = assertShellBase(shellDist, hostBase, die);
const hostTarget = path.join(outRoot, 'mfe', 'host', version);
fs.mkdirSync(hostTarget, { recursive: true });
fs.cpSync(shellDist, hostTarget, { recursive: true });
info(`主壳产物已落到 ${hostRel}(整目录新增,不存在半截状态)`);
// 站点的 SPA 回落目标。内容与版本目录里那份相同,但它的资源指向前者;
// 只覆盖这一个文件,运维用 rsync 也是「写临时文件再 rename」,没有混合态。
fs.copyFileSync(path.join(shellDist, 'index.html'), path.join(outRoot, 'index.html'));
info(`站点根 index.html 已指向 ${hostRel}(本次唯一会被原地覆盖的文件)`);
// 旧结构升级提示:根目录残留的主壳 assets 不会再被引用,也不该继续躺着。
const legacyAssets = path.join(outRoot, 'assets');
if (fs.existsSync(legacyAssets) && fs.statSync(legacyAssets).isDirectory()) {
info(
`⚠ 产物根仍有旧结构的 assets/(升级前的遗留)。部署前请清掉部署根的 assets/,` +
`否则会永久累积无人引用的旧文件。`,
);
}
return { hostRel, fileCount: refCount };
}
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* 纯文档/格式/编辑器/示例配置(docs 目录、*.md、.gitignore、.gitlab-ci.yml、 * 纯文档/格式/编辑器/示例配置(docs 目录、*.md、.gitignore、.gitlab-ci.yml、
* .env.example 等)不改变 bundle,已排除,见 NON_BUILD_ROOT_RE。 * .env.example 等)不改变 bundle,已排除,见 NON_BUILD_ROOT_RE。
* 4. 逐个对受影响子应用调 scripts/release/release.mjs(构建 + 版本化目录 + 清单增量更新原样复用); * 4. 逐个对受影响子应用调 scripts/release/release.mjs(构建 + 版本化目录 + 清单增量更新原样复用);
* 全部成功后才跑一次上传钩子(整包 .release 只传一遍,幂等)。 * 全部成功后才跑一次上传钩子(整包 dist 只传一遍,幂等)。
* *
* ⚠ 级联本质:micro-app 是把共享包打进 bundle 的,不是运行时远程引用; * ⚠ 级联本质:micro-app 是把共享包打进 bundle 的,不是运行时远程引用;
* 但级联严格按真实依赖图,不是「packages 目录一动就全发」: * 但级联严格按真实依赖图,不是「packages 目录一动就全发」:
...@@ -31,6 +31,8 @@ import fs from 'node:fs'; ...@@ -31,6 +31,8 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { deployHost, hostRelOf } from './host-deploy.mjs';
import { assertBaseline } from './release-spec.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
...@@ -273,8 +275,9 @@ function main() { ...@@ -273,8 +275,9 @@ function main() {
--base <ref> 对比基线,默认 origin/master。可填 main / 某 tag / HEAD~3 等。 --base <ref> 对比基线,默认 origin/master。可填 main / 某 tag / HEAD~3 等。
--version <ver> 本次发布的版本号(所有受影响子应用共用,如 1.3.0)。必填。 --version <ver> 本次发布的版本号(所有受影响子应用共用,如 1.3.0)。必填。
--public-base <url> 产物对外根地址,透传给 release.mjs(如 https://cdn.example.com)。 --public-base <url> 产物对外根地址,透传给 release.mjs(如 https://cdn.example.com)。
--out <dir> 待上传目录,透传给 release.mjs(默认 .release)。 --out <dir> 产物目录,透传给 release.mjs(默认 dist)。镜像部署根、每次重建。
--upload-cmd <cmd> 上传钩子,透传给最终一次性上传(模板变量 {dir}/{file} 等)。 --state <dir> manifest 累积状态目录(默认 .release-state / MFE_STATE_DIR),透传。
--upload-cmd <cmd> 上传钩子,透传给最终一次性上传({dir} 即产物根,覆盖部署根)。
也可用环境变量 MFE_UPLOAD_CMD 提供。 也可用环境变量 MFE_UPLOAD_CMD 提供。
--force 允许覆盖已存在版本目录,透传给 release.mjs。 --force 允许覆盖已存在版本目录,透传给 release.mjs。
--skip-build 复用已有 dist,不重新构建(CI 里 build job 已构建时用;host 与子应用均生效)。 --skip-build 复用已有 dist,不重新构建(CI 里 build job 已构建时用;host 与子应用均生效)。
...@@ -288,9 +291,10 @@ function main() { ...@@ -288,9 +291,10 @@ function main() {
- 根构建配置(pnpm-workspace.yaml / pnpm-lock.yaml / turbo.json / tsconfig.base.json / - 根构建配置(pnpm-workspace.yaml / pnpm-lock.yaml / turbo.json / tsconfig.base.json /
.npmrc / 根 package.json)改动会保守地全量重发;纯文档、*.md、docs 目录、 .npmrc / 根 package.json)改动会保守地全量重发;纯文档、*.md、docs 目录、
格式/编辑器/CI 配置、.env.example 不触发全量。 格式/编辑器/CI 配置、.env.example 不触发全量。
- 主壳(host) 改动会自动构建并部署到站点根:shell 自身文件、被 shell 依赖的共享包 - 主壳(host) 改动会自动构建并部署:shell 自身文件、被 shell 依赖的共享包
(platform-core / contracts / ui / biz / design-tokens,按真实依赖图判定)、或根构建配置 (platform-core / contracts / ui / biz / design-tokens,按真实依赖图判定)、或根构建配置
任一变动,都会触发主壳重建;主壳产物暂存到 {host},与子应用一并、一次性上传。 任一变动,都会触发主壳重建;主壳产物落到 /mfe/host/<version>/(与子应用同构的不可变目录),
站点根只覆盖一个指向它的 index.html,与子应用一并、一次性上传。
无需再单独跑 deploy:shell。 无需再单独跑 deploy:shell。
- ⚠ 默认基线是 origin/master:未 push 的本地提交也会被算进「改动」, - ⚠ 默认基线是 origin/master:未 push 的本地提交也会被算进「改动」,
第一次跑若不想全量,先 push/fetch 或用 --base HEAD~N 指定真实基线。 第一次跑若不想全量,先 push/fetch 或用 --base HEAD~N 指定真实基线。
...@@ -318,15 +322,15 @@ function main() { ...@@ -318,15 +322,15 @@ function main() {
} }
const workspace = scanWorkspace(); const workspace = scanWorkspace();
const { affectedApps, changedPackages, shellChanged, rootChanged, hostAffected, ignoredRootFiles } = const { affectedApps, changedPackages, rootChanged, hostAffected, ignoredRootFiles } =
computeAffected(changedFiles, workspace); computeAffected(changedFiles, workspace);
const isWin = process.platform === 'win32'; const isWin = process.platform === 'win32';
const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm'; const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm';
const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? '.release'); const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? 'dist');
const stateDir = args.state ?? process.env.MFE_STATE_DIR;
const skipBuild = Boolean(args['skip-build']); const skipBuild = Boolean(args['skip-build']);
const shellName = [...workspace.pkgs.values()].find((p) => p.isShell)?.name; const shellName = [...workspace.pkgs.values()].find((p) => p.isShell)?.name;
const hostStaging = path.join(outRoot, '_host');
// ---- 打印计划 ---- // ---- 打印计划 ----
console.log('\n[release:affected] ==== 受影响分析 ===='); console.log('\n[release:affected] ==== 受影响分析 ====');
...@@ -340,7 +344,7 @@ function main() { ...@@ -340,7 +344,7 @@ function main() {
} }
console.log(` 受影响子系统: ${affectedApps.length ? affectedApps.join(', ') : '(无)'}`); console.log(` 受影响子系统: ${affectedApps.length ? affectedApps.join(', ') : '(无)'}`);
if (hostAffected) { if (hostAffected) {
console.log(` ⚠ 主壳(host) 受影响 → 将一并构建并部署到站点根(${shellName})`); console.log(` ⚠ 主壳(host) 受影响 → 将一并构建并部署(${shellName} → mfe/host/${version}/)`);
} }
const skipped = [...workspace.pkgs.values()] const skipped = [...workspace.pkgs.values()]
.filter((p) => p.isMicroApp && !affectedApps.includes(p.microAppName)) .filter((p) => p.isMicroApp && !affectedApps.includes(p.microAppName))
...@@ -358,18 +362,23 @@ function main() { ...@@ -358,18 +362,23 @@ function main() {
const out = args.out; const out = args.out;
const force = Boolean(args.force); const force = Boolean(args.force);
const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD; const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD;
const remoteManifest = args['remote-manifest'] ?? process.env.MFE_REMOTE_MANIFEST;
if (dryRun) { if (dryRun) {
console.log('[release:affected] --dry-run:以下动作不会执行。'); console.log('[release:affected] --dry-run:以下动作不会执行。');
console.log(` 0. 重建产物目录 ${path.relative(ROOT, outRoot)}/(只装本次要覆盖的文件)`);
let step = 1; let step = 1;
for (const app of affectedApps) { for (const [i, app] of affectedApps.entries()) {
const cmd = [ const cmd = [
'node scripts/release/release.mjs', 'node scripts/release/release.mjs',
`--app ${app}`, `--app ${app}`,
`--version ${version}`, `--version ${version}`,
publicBase ? `--public-base ${publicBase}` : '', publicBase ? `--public-base ${publicBase}` : '',
out ? `--out ${out}` : '', out ? `--out ${out}` : '',
stateDir ? `--state ${stateDir}` : '',
force ? '--force' : '', force ? '--force' : '',
skipBuild ? '--skip-build' : '',
i > 0 ? '--no-clean' : '',
] ]
.filter(Boolean) .filter(Boolean)
.join(' '); .join(' ');
...@@ -378,85 +387,100 @@ function main() { ...@@ -378,85 +387,100 @@ function main() {
} }
if (hostAffected) { if (hostAffected) {
console.log( console.log(
` ${step}. 主壳 ${shellName} 构建 → 暂存 ${path.relative(ROOT, hostStaging)} → 部署到站点根(非 /mfe/)`, ` ${step}. 主壳 ${shellName} 构建(SHELL_BASE=/${hostRelOf(version)})→ 整目录落 ${hostRelOf(version)},根 index.html 只写指针`,
); );
step += 1; step += 1;
} }
console.log( console.log(
` ${step}. 一次性上传({dir}=${outRoot},{host}=${hostStaging}):${uploadCmd ?? '(未配置,仅产出入参)'}`, ` ${step}. 一次性上传({dir}=${outRoot} 覆盖部署根):${uploadCmd ?? '(未配置,仅产出入参)'}`,
); );
console.log(''); console.log('');
process.exit(0); process.exit(0);
} }
// ---- 逐个发版(不传 upload-cmd,最后统一传一次)---- // ---- 增量发版前必须确认能拼出完整清单(与 release:spec 同一道拦截)----
for (const app of affectedApps) { assertBaseline({
tag: 'release:affected',
apps: affectedApps,
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 affectedApps.entries()) {
info(`发版子系统 ${app}(${version})...`); info(`发版子系统 ${app}(${version})...`);
const cmd = ['node', 'scripts/release/release.mjs', '--app', app, '--version', version]; const cmd = ['node', 'scripts/release/release.mjs', '--app', app, '--version', version];
if (publicBase) cmd.push('--public-base', publicBase); if (publicBase) cmd.push('--public-base', publicBase);
if (out) cmd.push('--out', out); if (out) cmd.push('--out', out);
if (stateDir) cmd.push('--state', stateDir);
if (force) cmd.push('--force'); if (force) cmd.push('--force');
if (skipBuild) cmd.push('--skip-build'); if (skipBuild) cmd.push('--skip-build');
if (remoteManifest) cmd.push('--remote-manifest', remoteManifest);
if (i > 0) cmd.push('--no-clean');
const res = spawnSync(cmd[0], cmd.slice(1), { cwd: ROOT, stdio: 'inherit' }); const res = spawnSync(cmd[0], cmd.slice(1), { cwd: ROOT, stdio: 'inherit' });
if (res.status !== 0) die(`子系统 ${app} 发版失败(exit ${res.status}),已中止,未执行上传。`); if (res.status !== 0) die(`子系统 ${app} 发版失败(exit ${res.status}),已中止,未执行上传。`);
} }
// ---- 主壳(host)受影响时一并构建并暂存到 _host(部署到站点根,非 /mfe/)---- // 只发主壳时没有子应用负责清空,这里补一次(产物根只装主壳产物)。
if (hostAffected) { if (affectedApps.length === 0) {
if (!shellName) die('未找到主壳包(apps/web/shell),无法部署 host。'); fs.rmSync(outRoot, { recursive: true, force: true });
info(`主壳 ${shellName} 受影响 → 构建并部署到站点根(非 /mfe/)...`); fs.mkdirSync(outRoot, { recursive: true });
const shellMeta = workspace.pkgs.get(shellName); info(`产物目录已重建:${path.relative(ROOT, outRoot)}/`);
const shellDist = path.join(ROOT, shellMeta.dir, 'dist');
if (skipBuild) {
if (!fs.existsSync(path.join(shellDist, 'index.html'))) {
die(
`--skip-build 但找不到 ${path.relative(ROOT, shellDist)}/index.html;先构建或去掉 --skip-build。`,
);
} }
} else {
const bres = spawnSync(pnpmBin, ['--filter', shellName, 'build'], { // ---- 主壳(host)受影响时 → /mfe/host/<version>/,站点根只写指针 ----
cwd: ROOT, // 与 release:spec 共用 host-deploy.mjs,不另写一份(否则两边必然分叉)。
stdio: 'inherit', if (hostAffected) {
shell: isWin, info(`主壳 ${shellName} 受影响 → 构建并落到 ${hostRelOf(version)}...`);
env: process.env, deployHost({
root: ROOT,
outRoot,
version,
shellName,
workspace: workspace.pkgs,
skipBuild,
pnpmBin,
isWin,
info,
die,
}); });
if (bres.error) die(`启动 pnpm 失败:${bres.error.message}`);
if (bres.status !== 0) die(`主壳构建失败(exit ${bres.status}),未执行上传。`);
} }
fs.rmSync(hostStaging, { recursive: true, force: true }); // 主壳未受影响 → 产物根不会有它的文件(目录已重建),无需额外清理
fs.mkdirSync(hostStaging, { recursive: true });
fs.cpSync(shellDist, hostStaging, { recursive: true });
info(`主壳产物已暂存到 ${path.relative(ROOT, hostStaging)}`);
}
// 主壳未受影响 → 清掉暂存(避免 {dir} 同步时把旧 _host 误传到站点根)
if (!hostAffected) fs.rmSync(hostStaging, { recursive: true, force: true });
// ---- 成功后一次性上传(子应用走 {dir}/mfe,主壳走 {host} 到站点根)---- // ---- 成功后一次性上传:产物是一棵镜像部署根的树,{dir} 一个变量覆盖过去 ----
if (uploadCmd) { if (uploadCmd) {
const manifestFile = path.join(outRoot, 'mfe', 'manifest.json'); const manifestFile = path.join(outRoot, 'mfe', 'manifest.json');
const template = String(uploadCmd); const template = String(uploadCmd);
if (!/\{(?:dir|file|host)\}/.test(template)) { if (!/\{dir\}/.test(template)) {
info('⚠ 上传钩子未包含 {dir}/{file}/{host}:请确认 manifest 与 host 都会被上传,否则发布不生效。'); info('⚠ 上传钩子未包含 {dir}:产物是镜像部署根的一棵树,一个 {dir} 覆盖过去即可。');
} }
const cmd = template const cmd = template
.replaceAll('{dir}', outRoot) .replaceAll('{dir}', outRoot)
.replaceAll('{target}', outRoot) .replaceAll('{target}', outRoot)
.replaceAll('{remote}', '') .replaceAll('{remote}', '')
.replaceAll('{host}', hostStaging) .replaceAll('{host}', outRoot) // 兼容旧钩子:主壳已落在产物根
.replaceAll('{file}', manifestFile); .replaceAll('{file}', manifestFile);
info(`执行一次性上传钩子:${cmd}`); info(`执行一次性上传钩子:${cmd}`);
const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true }); const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true });
if (res.status !== 0) if (res.status !== 0)
die(`上传失败(exit ${res.status})。各子系统与 host 已落盘到 ${outRoot},远端尚未生效。`); die(`上传失败(exit ${res.status})。各子系统与 host 已落盘到 ${outRoot},远端尚未生效。`);
} }
// 清理主壳暂存:host 未受影响时已清;受影响时上传已完也清掉
fs.rmSync(hostStaging, { recursive: true, force: true });
console.log('\n[release:affected] ==== 完成 ===='); console.log('\n[release:affected] ==== 完成 ====');
console.log(` 已发版子系统: ${affectedApps.length ? affectedApps.join(', ') : '(无)'} @ ${version}`); console.log(
if (hostAffected) console.log(` 主壳(host) : ${shellName} 已构建并部署到站点根`); ` 已发版子系统: ${affectedApps.length ? affectedApps.join(', ') : '(无)'} @ ${version}`,
console.log(' 发布生效:浏览器必须【整页刷新】;manifest.json 与 host index.html 建议 no-cache。'); );
if (hostAffected)
console.log(` 主壳(host) : ${shellName} → ${hostRelOf(version)}(站点根 index.html 是指针)`);
console.log(
` 产物 : ${path.relative(ROOT, outRoot)}/ 只含本次内容,覆盖进部署根即生效;未出现的模块保持线上老版本。`,
);
console.log(
' 发布生效:浏览器必须【整页刷新】;manifest.json 与 host index.html 建议 no-cache。',
);
console.log(''); console.log('');
} }
......
#!/usr/bin/env node
/**
* 全量打包 —— 一条命令把「所有子系统 + 主壳」打成一棵镜像部署根的产物树,然后本地就能打开看。
*
* pnpm release:all # 构建全部 → dist/ → 自检 → 起预览(自动开浏览器)
* pnpm release:all --no-serve # 只打包(CI / 交给运维上传)
* pnpm release:all --version 1.1.0 # 指定版本号
*
* 与 release:spec / release:affected 的分工:
* - release:spec 「发哪几个」由 releases/<v>.json 明确写出(增量发版,线上保留老版本目录)
* - release:affected 「发哪几个」由 git 反查(CI 里跑,只发改过的)
* - release:all 「全发」,范围现场扫 workspace 得出,不需要写清单
*
* 全量包的使用场景是:第一次部署、本地要看完整效果、或者要一整套可归档的产物。
* 它复用 release:spec 的发版主流程(runRelease),不另写一份 —— 否则清空时机、
* --no-clean 传递、主壳落点这些细节必然分叉成两套行为。
*
* 关于 --force 默认开启:全量包的语义是「把这个版本整套重新打一遍」,重复跑同一个
* 版本号是常态(改代码 → 重新打包 → 刷新预览)。若沿用增量发版的不可变保护,
* 第二次就会报「版本已发布过」,把人拦在最没必要的时刻。要保护旧版本时换版本号,
* 或用 --no-force 显式恢复保护。
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { scanWorkspace } from './release-affected.mjs';
import { runRelease, listSpecFiles, cmpVersion } from './release-spec.mjs';
import { startStaticServer } from './static-server.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
const paint = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const green = paint('32');
const red = paint('31');
const yellow = paint('33');
const dim = paint('2');
const bold = paint('1');
const cyan = paint('36');
function die(message) {
console.error(`\n[release:all] ${red('✗')} ${message}\n`);
process.exit(1);
}
/** 去掉 ANSI 转义,否则按字符数算宽度会把转义序列当可见字符,边框整排推歪。 */
// 用构造式而非正则字面量:ESC 是控制字符,字面量会被 no-control-regex 判错
const ANSI_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g');
/** CJK 按 2 列算,否则中文会把边框推歪。 */
function width(s) {
let n = 0;
for (const ch of String(s).replace(ANSI_RE, '')) {
const c = ch.codePointAt(0) ?? 0;
n +=
(c >= 0x1100 && c <= 0x115f) ||
(c >= 0x2e80 && c <= 0xa4cf) ||
(c >= 0xac00 && c <= 0xd7a3) ||
(c >= 0xf900 && c <= 0xfaff) ||
(c >= 0xfe30 && c <= 0xfe6f) ||
(c >= 0xff00 && c <= 0xff60) ||
(c >= 0xffe0 && c <= 0xffe6)
? 2
: 1;
}
return n;
}
function padEnd(s, w) {
const gap = w - width(s);
return gap > 0 ? String(s) + ' '.repeat(gap) : String(s);
}
const HELP = `
release:all —— 全量打包:所有子系统 + 主壳 → 一棵镜像部署根的产物树,可直接预览
用法:
pnpm release:all [选项]
选项:
--version <v> 版本号,默认取 releases/ 下最新的清单版本,没有清单则用 1.0.0
--out <dir> 产物目录,默认 dist(或 MFE_OUT_DIR)
目录每次重建,形态即部署根:index.html/assets 在根,mfe/<app>/<ver>/ 在子目录
--state <dir> manifest 累积状态目录,默认 .release-state(或 MFE_STATE_DIR)
--skip-build 跳过构建,直接复用各应用已有 dist(调试发布脚本时用)
--no-verify 跳过打包后的自检
--no-serve 只打包,不起预览服务(CI 用)
--port <n> 预览端口,默认 4180(被占用则自动往后找)
--no-open 不自动打开浏览器
--no-force 恢复不可变保护:同名版本已发布过就报错,而不是就地重建
--upload-cmd <c> 打包后执行上传钩子,{dir} 为产物根
--help 显示本帮助
产物形态(= 部署根,整棵树覆盖过去即上线):
dist/
├── index.html 指针文件:只指向 mfe/host/<ver>/,站点根唯一被覆盖的文件
└── mfe/
├── manifest.json 全量清单(浏览器 no-cache)
├── host/1.0.0/ 主壳(版本化,整目录新增,不会出现新 HTML 配旧 JS)
├── store/1.0.0/
└── system/1.0.0/
上传(注意不要 --delete,会删掉线上旧版本目录、回滚就没了):
rsync -a dist/ /var/www/console/
`;
function parseArgs(argv) {
const flags = new Set(['help', 'skip-build', 'no-verify', 'no-serve', 'no-open', 'no-force']);
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;
}
/** 缺省版本号:取 releases/ 下最新的清单版本;没有清单就落到 1.0.0。 */
function defaultVersion() {
const specs = listSpecFiles();
if (specs.length === 0) return { version: '1.0.0', from: '缺省值(releases/ 下没有清单)' };
const latest = specs.sort((a, b) => cmpVersion(a.version, b.version)).pop();
return { version: latest.version, from: `releases/${latest.file}` };
}
function openBrowser(url) {
const cmd =
process.platform === 'win32'
? ['cmd', ['/c', 'start', '', url]]
: process.platform === 'darwin'
? ['open', [url]]
: ['xdg-open', [url]];
try {
const child = spawn(cmd[0], cmd[1], { stdio: 'ignore', detached: true, shell: false });
child.on('error', () => {}); // 没有浏览器/被策略拦,不影响预览服务本身
child.unref();
} catch {
/* 打不开就算了,URL 已经打印出来了 */
}
}
function panel(lines) {
const w = Math.max(...lines.map((l) => width(l)));
const bar = '─'.repeat(w + 2);
console.log(`\n ${dim('╭')}${dim(bar)}${dim('╮')}`);
for (const l of lines) console.log(` ${dim('│')} ${padEnd(l, w)} ${dim('│')}`);
console.log(` ${dim('╰')}${dim(bar)}${dim('╯')}\n`);
}
async function startPreview(dir, port, open) {
let started = null;
const base = Number(port);
for (let p = base; p < base + 10; p += 1) {
try {
started = await startStaticServer(dir, { port: p });
break;
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
}
}
if (!started) die(`端口 ${base}-${base + 9} 全被占用,用 --port 换一个。`);
const manifestFile = path.join(dir, 'mfe', 'manifest.json');
let subapps = {};
try {
subapps = JSON.parse(fs.readFileSync(manifestFile, 'utf8')).subapps ?? {};
} catch {
/* 清单坏了自检会报,这里只影响展示 */
}
/** 主壳版本目录:站点根 index.html 只是个指针,真实资源在这儿。 */
let hostRel = null;
const hostRoot = path.join(dir, 'mfe', 'host');
if (fs.existsSync(hostRoot)) {
const vers = fs
.readdirSync(hostRoot)
.filter((v) => fs.existsSync(path.join(hostRoot, v, 'index.html')));
if (vers.length) hostRel = `mfe/host/${vers.sort().pop()}/`;
}
const nameW = Math.max(4, ...Object.keys(subapps).map((n) => width(n)));
const urlW = Math.max(
12,
...Object.values(subapps).map((e) => width(e?.url ?? '')),
hostRel ? width(`/${hostRel}`) : 0,
);
const lines = [`${bold('就绪')} 本地产物预览 ${dim('(等价线上 nginx 行为)')}`, ''];
if (hostRel) {
lines.push(
`${green('✓')} ${padEnd('shell', nameW)} ${padEnd(`/${hostRel}`, urlW)} ${dim('站点根指针')}`,
);
} else {
lines.push(`${green('✓')} ${padEnd('shell', nameW)} ${padEnd('/', urlW)} ${dim('站点根')}`);
}
for (const [name, entry] of Object.entries(subapps)) {
lines.push(
`${green('✓')} ${padEnd(name, nameW)} ${padEnd(entry?.url ?? '', urlW)} ${dim(`v${entry?.version ?? '?'}`)}`,
);
}
lines.push('');
lines.push(`${cyan('▸')} ${cyan(`${started.url}/`)}`);
lines.push(`${dim(' Ctrl+C 停止预览')}`);
if (started.port !== base)
console.log(`\n ${yellow('!')} 端口 ${base} 被占用,改用 ${started.port}`);
panel(lines);
if (open) openBrowser(`${started.url}/`);
const stop = () => {
console.log(`\n ${dim('⏻')} 预览已停止`);
started.server.close();
process.exit(0);
};
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
}
function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (e) {
die(e.message);
}
if (args.help) {
console.log(HELP);
return;
}
const workspace = scanWorkspace();
const shellName = [...workspace.pkgs.values()].find((p) => p.isShell)?.name;
if (!shellName) die('未找到主壳包(apps/web/shell)。');
// 范围现场扫描,不依赖任何清单:源码里有的子系统全部参与。
const microApps = [...workspace.pkgs.values()]
.filter((p) => p.isMicroApp)
.map((p) => p.microAppName)
.sort();
if (microApps.length === 0) die('workspace 里没有找到任何子系统(apps/web/subapps/*)。');
const fallback = defaultVersion();
const version = args.version ?? fallback.version;
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(version) || version.includes('..')) {
die(`版本号 "${version}" 非法:只允许字母数字 . _ -,且不得含 ".."`);
}
const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? 'dist');
const force = !args['no-force'];
const skipBuild = Boolean(args['skip-build']);
const serve = !args['no-serve'];
console.log(`\n[release:all] ${bold('全量打包')}`);
console.log(` 版本 : ${version}${args.version ? '' : dim(`(取自 ${fallback.from})`)}`);
console.log(
` 子系统 : ${microApps.join(', ')}${dim(`(${microApps.length} 个,扫描 workspace 得出)`)}`,
);
console.log(` 主壳(host) : ${shellName} → mfe/host/${version}/(站点根只写指针)`);
console.log(` 产物目录 : ${path.relative(ROOT, outRoot)}/(每次重建,形态即部署根)`);
console.log(
` 构建 : ${skipBuild ? dim('跳过,复用已有 dist') : '逐个应用构建(注入 SUBAPP_BASE)'}`,
);
console.log('');
// 复用 release:spec 的主流程:清空时机、--no-clean 传递、主壳落点、上传钩子全在这里。
runRelease(
{
version,
apps: microApps,
host: true,
file: null,
note: '',
uploadCmd: args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD,
},
{
tag: 'release:all',
'no-header': true, // 上面已打过一份更贴场景的总览
out: args.out,
state: args.state,
force,
'skip-build': skipBuild,
'public-base': args['public-base'],
'upload-cmd': args['upload-cmd'],
},
{ workspace, shellName },
);
// ---- 自检:产物是不是真能打开(少文件、前缀错、清单指空目录都会在这里拦住)----
if (!args['no-verify']) {
console.log(`[release:all] 自检产物(清单 / 每个模块的 index.html 与资源)...`);
const res = spawnSync(
process.execPath,
[
path.join(ROOT, 'scripts/release/release-verify.mjs'),
'--serve',
path.relative(ROOT, outRoot),
],
{ cwd: ROOT, stdio: 'inherit' },
);
if (res.status !== 0) {
die(
'自检失败,产物不完整,先别上传。\n' +
' 逐条看上面的 ✗;若确认是误报可加 --no-verify 跳过(不建议)。',
);
}
}
if (!serve) {
console.log(`[release:all] 产物已就绪:${path.relative(ROOT, outRoot)}/`);
console.log(
` 上传(不要 --delete,会删掉线上旧版本目录):rsync -a ${path.relative(ROOT, outRoot)}/ <部署根>/`,
);
console.log(
` 想本地看效果:pnpm release:preview (站点根固定为该产物目录,别用 Live Server 从仓库根起)`,
);
console.log(` 或去掉 --no-serve 直接跑本命令。\n`);
return;
}
startPreview(outRoot, args.port ?? 4180, !args['no-open']).catch((err) =>
die(err.stack ?? err.message),
);
}
main();
#!/usr/bin/env node
/**
* 版本目录清理 —— 覆盖式部署的另一面。
*
* 发布是「整目录新增 + 覆盖」:不发 --delete,所以旧版本永远留在部署根上。这是
* 回滚能力的来源,但没有任何机制回收,跑半年后 mfe/ 下会堆几十个 24MB 的目录。
* 主壳以前更糟:assets 直接摊在站点根,hash 文件名让它连「版本」这个概念都没有,
* 只能靠人肉看着删。主壳版本化之后,清理统一成「删整个版本目录」,可枚举、可预演。
*
* node scripts/release/release-prune.mjs --dir /srv/www/console # 只报告
* node scripts/release/release-prune.mjs --dir /srv/www/console --apply --yes
*
* 保留规则(三个条件取并集,任一条命中就不删):
* 1. 清单 manifest.json 当前指向的版本(删了线上立刻坏);
* 2. 站点根 index.html 指向的 host 版本(同上);
* 3. 每个单元按修改时间最新的 --keep 个(默认 3,保证回滚有余量)。
*
* 刻意默认只报告:删除不可逆,而「保守留着」的代价只是硬盘。要真删必须
* --apply 与 --yes 同时给,两个开关是为了让手滑复制粘贴时不会直接删掉线上。
*/
import fs from 'node:fs';
import path from 'node:path';
const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
const paint = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const green = paint('32');
const red = paint('31');
const yellow = paint('33');
const dim = paint('2');
const bold = paint('1');
function die(message) {
console.error(`\n[prune] ${red('✗')} ${message}\n`);
process.exit(1);
}
function parseArgs(argv) {
const flags = new Set(['apply', 'yes', 'help']);
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === '--') continue;
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;
}
const HELP = `
[prune] 清理部署根上的历史版本目录(默认只报告,不删除)
用法:
node scripts/release/release-prune.mjs --dir <部署根> [选项]
参数:
--dir <path> 部署根(含 index.html 与 mfe/ 的那层),必填
--keep <n> 每个单元按时间保留最近 n 个版本,默认 3
--apply 真的删除(不加就是只报告)
--yes 与 --apply 一起用,确认知道删除不可逆
--help 显示本帮助
保留:清单指向的版本、根 index.html 指向的 host 版本、每个单元最近 n 个。
`;
function dirSize(dir) {
let total = 0;
const walk = (p) => {
for (const e of fs.readdirSync(p, { withFileTypes: true })) {
const abs = path.join(p, e.name);
if (e.isDirectory()) walk(abs);
else if (e.isFile()) total += fs.statSync(abs).size;
}
};
walk(dir);
return total;
}
function fmtSize(bytes) {
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)}G`;
if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)}M`;
return `${Math.max(1, Math.round(bytes / 1024))}K`;
}
/** 根 index.html 指向的 host 版本目录名。取不到返回 null(旧结构或没发过主壳)。 */
function hostPinnedVersion(rootDir) {
const file = path.join(rootDir, 'index.html');
if (!fs.existsSync(file)) return null;
const html = fs.readFileSync(file, 'utf8');
const m = html.match(/\/mfe\/host\/([^/"']+)\//);
return m ? m[1] : null;
}
function manifestPinned(rootDir) {
const file = path.join(rootDir, 'mfe', 'manifest.json');
if (!fs.existsSync(file)) return {};
try {
const man = JSON.parse(fs.readFileSync(file, 'utf8'));
const out = {};
for (const [name, entry] of Object.entries(man.subapps ?? {})) {
const m = String(entry?.url ?? '').match(/\/mfe\/[^/]+\/([^/"']+)\/?$/);
if (m) out[name] = m[1];
}
return out;
} catch {
return {};
}
}
function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (e) {
die(e.message);
}
if (args.help) {
console.log(HELP);
return;
}
const dirArg = args.dir ?? process.env.MFE_PRUNE_DIR;
if (!dirArg) die('缺少 --dir <部署根>。用 --help 查看用法。');
const rootDir = path.resolve(dirArg);
if (!fs.existsSync(rootDir)) die(`目录不存在:${rootDir}`);
const mfeDir = path.join(rootDir, 'mfe');
if (!fs.existsSync(mfeDir)) die(`${rootDir} 下没有 mfe/,不像是本项目的部署根,已拒绝。`);
const keep = Math.max(1, Number(args.keep ?? 3) || 3);
const apply = Boolean(args.apply);
if (apply && !args.yes) die('--apply 需要同时给 --yes(删除不可逆,两个开关防手滑)。');
const pinnedHost = hostPinnedVersion(rootDir);
const pinnedApps = manifestPinned(rootDir);
console.log(`\n[prune] ${bold('扫描')} ${dim(rootDir)}`);
console.log(` 每个单元保留最近 ${keep} 个版本`);
console.log(
` 在线引用:host=${pinnedHost ?? '(未识别)'} ` +
`apps=${
Object.entries(pinnedApps)
.map(([k, v]) => `${k}@${v}`)
.join(', ') || '(无)'
}`,
);
console.log('');
const units = [];
for (const entry of fs.readdirSync(mfeDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (!/^[a-z0-9_-]+$/i.test(entry.name)) continue; // 只认已知形态的单元目录
const unitDir = path.join(mfeDir, entry.name);
const versions = fs
.readdirSync(unitDir, { withFileTypes: true })
.filter(
(e) =>
e.isDirectory() && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(e.name) && !e.name.includes('..'),
)
.map((e) => ({
name: e.name,
dir: path.join(unitDir, e.name),
mtime: fs.statSync(path.join(unitDir, e.name)).mtimeMs,
}))
.sort((a, b) => b.mtime - a.mtime);
if (versions.length === 0) continue;
units.push({ name: entry.name, versions });
}
if (units.length === 0) {
console.log(dim(' mfe/ 下没有任何版本目录,无需清理。\n'));
return;
}
const doomed = [];
for (const unit of units) {
const pinned = unit.name === 'host' ? pinnedHost : pinnedApps[unit.name];
unit.versions.forEach((v, i) => {
const isPinned = v.name === pinned;
const inKeep = i < keep;
if (isPinned || inKeep) return;
doomed.push({ unit: unit.name, ...v });
});
}
for (const unit of units) {
const pinned = unit.name === 'host' ? pinnedHost : pinnedApps[unit.name];
console.log(` ${bold(unit.name)} ${dim(`(${unit.versions.length} 个版本)`)}`);
for (const v of unit.versions) {
const marks = [];
if (v.name === pinned) marks.push(green('在线'));
if (doomed.some((d) => d.unit === unit.name && d.name === v.name)) marks.push(red('将删除'));
console.log(
` ${v.name === pinned ? green('●') : '○'} ${v.name} ${dim(fmtSize(dirSize(v.dir)))} ${
marks.join(' ') || dim('保留')
}`,
);
}
}
if (doomed.length === 0) {
console.log(`\n[prune] 没有可清理的版本目录。\n`);
return;
}
const total = doomed.reduce((s, d) => s + dirSize(d.dir), 0);
console.log('');
console.log(
`[prune] 可清理 ${yellow(String(doomed.length))} 个版本目录,共 ${yellow(fmtSize(total))}`,
);
if (!apply) {
console.log(dim(' 这是预演,未删除任何文件。确认后加 --apply --yes 执行。\n'));
return;
}
let removed = 0;
for (const d of doomed) {
try {
fs.rmSync(d.dir, { recursive: true, force: true });
removed += 1;
console.log(` ${green('✓')} 已删除 mfe/${d.unit}/${d.name}/`);
} catch (err) {
console.log(` ${yellow('!')} 删除失败 mfe/${d.unit}/${d.name}/:${err.message}`);
}
}
console.log(`\n[prune] 完成:删除 ${removed}/${doomed.length} 个,释放约 ${fmtSize(total)}。\n`);
}
main();
...@@ -9,11 +9,10 @@ ...@@ -9,11 +9,10 @@
* - ops 永远只执行同一条固定命令,不发版前判断「用哪种模式」、也不填版本号; * - ops 永远只执行同一条固定命令,不发版前判断「用哪种模式」、也不填版本号;
* - 版本号由本命令自动解析,OPS 不接触: * - 版本号由本命令自动解析,OPS 不接触:
* * 有 releases/*.json 清单 → 取版本号最大的那份(清单模式,不比对 git); * * 有 releases/*.json 清单 → 取版本号最大的那份(清单模式,不比对 git);
* * 无清单(开发者忘了 gen)→ 取最新 git tag 作为版本(自动模式兜底),照样能发。 * * 无清单、有 git tag → 取最新 tag 为版本,git 分析只发改动的;
* * 无清单、无 tag(首次部署)→ 全量模式,扫描全部子系统 + 主壳一次打齐。
* - 「用不用清单」由开发者侧事实决定——releases/<version>.json 是否存在; * - 「用不用清单」由开发者侧事实决定——releases/<version>.json 是否存在;
* - 开发者若跑了 release:gen(或手写了清单)→ 命令走清单模式(release:spec,不比对 git); * - 三层兜底,ops 一条零参数命令在任何仓库状态下都能发版,永不卡住。
* - 开发者忘了 gen / 没建清单 → 命令自动降级到 git 分析模式(release:affected),照样能发,
* 不会卡住发版。
* *
* 本脚本只做「模式分发 + 版本解析」,不重复实现发版逻辑:解析后 spawn 对应的 * 本脚本只做「模式分发 + 版本解析」,不重复实现发版逻辑:解析后 spawn 对应的
* scripts/release/release-spec.mjs 或 scripts/release/release-affected.mjs,并把参数原样透传下去。 * scripts/release/release-spec.mjs 或 scripts/release/release-affected.mjs,并把参数原样透传下去。
...@@ -28,11 +27,6 @@ import { listSpecFiles, cmpVersion } from './release-spec.mjs'; ...@@ -28,11 +27,6 @@ import { listSpecFiles, cmpVersion } from './release-spec.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const SPECS_DIR = path.join(ROOT, 'releases'); const SPECS_DIR = path.join(ROOT, 'releases');
function die(message) {
console.error(`\n[release:run] ✗ ${message}\n`);
process.exit(1);
}
/** 取 --version(兼容 --version=1.3.0 与 --version 1.3.0 两种写法),无则 undefined。 */ /** 取 --version(兼容 --version=1.3.0 与 --version 1.3.0 两种写法),无则 undefined。 */
function pickVersion(argv) { function pickVersion(argv) {
for (let i = 0; i < argv.length; i += 1) { for (let i = 0; i < argv.length; i += 1) {
...@@ -55,11 +49,24 @@ function hasLatest(argv) { ...@@ -55,11 +49,24 @@ function hasLatest(argv) {
* - 其余参数(--base / --public-base / --out / --upload-cmd / --force / --skip-build / * - 其余参数(--base / --public-base / --out / --upload-cmd / --force / --skip-build /
* --dry-run / --verify)两种模式都能吃,原样透传。 * --dry-run / --verify)两种模式都能吃,原样透传。
*/ */
/**
* 预览类参数只有全量模式(release-all)认识;清单/自动模式没有预览阶段,
* 透传过去会因「未知参数」直接报错。这里剥离并提示,避免一条参数卡死发版。
*/
const PREVIEW_ONLY_ARGS = new Set(['--no-serve', '--no-open', '--port', '--no-verify']);
/** 这些参数各带一个取值,剥离时要连值一起跳过。 */
const ARGS_WITH_VALUE = new Set(['--port']);
function forwardArgs(argv, mode) { function forwardArgs(argv, mode) {
const out = []; const out = [];
for (let i = 0; i < argv.length; i += 1) { for (let i = 0; i < argv.length; i += 1) {
const t = argv[i]; const t = argv[i];
if (t === '--') continue; if (t === '--') continue;
if (PREVIEW_ONLY_ARGS.has(t) && mode !== 'all') {
console.log(`[release:run] 提示: ${t} 仅全量模式有效,本次(${mode} 模式)已忽略`);
if (ARGS_WITH_VALUE.has(t)) i += 1;
continue;
}
if (t === '--version' || t.startsWith('--version=')) { if (t === '--version' || t.startsWith('--version=')) {
if (mode === 'spec') { if (mode === 'spec') {
if (t.startsWith('--version=')) out.push(`--spec=${t.slice('--version='.length)}`); if (t.startsWith('--version=')) out.push(`--spec=${t.slice('--version='.length)}`);
...@@ -87,18 +94,21 @@ release:run —— 统一发版入口(ops 只跑这一条、零参数、永远 ...@@ -87,18 +94,21 @@ release:run —— 统一发版入口(ops 只跑这一条、零参数、永远
版本号自动解析(ops 不接触): 版本号自动解析(ops 不接触):
- releases/ 下有清单 → 取版本号最大的那份(清单模式,不比对 git) - releases/ 下有清单 → 取版本号最大的那份(清单模式,不比对 git)
- releases/ 下无清单(忘 gen)→ 取最新 git tag 为版本(自动模式兜底,照样能发) - 无清单、有 git tag → 取最新 tag 为版本,git 分析只发改动的(自动模式)
- 无清单、无 tag(首次部署) → 全量模式:扫描全部子系统 + 主壳一次打齐
模式由「清单文件是否存在」自动决定(开发者侧事实,ops 不决策): 模式自动判定(三层兜底,ops 永不卡住):
- releases/<ver>.json 存在 → 清单模式(release:spec,不比对 git) - releases/<ver>.json 存在 → 清单模式(release:spec,不比对 git)
- 不存在 → 自动模式(release:affected,git 分析兜底;忘了 gen 也能发) - 不存在但有 tag → 自动模式(release:affected,git 分析只发改动的)
- 都没有 → 全量模式(release:all,首次部署兜底)
透传选项(两种模式通用,ops 也一般不改): 透传选项(两种模式通用,ops 也一般不改):
--version <ver> 版本号(可选覆盖;即清单文件名 / 自动模式的 git tag 版本)。 --version <ver> 版本号(可选覆盖;即清单文件名 / 自动模式的 git tag 版本)。
--base <ref> 自动模式的 git 基线,默认 origin/master。 --base <ref> 自动模式的 git 基线,默认 origin/master。
--public-base <u> 产物公网基址(透传)。 --public-base <u> 产物公网基址(透传)。
--out <dir> 产物输出目录,默认 .release。 --out <dir> 产物目录,默认 dist。镜像部署根、每次发布重建,整棵树覆盖进部署目录即生效。
--upload-cmd <c> 上传钩子({dir}/{host}/{file} 占位);也可用 MFE_UPLOAD_CMD。 --state <dir> manifest 累积状态目录,默认 .release-state(或 MFE_STATE_DIR)。
--upload-cmd <c> 上传钩子({dir} 即产物根,一个变量覆盖部署根);也可用 MFE_UPLOAD_CMD。
--force 覆盖已存在版本目录 / 覆盖已有清单。 --force 覆盖已存在版本目录 / 覆盖已有清单。
--skip-build 复用已有 dist,不重新构建。 --skip-build 复用已有 dist,不重新构建。
--verify 清单模式下做 git 交叉校验(不符仅告警不阻断)。 --verify 清单模式下做 git 交叉校验(不符仅告警不阻断)。
...@@ -110,16 +120,13 @@ ops 再跑固定的 pnpm release:run 即可。忘了 gen 也没关系——命 ...@@ -110,16 +120,13 @@ ops 再跑固定的 pnpm release:run 即可。忘了 gen 也没关系——命
`); `);
} }
/** 无清单时,从最新 git tag 推断版本号(去掉前缀 v/V);拿不到则给开发者明确指引。 */ /** 无清单时,从最新 git tag 推断版本号(去掉前缀 v/V);拿不到返回 null(由调用方决定兜底方式)。 */
function resolveVersionFromGit() { function tryVersionFromGit() {
const res = spawnSync('git', ['describe', '--tags', '--abbrev=0'], { cwd: ROOT }); const res = spawnSync('git', ['describe', '--tags', '--abbrev=0'], { cwd: ROOT });
if (res.status === 0 && res.stdout && res.stdout.trim()) { if (res.status === 0 && res.stdout && res.stdout.trim()) {
return res.stdout.trim().replace(/^v/i, ''); return res.stdout.trim().replace(/^v/i, '');
} }
die( return null;
'未找到 releases/*.json 清单,且仓库无 git tag 可供推断版本。\n' +
'请开发者先运行 `pnpm release:gen --version X` 生成清单,或在发布 commit 上打 tag vX.Y.Z 后重试。',
);
} }
function main() { function main() {
...@@ -144,23 +151,35 @@ function main() { ...@@ -144,23 +151,35 @@ function main() {
mode = fs.existsSync(specFile) ? 'spec' : 'affected'; mode = fs.existsSync(specFile) ? 'spec' : 'affected';
} }
} else { } else {
// 零参数(OPS 固定命令):自动判定模式与版本 // 零参数(OPS 固定命令):自动判定模式与版本,三层兜底,永不 die 于「没清单」
const specs = listSpecFiles().sort((a, b) => cmpVersion(a.version, b.version)); const specs = listSpecFiles().sort((a, b) => cmpVersion(a.version, b.version));
if (specs.length > 0) { if (specs.length > 0) {
mode = 'spec'; // 下游用 --latest 取最大版本 mode = 'spec'; // 下游用 --latest 取最大版本
} else { } else {
const tagVersion = tryVersionFromGit();
if (tagVersion) {
mode = 'affected'; mode = 'affected';
resolvedVersion = resolveVersionFromGit(); resolvedVersion = tagVersion;
} else {
// 第三层兜底:无清单、无 tag —— 典型是首次部署(仓库刚建、还没人 gen 过)。
// 全量扫描 workspace,所有子系统 + 主壳一次打齐,保证 ops 一条命令永不卡住。
mode = 'all';
}
} }
} }
const child = mode === 'spec' ? 'scripts/release/release-spec.mjs' : 'scripts/release/release-affected.mjs'; const child =
mode === 'spec'
? 'scripts/release/release-spec.mjs'
: mode === 'affected'
? 'scripts/release/release-affected.mjs'
: 'scripts/release/release-all.mjs';
const childArgs = forwardArgs(argv, mode); const childArgs = forwardArgs(argv, mode);
// 零参数场景下补齐分发所需的版本/--latest 参数 // 零参数场景下补齐分发所需的版本/--latest 参数(all 模式版本号可省,默认 1.0.0)
if (!version && !latest) { if (!version && !latest) {
if (mode === 'spec') childArgs.push('--latest'); if (mode === 'spec') childArgs.push('--latest');
else childArgs.push('--version', resolvedVersion); else if (mode === 'affected') childArgs.push('--version', resolvedVersion);
} }
const label = const label =
...@@ -168,7 +187,9 @@ function main() { ...@@ -168,7 +187,9 @@ function main() {
? latest || !version ? latest || !version
? '清单模式(releases/ 最新版本,自动选取)' ? '清单模式(releases/ 最新版本,自动选取)'
: `清单模式(releases/${version}.json)` : `清单模式(releases/${version}.json)`
: '自动模式(git 分析兜底)'; : mode === 'affected'
? '自动模式(git 分析兜底)'
: '全量模式(无清单、无 git tag —— 首次部署兜底,扫描全部子系统 + 主壳)';
console.log(`[release:run] 模式: ${label}`); console.log(`[release:run] 模式: ${label}`);
if (mode === 'affected' && !version) { if (mode === 'affected' && !version) {
console.log(`[release:run] 自动版本: ${resolvedVersion}(取自最新 git tag)`); console.log(`[release:run] 自动版本: ${resolvedVersion}(取自最新 git tag)`);
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
* { * {
* "version": "1.3.0", // 可选;缺省取文件名 * "version": "1.3.0", // 可选;缺省取文件名
* "apps": ["system", "store"], // 要发的子系统(必须存在于 workspace) * "apps": ["system", "store"], // 要发的子系统(必须存在于 workspace)
* "host": false, // 主壳是否要重发(部署到站点根,非 /mfe/) * "host": false, // 主壳是否要重发(进 /mfe/host/<version>/,站点根只写指针)
* "note": "门店分页修复", // 备注(仅展示 / 历史留存) * "note": "门店分页修复", // 备注(仅展示 / 历史留存)
* "uploadCmd": "..." // 可选;不写则用 --upload-cmd 或 MFE_UPLOAD_CMD * "uploadCmd": "..." // 可选;不写则用 --upload-cmd 或 MFE_UPLOAD_CMD
* } * }
...@@ -27,20 +27,25 @@ import path from 'node:path'; ...@@ -27,20 +27,25 @@ import path from 'node:path';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { scanWorkspace, collectChangedFiles, computeAffected } from './release-affected.mjs'; 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 ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const SPECS_DIR = path.join(ROOT, 'releases'); const SPECS_DIR = path.join(ROOT, 'releases');
/** 日志前缀。release:all 复用本文件的 runRelease 时改成自己的标签,日志才不会互相串。 */
let TAG = 'release:spec';
function die(message) { function die(message) {
console.error(`\n[release:spec] ✗ ${message}\n`); console.error(`\n[${TAG}] ✗ ${message}\n`);
process.exit(1); process.exit(1);
} }
function info(message) { function info(message) {
console.log(`[release:spec] ${message}`); console.log(`[${TAG}] ${message}`);
} }
function parseArgs(argv) { function parseArgs(argv) {
const flags = new Set(['dry-run', 'force', 'help', 'skip-build', 'verify', 'latest']); const flags = new Set(['dry-run', 'force', 'no-force', 'help', 'skip-build', 'verify', 'latest']);
const out = {}; const out = {};
for (let i = 0; i < argv.length; i += 1) { for (let i = 0; i < argv.length; i += 1) {
const token = argv[i]; const token = argv[i];
...@@ -90,7 +95,9 @@ function loadSpec(args, microAppNames, shellName) { ...@@ -90,7 +95,9 @@ function loadSpec(args, microAppNames, shellName) {
if (!v) die('缺少 --spec <版本> 或 --latest。用 --help 查看用法。'); if (!v) die('缺少 --spec <版本> 或 --latest。用 --help 查看用法。');
fileName = v.endsWith('.json') ? v : `${v}.json`; fileName = v.endsWith('.json') ? v : `${v}.json`;
if (!fs.existsSync(path.join(SPECS_DIR, fileName))) { if (!fs.existsSync(path.join(SPECS_DIR, fileName))) {
die(`找不到清单文件 releases/${fileName}。可用:${specs.map((s) => s.file).join(', ') || '(无)'}`); die(
`找不到清单文件 releases/${fileName}。可用:${specs.map((s) => s.file).join(', ') || '(无)'}`,
);
} }
} }
...@@ -124,7 +131,8 @@ function verifySpec(spec, base, workspace) { ...@@ -124,7 +131,8 @@ function verifySpec(spec, base, workspace) {
const aff = computeAffected(changed, workspace); const aff = computeAffected(changed, workspace);
const warnings = []; const warnings = [];
for (const a of aff.affectedApps) { for (const a of aff.affectedApps) {
if (!spec.apps.includes(a)) warnings.push(`git 显示子系统 [${a}] 有改动,但清单未包含 → 可能漏发`); if (!spec.apps.includes(a))
warnings.push(`git 显示子系统 [${a}] 有改动,但清单未包含 → 可能漏发`);
} }
for (const a of spec.apps) { for (const a of spec.apps) {
if (!aff.affectedApps.includes(a)) if (!aff.affectedApps.includes(a))
...@@ -151,9 +159,11 @@ release:spec 芋撘ps 銵 ...@@ -151,9 +159,11 @@ release:spec 芋撘ps 銵
--base <ref> --verify 用的 git 基线,默认 origin/master --base <ref> --verify 用的 git 基线,默认 origin/master
--verify 发版前跑 git 反查交叉校验,清单与实改不符【仅告警不阻断】 --verify 发版前跑 git 反查交叉校验,清单与实改不符【仅告警不阻断】
--public-base <u> 子应用产物公网基址(透传给 release.mjs) --public-base <u> 子应用产物公网基址(透传给 release.mjs)
--out <dir> 产物输出目录,默认 .release(或 MFE_OUT_DIR) --out <dir> 产物目录,默认 dist(或 MFE_OUT_DIR)。它镜像部署根、
--upload-cmd <cmd> 上传钩子;支持 {dir}/{host}/{file} 占位。也可用 MFE_UPLOAD_CMD **每次发布重建**,只装本次要覆盖的文件,整棵树覆盖进部署目录即生效。
--force 允许覆盖已存在版本目录 --state <dir> manifest 累积状态目录,默认 .release-state(或 MFE_STATE_DIR)
--upload-cmd <cmd> 上传钩子;{dir} 即产物根(部署根镜像),{host} 为兼容别名。也可用 MFE_UPLOAD_CMD
--force 允许覆盖已发布过的同名版本目录
--skip-build 跳过构建,直接复用已有 dist(CI 已构建场景) --skip-build 跳过构建,直接复用已有 dist(CI 已构建场景)
--dry-run 只打印将执行的动作,不构建、不落盘、不上传 --dry-run 只打印将执行的动作,不构建、不落盘、不上传
--help 显示本帮助 --help 显示本帮助
...@@ -162,7 +172,7 @@ release:spec 芋撘ps 銵 ...@@ -162,7 +172,7 @@ release:spec 芋撘ps 銵
{ {
"version": "1.3.0", // 可选,缺省取文件名 "version": "1.3.0", // 可选,缺省取文件名
"apps": ["system", "store"], // 要发的子系统 "apps": ["system", "store"], // 要发的子系统
"host": false, // 主壳是否重发(站点根,非 /mfe/) "host": false, // 主壳是否重发(进 mfe/host/<version>/,站点根只写指针)
"note": "门店分页修复", // 备注 "note": "门店分页修复", // 备注
"uploadCmd": "..." // 可选,覆盖环境变量 "uploadCmd": "..." // 可选,覆盖环境变量
} }
...@@ -203,37 +213,139 @@ function main() { ...@@ -203,37 +213,139 @@ function main() {
} }
} }
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 isWin = process.platform === 'win32';
const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm'; const pnpmBin = isWin ? 'pnpm.cmd' : 'pnpm';
const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? '.release'); 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 publicBase = args['public-base'];
const out = args.out; const out = args.out;
const force = Boolean(args.force); /**
* 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 skipBuild = Boolean(args['skip-build']);
const uploadCmd = args['upload-cmd'] ?? spec.uploadCmd ?? process.env.MFE_UPLOAD_CMD; const uploadCmd = args['upload-cmd'] ?? spec.uploadCmd ?? process.env.MFE_UPLOAD_CMD;
const hostStaging = path.join(outRoot, '_host'); /**
* 线上清单地址,三级来源:CLI > 清单字段 remoteManifest > 环境变量。
* 清单字段最省事:清单入库后,任何同事拿到它都自动带上正确地址,
* 不依赖每台机器各自配 env。
*/
const remoteManifest =
args['remote-manifest'] ?? spec.remoteManifest ?? process.env.MFE_REMOTE_MANIFEST;
const dryRun = Boolean(args['dry-run']); const dryRun = Boolean(args['dry-run']);
/**
* 主壳的落点:/mfe/host/<version>/,与子应用的 /mfe/<app>/<version>/ 同构。
*
* 为什么不摊在站点根:站点根是唯一会被**原地覆盖**的地方。摊开时一次发布要逐个
* 覆盖 index.html 和一批 assets,在「HTML 已落地、JS 还没到」的几百毫秒里,线上
* 是新页面配旧资产 → 白屏 404,且窗口不可观测。版本化之后资产是整目录新增(原子),
* 站点根只覆盖 index.html 一个文件(单文件 rename 级原子),混合态消失。
* 顺带把「旧主壳 assets 散在根目录、覆盖式部署永不删除」这个坑一起收了。
*/
const hostRel = `mfe/host/${spec.version}/`;
const hostBase = `/${hostRel}`;
if (spec.apps.length === 0 && !spec.host) {
die('清单里既没有子系统也没有 host,没有可发布的内容。');
}
console.log('\n[release:spec] ==== 发布清单 ===='); // no-header:调用方(release:all)自己已经打过一份更贴场景的总览,这里不再重复一遍
console.log(` 清单文件 : ${spec.file}`); if (!args['no-header']) {
console.log(`\n[${TAG}] ==== 发版计划 ====`);
console.log(` 来源 : ${spec.file ?? '(全量,现场扫描 workspace)'}`);
console.log(` 版本 : ${spec.version}`); console.log(` 版本 : ${spec.version}`);
console.log(` 子系统 : ${spec.apps.length ? spec.apps.join(', ') : '(无)'}`); console.log(` 子系统 : ${spec.apps.length ? spec.apps.join(', ') : '(无)'}`);
console.log(` 主壳(host) : ${spec.host ? `是(${shellName})` : '否'}`); console.log(` 主壳(host) : ${spec.host ? `是(${shellName})` : '否'}`);
if (spec.note) console.log(` 备注 : ${spec.note}`); if (spec.note) console.log(` 备注 : ${spec.note}`);
if (remoteManifest)
console.log(` 线上清单 : ${remoteManifest}(增量合并 + 已发布判定以线上为准)`);
console.log(''); console.log('');
}
if (dryRun) { if (dryRun) {
console.log('[release:spec] --dry-run:以下动作不会执行。'); console.log(`[${TAG}] --dry-run:以下动作不会执行。`);
console.log(` 0. 重建产物目录 ${path.relative(ROOT, outRoot)}/(只装本次要覆盖的文件)`);
let step = 1; let step = 1;
for (const app of spec.apps) { for (const [i, app] of spec.apps.entries()) {
const cmd = [ const cmd = [
'node scripts/release/release.mjs', 'node scripts/release/release.mjs',
`--app ${app}`, `--app ${app}`,
`--version ${spec.version}`, `--version ${spec.version}`,
publicBase ? `--public-base ${publicBase}` : '', publicBase ? `--public-base ${publicBase}` : '',
out ? `--out ${out}` : '', out ? `--out ${out}` : '',
stateDir ? `--state ${stateDir}` : '',
force ? '--force' : '', force ? '--force' : '',
skipBuild ? '--skip-build' : '', skipBuild ? '--skip-build' : '',
i > 0 ? '--no-clean' : '',
] ]
.filter(Boolean) .filter(Boolean)
.join(' '); .join(' ');
...@@ -242,81 +354,120 @@ function main() { ...@@ -242,81 +354,120 @@ function main() {
} }
if (spec.host) { if (spec.host) {
console.log( console.log(
` ${step}. 主壳 ${shellName} 构建 → 暂存 ${path.relative(ROOT, hostStaging)} → 部署到站点根(非 /mfe/)`, ` ${step}. 主壳 ${shellName} 构建(SHELL_BASE=${hostBase})→ 整目录落 ${hostRel},根 index.html 只写指针`,
); );
step += 1; step += 1;
} }
console.log( console.log(
` ${step}. 一次性上传({dir}=${outRoot},{host}=${hostStaging}):${uploadCmd ?? '(未配置,仅产出入参)'}`, ` ${step}. 一次性上传({dir}=${outRoot} 覆盖部署根):${uploadCmd ?? '(未配置,仅产出入参)'}`,
); );
console.log(''); console.log('');
process.exit(0); 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'),
});
// ---- 逐个发版子系统 ---- // ---- 逐个发版子系统 ----
for (const app of spec.apps) { // 产物目录由**第一个**子应用负责清空(release.mjs 在构建与资源校验都过了才清),
// 后续一律 --no-clean 共用同一份产物树 —— 否则后一个会把前一个的产物删掉。
for (const [i, app] of spec.apps.entries()) {
info(`发版子系统 ${app}(${spec.version})...`); info(`发版子系统 ${app}(${spec.version})...`);
const cmd = ['node', 'scripts/release/release.mjs', '--app', app, '--version', spec.version]; const cmd = ['node', 'scripts/release/release.mjs', '--app', app, '--version', spec.version];
if (publicBase) cmd.push('--public-base', publicBase); if (publicBase) cmd.push('--public-base', publicBase);
if (out) cmd.push('--out', out); if (out) cmd.push('--out', out);
if (stateDir) cmd.push('--state', stateDir);
if (force) cmd.push('--force'); if (force) cmd.push('--force');
if (skipBuild) cmd.push('--skip-build'); 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' }); const res = spawnSync(cmd[0], cmd.slice(1), { cwd: ROOT, stdio: 'inherit' });
if (res.status !== 0) die(`子系统 ${app} 发版失败(exit ${res.status}),已中止,未执行上传。`); if (res.status !== 0) die(`子系统 ${app} 发版失败(exit ${res.status}),已中止,未执行上传。`);
} }
// ---- 主壳(host)按清单 host 标志部署到站点根 ---- // 只发主壳时没有子应用负责清空,这里补一次(产物根只装主壳产物)。
if (spec.host) { if (spec.apps.length === 0) {
if (!shellName) die('未找到主壳包(apps/web/shell),无法部署 host。'); fs.rmSync(outRoot, { recursive: true, force: true });
info(`主壳 ${shellName} 部署到站点根(非 /mfe/)...`); fs.mkdirSync(outRoot, { recursive: true });
const shellMeta = workspace.pkgs.get(shellName); info(`产物目录已重建:${path.relative(ROOT, outRoot)}/`);
const shellDist = path.join(ROOT, shellMeta.dir, 'dist');
if (skipBuild) {
if (!fs.existsSync(path.join(shellDist, 'index.html'))) {
die(`--skip-build 但找不到 ${path.relative(ROOT, shellDist)}/index.html;先构建或去掉 --skip-build。`);
} }
} else {
const bres = spawnSync(pnpmBin, ['--filter', shellName, 'build'], { // ---- 主壳(host)→ /mfe/host/<version>/,站点根只放一个指针 index.html ----
cwd: ROOT, // 实现抽在 host-deploy.mjs:release:affected 走同一条链路,避免两处行为分叉。
stdio: 'inherit', if (spec.host) {
shell: isWin, deployHost({
env: process.env, root: ROOT,
outRoot,
version: spec.version,
shellName,
workspace: workspace.pkgs,
skipBuild,
pnpmBin,
isWin,
info,
die,
}); });
if (bres.error) die(`启动 pnpm 失败:${bres.error.message}`);
if (bres.status !== 0) die(`主壳构建失败(exit ${bres.status}),未执行上传。`);
}
fs.rmSync(hostStaging, { recursive: true, force: true });
fs.mkdirSync(hostStaging, { recursive: true });
fs.cpSync(shellDist, hostStaging, { recursive: true });
info(`主壳产物已暂存到 ${path.relative(ROOT, hostStaging)}`);
} }
// 主壳未列入清单 → 清掉暂存,避免 {dir} 同步时把旧 _host 误传到站点根 // 主壳未列入清单 → 产物根不会有它的文件(目录已重建),无需额外清理
if (!spec.host) fs.rmSync(hostStaging, { recursive: true, force: true });
// ---- 一次性上传(子应用走 {dir}/mfe,主壳走 {host} 到站点根)---- // ---- 构建指纹:产物离开构建机后,这是唯一的溯源凭据 ----
if (uploadCmd) {
const manifestFile = path.join(outRoot, 'mfe', 'manifest.json'); const manifestFile = path.join(outRoot, 'mfe', 'manifest.json');
const buildInfo = writeBuildInfo({
root: ROOT,
outRoot,
releaseVersion: spec.version,
apps: spec.apps,
hostRel: spec.host ? hostRelOf(spec.version) : 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 信息)'),
);
// ---- 一次性上传:产物是一棵镜像部署根的树,{dir} 一个变量覆盖过去 ----
if (uploadCmd) {
const template = String(uploadCmd); const template = String(uploadCmd);
if (!/\{(?:dir|file|host)\}/.test(template)) { if (!/\{dir\}/.test(template)) {
info('⚠ 上传钩子未包含 {dir}/{file}/{host}:请确认 manifest 与 host 都会被上传,否则发布不生效。'); info('⚠ 上传钩子未包含 {dir}:产物是镜像部署根的一棵树,一个 {dir} 覆盖过去即可。');
} }
const cmd = template const cmd = template
.replaceAll('{dir}', outRoot) .replaceAll('{dir}', outRoot)
.replaceAll('{target}', outRoot) .replaceAll('{target}', outRoot)
.replaceAll('{remote}', '') .replaceAll('{remote}', '')
.replaceAll('{host}', hostStaging) .replaceAll('{host}', outRoot) // 兼容旧钩子:主壳已落在产物根
.replaceAll('{file}', manifestFile); .replaceAll('{file}', manifestFile);
info(`执行一次性上传钩子:${cmd}`); info(`执行一次性上传钩子:${cmd}`);
const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true }); const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true });
if (res.status !== 0) if (res.status !== 0)
die(`上传失败(exit ${res.status})。各子系统与 host 已落盘到 ${outRoot},远端尚未生效。`); die(`上传失败(exit ${res.status})。各子系统与 host 已落盘到 ${outRoot},远端尚未生效。`);
} }
fs.rmSync(hostStaging, { recursive: true, force: true });
console.log('\n[release:spec] ==== 完成 ===='); console.log(`\n[${TAG}] ==== 完成 ====`);
console.log(` 已发版子系统: ${spec.apps.length ? spec.apps.join(', ') : '(无)'} @ ${spec.version}`); console.log(
if (spec.host) console.log(` 主壳(host) : ${shellName} 已部署到站点根`); ` 已发版子系统: ${spec.apps.length ? spec.apps.join(', ') : '(无)'} @ ${spec.version}`,
console.log(' 发布生效:浏览器必须【整页刷新】;manifest.json 与 host index.html 建议 no-cache。'); );
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(''); console.log('');
} }
...@@ -325,4 +476,4 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me ...@@ -325,4 +476,4 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
main(); main();
} }
export { loadSpec, verifySpec, cmpVersion, listSpecFiles }; export { loadSpec, verifySpec, cmpVersion, listSpecFiles, runRelease };
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { startStaticServer } from './static-server.mjs';
/**
* 部署自检 —— 回答一个问题:「这次发的东西,用户真的能打开吗?」
*
* 发版脚本只管把产物摆对位置,管不到线上。最常见的三类事故都发生在部署之后:
* 1. 清单传上去了,但它指向的版本目录没传(或传错层级)→ 业务模块全 404;
* 2. 目录对了,但 index.html 里的资源前缀与清单里的 url 不一致 → 白屏且零报错;
* 3. 主壳 index.html 或 manifest.json 被缓存 → 发了等于没发。
* 这三类都不报错、只是用户点不开,所以必须有一条命令能主动查出来。
*
* node scripts/release/release-verify.mjs --serve dist # 传之前先验产物
* node scripts/release/release-verify.mjs --base https://console.x.com # 传之后验线上
*
* 两种模式跑同一套检查:本地模式在 127.0.0.1 起一个内置静态服务(无任何依赖),
* 所以「本地能过」和「线上能过」的判定口径完全一致,不存在两套逻辑漂移。
*
* 唯一的判定差异是「清单里的某个版本目录取不到」:
* 线上 → 失败(清单指向了不存在的目录,用户必然点不开)
* 本地 → 警告(本次产物只装本次内容,旧版本本来就不在本地,线上保留着)
*/
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
const paint = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const green = paint('32');
const red = paint('31');
const yellow = paint('33');
const dim = paint('2');
const bold = paint('1');
const cyan = paint('36');
/** CJK 按 2 列算,否则中文列名会把后续对齐全部推歪。 */
function width(s) {
let n = 0;
for (const ch of String(s)) {
const c = ch.codePointAt(0) ?? 0;
n +=
(c >= 0x1100 && c <= 0x115f) ||
(c >= 0x2e80 && c <= 0xa4cf) ||
(c >= 0xac00 && c <= 0xd7a3) ||
(c >= 0xf900 && c <= 0xfaff) ||
(c >= 0xfe30 && c <= 0xfe6f) ||
(c >= 0xff00 && c <= 0xff60) ||
(c >= 0xffe0 && c <= 0xffe6)
? 2
: 1;
}
return n;
}
function padEnd(s, w) {
const gap = w - width(s);
return gap > 0 ? String(s) + ' '.repeat(gap) : String(s);
}
function parseArgs(argv) {
const flags = new Set(['help']);
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === '--') continue;
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 die(message) {
console.error(`\n[verify] ${red('✗')} ${message}\n`);
process.exit(1);
}
const HELP = `
[verify] 部署自检 —— 验证清单与清单指向的每个版本目录真的可访问
用法:
node scripts/release/release-verify.mjs --serve <dir> 验本地产物(内置静态服务,不需上传)
node scripts/release/release-verify.mjs --base <url> 验已部署的站点
参数:
--base <url> 站点根地址,例如 https://console.example.com(也可用 MFE_VERIFY_BASE)
带子路径时写全:https://example.com/console
--serve <dir> 本地静态目录,一般是 dist(也可用 MFE_VERIFY_SERVE)
--manifest <p> 清单路径或完整 URL,默认 /mfe/manifest.json
--app <name> 只验指定子应用(逗号分隔),用于快速排查单个模块
--timeout <ms> 单请求超时,默认 8000
--help 显示本帮助
检查项(任一失败即退出码 1):
1. 清单可访问且是合法 JSON,含 subapps
2. 每个子应用的 url 能取到 index.html(200 + text/html)
3. index.html 里的每个资源引用的路径前缀与清单 url 一致(不一致 = 白屏无报错)
4. 每个资源引用真的可访问(200)
5. 主壳 / 与它的资源可访问
6. 线上清单响应 Cache-Control 是否 no-cache(不满足只告警,因为可能被 CDN 覆盖)
`;
// ---------------------------------------------------------------------------
async function probe(url, timeoutMs, { readBody = false } = {}) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' });
const ctype = res.headers.get('content-type') ?? '';
const cache = res.headers.get('cache-control') ?? '';
let body = '';
if (readBody && res.ok) body = await res.text();
else await res.body?.cancel();
return { ok: res.ok, status: res.status, ctype, cache, body, error: null };
} catch (err) {
return { ok: false, status: 0, ctype: '', cache: '', body: '', error: err.message };
}
}
/** 从 index.html 里取 src/href,过滤外链、data:、锚点与预连接。 */
function extractRefs(html) {
const refs = new Set();
const re = /(?:src|href)\s*=\s*["']([^"']+)["']/gi;
let m;
while ((m = re.exec(html))) {
const raw = m[1].trim();
if (!raw) continue;
if (/^(?:https?:)?\/\//i.test(raw)) {
// 绝对地址(CDN 部署)也验,但后面跳过前缀比对
refs.add(raw);
continue;
}
if (raw.startsWith('data:') || raw.startsWith('#') || raw.startsWith('mailto:')) continue;
refs.add(raw);
}
return [...refs];
}
function resolveUrl(base, ref) {
if (/^https?:\/\//i.test(ref)) return ref;
if (ref.startsWith('//')) return `${base.startsWith('https') ? 'https' : 'http'}:${ref}`;
const root = base.replace(/\/+$/, '');
return `${root}${ref.startsWith('/') ? '' : '/'}${ref}`;
}
/**
* 资源是否真的拿到了资源本体。
*
* 只判 200 是不够的:nginx 少了 `^~ /mfe/` 这道 location,或者主壳 SPA 回落配得太宽,
* 缺失的 js 会返回 200 + 主壳的 index.html,浏览器报 `Unexpected token '<'`。
* 把「请求的不是 HTML 却收到 HTML」判成失败,才抓得到这类配错。
*/
function isAssetHit(res, ref) {
if (!res.ok) return false;
if (/\.html?(?:$|\?)/i.test(ref)) return true;
return !res.ctype.includes('text/html');
}
function assetFailure(res, ref) {
if (res.error) return res.error;
if (!res.ok) return `HTTP ${res.status}`;
if (res.ctype.includes('text/html') && !/\.html?(?:$|\?)/i.test(ref)) {
return '拿到 HTML(被 SPA 回落吃掉了,nginx 的 /mfe/ location 需要 try_files ... =404)';
}
return `HTTP ${res.status}`;
}
function pathOf(value, base) {
if (/^https?:\/\//i.test(value)) {
try {
return new URL(value).pathname;
} catch {
return value;
}
}
try {
return new URL(value, base).pathname;
} catch {
return value;
}
}
// ---------------------------------------------------------------------------
async function main() {
const argv = process.argv.slice(2);
if (argv.includes('--help') || argv.includes('-h')) {
console.log(HELP);
return;
}
const args = parseArgs(argv);
const timeoutMs = Number(args.timeout ?? 8000);
const serveDir = args.serve ?? process.env.MFE_VERIFY_SERVE ?? null;
const baseArg = args.base ?? process.env.MFE_VERIFY_BASE ?? null;
const manifestArg = args.manifest ?? '/mfe/manifest.json';
const onlyApps = args.app
? String(args.app)
.split(',')
.map((s) => s.trim())
.filter(Boolean)
: null;
if (!serveDir && !baseArg) {
console.error(HELP);
die('必须给一个目标:--serve <dir>(验本地产物)或 --base <url>(验线上)');
}
const local = Boolean(serveDir);
let server = null;
let base = baseArg;
if (local) {
const dir = path.resolve(ROOT, serveDir);
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
die(`--serve 指向的目录不存在:${dir}`);
}
const started = await startStaticServer(dir);
server = started.server;
base = `http://127.0.0.1:${started.port}`;
console.log(
`\n[verify] ${bold('本地模式')} ${dim('产物')} ${path.relative(ROOT, dir) || '.'} ${dim('→')} ${cyan(base)}`,
);
} else {
base = String(base).replace(/\/+$/, '');
console.log(`\n[verify] ${bold('线上模式')} ${dim('目标')} ${cyan(base)}`);
}
const errors = [];
const warns = [];
let passes = 0;
const line = (ok, label, detail) => {
const mark = ok === true ? green('✓') : ok === false ? red('✗') : dim('·');
console.log(` ${mark} ${padEnd(label, 40)} ${detail}`);
};
// ---- 1. 清单 ----
const manifestUrl = resolveUrl(base, manifestArg);
const man = await probe(manifestUrl, timeoutMs, { readBody: true });
if (!man.ok) {
line(false, manifestArg, man.error ? red(man.error) : red(`HTTP ${man.status}`));
errors.push(`清单取不到:${manifestUrl}`);
finish({ errors, warns, passes, server, local });
return;
}
let manifest;
try {
manifest = JSON.parse(man.body);
} catch (err) {
line(false, manifestArg, red(`不是合法 JSON:${err.message}`));
errors.push('清单解析失败');
finish({ errors, warns, passes, server, local });
return;
}
if (!manifest.subapps || typeof manifest.subapps !== 'object') {
line(false, manifestArg, red('缺少 subapps 字段'));
errors.push('清单结构不对');
finish({ errors, warns, passes, server, local });
return;
}
passes += 1;
const names = Object.keys(manifest.subapps);
line(
true,
manifestArg,
`${dim('200')} ${dim('version=')}${manifest.version ?? '?'} ${dim('子应用')} ${names.join(', ') || '(无)'}`,
);
// 缓存头只对线上有意义:本地服务器的头是脚本自己设的,验它属于自证。
if (!local && man.cache && !/no-cache|no-store|max-age=0/i.test(man.cache)) {
warns.push(`清单 Cache-Control 是 "${man.cache}",应设 no-cache,否则发布可能被浏览器缓存卡住`);
}
const targets = names.filter((n) => !onlyApps || onlyApps.includes(n));
if (onlyApps && targets.length === 0) {
errors.push(`--app 指定的 ${onlyApps.join(',')} 不在清单里(清单只有 ${names.join(',')})`);
finish({ errors, warns, passes, server, local });
return;
}
// ---- 2. 每个子应用 ----
for (const name of targets) {
const entry = manifest.subapps[name] ?? {};
const appUrl = typeof entry.url === 'string' ? entry.url : '';
console.log('');
if (!appUrl) {
line(false, name, red('清单条目缺少 url'));
errors.push(`${name}: 清单条目缺少 url`);
continue;
}
const page = await probe(resolveUrl(base, appUrl), timeoutMs, { readBody: true });
const isHtml = page.ctype.includes('text/html');
if (!page.ok || !isHtml) {
const why = page.error
? red(page.error)
: red(`HTTP ${page.status}${page.ok ? ` ${page.ctype || '无 content-type'}` : ''}`);
if (local) {
// 本地产物只装本次内容,旧版本不在本地是正常的;线上必须存在。
line(
null,
`${name} ${appUrl}`,
`${yellow('本地无此版本')} ${dim('(线上应保留,覆盖后仍在)')}`,
);
warns.push(`${name}: 本地产物里没有 ${appUrl}(本次未发布该应用,属正常)`);
} else {
line(false, `${name} ${appUrl}`, why);
errors.push(
`${name}: ${appUrl} 取不到 index.html(${page.error ?? `HTTP ${page.status}`})`,
);
}
continue;
}
line(true, `${name} ${appUrl}`, `${dim('200')} ${dim(`v${entry.version ?? '?'}`)}`);
passes += 1;
// 2a. 资源前缀必须与清单 url 一致 —— 这是「白屏无报错」的唯一征兆
const refs = extractRefs(page.body);
const appPath = pathOf(appUrl, base);
const normalize = (p) => (p.endsWith('/') ? p : `${p}/`);
const prefix = normalize(appPath);
const mismatched = [];
for (const ref of refs) {
if (/^https?:\/\//i.test(ref)) continue; // CDN 绝对地址,前缀规则不同,只验可达
const refPath = pathOf(ref, base);
if (!refPath.startsWith(prefix)) mismatched.push(`${ref} ${dim(`(应为 ${prefix}…)`)}`);
}
if (mismatched.length > 0) {
for (const item of mismatched.slice(0, 5)) line(false, ' 资源前缀不一致', red(item));
errors.push(
`${name}: index.html 里有 ${mismatched.length} 个资源不以 ${prefix} 开头(构建期 SUBAPP_BASE 与清单版本不匹配,线上必然白屏)`,
);
} else {
line(true, ' 资源前缀', `${dim(`${refs.length} 个引用,全部以 ${prefix} 开头`)}`);
passes += 1;
}
// 2b. 每个资源真的可访问
let missing = 0;
const checked = [];
for (const ref of refs) {
const url = resolveUrl(base, ref);
const res = await probe(url, timeoutMs);
if (!isAssetHit(res, ref)) {
missing += 1;
if (checked.length < 5) checked.push(`${ref} → ${assetFailure(res, ref)}`);
}
}
if (missing > 0) {
for (const item of checked) line(false, ' 资源缺失', red(item));
errors.push(`${name}: ${missing}/${refs.length} 个资源引用取不到`);
} else {
line(true, ' 资源可达', `${dim(`${refs.length}/${refs.length}`)}`);
passes += 1;
}
}
// ---- 3. 主壳 ----
console.log('');
const root = await probe(`${base}/`, timeoutMs, { readBody: true });
const rootIsHtml = root.ctype.includes('text/html');
if (!root.ok || !rootIsHtml) {
const why = root.error ? red(root.error) : red(`HTTP ${root.status}`);
if (local) {
line(
null,
'主壳 /index.html',
`${yellow('本地产物无主壳')} ${dim('(本次未改 host,线上旧主壳保留)')}`,
);
warns.push('本地产物里没有主壳 index.html(本次未重建主壳,属正常)');
} else {
line(false, '主壳 /index.html', why);
errors.push(`主壳取不到:${why}`);
}
} else {
const rootRefs = extractRefs(root.body);
let missing = 0;
const checked = [];
for (const ref of rootRefs) {
const res = await probe(resolveUrl(base, ref), timeoutMs);
if (!isAssetHit(res, ref)) {
missing += 1;
if (checked.length < 5) checked.push(`${ref} → ${assetFailure(res, ref)}`);
}
}
if (missing > 0) {
line(false, '主壳 /index.html', red(`${missing}/${rootRefs.length} 个资源取不到`));
for (const item of checked) line(false, ' 资源缺失', red(item));
errors.push(`主壳 ${missing}/${rootRefs.length} 个资源引用取不到`);
} else {
line(true, '主壳 /index.html', `${dim('200')} ${dim(`${rootRefs.length} 个资源均可访问`)}`);
passes += 1;
}
if (!local && root.cache && !/no-cache|no-store|max-age=0/i.test(root.cache)) {
warns.push(`主壳 index.html 的 Cache-Control 是 "${root.cache}",建议 no-cache`);
}
// 3b. 入口 js 里引用的其它 chunk
// 主壳是多 chunk 的:index.html 只引入口 js/css,其余 chunk 由入口 js 用
// 「base + assets/xxx-<hash>.js」拼出来按需加载。它们 404 时首屏完全正常、
// 点开某个功能才炸 —— 只看 index.html 的自检会给绿灯,这里补上这一层。
const entryJs = rootRefs.find((ref) => /assets\/[^/]+\.js(?:$|\?)/i.test(ref));
const assetPrefix = entryJs ? entryJs.slice(0, entryJs.lastIndexOf('assets/')) : null;
if (assetPrefix) {
const chunks = new Set();
for (const ref of rootRefs.filter((r) => /\.m?js(?:$|\?)/i.test(r))) {
const res = await probe(resolveUrl(base, ref), timeoutMs, { readBody: true });
if (!res.ok || !res.body) continue;
for (const m of res.body.matchAll(/assets\/[A-Za-z0-9_-]+\.(?:js|css)/g)) {
chunks.add(m[0]);
if (chunks.size >= 40) break; // 防御:异常产物里可能有海量字符串
}
}
const broken = [];
for (const chunk of chunks) {
const url = `${assetPrefix}${chunk}`;
const res = await probe(resolveUrl(base, url), timeoutMs);
if (!isAssetHit(res, url) && broken.length < 5)
broken.push(`${url} → ${assetFailure(res, url)}`);
}
if (broken.length > 0) {
for (const item of broken) line(false, ' 入口 chunk 缺失', red(item));
errors.push(`主壳入口 js 引用的 ${broken.length}+ 个 chunk 取不到(首屏正常、点功能才炸)`);
} else if (chunks.size > 0) {
line(true, ' 入口 chunk', `${dim(`${chunks.size} 个引用均可访问`)}`);
passes += 1;
}
}
// 主壳能否拿到清单地址,是「点进去全挂」的根因。
// 注意它不在 index.html 里 —— Vite 把 import.meta.env 内联进打包后的 js 常量,
// 所以必须去主壳的 js 里搜,而不是搜 HTML。
if (!local) {
const needle = manifestArg.replace(/^\//, '');
const jsRefs = rootRefs.filter((ref) => /\.m?js(?:$|\?)/i.test(ref));
let found = false;
for (const ref of jsRefs) {
const res = await probe(resolveUrl(base, ref), timeoutMs, { readBody: true });
if (res.ok && res.body.includes(needle)) {
found = true;
break;
}
}
if (!found) {
warns.push(
`主壳产物里搜不到 "${needle}"(VITE_MANIFEST_URL 可能没注入):` +
'它启动时不会拉清单,entryOf() 会回落到 localhost 并被生产环境判为无效入口,' +
'症状是主壳能开、点业务模块全是「未找到子应用入口」',
);
}
}
}
finish({ errors, warns, passes, server, local });
}
function finish({ errors, warns, passes, server, local }) {
console.log('');
const total = `${green(`${passes} 通过`)}`;
const bad = errors.length > 0 ? red(`${errors.length} 失败`) : dim('0 失败');
const warn = warns.length > 0 ? yellow(`${warns.length} 警告`) : dim('0 警告');
console.log(`[verify] 结果:${total},${bad},${warn}${local ? dim('(本地模式)') : ''}`);
if (warns.length > 0) {
console.log('');
for (const w of warns) console.log(` ${yellow('!')} ${w}`);
}
if (errors.length > 0) {
console.log('');
for (const e of errors) console.log(` ${red('✗')} ${e}`);
console.log('');
console.log(dim(' 排查顺序:① 清单里 url 指向的目录在部署根上是否真的存在'));
console.log(dim(' ② 该目录里 index.html 的资源前缀是否与 url 一致'));
console.log(dim(' ③ nginx 是否把 /mfe/ 的 404 回落成了主壳 index.html'));
console.log('');
}
if (server) {
// keep-alive 连接会让 close 的回调姗姗来迟,进程退出不必等它收尾
server.close();
}
process.exit(errors.length > 0 ? 1 : 0);
}
main().catch((err) => {
die(err.stack ?? err.message);
});
...@@ -3,6 +3,8 @@ import fs from 'node:fs'; ...@@ -3,6 +3,8 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { writeBuildInfo } from './build-info.mjs';
import { mergeRemoteManifest } from './remote-manifest.mjs';
/** /**
* 单模块发版 —— 「只改了 system,就只发 system」的可执行入口。 * 单模块发版 —— 「只改了 system,就只发 system」的可执行入口。
...@@ -18,6 +20,22 @@ import { fileURLToPath } from 'node:url'; ...@@ -18,6 +20,22 @@ import { fileURLToPath } from 'node:url';
* 不自动上传:脚本只产出「待上传目录」,通过 --upload-cmd 交给实际制品库/CDN。 * 不自动上传:脚本只产出「待上传目录」,通过 --upload-cmd 交给实际制品库/CDN。
* 这样不把任何基础设施假设写进仓库。 * 这样不把任何基础设施假设写进仓库。
* *
* ── 产物语义(v2:产物树 = 部署树的剪影)────────────────────────────
* <out>(默认 dist)里的**每一次发布都重建**,只装本次要覆盖的文件:
* 改了 system → <out>/ 只有 mfe/system/<ver>/ 与 mfe/manifest.json
* 改了主壳 → <out>/ 根有 index.html(指针)+ mfe/host/<ver>/(主壳实体,不进 mfe/<app>/)
* 运维把 <out>/ 整棵树覆盖进部署根即可,未出现在产物里的模块保持线上老版本。
*
* 代价:本地不再残留历史版本目录,所以「同名版本不可覆盖」这条不变量没法靠
* 检查目录存在来判断,改为记在 state 文件的 published 里(见下)。
*
* ── 状态与产物分离 ───────────────────────────────────────────────────
* manifest 是**增量状态**(只改目标应用那一条,其余原样保留),它不能住在会被
* 重建的产物目录里,因此外移到 <state>(默认 .release-state,MFE_STATE_DIR 可覆盖):
* <state>/manifest.json = { version, updatedAt, subapps, published: { app: [版本...] } }
* <out>/mfe/manifest.json = 只含 { version, updatedAt, subapps }(运行时真正拉的那份)
* published 记录「已对外发布过的版本」,用来在产物重建后仍能拦住同名覆盖。
*
* 回滚 / 灰度不重建:--switch-only 1.2.0 只改清单,把 URL 指回旧版本目录。 * 回滚 / 灰度不重建:--switch-only 1.2.0 只改清单,把 URL 指回旧版本目录。
*/ */
...@@ -25,7 +43,15 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '. ...@@ -25,7 +43,15 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.
const MICRO_ROOT = path.join(ROOT, 'apps', 'web', 'subapps'); const MICRO_ROOT = path.join(ROOT, 'apps', 'web', 'subapps');
function parseArgs(argv) { function parseArgs(argv) {
const flags = new Set(['dry-run', 'skip-build', 'switch-only', 'force', 'help']); const flags = new Set([
'dry-run',
'skip-build',
'switch-only',
'force',
'help',
'no-clean',
'quiet',
]);
const out = {}; const out = {};
for (let i = 0; i < argv.length; i += 1) { for (let i = 0; i < argv.length; i += 1) {
const token = argv[i]; const token = argv[i];
...@@ -67,18 +93,27 @@ function printHelp() { ...@@ -67,18 +93,27 @@ function printHelp() {
--version <ver> 版本号,如 1.2.0 / 1.2.0-beta.1 / <commit-sha>(必填) --version <ver> 版本号,如 1.2.0 / 1.2.0-beta.1 / <commit-sha>(必填)
--public-base <url> 产物对外根地址,默认同源 ''。 --public-base <url> 产物对外根地址,默认同源 ''。
例如 https://cdn.example.com 会生成该域名下的 /mfe/... URL 例如 https://cdn.example.com 会生成该域名下的 /mfe/... URL
--out <dir> 待上传目录,默认 .release(建议加进 .gitignore) --out <dir> 产物目录,默认 dist。它镜像部署根、**每次发布重建**,
只装本次要覆盖的文件;运维把整棵树覆盖进部署目录即可。
--state <dir> manifest 累积状态目录,默认 .release-state(或 MFE_STATE_DIR)。
含已发布版本记账,产物重建后仍能拦住同名覆盖。
--skip-build 复用已有 dist,不重新构建(CI 里 build job 已构建时用) --skip-build 复用已有 dist,不重新构建(CI 里 build job 已构建时用)
--switch-only 只改 manifest,不构建不复制;用于回滚 / 灰度 --switch-only 只改清单,不构建不复制;用于回滚 / 灰度
--upload-cmd <cmd> 上传钩子,模板变量见下,例如 --upload-cmd <cmd> 上传钩子,模板变量见下,例如
"aws s3 sync {dir} s3://bucket/ --exclude '*' ..." "rsync -a {dir}/ /srv/www/"
也可用环境变量 MFE_UPLOAD_CMD 提供。 也可用环境变量 MFE_UPLOAD_CMD 提供。
{dir} 待上传根(含 mfe/manifest.json 与所有版本目录) {dir} 产物根(= 部署根镜像,主壳在根、子应用在 mfe/ 下)
{host} {dir} 的别名,仅为兼容旧钩子保留
{target} 本次单个版本目录 {target} 本次单个版本目录
{remote} 远端相对路径 mfe/<app>/<version>/ {remote} 远端相对路径 mfe/<app>/<version>/
{file} manifest.json 本地路径 {file} manifest.json 本地路径
⚠ 钩子必须覆盖 manifest.json,否则清单不更新、发布不生效。 ⚠ 钩子必须覆盖 manifest.json,否则清单不更新、发布不生效。
--force 允许覆盖已存在的版本目录(默认禁止,不可变产物) --remote-manifest <url>
线上清单地址(也可用 MFE_REMOTE_MANIFEST)。配了就发布前先拉一次
线上清单做合并基线:本次没发的 app 以线上为准,避免并发发版时
后上传的那份把先发的条目覆盖掉。拉取失败只告警不阻断。
--force 允许覆盖已发布过的同名版本(默认禁止,回滚依赖旧目录内容不变)
--no-clean 内部用:不清空产物目录(由外层 release:spec/affected 统一清一次)
--dry-run 只打印计划,不构建、不写文件、不上传 --dry-run 只打印计划,不构建、不写文件、不上传
--help 显示本帮助 --help 显示本帮助
...@@ -125,28 +160,78 @@ const publicBase = String(args['public-base'] ?? process.env.MFE_PUBLIC_BASE ?? ...@@ -125,28 +160,78 @@ const publicBase = String(args['public-base'] ?? process.env.MFE_PUBLIC_BASE ??
'', '',
); );
const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD; const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD;
/**
* 线上清单地址。配了就先拉一次做合并基线,把「并发发版互相覆盖」的窗口从
* 整个过程压缩到上传的几秒。不配则行为不变(纯本地状态)。
*/
const remoteManifestUrl = args['remote-manifest'] ?? process.env.MFE_REMOTE_MANIFEST;
const remotePath = `mfe/${app}/${version}/`; const remotePath = `mfe/${app}/${version}/`;
const remoteDir = `${publicBase}/${remotePath}`; // '/mfe/system/1.2.0/' 或 'https://cdn/.../mfe/system/1.2.0/' const remoteDir = `${publicBase}/${remotePath}`; // '/mfe/system/1.2.0/' 或 'https://cdn/.../mfe/system/1.2.0/'
const subappBase = remoteDir; // 直接作为 Vite base,产物资源路径与最终 URL 同源同前缀 const subappBase = remoteDir; // 直接作为 Vite base,产物资源路径与最终 URL 同源同前缀
const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? '.release'); const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? 'dist');
const stateDir = path.resolve(ROOT, args.state ?? process.env.MFE_STATE_DIR ?? '.release-state');
const targetDir = path.join(outRoot, 'mfe', app, version); const targetDir = path.join(outRoot, 'mfe', app, version);
const manifestFile = path.join(outRoot, 'mfe', 'manifest.json'); const manifestFile = path.join(outRoot, 'mfe', 'manifest.json'); // 产物里的快照(运行时拉这份)
const stateFile = path.join(stateDir, 'manifest.json'); // 累积状态(含已发布版本),不进产物
const distDir = path.join(appDir, 'dist'); const distDir = path.join(appDir, 'dist');
const switchOnly = Boolean(args['switch-only']); const switchOnly = Boolean(args['switch-only']);
const dryRun = Boolean(args['dry-run']); const dryRun = Boolean(args['dry-run']);
const skipBuild = Boolean(args['skip-build']) || switchOnly; const skipBuild = Boolean(args['skip-build']) || switchOnly;
/**
* --quiet:被 release:spec / release:all 批量调用时用。
* 批量入口自己会打印清单级的总览,子进程再各打一份「发版计划 + 三步提醒」就是纯噪音
* (3 个应用 ≈ 50 行,真正有用的端口/产物信息被淹没)。失败路径不受影响。
*/
const quiet = Boolean(args.quiet);
/** quiet 下的静默 info:只丢掉过程性提示,失败仍走 die。 */
const say = quiet ? () => {} : info;
console.log('\n[release] ==== 发版计划 ===='); /** 读累积状态;首次升级时从既有产物清单迁移种子,避免丢掉其它应用的条目。 */
console.log(` 子应用 : ${pkg.name} (${app})`); function readState() {
console.log(` 版本 : ${version}`); const empty = { version: '', updatedAt: '', subapps: {}, published: {} };
console.log(` SUBAPP_BASE : ${subappBase}`); if (fs.existsSync(stateFile)) {
console.log(` 产物目录 : ${path.relative(ROOT, targetDir)}`); let st;
console.log(` 清单 : ${path.relative(ROOT, manifestFile)}`); try {
console.log( st = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
} catch (err) {
die(`状态文件解析失败 ${path.relative(ROOT, stateFile)}: ${err.message}`);
}
if (!st.subapps || typeof st.subapps !== 'object') {
die(`${path.relative(ROOT, stateFile)} 缺少 subapps 字段,已拒绝覆盖,请人工确认该文件`);
}
if (!st.published || typeof st.published !== 'object') st.published = {};
return st;
}
if (fs.existsSync(manifestFile)) {
try {
const old = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
if (old && typeof old.subapps === 'object') {
info(`首次启用状态目录:从既有 ${path.relative(ROOT, manifestFile)} 迁移清单条目`);
return { ...empty, ...old, published: {} };
}
} catch {
/* 旧清单坏了就当没有,后续会按空状态重建 */
}
}
return empty;
}
if (!quiet) {
console.log('\n[release] ==== 发版计划 ====');
console.log(` 子应用 : ${pkg.name} (${app})`);
console.log(` 版本 : ${version}`);
console.log(` SUBAPP_BASE : ${subappBase}`);
console.log(` 产物目录 : ${path.relative(ROOT, targetDir)}`);
console.log(` 清单 : ${path.relative(ROOT, manifestFile)}`);
console.log(` 状态文件 : ${path.relative(ROOT, stateFile)}`);
console.log(
` 模式 : ${switchOnly ? '仅切换清单(回滚/灰度)' : dryRun ? '演练(不落盘)' : '完整发布'}`, ` 模式 : ${switchOnly ? '仅切换清单(回滚/灰度)' : dryRun ? '演练(不落盘)' : '完整发布'}`,
); );
console.log(''); if (!switchOnly && !dryRun)
console.log(` 产物范围 : 本次重建(${path.relative(ROOT, outRoot)}/ 只装本次产物)`);
console.log('');
}
if (dryRun) { if (dryRun) {
info('--dry-run:以下动作不会执行。'); info('--dry-run:以下动作不会执行。');
...@@ -163,19 +248,71 @@ if (dryRun) { ...@@ -163,19 +248,71 @@ if (dryRun) {
process.exit(0); process.exit(0);
} }
// ---- 1 / 2:不可变校验 + 定向构建 + 产物复制 ---- // ---- 0:读状态 + 不可变校验 + 重建产物目录 ----
// 产物目录每次重建(它只代表「本次要覆盖什么」),线下的历史版本目录不受影响。
// 「同名版本已发布过」的判定真源是【线上清单】(配置了 remoteManifest 且拉取成功时);
// 本地 state.published 只是拉不到线上时的兜底 —— 它是本机记录,同事的机器上没有。
let state = readState();
/** 线上条目(remoteManifest 拉取成功时为对象,否则 null)。 */
let remoteSubapps = null;
// ---- 0.5:拉线上清单做合并基线 ----
// 必须在不可变校验之前:合并只动 subapps,不动 published,校验依据不受影响;
// 但反过来先校验再合并,就会在 state 已被改写后才判冲突,语义更绕。
if (remoteManifestUrl && !switchOnly) {
const merged = await mergeRemoteManifest({
stateFile,
url: remoteManifestUrl,
keepLocal: [app],
info,
});
if (merged.ok) {
remoteSubapps = merged.remoteSubapps ?? {};
state = readState(); // 合并结果已写回状态文件,重新读一份再继续
} else {
info(
`⚠ 远端清单拉取失败(${merged.error}):本次以本地状态为基线。\n` +
' 若此刻有其它人并发发版,后上传的那份会整份覆盖先前的条目。',
);
}
}
if (!switchOnly) { if (!switchOnly) {
if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0 && !args.force) { const localSeen = Array.isArray(state.published?.[app]) ? state.published[app] : [];
const localHit = localSeen.includes(version);
const remoteEntry = remoteSubapps ? remoteSubapps[app] : undefined;
// url 相同即同一目录,version 字段只是人读的备注 —— 两者任一命中都视为「已在线上」
const remoteHit = Boolean(
remoteEntry && (remoteEntry.url === remoteDir || remoteEntry.version === version),
);
// 线上拉取成功 → 只信线上;拉不到/没配 → 退回本机记录,并如实告知它的局限
const hit = remoteSubapps ? remoteHit : localHit;
if (hit && !args.force) {
if (remoteSubapps) {
die(
`线上清单显示 ${app}@${version} 正在服务(subapps.${app} = ${JSON.stringify(remoteEntry)})。\n` +
'同名重建会把线上版本目录的内容换掉,回滚过去就不再是当初那个版本。\n' +
' 换版本号重发,或确认要就地覆盖时加 --force。',
);
}
die( die(
`版本目录已存在:${path.relative(ROOT, targetDir)}\n` + `版本 ${app}@${version} 已发布过(本机记录:${path.relative(ROOT, stateFile)})。\n` +
'不可变产物禁止覆盖(回滚依赖旧目录还在)。请换版本号,或确认后加 --force。', '同名覆盖会把线上旧目录的内容换掉,回滚过去就不再是当初那个版本。\n' +
' 换版本号重发,或确认要就地覆盖时加 --force。\n' +
' 注意:这条记录只在本机有效,其他同事的机器上不会有 —— 跨机器协作请配置\n' +
' MFE_REMOTE_MANIFEST 指向线上清单,让「已发布」判定以线上为准。',
); );
} }
}
if (!dryRun) fs.mkdirSync(stateDir, { recursive: true });
// ---- 1 / 2:定向构建 + 产物复制 ----
// 注意:清空产物目录放在构建与校验**之后**(见下方 cpSync 前)——
// 版本冲突、构建失败都发生在清空之前,这样失败时上一次的产物还在,不会被清成空目录。
if (!switchOnly) {
if (!skipBuild) { if (!skipBuild) {
const isWin = process.platform === 'win32'; const isWin = process.platform === 'win32';
const pnpm = isWin ? 'pnpm.cmd' : 'pnpm'; const pnpm = isWin ? 'pnpm.cmd' : 'pnpm';
info(`定向构建 ${pkg.name}(其余应用不参与)...`); say(`定向构建 ${pkg.name}(其余应用不参与)...`);
const result = spawnSync(pnpm, ['--filter', pkg.name, 'build'], { const result = spawnSync(pnpm, ['--filter', pkg.name, 'build'], {
cwd: ROOT, cwd: ROOT,
stdio: 'inherit', stdio: 'inherit',
...@@ -216,52 +353,86 @@ if (!switchOnly) { ...@@ -216,52 +353,86 @@ if (!switchOnly) {
'\n 部署到版本目录后会 404。确认 vite.config 用了 createWebAppConfig 且构建时带了 SUBAPP_BASE。', '\n 部署到版本目录后会 404。确认 vite.config 用了 createWebAppConfig 且构建时带了 SUBAPP_BASE。',
); );
} }
info(`资源路径校验通过(${refs.length} 个引用均带 ${basePrefix} 前缀)`); say(`资源路径校验通过(${refs.length} 个引用均带 ${basePrefix} 前缀)`);
// 走到这里说明构建与资源校验都过了,才清空产物目录写本次内容。
// --no-clean 由外层 release:spec/affected 传给第二及以后的子应用(它们共用同一份产物树)。
if (!args['no-clean']) {
fs.rmSync(outRoot, { recursive: true, force: true });
say(`产物目录已重建:${path.relative(ROOT, outRoot)}/(只装本次产物)`);
}
fs.mkdirSync(targetDir, { recursive: true }); fs.mkdirSync(targetDir, { recursive: true });
fs.cpSync(distDir, targetDir, { recursive: true }); fs.cpSync(distDir, targetDir, { recursive: true });
info(`产物已落到 ${path.relative(ROOT, targetDir)}`); say(`产物已落到 ${path.relative(ROOT, targetDir)}`);
} else if (!fs.existsSync(targetDir)) { } else {
info(`⚠ 本地没有 ${path.relative(ROOT, targetDir)};若产物只在远端 CDN,可忽略。`); // switch-only:产物里只留清单,版本目录不在本地(线上旧目录不动)。
} if (!args['no-clean'] && fs.existsSync(outRoot)) {
fs.rmSync(outRoot, { recursive: true, force: true });
// ---- 4:增量更新清单,其余子应用条目原样保留 ----
let manifest = { version: '', updatedAt: '', subapps: {} };
if (fs.existsSync(manifestFile)) {
try {
manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
if (!manifest.subapps || typeof manifest.subapps !== 'object') {
die(`${path.relative(ROOT, manifestFile)} 缺少 subapps 字段,已拒绝覆盖,请人工确认该文件`);
}
} catch (err) {
die(`清单解析失败 ${path.relative(ROOT, manifestFile)}: ${err.message}`);
} }
say('仅切换清单:本次产物只有 mfe/manifest.json,不含版本目录(线上旧目录不动)');
} }
manifest.version = `${new Date().toISOString().replace(/[:.]/g, '-')}-${app}-${version}`; // ---- 4:增量更新状态(其余子应用条目原样保留),再导出本次产物里的清单快照 ----
manifest.updatedAt = new Date().toISOString(); state.version = `${new Date().toISOString().replace(/[:.]/g, '-')}-${app}-${version}`;
state.updatedAt = new Date().toISOString();
// route 供 host 运行时动态注册用:host 不重建时读不到新子应用的 package.json, // route 供 host 运行时动态注册用:host 不重建时读不到新子应用的 package.json,
// 只能靠清单把 URL 首段反查回 shortName。缺省即 shortName,与构建期 subapps.ts 同语义。 // 只能靠清单把 URL 首段反查回 shortName。缺省即 shortName,与构建期 subapps.ts 同语义。
const entry = { url: remoteDir, version }; const entry = { url: remoteDir, version };
if (typeof pkg.uj?.route === 'string' && pkg.uj.route && pkg.uj.route !== app) { if (typeof pkg.uj?.route === 'string' && pkg.uj.route && pkg.uj.route !== app) {
entry.route = pkg.uj.route; entry.route = pkg.uj.route;
} }
manifest.subapps[app] = entry; state.subapps[app] = entry;
// 记账:本次真正落过盘的版本才算发布过;switch-only 只改指向,不算新发布。
if (!switchOnly) {
const seen = Array.isArray(state.published[app]) ? state.published[app] : [];
if (!seen.includes(version)) seen.push(version);
state.published[app] = seen;
}
fs.mkdirSync(stateDir, { recursive: true });
fs.writeFileSync(stateFile, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
say(`状态已更新:${path.relative(ROOT, stateFile)}`);
// 产物里那份只给运行时用:published 是本地记账,不该进部署目录。
const snapshot = {
version: state.version,
updatedAt: state.updatedAt,
subapps: state.subapps,
};
fs.mkdirSync(path.dirname(manifestFile), { recursive: true }); fs.mkdirSync(path.dirname(manifestFile), { recursive: true });
fs.writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8'); fs.writeFileSync(manifestFile, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
info(`清单已更新:${path.relative(ROOT, manifestFile)}`); say(`清单已写入产物:${path.relative(ROOT, manifestFile)}`);
console.log(JSON.stringify(manifest, null, 2)); if (!quiet) console.log(JSON.stringify(snapshot, null, 2));
// 单应用发版也留指纹:产物只有 mfe/<app>/<ver>/ + 清单,但溯源需求一样。
// 批量入口(release:spec / affected / all)会在最后用全量信息覆盖这一份。
const bi = writeBuildInfo({
root: ROOT,
outRoot,
releaseVersion: version,
apps: [app],
hostRel: null,
manifestVersion: snapshot.version,
source: 'release',
});
say(
`构建指纹:BUILD_INFO.json` +
(bi.git
? `(${bi.git.shortSha}${bi.git.dirty ? '+dirty' : ''} @ ${bi.git.branch})`
: '(无 git 信息)'),
);
// ---- 5:上传钩子(可选,不执行时只给提示)---- // ---- 5:上传钩子(可选,不执行时只给提示)----
// 钩子放在清单写完之后、且 switch-only 也执行:回滚只改清单,同样必须把新清单传上去。 // 钩子放在清单写完之后、且 switch-only 也执行:回滚只改清单,同样必须把新清单传上去。
if (uploadCmd) { if (uploadCmd) {
const template = String(uploadCmd); const template = String(uploadCmd);
if (!/\{(?:dir|file)\}/.test(template)) { if (!/\{dir\}/.test(template)) {
info('⚠ 上传钩子未包含 {dir} 或 {file}:请确认 manifest.json 会被上传,否则发布不生效。'); info('⚠ 上传钩子未包含 {dir}:产物是镜像部署根的一棵树,一个 {dir} 覆盖过去即可。');
} }
const cmd = template const cmd = template
.replaceAll('{dir}', outRoot) .replaceAll('{dir}', outRoot)
.replaceAll('{host}', outRoot) // 兼容旧钩子:主壳已落在产物根,不再是独立暂存目录
.replaceAll('{target}', targetDir) .replaceAll('{target}', targetDir)
.replaceAll('{remote}', remotePath) .replaceAll('{remote}', remotePath)
.replaceAll('{file}', manifestFile); .replaceAll('{file}', manifestFile);
...@@ -270,9 +441,11 @@ if (uploadCmd) { ...@@ -270,9 +441,11 @@ if (uploadCmd) {
if (res.status !== 0) die(`上传失败(exit ${res.status})。清单已在本地更新,远端尚未生效。`); if (res.status !== 0) die(`上传失败(exit ${res.status})。清单已在本地更新,远端尚未生效。`);
} }
console.log(` if (!quiet)
console.log(`
[release] ==== 完成,但发布还没生效,还差三步 ==== [release] ==== 完成,但发布还没生效,还差三步 ====
1. 把 ${path.relative(ROOT, outRoot)}/ 整体同步到静态站/ CDN 根(或配置 --upload-cmd 自动做)。 1. 把 ${path.relative(ROOT, outRoot)}/ 整棵树覆盖进部署根(或配置 --upload-cmd 自动做)。
它只含本次产物:没出现在里面的模块,线上保持老版本,不用管。
清单 manifest.json 必须响应 Cache-Control: no-cache,否则浏览器缓存会把发布卡住。 清单 manifest.json 必须响应 Cache-Control: no-cache,否则浏览器缓存会把发布卡住。
2. 主壳启动时才拉清单,且子应用 alive 保活 —— 已打开的页面必须【整页刷新】才拿到新 URL, 2. 主壳启动时才拉清单,且子应用 alive 保活 —— 已打开的页面必须【整页刷新】才拿到新 URL,
SPA 内点菜单切换不会生效。 SPA 内点菜单切换不会生效。
...@@ -282,3 +455,9 @@ console.log(` ...@@ -282,3 +455,9 @@ console.log(`
回滚:pnpm release -- --app ${app} --version <旧版本> --switch-only 回滚:pnpm release -- --app ${app} --version <旧版本> --switch-only
(只改清单指回旧目录,不重建、不重启 host) (只改清单指回旧目录,不重建、不重启 host)
`); `);
if (quiet) {
// 批量入口(release:spec / release:all)只要一行结果,总览由它自己打印
const target = switchOnly ? '仅清单' : remotePath;
console.log(`[release] ✓ ${app}@${version} → ${target}`);
}
/**
* 远端清单合并 —— 解决「两个团队同时发版,后发的把先发的覆盖掉」。
*
* ── 问题 ──────────────────────────────────────────────────────────────
* mfe/manifest.json 是一份**全量**清单,同时管着所有子系统。CI 里两个 job 并发跑
* (A 发 store、B 发 system),两边都基于自己机器上的 .release-state 生成清单,
* 最后上传的那个整份覆盖前一个 —— 先发的那条凭空消失,线上退回旧 URL。
*
* ── 做法 ──────────────────────────────────────────────────────────────
* 发布前 GET 一次**线上真实清单**,把它当作合并基线:
* - 本次要发的 app → 用本地(本次构建的)条目;
* - 其它 app → 用远端条目(别人可能刚发过,本地那份是旧的);
* - 远端没有、本地有的 → 保留本地(远端可能是首次部署,或该 app 还没上线)。
*
* 这不能彻底消除竞态(真正的原子性需要服务端 CAS 或 CI 串行),但把冲突窗口从
* 「整个构建过程(几十秒到几分钟)」压缩到「上传的那几秒」,且后发的一定包含先发的。
*
* 拉取失败**不阻断发布** —— 可能是网络、可能是首次部署(线上还没有清单)。
* 但必须明确告警,否则并发保护静默失效,人以为配了就安全了。
*/
import fs from 'node:fs/promises';
import path from 'node:path';
/**
* @param {object} o
* @param {string} o.stateFile 本地状态文件(.release-state/manifest.json)
* @param {string} o.url 线上清单地址(绝对 URL,或配合 origin 的 /mfe/manifest.json)
* @param {string[]} o.keepLocal 本次要发布的 app:这些条目以本地为准
* @param {(m: string) => void} o.info
* @param {number} [o.timeoutMs]
* @returns {Promise<{ok: boolean, error?: string, adopted?: string[], kept?: string[],
* remoteSubapps?: Record<string, {url: string, version?: string}>}>}
* ok 时带 remoteSubapps(线上条目原样),供「该版本是否已在线上」判定使用。
*/
export async function mergeRemoteManifest({ stateFile, url, keepLocal, info, timeoutMs = 8000 }) {
let remote;
try {
const res = await fetch(url, {
signal: AbortSignal.timeout(timeoutMs),
// 清单必须拿最新的:中间任何一层缓存命中,都会把刚发布的条目吃掉
headers: { 'cache-control': 'no-cache', pragma: 'no-cache' },
});
if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
remote = await res.json();
} catch (err) {
return { ok: false, error: err.message };
}
if (!remote || typeof remote.subapps !== 'object' || remote.subapps === null) {
return { ok: false, error: '远端清单缺少 subapps 字段' };
}
// 全新机器可能还没有状态文件(首次启用 remote 或同事首跑):以空为基线,
// 远端条目全部采纳 —— 这正是「以线上为真源」的初始状态,不能崩。
let state = {};
try {
state = JSON.parse(await fs.readFile(stateFile, 'utf8'));
} catch {
/* 无文件或坏文件都按空状态处理 */
}
if (!state.subapps || typeof state.subapps !== 'object') state.subapps = {};
const adopted = [];
for (const [name, entry] of Object.entries(remote.subapps)) {
if (keepLocal.includes(name)) continue;
if (!entry || typeof entry.url !== 'string' || !entry.url) continue; // 坏条目不带进本地
// 远端已有的 app 一律以远端为准:本地那份可能是几小时前的,把别人的发布覆盖回去
// 就等于「后发的一次静默回滚」。
const before = state.subapps[name];
state.subapps[name] = entry;
if (!before || before.version !== entry.version)
adopted.push(`${name}@${entry.version ?? '?'}`);
}
await fs.mkdir(path.dirname(stateFile), { recursive: true });
await fs.writeFile(stateFile, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
const kept = keepLocal.filter((n) => state.subapps[n]);
if (adopted.length) info(`远端清单已合并:沿用 ${adopted.join(', ')}(本次未发,以线上为准)`);
else info(`远端清单已合并:${kept.length} 个本次发布的条目以本地为准,其余无变化`);
return { ok: true, adopted, kept, remoteSubapps: remote.subapps };
}
/**
* 内置静态服务 —— 把产物目录当成真实站点来访问。
*
* 它同时服务两个场景,所以必须只有一份实现:
* - release-verify 用它做自检(起在随机端口,跑完即退)
* - release-all 用它做本地预览(起在固定端口,占住终端)
*
* 两份实现会漂移成「预览能开、自检说没事、上线却挂」,所以刻意不复写。
*
* 行为刻意对齐 DEPLOY.md 里的 nginx 配置,好在本地就复现线上的坑:
* /mfe/** 找不到就是 404,绝不回落(线上 `location ^~ /mfe/ { try_files $uri $uri/ =404; }`)
* 其它 目录取 index.html,缺文件回落主壳(线上 `location / { try_files $uri $uri/ /index.html; }`)
*/
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { pathToFileURL } from 'node:url';
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.map': 'application/json; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
};
/**
* @param {string} dir 站点根(产物目录)
* @param {{ port?: number, host?: string }} [opts] port=0 时由系统分配
* @returns {Promise<{ server: import('node:http').Server, port: number, url: string }>}
*/
export function startStaticServer(dir, opts = {}) {
const rootDir = path.resolve(dir);
const port = opts.port ?? 0;
const host = opts.host ?? '127.0.0.1';
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
let pathname;
try {
pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname);
} catch {
res.writeHead(400).end('bad request');
return;
}
const send404 = () => {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('404 not found');
};
const resolveFile = (p) => {
const abs = path.join(rootDir, p);
if (!abs.startsWith(rootDir)) return null; // 防目录穿越
if (!fs.existsSync(abs)) return null;
const st = fs.statSync(abs);
if (st.isDirectory()) {
const idx = path.join(abs, 'index.html');
return fs.existsSync(idx) ? idx : null;
}
return st.isFile() ? abs : null;
};
const withHeaders = (file, status = 200) => {
const ext = path.extname(file).toLowerCase();
const base = path.basename(file);
const headers = { 'content-type': MIME[ext] ?? 'application/octet-stream' };
// 与 DEPLOY.md 的缓存约定一致:入口类 no-cache,带 hash 的资源长缓存
headers['cache-control'] =
base === 'index.html' || base === 'manifest.json'
? 'no-cache'
: 'public, max-age=31536000, immutable';
res.writeHead(status, headers);
fs.createReadStream(file).pipe(res);
};
if (pathname.startsWith('/mfe/')) {
const file = resolveFile(pathname);
if (file) withHeaders(file);
else send404();
return;
}
// 主壳侧:真实文件优先,目录取 index.html,其余回落到根 index.html(SPA)
const direct = resolveFile(pathname);
if (direct) {
withHeaders(direct);
return;
}
const fallback = path.join(rootDir, 'index.html');
if (fs.existsSync(fallback)) {
withHeaders(fallback);
return;
}
send404();
});
server.on('error', reject);
server.listen(port, host, () => {
const actual = server.address().port;
resolve({ server, port: actual, url: `http://${host}:${actual}` });
});
});
}
export { MIME };
// ---------------------------------------------------------------------------
// CLI:pnpm release:preview [--dir dist] [--port 4180]
//
// 存在的理由:产物里的资源是绝对路径(/mfe/host/<ver>/assets/...),
// 只有「站点根 = 产物目录」时才解析得对。任何以仓库根为根的服务器
// (最典型是 VS Code Live Server 默认行为)都会把 /mfe/... 找成 <仓库>/mfe/...,
// 404 又被返回成 HTML,浏览器报 MIME 错误 + 资源 404,看起来像产物坏了。
// ---------------------------------------------------------------------------
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const argv = process.argv.slice(2);
// 取最后一次出现,这样 `pnpm release:preview -- --port 5180` 的追加参数能覆盖默认值
const getArg = (name) => {
const i = argv.lastIndexOf(`--${name}`);
return i >= 0 ? argv[i + 1] : undefined;
};
if (argv.includes('--help') || argv.includes('-h')) {
console.log(`用法: node scripts/release/static-server.mjs [--dir <产物目录>] [--port <n>] [--host <h>]
--dir 站点根,默认 dist(= 部署根镜像)
--port 端口,默认 4180;被占用时自动往后找 10 个
--host 监听地址,默认 127.0.0.1`);
process.exit(0);
}
const dir = path.resolve(getArg('dir') ?? 'dist');
if (!fs.existsSync(path.join(dir, 'index.html'))) {
console.error(`\n ✗ ${dir} 下没有 index.html,不是有效的站点根。`);
console.error(' 先跑 pnpm release:all(或 pnpm release --app <name>)生成产物。\n');
process.exit(1);
}
const basePort = Number(getArg('port') ?? 4180);
const host = getArg('host') ?? '127.0.0.1';
let started;
for (let p = basePort; p < basePort + 10 && !started; p += 1) {
try {
started = await startStaticServer(dir, { port: p, host });
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
}
}
if (!started) {
console.error(` ✗ 端口 ${basePort}-${basePort + 9} 全被占用,用 --port 换一个。`);
process.exit(1);
}
console.log(`\n 站点根 ${dir}`);
console.log(` 预览 ${started.url}\n`);
console.log(' 行为对齐线上 nginx:/mfe/** 缺失即 404(不回落),其它路径回落到主壳。');
console.log(' Ctrl+C 停止。\n');
}
...@@ -11,7 +11,8 @@ ...@@ -11,7 +11,8 @@
"VITE_SIGN_DEBUG", "VITE_SIGN_DEBUG",
"VITE_STRICT_VERIFY", "VITE_STRICT_VERIFY",
"VITE_MANIFEST_URL", "VITE_MANIFEST_URL",
"SUBAPP_BASE" "SUBAPP_BASE",
"SHELL_BASE"
], ],
"tasks": { "tasks": {
"build": { "build": {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!