1
0

feat: 跨平台发布打包,支持 7 个目标平台交叉编译和 tar.gz 分发

- 新增 scripts/release.ts,支持 7 个编译目标(linux/darwin/windows + musl 变体)
- 从 build.ts 提取共享构建逻辑到 build-common.ts,现有 build 行为不变
- 使用 tar-stream + node:zlib 创建 tar.gz,精确控制 Unix 权限位
- SHA256 校验和文件格式兼容 sha256sum -c
- 支持 --target 参数选择特定平台编译
- 新增 devDependency: tar-stream、@types/tar-stream
- 更新 README.md 和 DEVELOPMENT.md 文档
- 同步 openspec specs
This commit is contained in:
2026-05-20 23:24:36 +08:00
parent 8eac814cc6
commit ccd16a583e
13 changed files with 902 additions and 139 deletions

123
scripts/build-common.ts Normal file
View File

@@ -0,0 +1,123 @@
import { readdir, rm, writeFile } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { validateVersion } from "./bump-version-logic";
export const projectRoot = fileURLToPath(new URL("..", import.meta.url));
export const distWebDir = join(projectRoot, "dist/web");
export const buildDir = join(projectRoot, ".build");
export const packageJsonPath = join(projectRoot, "package.json");
export async function cleanup() {
await rm(buildDir, { force: true, recursive: true });
}
export async function codeGeneration() {
console.log("Step 2/3: Code generation...");
await rm(buildDir, { force: true, recursive: true });
await Bun.write(join(buildDir, ".gitkeep"), "");
const packageJson = (await Bun.file(packageJsonPath).json()) as { version: string };
const version = packageJson.version;
if (typeof version !== "string") {
console.error("package.json does not have a valid version field");
process.exit(1);
}
validateVersion(version);
const allFiles = await scanDir(distWebDir, "/");
const importLines: string[] = [];
const fileEntries: string[] = [];
let indexHtmlVar = "";
for (let i = 0; i < allFiles.length; i++) {
const urlPath = allFiles[i]!;
const varName = `f${i}`;
const filePath = toImportSpecifier(buildDir, join(distWebDir, urlPath.slice(1)));
importLines.push(`import ${varName} from "./${filePath}" with { type: "file" };`);
if (urlPath === "/index.html") {
indexHtmlVar = varName;
} else {
fileEntries.push(` "${urlPath}": Bun.file(${varName}),`);
}
}
if (!indexHtmlVar) {
console.error("index.html not found in dist/web/");
process.exit(1);
}
const staticAssetsTs = [
`import type { StaticAssets } from "../src/server/static";`,
"",
...importLines,
"",
`export const staticAssets: StaticAssets = {`,
` files: {`,
...fileEntries,
` },`,
` indexHtml: Bun.file(${indexHtmlVar}),`,
`};`,
"",
].join("\n");
await writeFile(join(buildDir, "static-assets.ts"), staticAssetsTs);
const serverEntryTs = [
`import { bootstrap } from "../src/server/bootstrap";`,
`import { readRuntimeConfig } from "../src/server/config";`,
`import { staticAssets } from "./static-assets";`,
"",
`const APP_VERSION = "${version}" as const;`,
"",
`async function main() {`,
` const { configPath } = readRuntimeConfig();`,
` await bootstrap({ configPath, mode: "production", staticAssets, version: APP_VERSION });`,
`}`,
"",
`void main().catch((error) => {`,
` console.error("启动失败:", error instanceof Error ? error.message : error);`,
` process.exit(1);`,
`});`,
"",
].join("\n");
await writeFile(join(buildDir, "server-entry.ts"), serverEntryTs);
return version;
}
export async function scanDir(dir: string, prefix: string): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true });
const paths: string[] = [];
for (const entry of entries) {
const fullPath = join(dir, entry.name);
const urlPath = `${prefix}${entry.name}`;
if (entry.isDirectory()) {
paths.push(...(await scanDir(fullPath, `${urlPath}/`)));
} else {
paths.push(urlPath);
}
}
return paths;
}
export function toImportSpecifier(fromDir: string, targetPath: string) {
return relative(fromDir, targetPath).split(sep).join("/");
}
export async function viteBuild() {
console.log("Step 1/3: Vite build...");
const proc = Bun.spawn(["bunx", "--bun", "vite", "build"], {
cwd: projectRoot,
stderr: "inherit",
stdout: "inherit",
});
const exitCode = await proc.exited;
if (exitCode !== 0) {
console.error("Vite build failed");
process.exit(1);
}
}

