release.mjs 12 KB
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

/**
 * 单模块发版 —— 「只改了 system,就只发 system」的可执行入口。
 *
 *   node scripts/release.mjs --app system --version 1.2.0
 *
 * 做四件事,每一步都对应 docs/DEPLOY.md 的一节:
 *   1. 定向构建(SUBAPP_BASE 注入 /mfe/<app>/<version>/,让资源路径对齐不可变目录)
 *   2. 产物落到 <out>/mfe/<app>/<version>/(已存在的版本拒绝覆盖)
 *   3. 校验 index.html 里的资源路径确实带上了该 base(防止「清单生效但白屏」)
 *   4. 增量更新 <out>/mfe/manifest.json,只改目标子应用那一条
 *
 * 不自动上传:脚本只产出「待上传目录」,通过 --upload-cmd 交给实际制品库/CDN。
 * 这样不把任何基础设施假设写进仓库。
 *
 * 回滚 / 灰度不重建:--switch-only 1.2.0 只改清单,把 URL 指回旧版本目录。
 */

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MICRO_ROOT = path.join(ROOT, 'apps', 'web', 'micro-apps');

function parseArgs(argv) {
  const flags = new Set(['dry-run', 'skip-build', 'switch-only', 'force', 'help']);
  const out = {};
  for (let i = 0; i < argv.length; i += 1) {
    const token = argv[i];
    if (!token.startsWith('--')) {
      throw new Error(`无法识别的参数:${token}`);
    }
    const eq = token.indexOf('=');
    const key = (eq > 0 ? token.slice(2, eq) : token.slice(2)).replace(/^--/, '');
    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[release] ✗ ${message}\n`);
  process.exit(1);
}

function info(message) {
  console.log(`[release] ${message}`);
}

function printHelp() {
  console.log(`
用法:
  node scripts/release.mjs --app <system|store> --version <ver> [选项]

选项:
  --app <name>          子应用目录名(必填,除 --help 外)
  --version <ver>       版本号,如 1.2.0 / 1.2.0-beta.1 / <commit-sha>(必填)
  --public-base <url>   产物对外根地址,默认同源 ''。
                        例如 https://cdn.example.com 会生成该域名下的 /mfe/... URL
  --out <dir>           待上传目录,默认 .release(建议加进 .gitignore)
  --skip-build          复用已有 dist,不重新构建(CI 里 build job 已构建时用)
  --switch-only         只改 manifest,不构建不复制;用于回滚 / 灰度
  --upload-cmd <cmd>    上传钩子,模板变量见下,例如
                        "aws s3 sync {dir} s3://bucket/ --exclude '*' ..."
                        也可用环境变量 MFE_UPLOAD_CMD 提供。
                        {dir}    待上传根(含 mfe/manifest.json 与所有版本目录)
                        {target} 本次单个版本目录
                        {remote} 远端相对路径 mfe/<app>/<version>/
                        {file}   manifest.json 本地路径
                        ⚠ 钩子必须覆盖 manifest.json,否则清单不更新、发布不生效。
  --force               允许覆盖已存在的版本目录(默认禁止,不可变产物)
  --dry-run             只打印计划,不构建、不写文件、不上传
  --help                显示本帮助

示例:
  # 本地演练
  node scripts/release.mjs --app system --version 1.2.0 --dry-run
  # 正式发 system 一个版本(host 不重建)
  pnpm release -- --app system --version 1.2.0
  # 回滚到旧版本
  pnpm release -- --app system --version 1.1.9 --switch-only
`);
}

const args = parseArgs(process.argv.slice(2));
if (args.help) {
  printHelp();
  process.exit(0);
}

const { app, version } = args;
if (!app) die('缺少 --app。用 --help 查看用法。');
if (!version) die('缺少 --version。用 --help 查看用法。');
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(version) || version.includes('..')) {
  die(`版本号 "${version}" 非法:只允许字母数字 . _ -,且不得含 ".."(防目录穿越)`);
}
if (!/^[\w-]+$/.test(app)) die(`子应用名 "${app}" 非法`);
if (!/^\d+\.\d+\.\d+/.test(version)) {
  info(`提示:版本 "${version}" 不是 semver 形态。CI 用 commit sha 可以,人工发版建议 1.2.0。`);
}

const appDir = path.join(MICRO_ROOT, app);
const pkgFile = path.join(appDir, 'package.json');
if (!fs.existsSync(pkgFile)) die(`子应用不存在:${path.relative(ROOT, appDir)}`);
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
const expectedName = `@uj/web-${app}`;
if (pkg.name !== expectedName) {
  die(`${app}/package.json 的 name=${pkg.name},期望 ${expectedName};--filter 会构建到别的包`);
}

// ---- 计算 URL 与目录:两者必须严格对齐 ----
// CI 里同名环境变量即可驱动,不必拼一长串 CLI 参数。
const publicBase = String(args['public-base'] ?? process.env.MFE_PUBLIC_BASE ?? '').replace(
  /\/+$/,
  '',
);
const uploadCmd = args['upload-cmd'] ?? process.env.MFE_UPLOAD_CMD;
const remotePath = `mfe/${app}/${version}/`;
const remoteDir = `${publicBase}/${remotePath}`; // '/mfe/system/1.2.0/' 或 'https://cdn/.../mfe/system/1.2.0/'
const subappBase = remoteDir; // 直接作为 Vite base,产物资源路径与最终 URL 同源同前缀

const outRoot = path.resolve(ROOT, args.out ?? process.env.MFE_OUT_DIR ?? '.release');
const targetDir = path.join(outRoot, 'mfe', app, version);
const manifestFile = path.join(outRoot, 'mfe', 'manifest.json');
const distDir = path.join(appDir, 'dist');
const switchOnly = Boolean(args['switch-only']);
const dryRun = Boolean(args['dry-run']);
const skipBuild = Boolean(args['skip-build']) || switchOnly;

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(
  `  模式        : ${switchOnly ? '仅切换清单(回滚/灰度)' : dryRun ? '演练(不落盘)' : '完整发布'}`,
);
console.log('');

if (dryRun) {
  info('--dry-run:以下动作不会执行。');
  console.log(
    `  1. ${switchOnly ? '(跳过)' : `SUBAPP_BASE=${subappBase} pnpm --filter ${pkg.name} build`}`,
  );
  console.log(`  2. ${switchOnly ? '(跳过)' : `dist/ -> ${path.relative(ROOT, targetDir)}`}`);
  console.log(`  3. ${switchOnly ? '(跳过)' : '校验 index.html 资源路径带 base 前缀'}`);
  console.log(`  4. 写 manifest:subapps.${app} = { url: "${remoteDir}", version: "${version}" }`);
  if (uploadCmd) console.log(`  5. 上传钩子:${uploadCmd}`);
  console.log('');
  process.exit(0);
}

// ---- 1 / 2:不可变校验 + 定向构建 + 产物复制 ----
if (!switchOnly) {
  if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0 && !args.force) {
    die(
      `版本目录已存在:${path.relative(ROOT, targetDir)}\n` +
        '不可变产物禁止覆盖(回滚依赖旧目录还在)。请换版本号,或确认后加 --force。',
    );
  }

  if (!skipBuild) {
    const isWin = process.platform === 'win32';
    const pnpm = isWin ? 'pnpm.cmd' : 'pnpm';
    info(`定向构建 ${pkg.name}(其余应用不参与)...`);
    const result = spawnSync(pnpm, ['--filter', pkg.name, 'build'], {
      cwd: ROOT,
      stdio: 'inherit',
      shell: isWin,
      env: { ...process.env, SUBAPP_BASE: subappBase },
    });
    if (result.error) {
      die(
        `启动 pnpm 失败:${result.error.message}\n` +
          '若 CI 的 build job 已产出 dist,可加 --skip-build 复用产物。',
      );
    }
    if (result.status !== 0) die(`构建失败(exit ${result.status}),未写 manifest。`);
  }

  if (!fs.existsSync(path.join(distDir, 'index.html'))) {
    die(`找不到 ${path.relative(ROOT, distDir)}/index.html;先构建或去掉 --skip-build。`);
  }

  // ---- 3:产物 base 校验(这条能自动抓到「清单生效但白屏」)----
  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));
  const basePrefix = publicBase ? subappBase : `/${remotePath}`;
  const bad = refs.filter((u) => {
    if (/^https?:\/\//.test(u)) return !u.startsWith(subappBase);
    if (u.startsWith('/')) return !u.startsWith(basePrefix);
    return false; // 相对路径交由 wujie 基于子应用 URL 补全
  });
  if (bad.length) {
    die(
      `产物 index.html 有 ${bad.length} 个资源路径未对齐 SUBAPP_BASE=${subappBase}:\n` +
        bad
          .slice(0, 5)
          .map((u) => `    ${u}`)
          .join('\n') +
        '\n  部署到版本目录后会 404。确认 vite.config 用了 createWebAppConfig 且构建时带了 SUBAPP_BASE。',
    );
  }
  info(`资源路径校验通过(${refs.length} 个引用均带 ${basePrefix} 前缀)`);

  fs.mkdirSync(targetDir, { recursive: true });
  fs.cpSync(distDir, targetDir, { recursive: true });
  info(`产物已落到 ${path.relative(ROOT, targetDir)}`);
} else if (!fs.existsSync(targetDir)) {
  info(`⚠ 本地没有 ${path.relative(ROOT, targetDir)};若产物只在远端 CDN,可忽略。`);
}

// ---- 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}`);
  }
}

