From c86ee6a235ebe989614f1b4965f2d2dc3983daab Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 25 Aug 2026 13:51:53 +0800 Subject: [PATCH] Add dual-mode self-update and multi-target binary build --- scripts/build-binary.mjs | 61 ++++++++++++--- src/cli.test.ts | 9 +++ src/cli/commands/update.ts | 150 +++++++++++++++++++++++++++++++++++-- src/cli/runner.ts | 6 +- 4 files changed, 207 insertions(+), 19 deletions(-) diff --git a/scripts/build-binary.mjs b/scripts/build-binary.mjs index 55217a1..5a9f104 100644 --- a/scripts/build-binary.mjs +++ b/scripts/build-binary.mjs @@ -5,22 +5,63 @@ import { fileURLToPath } from "node:url"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const bun = process.env.BUN_BIN || "bun"; -const output = resolve(root, "dist/bin/seal-home"); -mkdirSync(dirname(output), { recursive: true }); -run(bun, ["build", "--compile", "--outfile", output, "src/cli.ts"]); +const TARGET_MAP = { + "darwin-arm64": { bunTarget: "bun-darwin-arm64", outfile: "dist/bin/seal-home-darwin-arm64" }, + "darwin-x64": { bunTarget: "bun-darwin-x64", outfile: "dist/bin/seal-home-darwin-x64" }, + "linux-x64": { bunTarget: "bun-linux-x64", outfile: "dist/bin/seal-home-linux-x64" }, + "linux-arm64": { bunTarget: "bun-linux-arm64", outfile: "dist/bin/seal-home-linux-arm64" }, + "windows-x64": { bunTarget: "bun-windows-x64", outfile: "dist/bin/seal-home-windows-x64.exe" } +}; -// Bun's macOS standalone output can carry a stale code-signature blob on -// development machines. Re-signing ad hoc keeps the local binary executable. -if (process.platform === "darwin") { - run("/usr/bin/codesign", ["--remove-signature", output]); - run("/usr/bin/codesign", ["--force", "--sign", "-", output]); +const args = process.argv.slice(2); +const isAll = args.includes("--all") || args.includes("--matrix"); +const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", ""); + +if (isAll) { + for (const [name, config] of Object.entries(TARGET_MAP)) { + buildTarget(name, config.bunTarget, resolve(root, config.outfile)); + } +} else if (targetArg) { + const config = TARGET_MAP[targetArg]; + if (!config) { + throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`); + } + buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile)); +} else { + const output = resolve(root, "dist/bin/seal-home"); + buildTarget("host", null, output); } -function run(command, args) { +function buildTarget(name, bunTarget, output) { + mkdirSync(dirname(output), { recursive: true }); + const buildArgs = ["build", "--compile"]; + if (bunTarget) { + buildArgs.push(`--target=${bunTarget}`); + } + buildArgs.push("--outfile", output, "src/cli.ts"); + + console.log(`[build:binary] compiling target: ${name} -> ${output}`); + run(bun, buildArgs); + + if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) { + try { + run("/usr/bin/codesign", ["--remove-signature", output], { quiet: true }); + } catch { + // ignore + } + try { + run("/usr/bin/codesign", ["--force", "--sign", "-", output], { quiet: true }); + } catch { + // ignore + } + } +} + +function run(command, args, options = {}) { const result = spawnSync(command, args, { cwd: root, - stdio: "inherit" + stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit" }); if (result.error) throw result.error; if (result.status !== 0) { diff --git a/src/cli.test.ts b/src/cli.test.ts index fb4e8f5..517fc2b 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -111,6 +111,15 @@ describe("CLI version & help handling", () => { expect(current.status).toBe(1); expect(current.stderr).toContain("Stateless mode is enabled"); }); + + test("update command runs in source mode when executed from bun", () => { + const result = runCli(["update"]); + expect(result.status).toBe(0); + const parsed = JSON.parse(result.stdout.trim()); + expect(parsed.updated).toBe(true); + expect(parsed.mode).toBe("source"); + expect(parsed.version).toBe(VERSION); + }); }); function makeConfigEnv(): Record { diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 3372a3d..eb3797b 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -1,3 +1,4 @@ +import { chmodSync, renameSync, writeFileSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; import { VERSION } from "../../version.js"; @@ -6,7 +7,10 @@ import { printJson } from "../printer.js"; import { STATE_DIR } from "./service.js"; import type { CliRuntime } from "../types.js"; -export async function handleUpdateCommand(runtime: CliRuntime) { +const DEFAULT_GITHUB_REPO = "yunyingk/seal-home"; +const UPDATE_URL_ENV = "SEAL_HOME_UPDATE_URL"; + +export async function handleUpdateCommand(runtime: CliRuntime, options: { checkOnly?: boolean } = {}) { const serviceConfig = { appRoot: runtime.appRoot, entryFile: runtime.entryFile, @@ -14,23 +18,155 @@ export async function handleUpdateCommand(runtime: CliRuntime) { version: VERSION, launcher: runtime.launcher }; - const wasRunning = serviceStatus(serviceConfig).running; - if (wasRunning) await runServiceCommand("stop", serviceConfig); if (!isCompiledBinary()) { + const wasRunning = serviceStatus(serviceConfig).running; + if (wasRunning) await runServiceCommand("stop", serviceConfig); + runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]); runCommand("bun", ["install"], { cwd: runtime.appRoot }); + + if (wasRunning) await runServiceCommand("start", serviceConfig); + + printJson({ + updated: true, + serviceRestarted: wasRunning, + version: VERSION, + mode: "source" + }); + return; } - if (wasRunning) await runServiceCommand("start", serviceConfig); + // Standalone binary update + const currentPlatform = detectPlatformArch(); + const updateInfo = await fetchLatestReleaseInfo(); + + if (!updateInfo) { + printJson({ + updated: false, + version: VERSION, + mode: "binary", + message: "No update source configured or release server unreachable" + }); + return; + } + + if (isNewerVersion(updateInfo.version, VERSION)) { + if (options.checkOnly) { + printJson({ + updated: false, + updateAvailable: true, + currentVersion: VERSION, + latestVersion: updateInfo.version, + downloadUrl: updateInfo.downloads[currentPlatform]?.url + }); + return; + } + + const downloadUrl = updateInfo.downloads[currentPlatform]?.url; + if (!downloadUrl) { + throw new Error(`No prebuilt binary available for platform: ${currentPlatform} in release ${updateInfo.version}`); + } + + const wasRunning = serviceStatus(serviceConfig).running; + if (wasRunning) await runServiceCommand("stop", serviceConfig); + + const tmpBinary = `${process.execPath}.tmp.${Date.now()}`; + const response = await fetch(downloadUrl); + if (!response.ok) { + throw new Error(`Failed to download binary update: ${response.status} ${response.statusText}`); + } + const buffer = Buffer.from(await response.arrayBuffer()); + writeFileSync(tmpBinary, buffer); + chmodSync(tmpBinary, 0o755); + renameSync(tmpBinary, process.execPath); + + if (wasRunning) await runServiceCommand("start", serviceConfig); + + printJson({ + updated: true, + fromVersion: VERSION, + toVersion: updateInfo.version, + serviceRestarted: wasRunning, + mode: "binary" + }); + return; + } printJson({ - updated: true, - serviceRestarted: wasRunning, - version: VERSION + updated: false, + version: VERSION, + mode: "binary", + message: "seal-home is already up to date" }); } +function detectPlatformArch(): string { + const platform = process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : "linux"; + const arch = process.arch === "arm64" ? "arm64" : "x64"; + return `${platform}-${arch}`; +} + +type ReleaseInfo = { + version: string; + downloads: Record; +}; + +async function fetchLatestReleaseInfo(): Promise { + const customUrl = process.env[UPDATE_URL_ENV]?.trim(); + if (customUrl) { + try { + const res = await fetch(customUrl); + if (res.ok) { + return (await res.json()) as ReleaseInfo; + } + } catch { + // ignore + } + } + + // Fallback to GitHub API + try { + const res = await fetch(`https://api.github.com/repos/${DEFAULT_GITHUB_REPO}/releases/latest`, { + headers: { + "User-Agent": `seal-home/${VERSION}` + } + }); + if (!res.ok) return undefined; + const json = (await res.json()) as { + tag_name?: string; + assets?: Array<{ name: string; browser_download_url: string }>; + }; + const version = (json.tag_name ?? "").replace(/^v/, ""); + if (!version) return undefined; + + const downloads: Record = {}; + for (const asset of json.assets ?? []) { + for (const target of ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64", "windows-x64"]) { + if (asset.name.includes(target)) { + downloads[target] = { url: asset.browser_download_url }; + } + } + } + + return { version, downloads }; + } catch { + return undefined; + } +} + +function isNewerVersion(latest: string, current: string): boolean { + const lParts = latest.split(".").map(Number); + const cParts = current.split(".").map(Number); + for (let i = 0; i < Math.max(lParts.length, cParts.length); i++) { + const l = lParts[i] ?? 0; + const c = cParts[i] ?? 0; + if (l > c) return true; + if (l < c) return false; + } + return false; +} + function runCommand(command: string, args: string[], options: { cwd?: string } = {}) { const result = spawnSync(command, args, { cwd: options.cwd, diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 8c18d23..e7e549a 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -25,7 +25,7 @@ import { handleUpdateCommand } from "./commands/update.js"; import { handleUsersCommand } from "./commands/users.js"; import { handleWebhookCommand } from "./commands/webhook.js"; import { selectCorp } from "./helpers.js"; -import { parseArgs, stringOption } from "./parser.js"; +import { booleanOption, parseArgs, stringOption } from "./parser.js"; import { formatConsoleOutput, joinOutput, @@ -162,7 +162,9 @@ async function dispatch(argv: string[], runtime: CliRuntime) { } if (area === "update") { - await handleUpdateCommand(runtime); + await handleUpdateCommand(runtime, { + checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"]) + }); return; }