View File

@@ -1,14 +1,9 @@
import { readdir, rm, writeFile } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { validateVersion } from "./bump-version-logic";
import { buildDir, cleanup, codeGeneration, projectRoot, viteBuild } from "./build-common";
const projectRoot = fileURLToPath(new URL("..", import.meta.url));
const distWebDir = join(projectRoot, "dist/web");
const buildDir = join(projectRoot, ".build");
const executablePath = join(projectRoot, "dist/dial-server");
const packageJsonPath = join(projectRoot, "package.json");
async function build() {
try {
@@ -54,115 +49,4 @@ async function bunCompile() {
}
}
async function cleanup() {
await rm(buildDir, { force: true, recursive: true });
}
async function codeGeneration() {
console.log("Step 2/3: Code generation...");
await rm(buildDir, { force: true, recursive: true });
await Bun.write(join(buildDir, ".gitkeep"), "");
const packageJson = (await Bun.file(packageJsonPath).json()) as { version: string };
const version = packageJson.version;
if (typeof version !== "string") {
console.error("package.json does not have a valid version field");
process.exit(1);
}
validateVersion(version);
const allFiles = await scanDir(distWebDir, "/");
const importLines: string[] = [];
const fileEntries: string[] = [];
let indexHtmlVar = "";
for (let i = 0; i < allFiles.length; i++) {
const urlPath = allFiles[i]!;
const varName = `f${i}`;
const filePath = toImportSpecifier(buildDir, join(distWebDir, urlPath.slice(1)));
importLines.push(`import ${varName} from "./${filePath}" with { type: "file" };`);
if (urlPath === "/index.html") {
indexHtmlVar = varName;
} else {
fileEntries.push(` "${urlPath}": Bun.file(${varName}),`);
}
}
if (!indexHtmlVar) {
console.error("index.html not found in dist/web/");
process.exit(1);
}
const staticAssetsTs = [
`import type { StaticAssets } from "../src/server/static";`,
"",
...importLines,
"",
`export const staticAssets: StaticAssets = {`,
` files: {`,
...fileEntries,
` },`,
` indexHtml: Bun.file(${indexHtmlVar}),`,
`};`,
"",
].join("\n");
await writeFile(join(buildDir, "static-assets.ts"), staticAssetsTs);
const serverEntryTs = [
`import { bootstrap } from "../src/server/bootstrap";`,
`import { readRuntimeConfig } from "../src/server/config";`,
`import { staticAssets } from "./static-assets";`,
"",
`const APP_VERSION = "${version}" as const;`,
"",
`async function main() {`,
` const { configPath } = readRuntimeConfig();`,
` await bootstrap({ configPath, mode: "production", staticAssets, version: APP_VERSION });`,
`}`,
"",
`void main().catch((error) => {`,
` console.error("启动失败:", error instanceof Error ? error.message : error);`,
` process.exit(1);`,
`});`,
"",
].join("\n");
await writeFile(join(buildDir, "server-entry.ts"), serverEntryTs);
}
async function scanDir(dir: string, prefix: string): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true });
const paths: string[] = [];
for (const entry of entries) {
const fullPath = join(dir, entry.name);
const urlPath = `${prefix}${entry.name}`;
if (entry.isDirectory()) {
paths.push(...(await scanDir(fullPath, `${urlPath}/`)));
} else {
paths.push(urlPath);
}
}
return paths;
}
function toImportSpecifier(fromDir: string, targetPath: string) {
return relative(fromDir, targetPath).split(sep).join("/");
}
async function viteBuild() {
console.log("Step 1/3: Vite build...");
const proc = Bun.spawn(["bunx", "--bun", "vite", "build"], {
cwd: projectRoot,
stderr: "inherit",
stdout: "inherit",
});
const exitCode = await proc.exited;
if (exitCode !== 0) {
console.error("Vite build failed");
process.exit(1);
}
}
await build();

