682 lines
27 KiB
Python
682 lines
27 KiB
Python
# /// script
|
||
# requires-python = ">=3.9"
|
||
# dependencies = ["pyyaml"]
|
||
# ///
|
||
"""构建非 Docker 发布包(宝塔/1Panel 用 Node/PM2 部署)。
|
||
|
||
两种形态(代码 payload 相同,辅助文件/命名不同):
|
||
- 全新包(默认 / --fresh):含 .env.example、init.sh / init.ps1 与 README-deploy.md,首次启动进入安装向导。
|
||
- 升级包(--upgrade):不含配置示例,附 upgrade.sh / upgrade.ps1 与 README-upgrade.md,
|
||
就地替换代码,保留并不触碰服务器上的 .env / storage/ backups/。
|
||
|
||
配置/密钥/数据均在服务器的 .env / storage/ backups/ 与数据库中,发布包不写死这些内容。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tarfile
|
||
import zipfile
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
|
||
DIST = ROOT / ".release"
|
||
|
||
|
||
def run(cmd: str) -> None:
|
||
print(f"[artveris-build] $ {cmd}")
|
||
proc = subprocess.run(cmd, cwd=str(ROOT), shell=True)
|
||
if proc.returncode != 0:
|
||
sys.exit(proc.returncode)
|
||
|
||
|
||
def ensure_pnpm() -> None:
|
||
if shutil.which("pnpm"):
|
||
return
|
||
if not shutil.which("corepack"):
|
||
raise SystemExit("pnpm/corepack not found. Please install Node.js 24 LTS (minimum 20.11.1).")
|
||
run("corepack enable")
|
||
run("corepack prepare pnpm@10.28.0 --activate")
|
||
|
||
|
||
def copytree(src: Path, dst: Path) -> None:
|
||
if dst.exists():
|
||
shutil.rmtree(dst)
|
||
shutil.copytree(src, dst)
|
||
|
||
|
||
def write_text(path: Path, text: str) -> None:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_text(text, encoding="utf-8", newline="\n")
|
||
|
||
|
||
def write_markdown(path: Path, text: str) -> None:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_text(text, encoding="utf-8-sig", newline="\n")
|
||
|
||
|
||
def write_powershell(path: Path, text: str) -> None:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_text(text, encoding="utf-8-sig", newline="\n")
|
||
|
||
|
||
SERVER_CJS = """process.env.NODE_ENV ||= 'production';
|
||
process.env.ARTVERIS_PUBLIC_DIR ||= './apps/api/public';
|
||
|
||
require('./apps/api/dist/main.js');
|
||
"""
|
||
|
||
ECOSYSTEM_CJS = """module.exports = {
|
||
apps: [
|
||
{
|
||
name: 'artveris',
|
||
cwd: './',
|
||
script: 'server.cjs',
|
||
instances: 1,
|
||
exec_mode: 'fork',
|
||
env: {
|
||
NODE_ENV: 'production',
|
||
API_PORT: '3000',
|
||
ARTVERIS_PUBLIC_DIR: './apps/api/public',
|
||
},
|
||
},
|
||
],
|
||
};
|
||
"""
|
||
|
||
INSTALL_DEPS_SH = """#!/usr/bin/env sh
|
||
set -eu
|
||
|
||
ROOT="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||
cd "$ROOT"
|
||
|
||
PNPM_VERSION="${PNPM_VERSION:-10.28.0}"
|
||
NPM_REGISTRY="${NPM_REGISTRY:-https://registry.npmmirror.com}"
|
||
export COREPACK_NPM_REGISTRY="${COREPACK_NPM_REGISTRY:-$NPM_REGISTRY}"
|
||
export npm_config_registry="${npm_config_registry:-$NPM_REGISTRY}"
|
||
export PRISMA_ENGINES_MIRROR="${PRISMA_ENGINES_MIRROR:-https://registry.npmmirror.com/-/binary/prisma}"
|
||
|
||
if ! command -v node >/dev/null 2>&1; then
|
||
echo "[install] 未找到 Node.js,请先安装 Node.js 24 LTS(最低 20.11.1)。" >&2
|
||
exit 1
|
||
fi
|
||
if ! node -e "const [a,b,c]=process.versions.node.split('.').map(Number);process.exit(a>20||(a===20&&(b>11||(b===11&&c>=1)))?0:1)"; then
|
||
echo "[install] Node.js 版本过低,最低需要 20.11.1。" >&2
|
||
exit 1
|
||
fi
|
||
|
||
ACTUAL_PNPM_VERSION="$(pnpm --version 2>/dev/null || true)"
|
||
case "$ACTUAL_PNPM_VERSION" in
|
||
10.*) ;;
|
||
*)
|
||
if ! command -v corepack >/dev/null 2>&1; then
|
||
echo "[install] 未找到可用的 pnpm 10 或 corepack。" >&2
|
||
exit 1
|
||
fi
|
||
corepack enable
|
||
corepack prepare "pnpm@$PNPM_VERSION" --activate
|
||
ACTUAL_PNPM_VERSION="$(pnpm --version)"
|
||
;;
|
||
esac
|
||
case "$ACTUAL_PNPM_VERSION" in
|
||
10.*) ;;
|
||
*) echo "[install] 需要 pnpm 10,当前版本为 $ACTUAL_PNPM_VERSION。" >&2; exit 1 ;;
|
||
esac
|
||
|
||
echo "[install] Node $(node --version),pnpm $ACTUAL_PNPM_VERSION"
|
||
echo "[install] npm 镜像:$npm_config_registry"
|
||
echo "[install] Prisma 引擎镜像:$PRISMA_ENGINES_MIRROR"
|
||
pnpm install --prod --frozen-lockfile
|
||
pnpm --dir apps/api exec prisma generate --schema ./prisma/schema.prisma
|
||
node migrate.cjs
|
||
"""
|
||
|
||
INSTALL_DEPS_PS1 = r"""[CmdletBinding()]
|
||
param()
|
||
$ErrorActionPreference = 'Stop'
|
||
Set-StrictMode -Version Latest
|
||
|
||
function Resolve-NativeCommand {
|
||
param([Parameter(Mandatory=$true)][string]$Name)
|
||
$command = Get-Command $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||
if ($null -eq $command) { return $null }
|
||
return $command.Source
|
||
}
|
||
|
||
function Invoke-NativeCommand {
|
||
param(
|
||
[Parameter(Mandatory=$true)][string]$FilePath,
|
||
[string[]]$Arguments = @(),
|
||
[string]$FailureMessage = ''
|
||
)
|
||
& $FilePath @Arguments
|
||
$exitCode = $LASTEXITCODE
|
||
if ($exitCode -ne 0) {
|
||
if ($FailureMessage) { throw "$FailureMessage(退出码 $exitCode)。" }
|
||
throw "原生命令执行失败(退出码 $exitCode):$FilePath"
|
||
}
|
||
}
|
||
|
||
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||
Set-Location $root
|
||
$pnpmVersion = if ($env:PNPM_VERSION) { $env:PNPM_VERSION } else { '10.28.0' }
|
||
$npmRegistry = if ($env:NPM_REGISTRY) { $env:NPM_REGISTRY } else { 'https://registry.npmmirror.com' }
|
||
if (-not $env:COREPACK_NPM_REGISTRY) { $env:COREPACK_NPM_REGISTRY = $npmRegistry }
|
||
if (-not $env:npm_config_registry) { $env:npm_config_registry = $npmRegistry }
|
||
if (-not $env:PRISMA_ENGINES_MIRROR) {
|
||
$env:PRISMA_ENGINES_MIRROR = 'https://registry.npmmirror.com/-/binary/prisma'
|
||
}
|
||
|
||
$nodePath = Resolve-NativeCommand 'node'
|
||
if (-not $nodePath) {
|
||
throw '未找到 Node.js,请先安装 Node.js 24 LTS(最低 20.11.1)。'
|
||
}
|
||
$nodeVersion = [string](Invoke-NativeCommand -FilePath $nodePath -Arguments @('--version') | Select-Object -Last 1)
|
||
$nodeVersion = $nodeVersion.Trim()
|
||
if ($nodeVersion -notmatch '^v?(\d+)\.(\d+)\.(\d+)') {
|
||
throw "无法识别 Node.js 版本:$nodeVersion"
|
||
}
|
||
$nodeMajor = [int]$Matches[1]
|
||
$nodeMinor = [int]$Matches[2]
|
||
$nodePatch = [int]$Matches[3]
|
||
$nodeSupported = ($nodeMajor -gt 20) -or (
|
||
$nodeMajor -eq 20 -and ($nodeMinor -gt 11 -or ($nodeMinor -eq 11 -and $nodePatch -ge 1))
|
||
)
|
||
if (-not $nodeSupported) { throw 'Node.js 版本过低,最低需要 20.11.1。' }
|
||
|
||
$pnpmPath = Resolve-NativeCommand 'pnpm'
|
||
$actualPnpmVersion = ''
|
||
if ($pnpmPath) {
|
||
$versionOutput = & $pnpmPath --version
|
||
$versionExitCode = $LASTEXITCODE
|
||
if ($versionExitCode -eq 0) {
|
||
$actualPnpmVersion = ([string]($versionOutput | Select-Object -Last 1)).Trim()
|
||
} else {
|
||
Write-Host "[install] 当前 pnpm 无法运行(退出码 $versionExitCode),将尝试用 corepack 修复。"
|
||
}
|
||
}
|
||
if (-not $actualPnpmVersion.StartsWith('10.')) {
|
||
$corepackPath = Resolve-NativeCommand 'corepack'
|
||
if (-not $corepackPath) { throw '未找到可用的 pnpm 10 或 corepack。' }
|
||
Invoke-NativeCommand -FilePath $corepackPath -Arguments @('enable') -FailureMessage 'corepack enable 失败'
|
||
Invoke-NativeCommand -FilePath $corepackPath -Arguments @('prepare', "pnpm@$pnpmVersion", '--activate') -FailureMessage '准备 pnpm 失败'
|
||
$pnpmPath = Resolve-NativeCommand 'pnpm'
|
||
if (-not $pnpmPath) { throw 'corepack 执行后仍未找到 pnpm。' }
|
||
$actualPnpmVersion = [string](Invoke-NativeCommand -FilePath $pnpmPath -Arguments @('--version') | Select-Object -Last 1)
|
||
$actualPnpmVersion = $actualPnpmVersion.Trim()
|
||
}
|
||
if (-not $actualPnpmVersion.StartsWith('10.')) {
|
||
throw "需要 pnpm 10,当前版本为 $actualPnpmVersion。"
|
||
}
|
||
Write-Host "[install] Node $nodeVersion,pnpm $actualPnpmVersion"
|
||
Write-Host "[install] npm 镜像:$env:npm_config_registry"
|
||
Write-Host "[install] Prisma 引擎镜像:$env:PRISMA_ENGINES_MIRROR"
|
||
Invoke-NativeCommand -FilePath $pnpmPath -Arguments @('install', '--prod', '--frozen-lockfile') -FailureMessage '生产依赖安装失败'
|
||
Invoke-NativeCommand -FilePath $pnpmPath -Arguments @('--dir', 'apps/api', 'exec', 'prisma', 'generate', '--schema', './prisma/schema.prisma') -FailureMessage 'Prisma Client 生成失败'
|
||
Invoke-NativeCommand -FilePath $nodePath -Arguments @('migrate.cjs') -FailureMessage '数据库迁移失败'
|
||
"""
|
||
|
||
INIT_PS1 = r"""[CmdletBinding()]
|
||
param()
|
||
$ErrorActionPreference = 'Stop'
|
||
Set-StrictMode -Version Latest
|
||
|
||
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||
Set-Location $root
|
||
foreach ($required in @('package.json', 'pnpm-lock.yaml', 'install-deps.ps1', 'server.cjs', 'migrate.cjs')) {
|
||
$requiredPath = Join-Path $root $required
|
||
if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) {
|
||
throw "发布包不完整,缺少 $required。"
|
||
}
|
||
}
|
||
|
||
[System.IO.Directory]::CreateDirectory((Join-Path $root 'storage')) | Out-Null
|
||
[System.IO.Directory]::CreateDirectory((Join-Path $root 'backups')) | Out-Null
|
||
$envPath = Join-Path $root '.env'
|
||
if (Test-Path -LiteralPath $envPath) {
|
||
if (-not (Test-Path -LiteralPath $envPath -PathType Leaf)) { throw '.env 必须是文件。' }
|
||
Write-Host '[init] 检测到已有 .env,将原样保留。'
|
||
} else {
|
||
[System.IO.File]::WriteAllBytes($envPath, [byte[]]@())
|
||
Write-Host '[init] 已创建空 .env,首次启动后请在 /admin 完成安装向导。'
|
||
}
|
||
|
||
& (Join-Path $root 'install-deps.ps1')
|
||
if (-not $?) { throw '依赖初始化失败。' }
|
||
Write-Host '[init] 项目初始化完成。'
|
||
Write-Host "[init] 下一步:用 PM2 启动 $root/server.cjs,并访问 /admin 完成安装向导。"
|
||
"""
|
||
|
||
INIT_SH = """#!/usr/bin/env sh
|
||
set -eu
|
||
|
||
ROOT="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||
cd "$ROOT"
|
||
|
||
for required in package.json pnpm-lock.yaml install-deps.sh server.cjs migrate.cjs; do
|
||
if [ ! -f "$required" ]; then
|
||
echo "[init] 发布包不完整,缺少 $required。" >&2
|
||
exit 1
|
||
fi
|
||
done
|
||
|
||
APP_USER="${APP_USER:-www}"
|
||
APP_GROUP="${APP_GROUP:-}"
|
||
mkdir -p storage backups
|
||
if [ ! -e .env ]; then
|
||
(umask 077; : > .env)
|
||
echo "[init] 已创建空 .env,首次启动后请在 /admin 完成安装向导。"
|
||
else
|
||
echo "[init] 检测到已有 .env,将原样保留。"
|
||
fi
|
||
chmod 600 .env
|
||
|
||
if id "$APP_USER" >/dev/null 2>&1; then
|
||
if [ -z "$APP_GROUP" ]; then APP_GROUP="$(id -gn "$APP_USER")"; fi
|
||
if [ "$(id -u)" = "0" ]; then
|
||
chown -R "$APP_USER:$APP_GROUP" storage backups
|
||
chown "$APP_USER:$APP_GROUP" .env
|
||
elif [ "$(id -un)" != "$APP_USER" ]; then
|
||
echo "[init] 当前用户无法把运行目录授权给 $APP_USER,请改用 root 执行或设置 APP_USER。" >&2
|
||
exit 1
|
||
fi
|
||
else
|
||
echo "[init] 未找到运行用户 $APP_USER,保留当前文件所有者;可用 APP_USER 指定实际用户。"
|
||
fi
|
||
|
||
sh "$ROOT/install-deps.sh"
|
||
|
||
echo "[init] 项目初始化完成。"
|
||
echo "[init] 下一步:在宝塔/1Panel 用 PM2 启动 $ROOT/server.cjs,并访问 /admin 完成安装向导。"
|
||
"""
|
||
|
||
UPGRADE_SH = """#!/usr/bin/env sh
|
||
# 就地升级:用本包内新代码覆盖线上目录,保留并不触碰 .env / storage/ / backups/。
|
||
# 用法:sh upgrade.sh <线上部署目录,例如 /www/wwwroot/artveris>
|
||
set -eu
|
||
TARGET="${1:-}"
|
||
if [ -z "$TARGET" ]; then
|
||
echo "用法: sh upgrade.sh <线上部署目录,例如 /www/wwwroot/artveris>"
|
||
exit 1
|
||
fi
|
||
if [ ! -d "$TARGET" ]; then echo "目标目录不存在: $TARGET" >&2; exit 1; fi
|
||
SRC="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)"
|
||
TARGET="$(CDPATH= cd -- "$TARGET" && pwd -P)"
|
||
|
||
if [ "$TARGET" = "/" ]; then
|
||
echo "拒绝将系统根目录作为升级目标。" >&2
|
||
exit 1
|
||
fi
|
||
case "$SRC/" in
|
||
"$TARGET/"*) echo "升级包不能位于线上部署目录内部,请解压到其他目录后重试。" >&2; exit 1 ;;
|
||
esac
|
||
case "$TARGET/" in
|
||
"$SRC/"*) echo "线上部署目录不能与升级包目录相同,也不能位于升级包目录内部。" >&2; exit 1 ;;
|
||
esac
|
||
|
||
for required in package.json server.cjs apps/api .env; do
|
||
if [ ! -e "$TARGET/$required" ]; then
|
||
echo "目标目录不是完整的 Artveris 部署,缺少 $required: $TARGET" >&2
|
||
exit 1
|
||
fi
|
||
done
|
||
|
||
for required in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.sh init.ps1 install-deps.sh install-deps.ps1 package.json pnpm-lock.yaml pnpm-workspace.yaml; do
|
||
if [ ! -e "$SRC/$required" ]; then
|
||
echo "升级包不完整,缺少 $required。" >&2
|
||
exit 1
|
||
fi
|
||
done
|
||
|
||
echo "[upgrade] 用 $SRC 的新代码升级 $TARGET(保留 .env / storage/ / backups/)"
|
||
for item in apps packages server.cjs migrate.cjs ecosystem.config.cjs init.sh init.ps1 install-deps.sh install-deps.ps1 package.json pnpm-lock.yaml pnpm-workspace.yaml; do
|
||
rm -rf "$TARGET/$item"
|
||
cp -R "$SRC/$item" "$TARGET/$item"
|
||
done
|
||
cd "$TARGET"
|
||
sh install-deps.sh
|
||
echo "[upgrade] 完成。请重启 Node 服务(宝塔重启该 PM2 项目,或 pm2 restart artveris)。"
|
||
echo "[upgrade] .env / storage/ / backups/ 已原样保留。"
|
||
"""
|
||
|
||
UPGRADE_PS1 = r"""[CmdletBinding()]
|
||
param([Parameter(Mandatory=$true)][string]$Target)
|
||
$ErrorActionPreference = 'Stop'
|
||
Set-StrictMode -Version Latest
|
||
|
||
function Normalize-FullPath {
|
||
param([Parameter(Mandatory=$true)][string]$Path)
|
||
$fullPath = [System.IO.Path]::GetFullPath($Path)
|
||
$rootPath = [System.IO.Path]::GetPathRoot($fullPath)
|
||
$separators = [char[]]@(
|
||
[System.IO.Path]::DirectorySeparatorChar,
|
||
[System.IO.Path]::AltDirectorySeparatorChar
|
||
)
|
||
$trimmed = $fullPath.TrimEnd($separators)
|
||
$rootTrimmed = $rootPath.TrimEnd($separators)
|
||
if ([string]::Equals($trimmed, $rootTrimmed, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||
return $rootPath
|
||
}
|
||
return $trimmed
|
||
}
|
||
|
||
function Resolve-FileSystemDirectory {
|
||
param(
|
||
[Parameter(Mandatory=$true)][string]$Path,
|
||
[Parameter(Mandatory=$true)][string]$Label
|
||
)
|
||
if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "$Label 不存在或不是目录: $Path" }
|
||
$resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop
|
||
if ($resolved.Provider.Name -ne 'FileSystem') { throw "$Label 必须位于本地文件系统: $Path" }
|
||
return Normalize-FullPath $resolved.ProviderPath
|
||
}
|
||
|
||
function Test-SameOrChildPath {
|
||
param(
|
||
[Parameter(Mandatory=$true)][string]$Parent,
|
||
[Parameter(Mandatory=$true)][string]$Candidate
|
||
)
|
||
if ([string]::Equals($Parent, $Candidate, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
|
||
$prefix = $Parent
|
||
$separator = [string][System.IO.Path]::DirectorySeparatorChar
|
||
if (-not $prefix.EndsWith($separator)) { $prefix += $separator }
|
||
return $Candidate.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)
|
||
}
|
||
|
||
$src = Resolve-FileSystemDirectory (Split-Path -Parent $MyInvocation.MyCommand.Path) '升级包目录'
|
||
$targetPath = Resolve-FileSystemDirectory $Target '目标目录'
|
||
$targetRoot = Normalize-FullPath ([System.IO.Path]::GetPathRoot($targetPath))
|
||
if ([string]::Equals($targetPath, $targetRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||
throw '拒绝将文件系统根目录作为升级目标。'
|
||
}
|
||
if (Test-SameOrChildPath $targetPath $src) {
|
||
throw '升级包不能位于线上部署目录内部,请解压到其他目录后重试。'
|
||
}
|
||
if (Test-SameOrChildPath $src $targetPath) {
|
||
throw '线上部署目录不能与升级包目录相同,也不能位于升级包目录内部。'
|
||
}
|
||
|
||
foreach ($required in @('package.json', 'server.cjs', 'apps/api', '.env')) {
|
||
$requiredPath = Join-Path $targetPath $required
|
||
$expectedType = if ($required -eq 'apps/api') { 'Container' } else { 'Leaf' }
|
||
if (-not (Test-Path -LiteralPath $requiredPath -PathType $expectedType)) {
|
||
throw "目标目录不是完整的 Artveris 部署,缺少 ${required}: $targetPath"
|
||
}
|
||
}
|
||
|
||
$items = @(
|
||
'apps', 'packages', 'server.cjs', 'migrate.cjs', 'ecosystem.config.cjs',
|
||
'init.sh', 'init.ps1', 'install-deps.sh', 'install-deps.ps1',
|
||
'package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'
|
||
)
|
||
foreach ($item in $items) {
|
||
$sourcePath = Join-Path $src $item
|
||
if (-not (Test-Path -LiteralPath $sourcePath)) { throw "升级包不完整,缺少 $item。" }
|
||
}
|
||
|
||
Write-Host "[upgrade] 用 $src 的新代码升级 $targetPath(保留 .env / storage/ / backups/)"
|
||
foreach ($item in $items) {
|
||
$sourcePath = Join-Path $src $item
|
||
$destinationPath = Normalize-FullPath ([System.IO.Path]::GetFullPath((Join-Path $targetPath $item)))
|
||
if (-not (Test-SameOrChildPath $targetPath $destinationPath) -or
|
||
[string]::Equals($targetPath, $destinationPath, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||
throw "拒绝操作目标目录之外的路径: $destinationPath"
|
||
}
|
||
if (Test-Path -LiteralPath $destinationPath) {
|
||
Remove-Item -LiteralPath $destinationPath -Recurse -Force
|
||
}
|
||
Copy-Item -LiteralPath $sourcePath -Destination $destinationPath -Recurse -Force
|
||
}
|
||
|
||
Set-Location $targetPath
|
||
& (Join-Path $targetPath 'install-deps.ps1')
|
||
if (-not $?) { throw '升级依赖安装失败。' }
|
||
Write-Host "[upgrade] 完成。请重启 Node 服务。.env / storage/ / backups/ 已保留。"
|
||
"""
|
||
|
||
README_DEPLOY = """# Artveris 全新安装包部署说明
|
||
|
||
本发布包是单端口版本。启动后同一个 Node 服务提供:
|
||
|
||
- `/admin` 后台
|
||
- `/trace` 客户端
|
||
- `/api` 接口
|
||
- `/t/:code` 短链
|
||
- `/uploads` 本地上传资源
|
||
|
||
压缩包内不写死 MySQL、Redis、域名、OSS/CDN、天河链密钥。首次启动后访问 `/admin`,未安装会自动进入安装向导填写。
|
||
|
||
## 1. 上传和解压
|
||
|
||
建议解压到固定目录,例如:
|
||
|
||
```bash
|
||
/www/wwwroot/artveris
|
||
```
|
||
|
||
后续文档都用这个目录举例;如果你的目录不同,把路径替换成你的真实目录。
|
||
|
||
## 2. 安装依赖
|
||
|
||
推荐先用 SSH 进入服务器执行一键初始化,再到宝塔添加 Node 项目:
|
||
|
||
```bash
|
||
cd /www/wwwroot/artveris
|
||
sh init.sh
|
||
```
|
||
|
||
Windows PowerShell 部署执行:
|
||
|
||
```powershell
|
||
.\\init.ps1
|
||
```
|
||
|
||
`init.sh` / `init.ps1` 会自动准备项目要求的 pnpm 10、配置国内 npm/Prisma 镜像、安装生产依赖、生成 Prisma Client、执行已有数据库迁移,并准备 `.env`、`storage/`、`backups/`。脚本可重复执行:已有 `.env` 不会被覆盖。Linux 默认把运行目录授权给 `www`,其他环境可用 `APP_USER=实际用户 sh init.sh` 覆盖。
|
||
|
||
如果服务器没有 `corepack`,请在宝塔里安装 Node.js 24 LTS 后再执行;最低兼容版本为 20.11.1。海外服务器如需使用官方源,可在执行时覆盖 `NPM_REGISTRY` 与 `PRISMA_ENGINES_MIRROR`。
|
||
|
||
首次安装会在根目录生成 `.env` 保存配置与密钥;`storage/` 保存本地上传文件,`backups/` 保存备份文件。正式环境不要随意删除 `.env` 与这两个目录。
|
||
|
||
## 3. 宝塔 Node 项目填写方式
|
||
|
||
在宝塔添加 Node 项目时,推荐选择“PM2项目”,按下面填写。
|
||
|
||
| 字段 | 推荐填写 |
|
||
| --- | --- |
|
||
| 项目名称 | `artveris` |
|
||
| Node版本 | 推荐 Node.js 24 LTS,最低 20.11.1 |
|
||
| 启动文件 | 选择根目录下的 `server.cjs`;手填时用 `/www/wwwroot/artveris/server.cjs` |
|
||
| 运行目录 | `/www/wwwroot/artveris` |
|
||
| 负载实例数量 | `1` |
|
||
| 内存上限 | `1024` MB 起步;作品和导入较多可填 `1536` 或 `2048` |
|
||
| 自动重载 | 关闭 |
|
||
| 包管理器 | `pnpm` |
|
||
| 不安装 node_module | 如果已经执行过 `sh init.sh`,建议勾选 |
|
||
| 运行用户 | `www` |
|
||
| 项目端口 | `3000`,如端口被占用可改成其他端口 |
|
||
| 绑定域名 | 每行一个域名,不写 `http://` 或 `https://` |
|
||
|
||
环境变量建议填写:
|
||
|
||
```env
|
||
NODE_ENV=production
|
||
API_PORT=3000
|
||
ARTVERIS_PUBLIC_DIR=./apps/api/public
|
||
```
|
||
|
||
如果“项目端口”不是 `3000`,这里的 `API_PORT` 必须改成同一个端口。首次安装向导会在根目录生成 `.env`,服务启动时会自动读取。
|
||
|
||
## 4. 反向代理与大批量出库导入
|
||
|
||
宝塔/1Panel/Nginx 反向代理必须取消请求体大小限制,并将代理读写超时延长到 1 小时,否则大 ZIP 会在到达应用前被拒绝或中断。站点 Nginx 配置至少包含:
|
||
|
||
```nginx
|
||
client_max_body_size 0;
|
||
proxy_read_timeout 3600s;
|
||
proxy_send_timeout 3600s;
|
||
proxy_request_buffering off;
|
||
```
|
||
|
||
批量出库 ZIP 总体没有应用层固定体积上限,但实际容量受服务器磁盘、内存、网络带宽和处理时长约束。ZIP 内单个 xlsx 不超过 100MB;单张图片不超过 100MB,仅支持 JPG/JPEG/PNG/WebP,且不超过 4000 万像素。批量导入只登记出库,不会自动发起上链;需要在导入完成后按业务流程另行执行上链。
|
||
|
||
## 5. 首次安装向导
|
||
|
||
启动 Node 项目后,打开后台地址(未安装时会自动进入安装向导):
|
||
|
||
```text
|
||
https://你的域名/admin
|
||
```
|
||
|
||
如果还没有配置 HTTPS,也可以临时打开:
|
||
|
||
```text
|
||
http://服务器IP:3000/admin
|
||
```
|
||
|
||
安装向导中建议这样填:
|
||
|
||
| 字段 | 示例 |
|
||
| --- | --- |
|
||
| 平台名称 | 按你的项目名称填写 |
|
||
| 对外访问地址 | 一个域名即可,三端共用,如 `https://art.asio.asia`;客户端自动位于 `/trace` |
|
||
| 监听端口 | 默认 `3000`,由 Nginx/宝塔反代指向该端口 |
|
||
| MySQL 地址 | 宝塔本机 MySQL 通常填 `127.0.0.1` |
|
||
| MySQL 端口 | 通常 `3306` |
|
||
| MySQL 数据库 | 建议 `artveris`(不存在会自动创建) |
|
||
| MySQL 用户/密码 | 填宝塔数据库里创建的用户和密码 |
|
||
| 建库管理员账号/密码 | 可选;仅当业务账号无建库权限时填写 |
|
||
| Redis 地址 | 宝塔本机 Redis 通常填 `127.0.0.1` |
|
||
| Redis 端口 | 通常 `6379` |
|
||
| Redis 密码 | 没有密码就留空 |
|
||
| 管理员账号 | 首个后台超级管理员 |
|
||
| 存储方式 | 默认选本地 |
|
||
| 本地存储目录 | `/www/wwwroot/artveris/storage` |
|
||
| CDN Base URL | 没有 CDN 就留空 |
|
||
|
||
安装向导会自动创建数据库、建表并初始化系统数据。安装成功后服务会主动退出一次,由宝塔/PM2 自动拉起。
|
||
|
||
## 6. 升级
|
||
|
||
升级请使用「升级包」(`--upgrade` 构建),它自带 `upgrade.sh` / `upgrade.ps1`,会只替换代码并保留根目录 `.env`、`storage/`、`backups/`。切勿删除这三者。
|
||
|
||
> **迁移基线限制**:当前迁移历史已重做为干净基线 `20260715000000_init`,不兼容此前数据库、备份和追溯码。只能全新安装,或升级已经由该基线创建的环境;旧环境不得直接升级。
|
||
"""
|
||
|
||
README_UPGRADE = """# Artveris 升级包说明
|
||
|
||
本包只包含代码产物,**不含任何配置**。升级只替换代码,保留服务器上的根目录
|
||
`.env`(安装配置与密钥)、`storage/`(上传文件)、`backups/`(备份)与数据库,不会丢数据。
|
||
|
||
> **迁移基线限制**:当前迁移历史已重做为干净基线 `20260715000000_init`,不兼容此前数据库、备份和追溯码。本包只适用于已经由该基线创建的环境;旧环境请停止升级并重新安装。
|
||
|
||
升级后请同时检查外层宝塔/1Panel/Nginx 反向代理:大批量出库导入要求取消请求体大小限制(`client_max_body_size 0;`),将 `proxy_read_timeout`、`proxy_send_timeout` 都设为 `3600s`,并关闭请求缓冲(`proxy_request_buffering off;`)。批量 ZIP 总体没有应用层固定体积上限,但仍受服务器资源约束;单个 xlsx 与单张图片各不超过 100MB,图片仅支持 JPG/JPEG/PNG/WebP 且不超过 4000 万像素。批量导入不会自动发起上链。
|
||
|
||
## 一键升级(推荐)
|
||
|
||
先在后台完成系统备份并停止 Node 服务,再把本包解压到线上部署目录之外,然后执行(把路径换成你的线上部署目录):
|
||
|
||
Linux / 宝塔:
|
||
|
||
```bash
|
||
sh upgrade.sh /www/wwwroot/artveris
|
||
```
|
||
|
||
Windows:
|
||
|
||
```powershell
|
||
./upgrade.ps1 -Target "C:\\path\\to\\artveris"
|
||
```
|
||
|
||
脚本会用新代码覆盖 `apps/`、`packages/`、`server.cjs` 等,保留根目录 `.env`、`storage/`、`backups/`,
|
||
随后自动安装生产依赖、生成 Prisma Client 并执行 `prisma migrate deploy`;任一步失败都会中止升级。完成后请重启 Node 服务
|
||
(宝塔重启该 PM2 项目,或 `pm2 restart artveris`)。
|
||
|
||
## 手动升级
|
||
|
||
1. 后台先做一次系统备份,并停止 Node 服务。
|
||
2. 用本包内的 `apps/`、`packages/`、`server.cjs`、`migrate.cjs`、`ecosystem.config.cjs`、`init.*`、`install-deps.*`、
|
||
`package.json`、`pnpm-lock.yaml`、`pnpm-workspace.yaml` 覆盖线上同名文件;**不要动根目录 `.env`、`storage/`、`backups/`**。
|
||
3. Linux 执行 `sh install-deps.sh`;Windows 执行 `.\\install-deps.ps1`。
|
||
4. 启动 Node 服务。
|
||
|
||
如需修改数据库/域名等配置,直接编辑根目录 `.env` 后重启;平台名/存储等也可在后台系统设置在线改。
|
||
"""
|
||
|
||
|
||
def copy_code_payload(package_dir: Path) -> None:
|
||
copytree(ROOT / "apps/api/dist", package_dir / "apps/api/dist")
|
||
copytree(ROOT / "apps/api/prisma", package_dir / "apps/api/prisma")
|
||
shutil.copy2(ROOT / "apps/api/package.json", package_dir / "apps/api/package.json")
|
||
shared_dir = package_dir / "packages/shared"
|
||
shared_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(ROOT / "packages/shared/package.json", shared_dir / "package.json")
|
||
copytree(ROOT / "packages/shared/dist", shared_dir / "dist")
|
||
for app in ("admin", "client"):
|
||
app_dir = package_dir / "apps" / app
|
||
app_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(ROOT / "apps" / app / "package.json", app_dir / "package.json")
|
||
copytree(ROOT / "apps/admin/dist", package_dir / "apps/api/public/admin")
|
||
copytree(ROOT / "apps/client/dist", package_dir / "apps/api/public/trace")
|
||
shutil.copy2(ROOT / "package.json", package_dir / "package.json")
|
||
shutil.copy2(ROOT / "pnpm-lock.yaml", package_dir / "pnpm-lock.yaml")
|
||
shutil.copy2(ROOT / "pnpm-workspace.yaml", package_dir / "pnpm-workspace.yaml")
|
||
write_text(package_dir / "server.cjs", SERVER_CJS)
|
||
shutil.copy2(ROOT / "scripts/migrate.cjs", package_dir / "migrate.cjs")
|
||
write_text(package_dir / "ecosystem.config.cjs", ECOSYSTEM_CJS)
|
||
write_text(package_dir / "init.sh", INIT_SH)
|
||
write_powershell(package_dir / "init.ps1", INIT_PS1)
|
||
write_text(package_dir / "install-deps.sh", INSTALL_DEPS_SH)
|
||
write_powershell(package_dir / "install-deps.ps1", INSTALL_DEPS_PS1)
|
||
|
||
|
||
def build(mode: str) -> Path:
|
||
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
||
package_dir = DIST / f"artveris-{mode}-{stamp}"
|
||
if DIST.exists():
|
||
shutil.rmtree(DIST)
|
||
package_dir.mkdir(parents=True)
|
||
|
||
ensure_pnpm()
|
||
run("pnpm install --frozen-lockfile")
|
||
run("pnpm build:shared")
|
||
run("pnpm --filter @artveris/api exec prisma generate")
|
||
run("pnpm --filter @artveris/api build")
|
||
run("pnpm --filter @artveris/admin build")
|
||
run("pnpm --filter @artveris/client build")
|
||
|
||
copy_code_payload(package_dir)
|
||
|
||
if mode == "upgrade":
|
||
write_text(package_dir / "upgrade.sh", UPGRADE_SH)
|
||
write_powershell(package_dir / "upgrade.ps1", UPGRADE_PS1)
|
||
write_markdown(package_dir / "README-upgrade.md", README_UPGRADE)
|
||
else: # fresh
|
||
shutil.copy2(ROOT / ".env.example", package_dir / ".env.example")
|
||
write_markdown(package_dir / "README-deploy.md", README_DEPLOY)
|
||
|
||
zip_path = DIST / f"{package_dir.name}.zip"
|
||
tar_path = DIST / f"{package_dir.name}.tar.gz"
|
||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||
for file in package_dir.rglob("*"):
|
||
zf.write(file, file.relative_to(package_dir.parent))
|
||
with tarfile.open(tar_path, "w:gz") as tf:
|
||
tf.add(package_dir, arcname=package_dir.name)
|
||
return package_dir
|
||
|
||
|
||
def main() -> None:
|
||
args = sys.argv[1:]
|
||
mode = "upgrade" if "--upgrade" in args else "fresh"
|
||
package_dir = build(mode)
|
||
print(f"[artveris] {mode} 发布包已生成:")
|
||
print(f" {package_dir}")
|
||
print(f" {package_dir.with_suffix('.zip')}")
|
||
print(f" {package_dir.with_suffix('.tar.gz')}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|