manifest.version = `${new Date().toISOString().replace(/[:.]/g, '-')}-${app}-${version}`;
manifest.updatedAt = new Date().toISOString();
manifest.subapps[app] = { url: remoteDir, version };

fs.mkdirSync(path.dirname(manifestFile), { recursive: true });
fs.writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
info(`清单已更新:${path.relative(ROOT, manifestFile)}`);
console.log(JSON.stringify(manifest, null, 2));

// ---- 5:上传钩子(可选,不执行时只给提示)----
// 钩子放在清单写完之后、且 switch-only 也执行:回滚只改清单,同样必须把新清单传上去。
if (uploadCmd) {
  const template = String(uploadCmd);
  if (!/\{(?:dir|file)\}/.test(template)) {
    info('⚠ 上传钩子未包含 {dir} 或 {file}:请确认 manifest.json 会被上传,否则发布不生效。');
  }
  const cmd = template
    .replaceAll('{dir}', outRoot)
    .replaceAll('{target}', targetDir)
    .replaceAll('{remote}', remotePath)
    .replaceAll('{file}', manifestFile);
  info(`执行上传钩子:${cmd}`);
  const res = spawnSync(cmd, { cwd: ROOT, stdio: 'inherit', shell: true });
  if (res.status !== 0) die(`上传失败(exit ${res.status})。清单已在本地更新,远端尚未生效。`);
}

console.log(`
[release] ==== 完成,但发布还没生效,还差三步 ====
  1. 把 ${path.relative(ROOT, outRoot)}/ 整体同步到静态站/ CDN 根(或配置 --upload-cmd 自动做)。
     清单 manifest.json 必须响应 Cache-Control: no-cache,否则浏览器缓存会把发布卡住。
  2. 主壳启动时才拉清单,且子应用 alive 保活 —— 已打开的页面必须【整页刷新】才拿到新 URL,
     SPA 内点菜单切换不会生效。
  3. 用构建产物起静态服务逐路由冒烟(dev 走 Vite dev server、prod 走产物 URL,两条链路不同)。
     至少验 /system/role、/system/user 首屏与 props.request 不报 10011。

  回滚:pnpm release -- --app ${app} --version <旧版本> --switch-only
  (只改清单指回旧目录,不重建、不重启 host)
`);