release-verify.mjs 19 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
#!/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);
});