View File

@@ -8,6 +8,7 @@ const dirs: Array<{ desc: string; path: string }> = [
{ desc: "Bun 构建缓存", path: ".build" },
{ desc: "Playwright 测试报告", path: "playwright-report" },
{ desc: "测试结果", path: "test-results" },
{ desc: "发布产物", path: "dist/release" },
];
const filePatterns: Array<{ desc: string; glob: string }> = [{ desc: "Bun 构建临时文件", glob: ".*.bun-build" }];

196
scripts/release.ts Normal file
View File

@@ -0,0 +1,196 @@
import { createHash } from "node:crypto";
import { mkdir, rm, stat } from "node:fs/promises";
import { join, relative } from "node:path";
import { createGzip } from "node:zlib";
import tar from "tar-stream";
import { buildDir, cleanup, codeGeneration, projectRoot, viteBuild } from "./build-common";
const releaseDir = join(projectRoot, "dist/release");
const binariesDir = join(releaseDir, "binaries");
const packagesDir = join(releaseDir, "packages");
export interface ReleaseTarget {
arch: string;
bunTarget: string;
displayName: string;
os: string;
}
export const ALL_TARGETS: ReleaseTarget[] = [
{ arch: "x64", bunTarget: "bun-linux-x64", displayName: "Linux x64 (glibc)", os: "linux" },
{ arch: "arm64", bunTarget: "bun-linux-arm64", displayName: "Linux ARM64 (glibc)", os: "linux" },
{ arch: "x64-musl", bunTarget: "bun-linux-x64-musl", displayName: "Linux x64 (musl)", os: "linux" },
{ arch: "arm64-musl", bunTarget: "bun-linux-arm64-musl", displayName: "Linux ARM64 (musl)", os: "linux" },
{ arch: "x64", bunTarget: "bun-windows-x64", displayName: "Windows x64", os: "windows" },
{ arch: "x64", bunTarget: "bun-darwin-x64", displayName: "macOS x64 (Intel)", os: "darwin" },
{ arch: "arm64", bunTarget: "bun-darwin-arm64", displayName: "macOS ARM64 (Apple Silicon)", os: "darwin" },
];
export function archiveName(target: ReleaseTarget, version: string): string {
return `dial-server_${version}_${target.os}_${target.arch}.tar.gz`;
}
export function checksumName(target: ReleaseTarget, version: string): string {
return `${archiveName(target, version)}.sha256`;
}
export async function compileTarget(target: ReleaseTarget, version: string): Promise<string> {
const outfile = join(binariesDir, execName(target, version));
console.log(` 编译 ${target.displayName}...`);
const result = await Bun.build({
compile: {
autoloadBunfig: true,
autoloadDotenv: true,
outfile,
target: target.bunTarget as Bun.Build.CompileTarget,
},
entrypoints: [join(buildDir, "server-entry.ts")],
minify: true,
});
if (!result.success) {
console.error(` 编译失败 (${target.displayName}):`, result.logs);
process.exit(1);
}
return outfile;
}
export async function computeChecksum(archivePath: string): Promise<string> {
const content = await Bun.file(archivePath).arrayBuffer();
const hash = createHash("sha256").update(Buffer.from(content)).digest("hex");
const filename = relative(packagesDir, archivePath);
const checksumPath = `${archivePath}.sha256`;
const checksumContent = `${hash} ${filename}\n`;
await Bun.write(checksumPath, checksumContent);
return checksumPath;
}
export function execName(target: ReleaseTarget, version: string): string {
const suffix = target.os === "windows" ? ".exe" : "";
return `dial-server-${version}-${target.os}-${target.arch}${suffix}`;
}
export async function packageTarget(target: ReleaseTarget, version: string, binaryPath: string): Promise<string> {
const archivePath = join(packagesDir, archiveName(target, version));
const prefix = `dial-server_${version}_${target.os}_${target.arch}`;
const binaryName = target.os === "windows" ? "dial-server.exe" : "dial-server";
const binaryContent = await Bun.file(binaryPath).arrayBuffer();
const probesContent = await Bun.file(join(projectRoot, "probes.example.yaml")).arrayBuffer();
const licenseContent = await Bun.file(join(projectRoot, "LICENSE")).arrayBuffer();
const pack = tar.pack();
pack.entry(
{ mode: 0o755, name: `${prefix}/${binaryName}`, size: binaryContent.byteLength },
Buffer.from(binaryContent),
);
pack.entry(
{ mode: 0o644, name: `${prefix}/probes.example.yaml`, size: probesContent.byteLength },
Buffer.from(probesContent),
);
pack.entry({ mode: 0o644, name: `${prefix}/LICENSE`, size: licenseContent.byteLength }, Buffer.from(licenseContent));
pack.finalize();
const gzip = createGzip();
const chunks: Buffer[] = [];
await new Promise<void>((resolve, reject) => {
pack.pipe(gzip);
gzip.on("data", (chunk: Buffer) => chunks.push(chunk));
gzip.on("end", resolve);
gzip.on("error", reject);
});
await Bun.write(archivePath, Buffer.concat(chunks));
return archivePath;
}
export function parseTargets(args: string[]): ReleaseTarget[] {
const targetIndex = args.indexOf("--target");
if (targetIndex === -1 || targetIndex === args.length - 1) {
return ALL_TARGETS;
}
const targetValues = args[targetIndex + 1]!.split(",");
const targets: ReleaseTarget[] = [];
for (const value of targetValues) {
const bunTarget = `bun-${value.trim()}`;
const found = ALL_TARGETS.find((t) => t.bunTarget === bunTarget);
if (!found) {
const available = ALL_TARGETS.map((t) => t.bunTarget.replace(/^bun-/, "")).join(", ");
console.error(`无效的 target: ${value.trim()}`);
console.error(`可用的 target 值: ${available}`);
process.exit(1);
}
targets.push(found);
}
return targets;
}
export async function printReport(binaries: string[], archives: string[]): Promise<void> {
console.log("\n=== Release 报告 ===\n");
console.log("裸二进制:");
for (const binary of binaries) {
const size = (await stat(binary)).size;
const mb = (size / 1024 / 1024).toFixed(1);
console.log(` ${relative(projectRoot, binary)} (${mb} MB)`);
}
console.log("\n压缩包:");
for (const archive of archives) {
const size = (await stat(archive)).size;
const mb = (size / 1024 / 1024).toFixed(1);
console.log(` ${relative(projectRoot, archive)} (${mb} MB)`);
}
}
async function release() {
const targets = parseTargets(process.argv);
console.log(`Release 目标: ${targets.map((t) => t.displayName).join(", ")}\n`);
try {
await viteBuild();
const version = await codeGeneration();
console.log(`\n版本: ${version}`);
console.log(`编译 ${targets.length} 个目标...\n`);
await rm(releaseDir, { force: true, recursive: true });
await mkdir(binariesDir, { recursive: true });
await mkdir(packagesDir, { recursive: true });
const binaries: string[] = [];
for (const target of targets) {
const binaryPath = await compileTarget(target, version);
binaries.push(binaryPath);
}
const archives: string[] = [];
for (let i = 0; i < targets.length; i++) {
const target = targets[i]!;
const binaryPath = binaries[i]!;
console.log(` 打包 ${target.displayName}...`);
const archivePath = await packageTarget(target, version, binaryPath);
await computeChecksum(archivePath);
archives.push(archivePath);
}
await cleanup();
await printReport(binaries, archives);
console.log("\nRelease 完成!");
} catch (error) {
await cleanup();
console.error("Release 失败:", error);
process.exit(1);
}
}
if (import.meta.main) {
await release();
}