diff --git a/.gitignore b/.gitignore index 67b71e9..640b61a 100644 --- a/.gitignore +++ b/.gitignore @@ -11,10 +11,13 @@ coverage/ .nyc_output/ # 上传的文件资源(本地磁盘,不入库) uploads/ -# 后端真实部署配置(含服务器地址与 SSH 私钥路径,不入库; -# 模板见 backend/config/deploy.config.example.cjs) -backend/config/deploy.config.local.cjs -# 后端发布脚本的本地临时工作目录(发布包/文件清单) +# 真实部署配置(含服务器地址与 SSH 私钥路径,不入库;模板见 tools/config/*.example.*) +tools/config/deploy.config.local.cjs +# 生产环境变量本机权威副本(发布时覆盖服务端 shared-config,不入库) +tools/config/env.production.local +# 发布工具的本地临时工作目录(发布包/文件清单) +tools/temp/ +# 早期发布脚本留在 backend 下的临时工作目录(历史遗留,不入库) backend/temp/ # 导出任务生成的运行期文件(backend/upload/exports/…,不入库) backend/upload/ diff --git a/backend/config/deploy.config.example.cjs b/backend/config/deploy.config.example.cjs deleted file mode 100644 index ff0f3af..0000000 --- a/backend/config/deploy.config.example.cjs +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -/** - * 后端部署配置模板(此文件提交 git,供复制使用) - * - * 真实配置请复制为同目录下的 config/deploy.config.local.cjs 并填写实际值; - * 该文件已被 .gitignore 排除,**不要提交**(内含服务器地址与 SSH 私钥路径)。 - * - * 发布模型(双实例蓝绿,与 WMS 后端一致): - * /v1、/v2 两套代码目录,每次发布交替部署另一套 - * /current.md 当前活跃版本(内容为 v1 或 v2) - * /nginx-upstream.conf Nginx 反代目标:proxy_pass http://127.0.0.1:<端口>; - * 需要站点配置里 include 它(见下方「Nginx 前置」) - * /.env 服务器端真实环境变量(密钥/数据库等),不入库、 - * 发布时按需复制到各版本目录 - * /.deploy/ 发布工作目录(incoming 上传包、state 状态文件) - * - * Nginx 前置(仅首次,站点 api.oms.gztbyc.com): - * 把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成 - * `include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;` - * 之后每次发布只需改写该文件并 reload,即可实现零中断切换。 - * (若不改,发布脚本会在切换 upstream 时告警:新版实例已起在另一个端口, - * 但站点仍指向旧端口,需要人工处理。) - * - * 服务器端环境变量(仅首次,需手工创建一次): - * /www/wwwroot/api.oms.gztbyc.com/.env —— 真实配置,不入库 - * 可从本地 backend/.env 复制,并注意: - * - MYSQL_HOST / MYSQL_PORT / MYSQL_USER / MYSQL_PASSWORD / MYSQL_DATABASE:生产数据库 - * - REDIS_HOST / REDIS_PORT / REDIS_PASSWORD - * - JWT_SECRET:生产必须单独设置 - * - UPLOAD_DIR=/www/wwwroot/api.oms.gztbyc.com/uploads - * (上传文件必须放在 deployRoot 下、版本目录之外,v1/v2 才能共用同一份文件) - * - OMS_CALLBACK_BASE_URL=http://api.oms.gztbyc.com (可选,用于对外展示回调地址) - * 发布时若目标版本目录没有 .env,会自动从该文件复制一份(各版本目录各自保留副本, - * 已存在则不覆盖)。 - */ -module.exports = { - production: { - // —— SSH 连接 —— - host: '112.124.21.102', - port: 22, - username: 'root', - // SSH 私钥:可用绝对路径,或相对 backend 根目录的路径 - privateKeyPath: 'C:/Users/lfmingren/.ssh/112.124.21.102_id_ed25519', - sshOptions: [ 'StrictHostKeyChecking=accept-new' ], - - // —— 发布目录 —— - deployRoot: '/www/wwwroot/api.oms.gztbyc.com', - - // —— 双实例端口(v1 / v2);nginx-upstream.conf 指向当前活跃版本的端口 —— - ports: { v1: 6090, v2: 6091 }, - - // —— 版本目录内需要跨发布保留的目录/文件(清理旧代码时不会删除)—— - // node_modules 保留可让 npm install 增量安装;如需每次全新安装,去掉它即可 - // .env 必须保留:每个版本目录的 .env 里写着本实例的 EGG_PORT(v1=6090 / v2=6091), - // 被清理掉后会从 deployRoot/.env 复制一份(那份是 v1 的端口),导致 v2 起在 6090 上 - sharedDirs: [ 'logs', 'run', 'node_modules', '.env' ], - - // —— 发布包内容(相对 backend 根目录,`**` 表示该目录下全部内容)—— - // 说明:.env / uploads / logs / run 等已被 .gitignore 忽略,git ls-files 不会列出, - // 这里再写进 deployExcludePaths 作为兜底。 - deployIncludePaths: [ - '.sequelizerc', - 'app.js', - 'app/**', - 'config/**', - 'database/**', - 'package.json', - 'package-lock.json', - ], - deployExcludePaths: [ - 'config/deploy.config.local.cjs', - 'config/deploy.config.example.cjs', - '.env', - '.env.*', - 'uploads/**', - 'logs/**', - 'run/**', - 'temp/**', - 'test/**', - 'swagger.json', - ], - - // —— 启动 / 安装命令 —— - // 若需要在服务器上跑迁移(npm run migration:up)、或希望 npx sequelize-cli 可用, - // 把 installCommand 改成 'npm install'(会一并装 devDependencies) - installCommand: 'npm install --production', - // 实例端口由 config/config.local.js 的 EGG_PORT 决定(默认 6090), - // 双实例发布时请在各版本目录的 .env 里分别写 EGG_PORT(v1=6090、v2=6091) - startCommand: 'npm start', - // 健康检查:实例启动后轮询 http://127.0.0.1:<端口> - healthCheckPath: '/', - }, -}; diff --git a/backend/package.json b/backend/package.json index 104ff3e..c012e69 100644 --- a/backend/package.json +++ b/backend/package.json @@ -18,10 +18,12 @@ "migration:create": "sequelize-cli migration:generate --name", "swagger:export": "node scripts/export-swagger.js", "deploy": "npm run deploy:prod", - "deploy:prod": "node ./script/deploy-remote.cjs production", - "deploy:init": "node ./script/init-deploy-config.cjs", + "deploy:prod": "npm --prefix ../tools run deploy --", + "deploy:backend": "npm --prefix ../tools run deploy:backend --", + "deploy:init": "npm --prefix ../tools run init", "rollback": "npm run rollback:prod", - "rollback:prod": "node ./script/rollback-remote.cjs production" + "rollback:prod": "npm --prefix ../tools run rollback --", + "rollback:backend": "npm --prefix ../tools run rollback:backend --" }, "dependencies": { "dotenv": "^17.4.2", diff --git a/backend/script/deploy-lib.cjs b/backend/script/deploy-lib.cjs deleted file mode 100644 index 2caec61..0000000 --- a/backend/script/deploy-lib.cjs +++ /dev/null @@ -1,498 +0,0 @@ -'use strict'; - -/** - * 后端发布公共库(配置加载/校验、SSH/SCP 封装、发布包构建、远端脚本片段) - * - * 发布模型:双实例蓝绿(参考 WMS 后端) - * /{v1,v2} 两套代码目录,发布时交替部署 - * /current.md 当前活跃版本(v1 / v2) - * /nginx-upstream.conf Nginx 反代目标(proxy_pass http://127.0.0.1:<端口>;) - * /.deploy/incoming 上传的发布包 - * /.deploy/state 状态文件(当前发布版本号) - */ - -const fs = require('node:fs'); -const path = require('node:path'); -const { spawnSync } = require('node:child_process'); - -/** backend 根目录(本文件在 backend/script 下) */ -const ROOT = path.resolve(__dirname, '..'); -const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs'); -const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs'); -const DEFAULT_ENV = 'production'; -const VERSIONS = [ 'v1', 'v2' ]; - -/** 发布包默认包含的文件(相对 backend 根目录) */ -const DEFAULT_INCLUDE_PATHS = [ - 'app.js', - 'app/**', - 'config/**', - 'database/**', - 'package.json', - 'package-lock.json', -]; - -/** 发布包默认排除(叠加在 include 之上) */ -const DEFAULT_EXCLUDE_PATHS = [ - 'config/deploy.config.local.cjs', - 'config/deploy.config.example.cjs', - '.env', - '.env.*', - 'uploads/**', - 'logs/**', - 'run/**', - 'temp/**', - 'test/**', - 'swagger.json', -]; - -/** - * bash 单引号字符串里的单引号转义(' → '\'') - * @param {String} value 原始值 - * @return {String} 可安全放进单引号中的字符串 - */ -function quoteForBash(value) { - return `'${String(value).replace(/'/g, "'\\''")}'`; -} - -/** - * 执行本地命令 - * @param {String} command 命令 - * @param {String[]} args 参数 - * @param {Object} [options] 选项(cwd / stdio) - * @return {String} stdout(trim 后) - */ -function runCommand(command, args, options = {}) { - const result = spawnSync(command, args, { - cwd: options.cwd || ROOT, - encoding: 'utf8', - stdio: options.stdio || 'pipe', - shell: false, - }); - - if (result.error) throw result.error; - - if (result.status !== 0) { - const stderr = (result.stderr || '').trim(); - const stdout = (result.stdout || '').trim(); - throw new Error(stderr || stdout || `${command} 退出码 ${result.status}`); - } - - return (result.stdout || '').trim(); -} - -/** - * 检查本地命令是否存在(不存在时给出安装提示) - * @param {String} command 命令名 - * @param {String} installHint 安装提示 - * @return {void} - */ -function ensureCommandAvailable(command, installHint) { - const result = spawnSync(command, [], { cwd: ROOT, encoding: 'utf8', stdio: 'pipe', shell: false }); - if (result.error && result.error.code === 'ENOENT') { - throw new Error(`${command} 不可用。${installHint}`); - } -} - -/** @return {String} yyyyMMddHHmmss 时间戳 */ -function getNowStamp() { - const now = new Date(); - const pad = value => String(value).padStart(2, '0'); - return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; -} - -/** @return {String} 本地临时工作目录 backend/temp/deploy(自动创建) */ -function ensureTempDeployDir() { - const tempDir = path.join(ROOT, 'temp', 'deploy'); - fs.mkdirSync(tempDir, { recursive: true }); - return tempDir; -} - -/** - * 是否为未填写的占位值 - * @param {String} value 值 - * @return {Boolean} 是占位值返回 true - */ -function isPlaceholder(value) { - if (!value) return true; - return String(value).includes('__FILL_'); -} - -/** - * 校验并补齐配置默认值 - * @param {Object} config 原始配置 - * @param {String} envName 环境名 - * @return {Object} 规范化后的配置 - */ -function normalizeDeployConfig(config, envName) { - const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : []; - const guardedOptions = [ - 'IdentitiesOnly=yes', - 'PreferredAuthentications=publickey', - 'PubkeyAuthentication=yes', - 'PasswordAuthentication=no', - 'KbdInteractiveAuthentication=no', - 'BatchMode=yes', - 'ConnectTimeout=10', - ]; - for (const option of guardedOptions) { - const key = option.split('=')[0]; - if (!sshOptions.some(item => new RegExp(`^${key}=`, 'i').test(item))) sshOptions.push(option); - } - - const deployRoot = String(config.deployRoot || '/www/wwwroot/api.oms.gztbyc.com').replace(/\/+$/, ''); - const ports = config.ports || {}; - - return { - envName, - host: config.host, - port: Number(config.port || 22), - username: config.username, - // 支持绝对路径(Windows 下如 C:/Users/x/.ssh/id_ed25519)与相对 backend 根目录的路径 - privateKeyPath: config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '', - deployRoot, - ports: { v1: Number(ports.v1 || 6090), v2: Number(ports.v2 || 6091) }, - incomingDir: `${deployRoot}/.deploy/incoming`, - stateDir: `${deployRoot}/.deploy/state`, - sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'node_modules' ], - deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length - ? config.deployIncludePaths - : DEFAULT_INCLUDE_PATHS, - deployExcludePaths: Array.isArray(config.deployExcludePaths) && config.deployExcludePaths.length - ? config.deployExcludePaths - : DEFAULT_EXCLUDE_PATHS, - installCommand: config.installCommand || 'npm install --production', - startCommand: config.startCommand || 'npm start', - healthCheckPath: config.healthCheckPath || '/', - sshOptions, - }; -} - -/** - * 校验配置必填项 - * @param {Object} config 原始配置 - * @param {String} configPath 配置文件路径 - * @param {String} envName 环境名 - * @return {void} - */ -function validateDeployConfig(config, configPath, envName) { - if (!config) throw new Error(`${configPath} 中未找到 ${envName} 配置。`); - - const missing = []; - if (isPlaceholder(config.host)) missing.push('host'); - if (isPlaceholder(config.username)) missing.push('username'); - if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath'); - if (missing.length) { - throw new Error(`请先完善配置字段: ${missing.join(', ')}。配置文件: ${configPath}`); - } - - const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath); - if (!fs.existsSync(resolvedPrivateKeyPath)) { - throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请修正 ${configPath} 中的 privateKeyPath。`); - } -} - -/** - * 加载本地部署配置 - * @param {String} [envName] 环境名,默认 production - * @return {Object} 规范化后的配置 - */ -function loadDeployConfig(envName = DEFAULT_ENV) { - if (!fs.existsSync(LOCAL_CONFIG_PATH)) { - throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 为 deploy.config.local.cjs 并填写 SSH 信息。`); - } - - delete require.cache[require.resolve(LOCAL_CONFIG_PATH)]; - const loaded = require(LOCAL_CONFIG_PATH); - const config = loaded[envName]; - validateDeployConfig(config, LOCAL_CONFIG_PATH, envName); - return normalizeDeployConfig(config, envName); -} - -/** - * 构造 ssh/scp 公共参数 - * @param {Object} config 部署配置 - * @return {String[]} 参数数组 - */ -function buildSshBaseArgs(config) { - const args = [ '-p', String(config.port), '-i', config.privateKeyPath ]; - for (const option of config.sshOptions) args.push('-o', option); - return args; -} - -/** - * 在服务器上执行 bash 脚本(通过 bash -lc,保证加载登录环境里的 node/npm) - * @param {Object} config 部署配置 - * @param {String} remoteScript 脚本内容 - * @param {Object} [options] 选项(stdio) - * @return {String} 输出 - */ -function runSsh(config, remoteScript, options = {}) { - const args = [ - ...buildSshBaseArgs(config), - `${config.username}@${config.host}`, - `bash -lc ${quoteForBash(remoteScript)}`, - ]; - return runCommand('ssh', args, { stdio: options.stdio || 'inherit' }); -} - -/** - * 上传文件到服务器 - * @param {Object} config 部署配置 - * @param {String} localPath 本地路径 - * @param {String} remotePath 远端路径 - * @return {String} 输出 - */ -function runScp(config, localPath, remotePath) { - const args = [ '-P', String(config.port), '-i', config.privateKeyPath ]; - for (const option of config.sshOptions) args.push('-o', option); - args.push(localPath, `${config.username}@${config.host}:${remotePath}`); - return runCommand('scp', args, { stdio: 'inherit' }); -} - -/** - * 判断路径是否命中规则(`a/**` 匹配 a 及其全部子项,其余为精确匹配) - * @param {String} filePath 相对路径 - * @param {String} rule 规则 - * @return {Boolean} 命中返回 true - */ -function pathMatchesRule(filePath, rule) { - const normalizedPath = String(filePath || '').replace(/\\/g, '/'); - const normalizedRule = String(rule || '').replace(/\\/g, '/').trim(); - if (!normalizedRule) return false; - if (normalizedRule.endsWith('/**')) { - const prefix = normalizedRule.slice(0, -3); - return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`); - } - return normalizedPath === normalizedRule; -} - -/** - * 列出可发布文件:以 git 的视角取文件(天然排除 .gitignore 里的 .env / uploads 等), - * 再按 include / exclude 规则过滤 - * @param {Object} config 部署配置 - * @return {String[]} 相对 backend 根目录的文件列表 - */ -function listDeployableFiles(config) { - const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ], { cwd: ROOT }); - - return Array.from(new Set( - output - .split(/\r?\n/) - .map(item => item.trim()) - .filter(Boolean) - .filter(item => !item.startsWith('.git/')) - .filter(item => fs.existsSync(path.join(ROOT, item))) - .filter(item => config.deployIncludePaths.some(rule => pathMatchesRule(item, rule))) - .filter(item => !config.deployExcludePaths.some(rule => pathMatchesRule(item, rule))) - )); -} - -/** - * 构建本地发布包(tar.gz) - * @param {String} stamp 时间戳 - * @param {Object} config 部署配置 - * @return {{ archivePath: String, fileCount: Number }} 发布包路径与文件数 - */ -function buildArchive(stamp, config) { - const tempDir = ensureTempDeployDir(); - const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`); - const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`); - const files = listDeployableFiles(config); - - if (!files.length) throw new Error('未找到可发布文件(请检查 deployIncludePaths 配置)。'); - - fs.writeFileSync(listPath, `${files.join('\n')}\n`, 'utf8'); - runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit', cwd: ROOT }); - - return { archivePath, fileCount: files.length }; -} - -/** - * 生成远端清理守卫:`find . -mindepth 1 -maxdepth 1 <守卫> -exec rm -rf {} +` - * 保留 .deploy 与 sharedDirs(logs / run / node_modules 等) - * @param {String[]} sharedDirs 需保留的目录名 - * @return {String} find 命令的守卫参数 - */ -function buildRemoteCleanupGuard(sharedDirs) { - const preserved = [ '.deploy', ...sharedDirs ]; - return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' '); -} - -/** - * 生成「按目录停止 egg 进程」的远端脚本行: - * 通过 ps 匹配命令行里的版本目录 + node,先 kill 再 kill -9 兜底。 - * 不用 `npm run stop`(egg-scripts 按 title 停止,v1/v2 同 title 会互相误杀)。 - * @param {String} dirPath 目标目录绝对路径 - * @param {String} label 日志前缀 - * @return {String[]} 脚本行 - */ -function buildScopedEggStopLines(dirPath, label) { - const matchNode = '$2 == "node" || $2 ~ /\\/node$/'; - const awkProgram = `index($0, root) && (${matchNode}) { print $1 }`; - return [ - `TARGET_DIR=${quoteForBash(dirPath)}`, - `TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`, - 'if [ -z "$TARGET_PIDS" ]; then', - ` echo "${label}_NONE"`, - 'else', - ` echo "${label} $TARGET_PIDS"`, - ' kill $TARGET_PIDS || true', - ' sleep 5', - ` REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`, - ' if [ -n "$REMAIN_PIDS" ]; then', - ` echo "${label}_FORCE $REMAIN_PIDS"`, - ' kill -9 $REMAIN_PIDS || true', - ' fi', - 'fi', - ]; -} - -/** - * 读取远端当前活跃版本 - * @param {Object} config 部署配置 - * @return {String} 'v1' / 'v2';尚未初始化(无 current.md)时返回空字符串 - */ -function readRemoteCurrentVersion(config) { - const currentMdPath = `${config.deployRoot}/current.md`; - const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`; - const output = String(runSsh(config, script, { stdio: 'pipe' }) || '').replace(/\r/g, '').trim(); - - if (!output) return ''; - if (!VERSIONS.includes(output)) { - throw new Error(`远端 ${currentMdPath} 内容无效: "${output}",期望 v1 或 v2。`); - } - return output; -} - -/** - * 取另一个版本标识(v1 ↔ v2) - * @param {String} version 当前版本,为空时返回首次部署使用的 v1 - * @return {String} 目标版本 - */ -function otherVersion(version) { - if (!version) return 'v1'; - if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`); - return version === 'v1' ? 'v2' : 'v1'; -} - -/** - * 取版本对应端口 - * @param {Object} config 部署配置 - * @param {String} version 版本标识 - * @return {Number} 端口 - */ -function portOf(config, version) { - if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`); - return config.ports[version]; -} - -/** - * 生成「释放指定端口」的远端脚本行(结束占用该端口的残留进程) - * @param {Number} port 端口 - * @return {String[]} 脚本行 - */ -function buildFreePortLines(port) { - return [ - `TARGET_PORT=${port}`, - 'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', - 'if [ -n "$PORT_PID" ]; then', - ' echo "端口 $TARGET_PORT 被进程 $PORT_PID 占用,先停止..."', - ' kill "$PORT_PID" 2>/dev/null || true', - ' sleep 5', - ' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', - ' if [ -n "$PORT_PID_CHECK" ]; then', - ' echo "端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,强制停止"', - ' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true', - ' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true', - ' fi', - 'else', - ' echo "端口 $TARGET_PORT 空闲"', - 'fi', - ]; -} - -/** - * 生成「启动实例」的远端脚本行(后台运行,输出重定向到启动日志) - * @param {String} dirPath 版本目录 - * @param {String} startCommand 启动命令(如 npm start) - * @param {String} logPath 启动日志路径 - * @return {String[]} 脚本行 - */ -function buildStartInstanceLines(dirPath, startCommand, logPath) { - return [ - `cd ${quoteForBash(dirPath)}`, - `nohup bash -lc ${quoteForBash(startCommand)} > ${quoteForBash(logPath)} 2>&1 < /dev/null &`, - `echo "已启动实例: ${dirPath},启动日志: ${logPath}"`, - ]; -} - -/** - * 生成「健康检查」的远端脚本行(轮询 http://127.0.0.1:<端口><路径>) - * @param {Number} port 端口 - * @param {String} healthPath 检查路径 - * @param {String} label 日志标签 - * @param {Number} [attempts] 重试次数 - * @param {Number} [interval] 重试间隔秒数 - * @return {String[]} 脚本行 - */ -function buildHealthCheckLines(port, healthPath, label, attempts = 10, interval = 2) { - return [ - `TARGET_PORT=${port}`, - `HEALTH_PATH=${quoteForBash(healthPath)}`, - `for attempt in $(seq 1 ${attempts}); do`, - ' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then', - ` echo "健康检查通过: ${label} 已就绪(端口 $TARGET_PORT)"`, - ' break', - ' fi', - ` if [ "$attempt" -eq ${attempts} ]; then`, - ` echo "健康检查超时: ${label}(端口 $TARGET_PORT)未就绪" >&2`, - ' exit 1', - ' fi', - ` sleep ${interval}`, - 'done', - ]; -} - -/** - * 生成「切换 Nginx upstream 并 reload」的远端脚本行 - * @param {String} upstreamPath upstream 文件路径 - * @param {Number} port 目标端口 - * @return {String[]} 脚本行 - */ -function buildNginxSwitchLines(upstreamPath, port) { - return [ - `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${port} > ${quoteForBash(upstreamPath)}`, - 'nginx -t && nginx -s reload', - `echo "Nginx upstream 已切换至 127.0.0.1:${port}"`, - ]; -} - -module.exports = { - ROOT, - VERSIONS, - DEFAULT_ENV, - LOCAL_CONFIG_PATH, - EXAMPLE_CONFIG_PATH, - buildArchive, - buildFreePortLines, - buildHealthCheckLines, - buildNginxSwitchLines, - buildRemoteCleanupGuard, - buildScopedEggStopLines, - buildSshBaseArgs, - buildStartInstanceLines, - ensureCommandAvailable, - ensureTempDeployDir, - getNowStamp, - listDeployableFiles, - loadDeployConfig, - otherVersion, - pathMatchesRule, - portOf, - quoteForBash, - readRemoteCurrentVersion, - runCommand, - runScp, - runSsh, -}; diff --git a/backend/script/deploy-remote.cjs b/backend/script/deploy-remote.cjs deleted file mode 100644 index b69dfb1..0000000 --- a/backend/script/deploy-remote.cjs +++ /dev/null @@ -1,202 +0,0 @@ -'use strict'; - -/** - * 后端发布脚本(双实例蓝绿) - * - * npm run deploy # 等价 npm run deploy:prod - * npm run deploy:prod - * - * 流程: - * 1. 本地按 git 文件清单打发布包(不含 .env / uploads / logs 等) - * 2. 读取远端 current.md,确定目标版本(v1 ↔ v2 交替;首次发布用 v1) - * 3. 上传到 /.deploy/incoming,清理目标版本目录(保留 logs/run/node_modules)后解压 - * 4. 补齐 .env、安装生产依赖、释放目标端口、启动新实例 - * 5. 健康检查通过后切换 Nginx upstream(nginx -t && nginx -s reload) - * 6. 停止旧实例、记录当前发布版本号 - * 健康检查失败:回滚 current.md、杀掉新实例,旧实例不受影响(线上不中断) - */ - -const fs = require('node:fs'); -const path = require('node:path'); -const { - ROOT, - buildArchive, - buildFreePortLines, - buildHealthCheckLines, - buildNginxSwitchLines, - buildRemoteCleanupGuard, - buildScopedEggStopLines, - buildStartInstanceLines, - ensureCommandAvailable, - getNowStamp, - loadDeployConfig, - otherVersion, - portOf, - quoteForBash, - readRemoteCurrentVersion, - runCommand, - runScp, - runSsh, -} = require('./deploy-lib.cjs'); - -function main() { - const envName = process.argv[2] || 'production'; - const config = loadDeployConfig(envName); - - ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); - ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); - ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); - ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); - - // 1. 远端当前活跃版本 → 本次目标版本 - const currentVersion = readRemoteCurrentVersion(config); - const targetVersion = otherVersion(currentVersion); - const targetPort = portOf(config, targetVersion); - const targetDir = `${config.deployRoot}/${targetVersion}`; - const oldDir = currentVersion ? `${config.deployRoot}/${currentVersion}` : ''; - - if (currentVersion) { - console.log(`远端当前活跃版本: ${currentVersion}(端口 ${portOf(config, currentVersion)})`); - } else { - console.log('远端尚未初始化(无 current.md),本次作为首次发布,落到 v1'); - } - console.log(`本次发布目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`); - - // 2. 本地打包 - const stamp = getNowStamp(); - const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); - const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); - const releaseVersion = `v${packageJson.version || '0.0.0'}-${stamp}-${gitCommitShort}`; - const { archivePath, fileCount } = buildArchive(stamp, config); - const remoteArchive = `${config.incomingDir}/${path.basename(archivePath)}`; - console.log(`发布包已生成: ${archivePath}(${fileCount} 个文件,版本号 ${releaseVersion})`); - - // 3. 远端准备目录并上传发布包 - runSsh(config, [ - 'set -euo pipefail', - `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.stateDir)}`, - `echo "远端目录已就绪: ${targetDir}"`, - ].join('\n')); - - runScp(config, archivePath, remoteArchive); - console.log(`发布包已上传: ${remoteArchive}`); - - // 4. 清理目标目录 → 解压 → 补齐 .env → 安装生产依赖 - const envFile = `${config.deployRoot}/.env`; - const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs); - const installScript = [ - 'set -euo pipefail', - `TARGET_DIR=${quoteForBash(targetDir)}`, - `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, - `ENV_FILE=${quoteForBash(envFile)}`, - 'cd "$TARGET_DIR"', - // 清理上一次遗留的代码(保留 .deploy 与 sharedDirs:logs / run / node_modules) - `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, - 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', - 'rm -f "$REMOTE_ARCHIVE"', - // 服务器端真实环境变量只维护一份(/.env),首次落到某版本目录时复制过去; - // 已存在则不覆盖,便于个别版本目录单独调整 - 'if [ ! -f "$TARGET_DIR/.env" ]; then', - ' if [ -f "$ENV_FILE" ]; then', - ' cp -a "$ENV_FILE" "$TARGET_DIR/.env"', - ' echo "ENV_COPIED $ENV_FILE -> $TARGET_DIR/.env"', - ' else', - ' echo "WARN_ENV_MISSING 未找到 $ENV_FILE,请先在该文件写入生产环境变量(数据库、JWT_SECRET 等)" >&2', - ' fi', - 'else', - ' echo "ENV_KEPT $TARGET_DIR/.env(已存在,未覆盖)"', - 'fi', - config.installCommand, - ].join('\n'); - runSsh(config, installScript); - console.log(`远端代码已更新并安装依赖: ${targetDir}`); - - // 5. 释放目标端口(防止残留进程占用导致新实例起不来) - runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n')); - const startLogPath = `/tmp/oms-${targetVersion}-start.log`; - - // 6. 记录 current.md 并启动新实例 - runSsh(config, [ - 'set -euo pipefail', - `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, - ...buildStartInstanceLines(targetDir, config.startCommand, startLogPath), - ].join('\n')); - - // 7. 健康检查(20 秒内轮询;失败则回滚记录并清理新实例,旧实例继续服务) - const healthCheckScript = [ - 'set -euo pipefail', - ...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion), - ].join('\n'); - - try { - runSsh(config, healthCheckScript); - } catch (err) { - console.error(`[ERROR] 新实例健康检查失败: ${err.message}`); - console.error(`[ERROR] 发布中止(未切换 Nginx),请查看启动日志 ${startLogPath}`); - - if (currentVersion) { - try { - runSsh(config, [ - 'set -euo pipefail', - `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, - `echo "current.md 已回滚为 ${currentVersion}"`, - ].join('\n')); - } catch (revertErr) { - console.error(`[ERROR] current.md 回滚失败: ${revertErr.message}`); - } - } - - try { - runSsh(config, [ - 'set -euo pipefail', - ...buildScopedEggStopLines(targetDir, 'STOP_FAILED_NEW'), - ].join('\n')); - } catch (killErr) { - console.error(`[ERROR] 清理失败的新实例出错: ${killErr.message}`); - } - - console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`); - if (currentVersion) console.error(`[ERROR] 旧实例(${currentVersion})仍在服务,线上不受影响`); - process.exit(1); - } - - // 8. 切换 Nginx upstream(仅健康检查通过后执行) - const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`; - try { - runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n')); - } catch (err) { - console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); - console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`); - console.warn('[WARN] 若站点配置尚未 include 该文件,请先按 config/deploy.config.example.cjs 顶部说明改一次站点配置'); - } - - // 9. 停止旧实例 - if (currentVersion) { - try { - runSsh(config, [ - 'set -euo pipefail', - ...buildScopedEggStopLines(oldDir, 'STOP_OLD'), - `echo "旧实例 ${currentVersion} 已停止"`, - ].join('\n')); - } catch (err) { - console.warn(`[WARN] 停止旧实例失败: ${err.message},请人工确认并停止 ${oldDir} 下的进程`); - } - } - - // 10. 记录当前发布版本号 - try { - runSsh(config, [ - 'set -euo pipefail', - `printf '%s\\n' ${quoteForBash(releaseVersion)} > ${quoteForBash(`${config.stateDir}/current-release.txt`)}`, - `echo "当前发布版本: ${releaseVersion}"`, - ].join('\n')); - } catch (err) { - console.warn(`[WARN] 记录发布版本号失败: ${err.message}`); - } - - console.log(`发布完成: ${config.username}@${config.host}:${targetDir}`); - console.log(`活跃版本: ${targetVersion}(端口 ${targetPort})`); - console.log(`发布版本号: ${releaseVersion}`); -} - -main(); diff --git a/backend/script/init-deploy-config.cjs b/backend/script/init-deploy-config.cjs deleted file mode 100644 index 5d98ce7..0000000 --- a/backend/script/init-deploy-config.cjs +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -/** - * 初始化后端部署配置:把 config/deploy.config.example.cjs 复制为 config/deploy.config.local.cjs。 - * deploy.config.local.cjs 含服务器地址与 SSH 私钥路径,已被 .gitignore 排除,不要提交。 - * - * 用法:npm run deploy:init - */ - -const fs = require('node:fs'); -const { EXAMPLE_CONFIG_PATH, LOCAL_CONFIG_PATH } = require('./deploy-lib.cjs'); - -if (fs.existsSync(LOCAL_CONFIG_PATH)) { - console.log('ℹ️ config/deploy.config.local.cjs 已存在,未覆盖。'); - console.log(` 如需重新生成,请先删除该文件:${LOCAL_CONFIG_PATH}`); - process.exit(0); -} - -fs.copyFileSync(EXAMPLE_CONFIG_PATH, LOCAL_CONFIG_PATH); -console.log('✅ 已生成 config/deploy.config.local.cjs'); -console.log(' 请按实际服务器信息确认 host / username / privateKeyPath / deployRoot / ports,然后执行 npm run deploy。'); diff --git a/backend/script/rollback-remote.cjs b/backend/script/rollback-remote.cjs deleted file mode 100644 index 1bbdd12..0000000 --- a/backend/script/rollback-remote.cjs +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -/** - * 后端回滚脚本(双实例蓝绿:切回另一套版本目录,无需重新构建/上传) - * - * npm run rollback # 回滚到上一个版本(v1 ↔ v2) - * npm run rollback -- --to=v1 # 指定切回某个版本 - * - * 流程:启动目标版本实例 → 健康检查通过 → 切换 Nginx upstream → 记录 current.md → 停止当前实例 - * 目标版本目录不可用(未发布过)时会直接报错,当前实例不受影响。 - */ - -const { - VERSIONS, - buildFreePortLines, - buildHealthCheckLines, - buildNginxSwitchLines, - buildScopedEggStopLines, - buildStartInstanceLines, - ensureCommandAvailable, - loadDeployConfig, - otherVersion, - portOf, - quoteForBash, - readRemoteCurrentVersion, - runSsh, -} = require('./deploy-lib.cjs'); - -/** - * 解析 --to=v1|v2 参数 - * @param {String[]} argv 参数数组 - * @return {String} 目标版本(未指定时返回空字符串) - */ -function parseTargetArg(argv) { - const arg = argv.find(item => item.startsWith('--to=')); - if (!arg) return ''; - const value = arg.slice('--to='.length).trim(); - if (!VERSIONS.includes(value)) { - throw new Error(`--to 取值无效: ${value}(支持 v1 / v2)`); - } - return value; -} - -function main() { - const envName = process.argv[2] || 'production'; - const config = loadDeployConfig(envName); - ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); - - const currentVersion = readRemoteCurrentVersion(config); - if (!currentVersion) { - throw new Error(`远端 ${config.deployRoot}/current.md 不存在或为空,没有可回滚的版本(请先执行 npm run deploy)。`); - } - - const targetVersion = parseTargetArg(process.argv.slice(3)) || otherVersion(currentVersion); - if (targetVersion === currentVersion) { - throw new Error(`目标版本与当前活跃版本相同(${targetVersion}),无需回滚。`); - } - - const currentPort = portOf(config, currentVersion); - const targetPort = portOf(config, targetVersion); - const currentDir = `${config.deployRoot}/${currentVersion}`; - const targetDir = `${config.deployRoot}/${targetVersion}`; - const startLogPath = `/tmp/oms-${targetVersion}-start.log`; - - console.log(`当前活跃版本: ${currentVersion}(端口 ${currentPort})`); - console.log(`回滚目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`); - - // 1. 校验目标版本可用;缺依赖时补装 - runSsh(config, [ - 'set -euo pipefail', - `TARGET_DIR=${quoteForBash(targetDir)}`, - 'if [ ! -f "$TARGET_DIR/package.json" ]; then', - ' echo "目标版本目录不可用:$TARGET_DIR/package.json 不存在(该版本可能尚未发布过)" >&2', - ' exit 1', - 'fi', - 'if [ ! -d "$TARGET_DIR/node_modules" ]; then', - ' echo "目标版本缺少 node_modules,先安装依赖..."', - ` ( cd "$TARGET_DIR" && ${config.installCommand} )`, - 'fi', - ].join('\n')); - - // 2. 释放目标端口并启动目标实例 - runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n')); - runSsh(config, [ - 'set -euo pipefail', - ...buildStartInstanceLines(targetDir, config.startCommand, startLogPath), - ].join('\n')); - - // 3. 健康检查(失败则清理刚启动的实例,当前实例继续服务) - try { - runSsh(config, [ - 'set -euo pipefail', - ...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion), - ].join('\n')); - } catch (err) { - console.error(`[ERROR] 回滚目标健康检查失败: ${err.message}`); - console.error(`[ERROR] 回滚中止(未切换 Nginx),请查看启动日志 ${startLogPath}`); - try { - runSsh(config, [ - 'set -euo pipefail', - ...buildScopedEggStopLines(targetDir, 'STOP_ROLLBACK_TARGET'), - ].join('\n')); - } catch (killErr) { - console.error(`[ERROR] 清理回滚目标实例出错: ${killErr.message}`); - } - console.error(`[ERROR] 当前实例(${currentVersion})仍在服务,线上不受影响`); - process.exit(1); - } - - // 4. 切换 Nginx upstream - const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`; - try { - runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n')); - } catch (err) { - console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); - console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`); - } - - // 5. 记录 current.md 并停止原实例 - runSsh(config, [ - 'set -euo pipefail', - `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, - ...buildScopedEggStopLines(currentDir, 'STOP_ROLLED_BACK'), - `echo "current.md 已更新为 ${targetVersion}"`, - ].join('\n')); - - console.log(`回滚完成: 线上已切回 ${targetVersion}(端口 ${targetPort})`); - console.log(`如需再次前进,执行 npm run rollback -- --to=${currentVersion}`); -} - -main(); diff --git a/frontend/package.json b/frontend/package.json index 0dd29c5..786291b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -7,13 +7,16 @@ "dev": "vite", "build": "vue-tsc --noEmit && vite build", "preview": "vite preview", - "deploy": "node ./scripts/deploy.mjs", - "rollback": "node ./scripts/rollback.mjs", - "deploy:init": "node ./scripts/init-config.mjs" + "deploy": "npm --prefix ../tools run deploy --", + "deploy:frontend": "npm --prefix ../tools run deploy:frontend --", + "rollback": "npm --prefix ../tools run rollback --", + "rollback:frontend": "npm --prefix ../tools run rollback:frontend", + "deploy:init": "npm --prefix ../tools run init" }, "dependencies": { "@element-plus/icons-vue": "^2.3.1", "axios": "^1.20.0", + "element-china-area-data": "^6.1.0", "element-plus": "^2.9.1", "pinia": "^2.3.1", "vue": "^3.5.13", diff --git a/frontend/scripts/DEPLOY.md b/frontend/scripts/DEPLOY.md deleted file mode 100644 index c90183c..0000000 --- a/frontend/scripts/DEPLOY.md +++ /dev/null @@ -1,100 +0,0 @@ -# OMS 前端蓝绿发布 - -发布方式与 WMS 前端一致:服务器上按版本目录存放,`current` 软链接指向当前线上版本,切换是原子的,因此**发布/回滚都不中断服务**。 - -## 目录结构 - -``` -frontend/ -├─ scripts/ -│ ├─ deploy.mjs # 本地:构建 → 打包 → 上传 → 触发远程切换 -│ ├─ rollback.mjs # 本地:把 current 切回上一个版本 -│ ├─ init-config.mjs # 生成本地部署配置 -│ ├─ deploy.config.example.json # 配置模板(提交 git) -│ ├─ deploy.config.json # 真实配置(.gitignore 排除,禁止提交) -│ └─ remote/ -│ ├─ deploy.sh # 服务器端执行:解压 → 校验 → 原子切换 → 清理 -│ └─ rollback.sh # 服务器端执行:原子回滚 -``` - -服务器上的布局(`basePath` = `/www/wwwroot/oms.gztbyc.com`): - -``` -/www/wwwroot/oms.gztbyc.com/ -├─ releases/ -│ ├─ v20260914_153000_12345/ # 各版本静态文件(index.html + assets/…) -│ └─ ... -└─ current -> releases/v2026... # 软链接,Nginx 站点根目录指向它 -``` - -## 服务器前置条件(仅首次) - -```bash -mkdir -p /www/wwwroot/oms.gztbyc.com/releases -``` - -宝塔面板:站点 `oms.gztbyc.com` 的**网站目录**要设为 `/www/wwwroot/oms.gztbyc.com/current` -(而不是 `.../oms.gztbyc.com`),其余 `index.html`、`/api` 反向代理到后端等配置保持不变。 - -不需要 `chown` 到 www 用户,但站点目录需对 ssh 用户可写(示例用 `root`)。 - -## 使用 - -```bash -cd frontend - -# 首次:生成本地部署配置,然后按实际服务器信息修改 -npm run deploy:init - -# 发布(内部执行 npm run build → 打包 → 上传 → 原子切换) -npm run deploy - -# 跳过构建,直接发布现有 dist(调试用) -npm run deploy -- --skip-build - -# 回滚到上一个版本(不构建、不上传,秒级) -npm run rollback -``` - -## 配置项(`scripts/deploy.config.json`) - -| 字段 | 说明 | -| --- | --- | -| `user` | ssh 登录用户 | -| `ip` | 服务器 IP | -| `basePath` | 站点根目录,`releases/` 与 `current` 都在其下 | -| `keepReleases` | 服务器保留的最近版本数(默认 5,超出的自动清理,不会删除 current 指向的版本) | -| `siteHost` | 发版后健康检查用的域名(本机 curl 带 Host 头访问 `https://127.0.0.1/`,仅打印状态码,不阻断发布) | -| `sshKey` | 私钥:绝对路径或 `~/.ssh` 下的文件名;留空则用 ssh 默认密钥/agent | - -## 发布流程细节(`remote/deploy.sh`) - -1. 解压到独立的新版本目录,**全程不触碰线上目录** -2. 校验 `index.html` 非空,且 `index.html` 中引用的 `/assets/*.js|css` 都存在,否则中止(线上版本不受影响) -3. 把最近若干个历史版本中、本版本缺失的文件并入新版本 —— 保证切换后仍停留在旧版页面的用户动态加载旧 chunk 不 404(无感切换的关键) -4. `ln -sfn` 建临时软链 + `mv -Tf` 改名,原子切换 -5. 健康检查(仅提示) -6. 清理超出 `keepReleases` 的旧版本 - -## 注意 - -- `scripts/deploy.config.json` **不要提交 git**(已在 `frontend/.gitignore` 中排除),只提交 `deploy.config.example.json` 模板。 -- 需要本机具备 `ssh`、`scp`、`tar`(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。 -- 后端 `oms` 服务不在本脚本范围内,本脚本只发布前端静态文件。 - -## 前后端域名与跨域(CORS) - -| 站点 | 说明 | -| --- | --- | -| `oms.gztbyc.com` | 前端静态站点,由本脚本发布(Nginx 根目录指向 `current`) | -| `api.oms.gztbyc.com` | 后端 API 站点,Nginx 反代到 egg 后端(端口 6090),接口路由前缀 `/api` | - -- 前端 API 地址由构建期环境变量 `VITE_API_BASE_URL` 决定: - - 生产 `${VITE_API_BASE_URL}=http://api.oms.gztbyc.com/api`(`frontend/.env.production`) - - 开发 `VITE_API_BASE_URL=/api`(`frontend/.env.development`,由 vite dev server 代理到 `http://localhost:6090`) -- 两个域名**不同源**,跨域请求由后端 `backend/app/middleware/cors.js` 按白名单放行 - (默认已含 http/https 的 `oms.gztbyc.com`,可用后端环境变量 `CORS_ORIGINS` 覆盖)。 -- 后端返回的图片/头像地址是相对路径(`/api/files/raw/...`),前端渲染时由 - `frontend/src/utils/media.ts` 的 `mediaUrl()` 补全为 API 站点绝对地址。 -- ⚠️ 若前端站点改用 HTTPS 访问,`VITE_API_BASE_URL` 必须同步改为 `https://api.oms.gztbyc.com/api`, - 否则浏览器会按「混合内容(Mixed Content)」拦截请求。 diff --git a/frontend/scripts/deploy.config.example.json b/frontend/scripts/deploy.config.example.json deleted file mode 100644 index 1a077b4..0000000 --- a/frontend/scripts/deploy.config.example.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "user": "root", - "ip": "112.124.21.102", - "basePath": "/www/wwwroot/oms.gztbyc.com", - "keepReleases": 5, - "siteHost": "oms.gztbyc.com", - "sshKey": "C:\\Users\\lfmingren\\.ssh\\112.124.21.102_id_ed25519" -} diff --git a/frontend/scripts/deploy.mjs b/frontend/scripts/deploy.mjs deleted file mode 100644 index 5a3242c..0000000 --- a/frontend/scripts/deploy.mjs +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env node -/** - * OMS 前端蓝绿发布脚本(Windows / macOS / Linux 通用) - * - * 发布原理: - * 1. 本地构建 dist,压缩后上传到服务器 `${basePath}/releases/<版本号>/`(全新目录,不触碰线上目录) - * 2. 服务器上解压并做完整性校验,再把历史版本的静态资源补齐(旧 chunk 不 404) - * 3. 通过 `current` 软链接「先建临时链接再 mv 改名」原子切换,切换瞬间服务不中断 - * 4. 健康检查(仅提示)并清理超出保留数量的旧版本 - * - * 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。 - * - * 用法: - * npm run deploy 构建 + 发布 - * npm run deploy -- --skip-build 跳过本地构建,直接发布现有 dist(调试用) - */ -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 PROJECT_ROOT = path.resolve(__dirname, '..'); - -// --- 配置(读取独立配置文件,该文件不纳入版本控制) --- -const CONFIG_PATH = path.join(__dirname, 'deploy.config.json'); -const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json'); -if (!existsSync(CONFIG_PATH)) { - console.error('❌ 缺少配置文件 scripts/deploy.config.json'); - console.error(` 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。`); - console.error(` 模板路径:${EXAMPLE_PATH}`); - process.exit(1); -} -const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8')); - -// --- 配置校验 --- -const REQUIRED_KEYS = ['user', 'ip', 'basePath', 'siteHost']; -const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]); -if (missingKeys.length) { - console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`); - console.error(' 参考 scripts/deploy.config.example.json 补齐。'); - process.exit(1); -} - -const SKIP_BUILD = process.argv.includes('--skip-build'); - -const USER = config.user; -const IP = config.ip; // 服务器 IP -const BASE_PATH = config.basePath; // 站点在服务器上的存放路径(releases/current 都在其下) -const KEEP_RELEASES = Number(config.keepReleases) > 0 ? Number(config.keepReleases) : 5; // 服务器保留的最近版本数 -const SITE_HOST = config.siteHost; // 发版后健康检查域名 -const LOCAL_DIST = path.join(PROJECT_ROOT, 'dist'); -const SSH_KEY = resolveSshKey(config.sshKey); -const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])]; -const HOST = `${USER}@${IP}`; -const TARBALL = 'dist.tar.gz'; - -const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm'; - -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())}`; -} - -/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */ -function resolveSshKey(value) { - if (!value) return ''; - if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1)); - return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value); -} - -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); -} - -console.log(`🚀 开始发布 OMS 前端,版本: ${RELEASE_NAME}`); -console.log(` 目标:${HOST}:${REMOTE_RELEASE}`); - -try { - // 1. 本地打包(失败立即中止,防止把坏产物发到线上) - if (SKIP_BUILD) { - console.log('⏭️ 已跳过本地构建(--skip-build)'); - } else { - run(NPM, ['run', 'build'], { cwd: PROJECT_ROOT }); - } - - // 2. 校验本地产物完整性 - if (!existsSync(path.join(LOCAL_DIST, 'index.html')) || !existsSync(path.join(LOCAL_DIST, 'assets'))) { - console.error('❌ 本地构建产物不完整(缺少 index.html 或 assets),中止发布'); - process.exit(1); - } - - // 3. 压缩并上传到服务器上的新版本目录(全程不触碰 current 指向的线上目录) - run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.'], { cwd: PROJECT_ROOT }); - run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]); - run('scp', [...SSH_OPTS, path.join(PROJECT_ROOT, TARBALL), `${HOST}:${REMOTE_RELEASE}/${TARBALL}`]); - - // 4. 远程:解压 → 校验 → 补齐旧资源 → 原子切换 → 健康检查 → 清理 - 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(path.join(PROJECT_ROOT, TARBALL), { force: true }); -} diff --git a/frontend/scripts/init-config.mjs b/frontend/scripts/init-config.mjs deleted file mode 100644 index d88b996..0000000 --- a/frontend/scripts/init-config.mjs +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env node -/** - * 初始化部署配置:把 scripts/deploy.config.example.json 复制为 scripts/deploy.config.json。 - * deploy.config.json 含服务器/密钥信息,已被 .gitignore 排除,不要提交。 - * - * 用法:npm run deploy:init - */ -import { copyFileSync, existsSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json'); -const CONFIG_PATH = path.join(__dirname, 'deploy.config.json'); - -if (existsSync(CONFIG_PATH)) { - console.log('ℹ️ scripts/deploy.config.json 已存在,未覆盖。'); - console.log(` 如需重新生成,请先删除该文件:${CONFIG_PATH}`); - process.exit(0); -} - -copyFileSync(EXAMPLE_PATH, CONFIG_PATH); -console.log('✅ 已生成 scripts/deploy.config.json'); -console.log(' 请按实际服务器信息修改其中的 user / ip / basePath / siteHost / sshKey,然后再执行 npm run deploy。'); diff --git a/frontend/scripts/rollback.mjs b/frontend/scripts/rollback.mjs deleted file mode 100644 index 67b2a7c..0000000 --- a/frontend/scripts/rollback.mjs +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env node -/** - * OMS 前端蓝绿回滚脚本(Windows / macOS / Linux 通用) - * - * 回滚原理:把服务器上的 `current` 软链接原子切回 releases 里按时间排序的上一个版本。 - * 不做构建、不重新上传,秒级完成。 - * - * 依赖本机已安装:ssh(Windows 10 1803+ 自带 OpenSSH 客户端)。 - * - * 用法: - * npm run rollback - */ -import { spawnSync } from 'node:child_process'; -import { existsSync, readFileSync } 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('❌ 缺少配置文件 scripts/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 REQUIRED_KEYS = ['user', 'ip', 'basePath']; -const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]); -if (missingKeys.length) { - console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`); - process.exit(1); -} - -const USER = config.user; -const IP = config.ip; // 服务器 IP -const BASE_PATH = config.basePath; // 站点在服务器上的存放路径 -const SSH_KEY = resolveSshKey(config.sshKey); -const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])]; -const HOST = `${USER}@${IP}`; - -/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */ -function resolveSshKey(value) { - if (!value) return ''; - if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1)); - return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value); -} - -console.log('⏪ 正在回滚 OMS 前端到上一个版本...'); - -const remoteScript = readFileSync(path.join(__dirname, 'remote', 'rollback.sh'), 'utf8'); -const res = spawnSync('ssh', [...SSH_OPTS, HOST, `BASE='${BASE_PATH}' bash -s`], { - input: remoteScript, - stdio: ['pipe', 'inherit', 'inherit'], -}); - -if (res.error) { - console.error(`❌ 无法执行 ssh: ${res.error.message}`); - if (res.error.code === 'ENOENT') { - console.error(' 请确认本机已安装 OpenSSH 客户端(Windows 10 1803+ 自带)。'); - } - process.exit(1); -} -process.exit(res.status ?? 1); diff --git a/tools/.env.example b/tools/.env.example new file mode 100644 index 0000000..31c3353 --- /dev/null +++ b/tools/.env.example @@ -0,0 +1,3 @@ +# 可选:CLI 启动时会自动加载 tools/.env;当前发布脚本不依赖环境变量, +# 需要时可复制本文件为 .env 并按需填写 +# EXAMPLE_KEY=value diff --git a/tools/DEPLOY.md b/tools/DEPLOY.md new file mode 100644 index 0000000..7c22c50 --- /dev/null +++ b/tools/DEPLOY.md @@ -0,0 +1,189 @@ +# OMS 发布工具(tools) + +`tools/` 是前后端**统一的发布入口**:一次 `npm run deploy` 同时更新后端(Egg 双实例蓝绿)与前端 +(releases 目录 + `current` 软链接),两条链路都是原子切换,线上不中断。 + +``` +tools/ +├─ src/ +│ ├─ cli.ts # 命令入口(tsx 直跑,或 tsc 后 node dist/cli.js) +│ ├─ commands/ # deploy(发布)/ rollback(回滚) +│ └─ lib/ # 配置、git 约束、打包、ssh/scp、远端脚本生成 +├─ config/ +│ ├─ deploy.config.example.cjs # 发布配置模板(提交 git) +│ ├─ deploy.config.local.cjs # 发布配置本地真实值(.gitignore 排除) +│ ├─ env.production.example # 生产环境变量模板(本机权威副本) +│ └─ env.production.local # 生产环境变量本地真实值(.gitignore 排除) +├─ remote/ # 前端服务器端 bash 脚本(deploy.sh / rollback.sh) +├─ temp/ # 本地发布包(.gitignore 排除) +└─ DEPLOY.md +``` + +## 一次性准备 + +```bash +cd tools +npm install # tsx / typescript(发布脚本本身零运行时依赖) +npm run init # 生成 config/deploy.config.local.cjs,然后填写 SSH 等信息 +``` + +需要本机具备 `git`、`tar`、`ssh`、`scp`(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。 + +## 命令 + +| 命令 | 说明 | +| --- | --- | +| `npm run deploy` | **前后端同时发布**:构建前端 → 打包前后端 → 上传 → 一次 SSH 完成切换 | +| `npm run deploy -- --skip-build` | 复用已有 `frontend/dist`,不重新构建 | +| `npm run deploy -- --dry-run` | 只做本地构建与打包,打印远端脚本,不连服务器(同样受 git 约束,可加 `--allow-dirty`) | +| `npm run deploy -- --allow-dirty` | 允许工作区有未提交改动时发布 | +| `npm run deploy:backend` | 只发布后端 | +| `npm run deploy:frontend` | 只发布前端 | +| `npm run rollback` | 前后端一起回滚 | +| `npm run rollback -- --to=v1` | 指定后端回滚到 v1(前端仍回上一个 releases 版本) | +| `npm run rollback -- --dry-run` | 只打印回滚脚本 | +| `npm run cli -- help` | 查看用法 | + +在项目目录里也能触发(内部转发到 tools): + +```bash +cd backend && npm run deploy # 前后端一起发布 +cd backend && npm run deploy:backend # 只发后端 +cd frontend && npm run deploy # 前后端一起发布 +cd frontend && npm run deploy:frontend # 只发前端 +cd frontend && npm run deploy -- --skip-build +``` + +> 首次在 `backend/` 或 `frontend/` 里调用前,请先在 `tools/` 执行过 `npm install`。 + +## 发布受限于 git + +- 工作区有未提交改动时**默认中止**,并列出改动文件;确认要带改动发布可加 `--allow-dirty` + (或在配置里设 `allowDirtyGit: true`),此时版本记录会标记 `dirty: true`。 +- 后端发布包严格按 `git ls-files --cached --others --exclude-standard` 生成,再按 + `deployIncludePaths` / `deployExcludePaths` 过滤,天然排除 `.env`、`uploads/`、`logs/` 等未入库内容。 +- 远端 `.deploy/state/versions.jsonl` 记录每次发布的 `version / commit / branch / env / dirty / + targets / frontendRelease / operator / time / files / size`,保留最近 `keepVersions` 条。 + +## 发布配置(独立文件) + +发布配置只放在 `tools/config/deploy.config.local.cjs`,不散落在前后端项目里: + +```js +module.exports = { + production: { + host, port, username, privateKeyPath, sshOptions, // SSH + allowDirtyGit: false, keepVersions: 30, keepBackups: 5, + backend: { + deployRoot, ports: { v1: 6090, v2: 6091 }, + healthCheckPath, healthCheckAttempts, healthCheckInterval, + sharedDirs, deployIncludePaths, deployExcludePaths, + installCommand, startCommand, runMigrations, startTitlePrefix, + sharedConfigDir, envFile, envFileLocalPath, uploadEnvFile, // 服务端共享配置 + nginxUpstreamFile, nginxReloadCommand, // Nginx + }, + frontend: { + enabled, basePath, distDir, buildCommand, keepReleases, siteHost, + }, + }, +}; +``` + +`backend` / `frontend` 任一段设为 `false` 即可停用对应的发布目标。 + +## 后端共享配置(服务的配置只有一份,本地覆盖它) + +服务器上后端的运行配置集中放在 `/shared-config/`: + +``` +/shared-config/ +├─ .env # 生产环境变量(数据库 / Redis / JWT_SECRET / UPLOAD_DIR …) +└─ config.*.js # 可选:不入库的服务端 Egg 配置 +``` + +发布流程里: + +1. **本地覆盖**:若本机 `tools/config/env.production.local` 存在(`envFileLocalPath` 可改),发布前先 + `scp` 到 `/shared-config/.env`,即本地权威副本覆盖服务端共享配置; + 本机没有该文件时跳过上传,沿用服务器上现有配置。 +2. **下发到实例**:发布时把 `shared-config/.env` 复制为版本目录的 `.env`, + `shared-config/config.*.js` 复制到版本目录的 `config/`,**覆盖**包内同名文件。 +3. **首次迁移**:若 `shared-config/.env` 还不存在,而老部署的 `/.env` 存在,会自动搬过去。 + +> 实例端口不再写进 `.env`:发布脚本以 `EGG_PORT=<槽位端口>` 启动实例(`dotenv` 不覆盖已存在的环境变量), +> v1/v2 共用同一份 `.env` 也不会串端口。 + +本地生产环境变量用 `config/env.production.example` 作为模板复制为 `config/env.production.local`,该文件已被 gitignore。 + +## 后端发布(双实例蓝绿) + +``` +/ +├─ v1/ v2/ # 两套代码目录,每次发布交替部署另一套 +├─ current.md # 当前活跃版本(v1 / v2) +├─ nginx-upstream.conf # proxy_pass http://127.0.0.1:<端口>; +├─ shared-config/ # 共享配置(见上) +└─ .deploy/ # incoming 上传包、backups 备份、state 版本记录、logs 启动日志 +``` + +单次远程序列:确定空闲槽位 → 释放端口 → 备份旧槽位 → 清理代码(保留 `sharedDirs`)→ 解压 +→ 应用共享配置 → 安装依赖(可选迁移)→ 启动新实例 → 健康检查 → 切 Nginx upstream → 写 `current.md` +→ 停旧实例 → 清理旧备份。 + +健康检查失败时脚本自己停掉新实例并退出,旧实例继续服务(`current.md` / upstream 都未改动)。 + +### Nginx 前置(仅首次,站点 api.oms.gztbyc.com) + +把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成 +`include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;`。 + +### 服务器端 `.env`(仅首次,之后由 shared-config 管理) + +需要包含:`MYSQL_*`、`REDIS_*`、`JWT_SECRET`、`UPLOAD_DIR=/uploads`(版本目录之外, +v1/v2 共用)、可选 `OMS_CALLBACK_BASE_URL`。 + +## 前端发布(releases + current 软链) + +``` +/ +├─ releases/ +│ ├─ v20261030_190028_2220/ # 各版本静态文件(index.html + assets/…) +│ └─ ... +└─ current -> releases/v2026... # 软链接,Nginx 站点根目录指向它 +``` + +服务器前置(仅首次):`mkdir -p /releases`,并把宝塔站点**网站目录**设为 `/current`。 + +`remote/deploy.sh` 流程:解压到新版本目录(不触碰线上目录)→ 校验 `index.html` 与引用的 +`/assets/*.js|css` → 合并历史版本中缺失的文件(旧 chunk 不 404)→ `ln -sfn` + `mv -Tf` 原子切换 +→ 健康检查(仅提示)→ 按 `keepReleases` 清理旧版本。失败时脚本会删除未上线的版本目录。 + +## 前后端同时发布时的顺序 + +后端先完成(健康检查通过、Nginx 已切到新实例、`current.md` 已更新),再切前端 `current` 软链: + +- 后端失败 → 前端完全不执行,线上保持原样; +- 后端成功、前端失败 → 后端已上线(新 API 可用),前端仍是上一版,脚本会清理失败的前端目录。 + +## 注意 + +- `tools/config/deploy.config.local.cjs`、`tools/config/env.production.local` **不要提交 git** + (根 `.gitignore` 已排除),只提交 `*.example.*` 模板。 +- `tools/temp/` 是本地发布包临时目录,已被忽略(保留最近 3 个包)。 + +## 前后端域名与跨域(CORS) + +| 站点 | 说明 | +| --- | --- | +| `oms.gztbyc.com` | 前端静态站点,由前端发布流程更新(Nginx 根目录指向 `current`) | +| `api.oms.gztbyc.com` | 后端 API 站点,Nginx 反代到 egg 后端(端口由 `nginx-upstream.conf` 决定),路由前缀 `/api` | + +- 前端 API 地址由构建期环境变量 `VITE_API_BASE_URL` 决定: + - 生产 `${VITE_API_BASE_URL}=http://api.oms.gztbyc.com/api`(`frontend/.env.production`) + - 开发 `VITE_API_BASE_URL=/api`(`frontend/.env.development`,由 vite dev server 代理到 `http://localhost:6090`) +- 两个域名**不同源**,跨域请求由后端 `backend/app/middleware/cors.js` 按白名单放行 + (默认已含 http/https 的 `oms.gztbyc.com`,可用后端环境变量 `CORS_ORIGINS` 覆盖)。 +- 后端返回的图片/头像地址是相对路径(`/api/files/raw/...`),前端渲染时由 + `frontend/src/utils/media.ts` 的 `mediaUrl()` 补全为 API 站点绝对地址。 +- ⚠️ 若前端站点改用 HTTPS 访问,`VITE_API_BASE_URL` 必须同步改为 `https://api.oms.gztbyc.com/api`, + 否则浏览器会按「混合内容(Mixed Content)」拦截请求。 diff --git a/tools/config/deploy.config.example.cjs b/tools/config/deploy.config.example.cjs new file mode 100644 index 0000000..3b49f01 --- /dev/null +++ b/tools/config/deploy.config.example.cjs @@ -0,0 +1,114 @@ +'use strict'; + +/** + * OMS 发布配置模板(此文件提交 git,供复制使用) + * + * 使用方式: + * cd tools && npm run init # 生成 deploy.config.local.cjs + * 然后填写 SSH / 目录等真实信息 + * deploy.config.local.cjs 已被 .gitignore 排除,**不要提交**(内含服务器地址与私钥路径)。 + * + * 发布模型(一次发布同时更新前后端): + * 后端:/{v1,v2} 双实例蓝绿 + current.md + nginx-upstream.conf + * 前端:/releases/<版本>/ 目录 + current 软链接原子切换 + * + * /shared-config/ 服务端共享配置(不入库):可放 config.*.js 与 .env; + * 每次发布复制到版本目录,覆盖包内同名文件 + * /.deploy/ 发布工作目录:incoming 上传包、backups 备份、state 版本记录 + * + * Nginx 前置(仅首次,站点 api.oms.gztbyc.com): + * 把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成 + * `include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;` + */ +module.exports = { + production: { + // ==================== SSH ==================== + host: '__FILL_SSH_HOST__', + port: 22, + username: '__FILL_SSH_USERNAME__', + // 私钥:绝对路径、~/ 开头,或相对仓库根目录的路径 + privateKeyPath: '__FILL_PRIVATE_KEY_PATH__', + sshOptions: [ 'StrictHostKeyChecking=accept-new' ], + + // ==================== 发布约束(受限于 git)==================== + // 工作区有未提交改动时禁止发布(可用 npm run deploy -- --allow-dirty 临时放行) + allowDirtyGit: false, + // 远端保留的版本记录条数 / 备份包个数 + keepVersions: 30, + keepBackups: 5, + + // ==================== 后端(Egg 双实例蓝绿)==================== + backend: { + deployRoot: '/www/wwwroot/api.oms.gztbyc.com', + + // 双实例端口;nginx-upstream.conf 指向当前活跃版本的端口 + ports: { v1: 6090, v2: 6091 }, + + // 新实例启动后轮询 http://127.0.0.1:<端口> + healthCheckPath: '/', + healthCheckAttempts: 10, + healthCheckInterval: 2, + + // 清理旧代码时保留的目录(位于版本目录内) + // 注意:.env 不保留,每次发布都从 shared-config 重新覆盖 + sharedDirs: [ 'logs', 'run', 'node_modules' ], + + // 发布包内容(相对 backend 根目录,`**` 表示该目录下全部内容) + deployIncludePaths: [ + '.sequelizerc', + 'app.js', + 'app/**', + 'config/**', + 'database/**', + 'package.json', + 'package-lock.json', + ], + deployExcludePaths: [ + '.env', + '.env.*', + 'uploads/**', + 'logs/**', + 'run/**', + 'temp/**', + 'test/**', + 'swagger.json', + ], + + // 远端安装 / 启动命令;实例端口由发布脚本强制注入 EGG_PORT,无需写进 .env + installCommand: 'npm install --production', + startCommand: 'npm start', + // 启动前是否执行数据库迁移(npm run migration:up,需要 installCommand 安装 devDependencies) + runMigrations: false, + startTitlePrefix: 'oms', + + // ===== 服务端共享配置(后端的配置共享出来)===== + // 不写该字段则默认 /shared-config;设为 '' 表示不启用共享配置 + // 共享目录内可放 config.*.js 与 envFile,发布时复制到版本目录并覆盖包内同名文件 + envFile: '.env', + // 本机权威副本(相对仓库根目录,已 gitignore);存在时发布前上传,覆盖服务端共享 env + envFileLocalPath: 'tools/config/env.production.local', + uploadEnvFile: true, + + // ===== Nginx ===== + // 不写 nginxUpstreamFile 则默认 /nginx-upstream.conf;设为 '' 表示不管理 upstream + // 切换 upstream 后执行的重载命令;设为 '' 则只写文件不重载 + nginxReloadCommand: 'nginx -t && nginx -s reload', + }, + + // ==================== 前端(releases + current 软链)==================== + frontend: { + // false 表示本次发布不动前端 + enabled: true, + // 站点根目录,releases/ 与 current 都在其下 + basePath: '/www/wwwroot/oms.gztbyc.com', + // 本机构建产物的目录(相对仓库根目录) + distDir: 'frontend/dist', + // 发布前本地构建命令(在 frontend/ 下执行) + buildCommand: 'npm run build', + // 服务器保留的最近版本数 + keepReleases: 5, + // 发版后健康检查用的域名(本机 curl 带 Host 头访问 https://127.0.0.1/,仅提示) + siteHost: 'oms.gztbyc.com', + }, + }, +}; diff --git a/tools/config/env.production.example b/tools/config/env.production.example new file mode 100644 index 0000000..29be996 --- /dev/null +++ b/tools/config/env.production.example @@ -0,0 +1,37 @@ +# 生产环境变量模板(本机权威副本) +# +# 用法:复制为 tools/config/env.production.local(已 gitignore),填好后执行 +# cd tools && npm run deploy +# 发布时会先上传到服务器 /shared-config/.env,再覆盖到各版本目录的 .env。 +# 文件不存在时跳过上传,沿用服务器上已有的 shared-config/.env。 +# +# 注意:服务器上 shared-config/.env 首次会从老位置的 /.env 自动初始化。 + +# ---- Egg 实例(端口由发布脚本注入 EGG_PORT,此处无需配置)---- +# UPLOAD_DIR=/www/wwwroot/api.oms.gztbyc.com/uploads + +# ---- MySQL ---- +MYSQL_HOST= +MYSQL_PORT=3306 +MYSQL_USER= +MYSQL_PASSWORD= +MYSQL_DATABASE= + +# ---- Redis ---- +REDIS_HOST= +REDIS_PORT=6379 +REDIS_PASSWORD= + +# ---- 鉴权 ---- +JWT_SECRET= + +# ---- 邮件(可选)---- +SMTP_HOST= +SMTP_PORT= +SMTP_SECURE= +SMTP_USER= +SMTP_PASS= +SMTP_FROM= + +# ---- 对外回调地址(可选)---- +OMS_CALLBACK_BASE_URL=http://api.oms.gztbyc.com diff --git a/tools/package-lock.json b/tools/package-lock.json new file mode 100644 index 0000000..6195902 --- /dev/null +++ b/tools/package-lock.json @@ -0,0 +1,584 @@ +{ + "name": "oms-tools", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "oms-tools", + "version": "1.0.0", + "dependencies": { + "dotenv": "^17.4.2" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "tsx": "^4.19.2", + "typescript": "~5.7.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/tools/package.json b/tools/package.json new file mode 100644 index 0000000..a619f2d --- /dev/null +++ b/tools/package.json @@ -0,0 +1,34 @@ +{ + "name": "oms-tools", + "version": "1.0.0", + "description": "OMS 发布与运维工具集", + "private": true, + "main": "dist/cli.js", + "bin": { + "oms-tools": "dist/cli.js" + }, + "scripts": { + "cli": "tsx src/cli.ts", + "init": "tsx src/cli.ts init", + "deploy": "tsx src/cli.ts deploy", + "deploy:backend": "tsx src/cli.ts deploy:backend", + "deploy:frontend": "tsx src/cli.ts deploy:frontend", + "rollback": "tsx src/cli.ts rollback", + "rollback:backend": "tsx src/cli.ts rollback:backend", + "rollback:frontend": "tsx src/cli.ts rollback:frontend", + "build": "tsc -p tsconfig.json", + "start": "node dist/cli.js", + "typecheck": "tsc -p tsconfig.json --noEmit" + }, + "engines": { + "node": ">=18.0.0" + }, + "dependencies": { + "dotenv": "^17.4.2" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "tsx": "^4.19.2", + "typescript": "~5.7.2" + } +} diff --git a/frontend/scripts/remote/deploy.sh b/tools/remote/deploy.sh similarity index 100% rename from frontend/scripts/remote/deploy.sh rename to tools/remote/deploy.sh diff --git a/frontend/scripts/remote/rollback.sh b/tools/remote/rollback.sh similarity index 100% rename from frontend/scripts/remote/rollback.sh rename to tools/remote/rollback.sh diff --git a/tools/src/cli.ts b/tools/src/cli.ts new file mode 100644 index 0000000..45c33ed --- /dev/null +++ b/tools/src/cli.ts @@ -0,0 +1,77 @@ +#!/usr/bin/env node +import 'dotenv/config'; +import { runDeploy } from './commands/deploy'; +import { runRollback } from './commands/rollback'; +import { initDeployConfig } from './lib/config'; + +interface Command { + summary: string; + run: (args: string[]) => void; +} + +const COMMANDS: Record = { + deploy: { + summary: '前后端同时发布 npm run deploy [-- --skip-build|--dry-run|--allow-dirty]', + run: args => runDeploy(args, { backend: true, frontend: true }), + }, + 'deploy:backend': { + summary: '仅发布后端 npm run deploy:backend [-- 参数同上]', + run: args => runDeploy(args, { backend: true, frontend: false }), + }, + 'deploy:frontend': { + summary: '仅发布前端 npm run deploy:frontend [-- 参数同上]', + run: args => runDeploy(args, { backend: false, frontend: true }), + }, + rollback: { + summary: '前后端一起回滚 npm run rollback [-- --to=v1|v2] [--dry-run]', + run: args => runRollback(args, { backend: true, frontend: true }), + }, + 'rollback:backend': { + summary: '仅回滚后端 npm run rollback:backend [-- --to=v1|v2]', + run: args => runRollback(args, { backend: true, frontend: false }), + }, + 'rollback:frontend': { + summary: '仅回滚前端 npm run rollback:frontend', + run: args => runRollback(args, { backend: false, frontend: true }), + }, + init: { + summary: '生成发布配置(deploy.config.local.cjs)', + run: () => initDeployConfig(), + }, +}; + +function printUsage(): void { + console.log('OMS 发布工具'); + console.log(''); + console.log('用法: npm run