release-all.mjs 12.7 KB
#!/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();