WEB/scripts/deploy.mjs
2026-10-10 18:04:26 +08:00

183 lines
7.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* 跨平台发布脚本(Windows / macOS / Linux 通用)
*
* 等价于原 deploy.sh,改用 Node.js 实现,使 Windows 开发环境无需安装 sh/bash。
* 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
*
* 用法:npm run deploy
* npm run deploy -- --pack-only (只打包+校验,不上传,用于排查)
* npm run deploy -- --pack-only --skip-build
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 deploy.config.json');
console.error(' 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。');
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 项目在服务器上的存放路径
const KEEP_RELEASES = config.keepReleases; // 服务器上保留的最近版本数
const SITE_HOST = config.siteHost; // 发版后健康检查域名
const LOCAL_DIST = path.resolve('dist');
const SSH_KEY = path.isAbsolute(config.sshKey) ? config.sshKey : path.join(os.homedir(), '.ssh', config.sshKey);
const SSH_OPTS = ['-i', SSH_KEY, '-o', 'StrictHostKeyChecking=no'];
const HOST = `${USER}@${IP}`;
// 远端解压用的固定文件名(remote/deploy.sh 里写死了 dist.tar.gz)
const TARBALL_NAME = 'dist.tar.gz';
// ⚠️ 本地压缩包必须放在项目目录之外(这里用系统临时目录)。
// Windows 自带 bsdtar(tar.exe)有一条"不要把自己加进自己"的保护,按 (dev, ino) 判断文件身份;
// 而 Windows 下该身份信息不可靠:当压缩包与被打包目录同处一个目录/卷时,
// 某个普通文件会被误判为"归档自身"而被**静默丢弃**(实测丢 dist/index.html),
// 且 tar 退出码仍为 0,导致坏产物被上传、远端校验才报错。
// 详见 docs/部署-本地打包丢文件问题与修复.md
const TARBALL = path.join(os.tmpdir(), `new3-dist-${process.pid}-${Date.now()}.tar.gz`);
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
// --pack-only:只做构建+打包+校验,不上传(排查用);配合 --skip-build 复用已有 dist
const PACK_ONLY = process.argv.includes('--pack-only');
const SKIP_BUILD = process.argv.includes('--skip-build');
const RELEASE_NAME = `v${timestamp()}_${process.pid}`; // 版本号(带 PID,避免并发/重复发布冲突)
const REMOTE_RELEASE = `${BASE_PATH}/releases/${RELEASE_NAME}`;
function timestamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
}
function run(cmd, args, opts = {}) {
// Windows 下 .cmd/.bat(如 npm.cmd)不能直接用 spawnSync 执行(报 EINVAL):
// 优先用 node 直接运行 npm-cli.js(无 shell、无 DEP0190 警告),否则回退到 shell: true
const isWinCmd = process.platform === 'win32' && /\.(cmd|bat)$/i.test(cmd)
let res
if (isWinCmd) {
const npmCli = process.env.npm_execpath
if (npmCli && /npm-cli\.js$/i.test(npmCli)) {
res = spawnSync(process.execPath, [npmCli, ...args], { stdio: 'inherit', ...opts })
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', shell: true, ...opts })
}
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', ...opts })
}
if (res.error) {
console.error(`❌ 无法执行命令 ${cmd}: ${res.error.message}`);
if (res.error.code === 'ENOENT') {
console.error(
' 请确认本机已安装对应命令(ssh/scp/tar)。Windows 10 1803+ 自带 OpenSSH 客户端与 tar。'
);
}
process.exit(1);
}
if (res.status !== 0) process.exit(res.status ?? 1);
}
/**
* 列出压缩包内的条目(去掉 tar 输出的 './' 前缀),失败直接中止。
*/
function tarList(archive) {
const res = spawnSync('tar', ['-tzf', archive], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
if (res.error || res.status !== 0) {
console.error(`❌ 读取压缩包内容失败: ${res.error ? res.error.message : (res.stderr || '').trim()}`);
process.exit(1);
}
return res.stdout
.split(/\r?\n/)
.filter(Boolean)
.map((name) => name.replace(/^\.\//, ''));
}
/**
* 压缩 dist 并校验压缩包内容。
*
* 不能只看 tar 的退出码:Windows bsdtar 丢文件时仍返回 0(见 TARBALL 处的说明),
* 因此这里按**与远端 deploy.sh 相同的规则**回读压缩包校验,缺文件则重新打包,
* 仍缺则本地中止,绝不把坏产物传上去。
*/
function packDist() {
const html = readFileSync(path.join(LOCAL_DIST, 'index.html'), 'utf8');
const refs = [...html.matchAll(/\/assets\/[A-Za-z0-9._-]+\.(?:js|css)/g)].map((m) => m[0].slice(1));
for (let attempt = 1; attempt <= 2; attempt++) {
rmSync(TARBALL, { force: true });
run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.']);
const entries = new Set(tarList(TARBALL));
const missing = [];
if (!entries.has('index.html')) missing.push('index.html');
for (const ref of refs) if (!entries.has(ref)) missing.push(ref);
if (missing.length === 0) {
console.log(`📦 压缩包校验通过(${entries.size} 个条目,index.html + ${refs.length} 个入口资源齐全)`);
return;
}
console.error(`⚠️ 压缩包缺少文件: ${[...new Set(missing)].join(', ')}(疑似 bsdtar 误判“归档自身”导致丢文件)`);
if (attempt === 2) {
console.error('❌ 重新打包后仍然缺文件,中止发布');
process.exit(1);
}
console.log('🔁 重新打包…');
}
}
console.log(`🚀 开始发布版本: ${RELEASE_NAME}`);
try {
// 1. 本地打包(失败立即中止,防止把坏产物发到线上)
if (!SKIP_BUILD) run(NPM, ['run', 'build']);
// 2. 校验本地产物完整性
const localIndex = path.join(LOCAL_DIST, 'index.html');
if (!existsSync(localIndex) || readFileSync(localIndex, 'utf8').trim() === '' || !existsSync(path.join(LOCAL_DIST, 'assets'))) {
console.error('❌ 本地构建产物不完整(缺少 index.html / assets 或 index.html 为空),中止发布');
process.exit(1);
}
// 3. 压缩 + 校验压缩包(防 bsdtar 静默丢文件)
packDist();
if (PACK_ONLY) {
rmSync(TARBALL, { force: true });
console.log('✅ --pack-only:已完成构建与打包校验,未上传');
process.exit(0);
}
// 4. 上传到独立的新版本目录(全程不触碰当前运行目录)
run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]);
run('scp', [...SSH_OPTS, TARBALL, `${HOST}:${REMOTE_RELEASE}/${TARBALL_NAME}`]);
// 5. 远程:解压 → 校验 → 补齐旧资源 → 原子切换 → 健康检查 → 清理
const remoteScript = readFileSync(path.join(__dirname, 'remote', 'deploy.sh'), 'utf8');
run(
'ssh',
[
...SSH_OPTS,
HOST,
`RELEASE='${REMOTE_RELEASE}' BASE='${BASE_PATH}' KEEP=${KEEP_RELEASES} HOST='${SITE_HOST}' bash -s`,
],
{ input: remoteScript, stdio: ['pipe', 'inherit', 'inherit'] }
);
console.log(`✨ 发布成功!当前版本: ${RELEASE_NAME}`);
} finally {
// 无论成功失败都清理本地临时压缩包
rmSync(TARBALL, { force: true });
}