954 lines
33 KiB
TypeScript
954 lines
33 KiB
TypeScript
import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||
import { basename, dirname, join } from "node:path";
|
||
import { spawnSync } from "node:child_process";
|
||
import { isCompiledBinary } from "../../core/runtime.js";
|
||
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
||
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
|
||
import { saveUpdateCache } from "../../core/update-cache.js";
|
||
import { VERSION, IS_RELEASE } from "../../version.js";
|
||
import { printJson } from "../printer.js";
|
||
import { validationError } from "../../core/errors.js";
|
||
import type { CliRuntime } from "../types.js";
|
||
|
||
const DEFAULT_GITHUB_REPO = "yunyingk/seal-use";
|
||
const LEGACY_GITHUB_REPO = "yunyingk/seal-home";
|
||
const GITHUB_REPO_ENV = "SEAL_USE_GITHUB_REPO";
|
||
const LEGACY_GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO";
|
||
|
||
export type UpdateOptions = {
|
||
checkOnly?: boolean;
|
||
changelogOnly?: boolean;
|
||
limit?: number;
|
||
force?: boolean;
|
||
targetVersion?: string;
|
||
repo?: string;
|
||
bgSave?: boolean;
|
||
};
|
||
|
||
export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) {
|
||
const repo = options.repo
|
||
|| process.env[GITHUB_REPO_ENV]?.trim()
|
||
|| process.env[LEGACY_GITHUB_REPO_ENV]?.trim()
|
||
|| DEFAULT_GITHUB_REPO;
|
||
const rawTarget = options.targetVersion?.trim();
|
||
const targetVersion = rawTarget && rawTarget.toLowerCase() !== "latest" ? rawTarget : undefined;
|
||
|
||
// Validate targetVersion: prevent downgrade to older versions
|
||
if (targetVersion) {
|
||
const cleanTarget = targetVersion.replace(/^v/, "");
|
||
const cmp = compareSemVer(cleanTarget, VERSION);
|
||
if (cmp < 0) {
|
||
if (!IS_RELEASE && options.force) {
|
||
// Allow force reinstall/switch from dev build to target release
|
||
} else {
|
||
printJson({
|
||
updated: false,
|
||
currentVersion: VERSION,
|
||
targetVersion: cleanTarget,
|
||
mode: isCompiledBinary() ? "binary" : "source",
|
||
message: !IS_RELEASE
|
||
? `Cannot downgrade seal-use from dev build v${VERSION} to release v${cleanTarget}. Use --force to overwrite.`
|
||
: `Cannot downgrade seal-use from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.`
|
||
});
|
||
return;
|
||
}
|
||
}
|
||
if (cmp === 0 && !options.force) {
|
||
printJson({
|
||
updated: false,
|
||
currentVersion: VERSION,
|
||
targetVersion: cleanTarget,
|
||
mode: isCompiledBinary() ? "binary" : "source",
|
||
message: `seal-use is already at version v${VERSION}. Use --force to reinstall.`
|
||
});
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 1. Changelog / Release History query
|
||
if (options.changelogOnly) {
|
||
const releases = await fetchGitHubReleases(repo, options.limit ?? 10);
|
||
printJson({
|
||
currentVersion: VERSION,
|
||
totalQueried: releases.length,
|
||
releases: releases.map((r) => ({
|
||
version: r.version,
|
||
tagName: r.tagName,
|
||
publishedAt: r.publishedAt,
|
||
author: r.author,
|
||
releaseNotes: r.notes,
|
||
releaseUrl: r.htmlUrl,
|
||
isCurrent: r.version === VERSION,
|
||
isNewer: isNewerVersion(r.version, VERSION)
|
||
}))
|
||
});
|
||
return;
|
||
}
|
||
|
||
// 2. Source development mode (running via bun/node)
|
||
if (!isCompiledBinary()) {
|
||
if (options.checkOnly) {
|
||
const releases = await fetchGitHubReleases(repo, 30);
|
||
const latestRelease = releases[0];
|
||
const latestVersion = latestRelease?.version ?? VERSION;
|
||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
||
|
||
if (latestRelease?.version) {
|
||
saveUpdateCache({
|
||
latestVersion: latestRelease.version,
|
||
publishedAt: latestRelease.publishedAt,
|
||
releaseUrl: latestRelease.htmlUrl
|
||
});
|
||
}
|
||
|
||
if (options.bgSave) {
|
||
return;
|
||
}
|
||
|
||
printJson({
|
||
updated: false,
|
||
updateAvailable: isUpgrade,
|
||
currentVersion: VERSION,
|
||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||
latestVersion,
|
||
latestVersionPublishedAt: latestRelease?.publishedAt,
|
||
behindCount: pendingReleases.length,
|
||
pendingReleases: pendingReleases.map((r) => ({
|
||
version: r.version,
|
||
tagName: r.tagName,
|
||
publishedAt: r.publishedAt,
|
||
author: r.author,
|
||
releaseNotes: r.notes,
|
||
releaseUrl: r.htmlUrl
|
||
})),
|
||
releaseNotes: latestRelease?.notes ?? "",
|
||
releaseUrl: latestRelease?.htmlUrl ?? "",
|
||
mode: "source",
|
||
message: "当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"
|
||
});
|
||
return;
|
||
}
|
||
|
||
// Source updates must operate on this package's checkout, never a parent app's repository.
|
||
if (!existsSync(join(runtime.appRoot, ".git"))) {
|
||
throw validationError("当前源码安装目录不是 seal-use 的 Git 工作区。请使用发行版二进制,或从 seal-use 仓库通过 npm link 安装。");
|
||
}
|
||
try {
|
||
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
|
||
} catch (err) {
|
||
console.error(`⚠️ 开发版更新同步失败,继续刷新本地依赖: ${err instanceof Error ? err.message : String(err)}`);
|
||
}
|
||
runCommand("bun", ["install"], { cwd: runtime.appRoot });
|
||
|
||
printJson({
|
||
updated: true,
|
||
version: VERSION,
|
||
mode: "source"
|
||
});
|
||
return;
|
||
}
|
||
|
||
// 3. Standalone binary mode: check GitHub Releases
|
||
const platform = detectPlatform();
|
||
const arch = detectArch();
|
||
|
||
// Every binary-mode invocation sweeps here, not just real updates: the SWR
|
||
// background check (`update check --bg-save`) is the only command many users
|
||
// ever run after their last update, so it is what reclaims that update's
|
||
// `.old.<timestamp>` backup (undeletable while its image was executing).
|
||
pruneUpdateLeftovers(process.execPath);
|
||
|
||
const { releases, source } = await fetchReleasesWithSource(repo, 30);
|
||
const release = targetVersion
|
||
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
|
||
await fetchGitHubRelease(repo, targetVersion))
|
||
: (releases[0] ?? await fetchGitHubRelease(repo));
|
||
|
||
if (!release) {
|
||
const mirrorMode = getMirrorMode();
|
||
const newest = releases[0]?.version;
|
||
const wanted = targetVersion ? `v${targetVersion.replace(/^v/, "")}` : "最新版本";
|
||
const sourcesTried = mirrorMode === "auto"
|
||
? ["Gitea 国内镜像", "GitHub"]
|
||
: mirrorMode === "gitea" ? ["Gitea 国内镜像"] : ["GitHub"];
|
||
const message = targetVersion && newest
|
||
? `${source === "gitea" ? "国内镜像(Gitea)" : "GitHub"} 尚未提供 ${wanted}(该源当前最新 v${newest})。已尝试的更新源:${sourcesTried.join("、")};镜像同步存在时间差,请稍后重试。`
|
||
: `无法访问更新源(已尝试:${sourcesTried.join("、")})。请检查网络后重试。`;
|
||
|
||
printJson({
|
||
updated: false,
|
||
currentVersion: VERSION,
|
||
mode: "binary",
|
||
mirrorMode,
|
||
sourcesTried,
|
||
releaseSource: source,
|
||
sourceLatestVersion: newest ?? null,
|
||
message
|
||
});
|
||
return;
|
||
}
|
||
|
||
const latestVersion = release.version;
|
||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||
const shouldUpdate = isUpgrade || Boolean(options.force);
|
||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
||
|
||
if (release?.version) {
|
||
saveUpdateCache({
|
||
latestVersion: release.version,
|
||
publishedAt: release.publishedAt,
|
||
releaseUrl: release.htmlUrl
|
||
});
|
||
}
|
||
|
||
if (options.bgSave) {
|
||
return;
|
||
}
|
||
|
||
if (options.checkOnly) {
|
||
printJson({
|
||
updated: false,
|
||
updateAvailable: isUpgrade,
|
||
currentVersion: VERSION,
|
||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||
latestVersion,
|
||
latestVersionPublishedAt: release.publishedAt,
|
||
behindCount: pendingReleases.length,
|
||
pendingReleases: pendingReleases.map((r) => ({
|
||
version: r.version,
|
||
tagName: r.tagName,
|
||
publishedAt: r.publishedAt,
|
||
author: r.author,
|
||
releaseNotes: r.notes,
|
||
releaseUrl: r.htmlUrl
|
||
})),
|
||
releaseNotes: release.notes,
|
||
releaseUrl: release.htmlUrl,
|
||
mode: "binary"
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (!shouldUpdate) {
|
||
printJson({
|
||
updated: false,
|
||
currentVersion: VERSION,
|
||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||
latestVersion,
|
||
latestVersionPublishedAt: release.publishedAt,
|
||
mode: "binary",
|
||
message: `seal-use is already up to date (v${VERSION})`
|
||
});
|
||
return;
|
||
}
|
||
|
||
// Find matching asset
|
||
const asset = matchAssetForPlatform(release.assets, platform, arch);
|
||
if (!asset) {
|
||
throw new Error(
|
||
`No compatible binary found for ${platform}-${arch} in release v${latestVersion}. ` +
|
||
`Available assets: ${release.assets.map((a) => a.name).join(", ")}`
|
||
);
|
||
}
|
||
|
||
// Download binary or archive
|
||
const execPath = process.execPath;
|
||
const execDir = dirname(execPath);
|
||
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
|
||
mkdirSync(tmpDir, { recursive: true });
|
||
|
||
try {
|
||
const downloadedFile = join(tmpDir, asset.name);
|
||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name);
|
||
|
||
let newBinaryPath = downloadedFile;
|
||
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
|
||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
|
||
} else if (asset.name.endsWith(".zip")) {
|
||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
|
||
}
|
||
|
||
chmodSync(newBinaryPath, 0o755);
|
||
|
||
// Re-sign on macOS ad-hoc if codesign exists
|
||
if (process.platform === "darwin") {
|
||
try {
|
||
spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" });
|
||
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" });
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
// Atomic replace
|
||
if (process.platform === "win32") {
|
||
const oldBinary = `${execPath}.old.${Date.now()}`;
|
||
try {
|
||
renameSync(execPath, oldBinary);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
renameSync(newBinaryPath, execPath);
|
||
} else {
|
||
renameSync(newBinaryPath, execPath);
|
||
}
|
||
|
||
// Refresh the Agent Skill from the binary that is now on disk — never from this process.
|
||
//
|
||
// `renameSync` above advanced the file at `execPath`, but this process keeps executing the
|
||
// previous image, so its in-memory `EMBEDDED_SKILL_FILES` still holds the release we just
|
||
// replaced. Calling `syncGlobalSkillIfPresent()` here therefore wrote the *old* skill over the
|
||
// new one, leaving the agent a full release behind (and `skillSynced: <dir>` reported success
|
||
// either way). One synchronous child reads the new image's embedded copy; it exits before this
|
||
// function returns, and nothing is left running.
|
||
const skillSync = installSkillFromInstalledBinary(execPath, latestVersion);
|
||
|
||
saveUpdateCache({
|
||
latestVersion,
|
||
publishedAt: release.publishedAt,
|
||
releaseUrl: release.htmlUrl
|
||
});
|
||
|
||
printJson({
|
||
updated: true,
|
||
fromVersion: VERSION,
|
||
toVersion: latestVersion,
|
||
skillSynced: skillSync.targetDir ?? false,
|
||
skillVersion: skillSync.version ?? false,
|
||
mode: "binary"
|
||
});
|
||
} finally {
|
||
try {
|
||
rmSync(tmpDir, { recursive: true, force: true });
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Deletes the debris earlier self-updates left next to the installed binary.
|
||
*
|
||
* Windows cannot `renameSync`-replace a running executable, so the win32 branch
|
||
* first renames the live image to `<binary>.old.<timestamp>` and never removes
|
||
* it — one full binary (tens of MB) leaked per update. The same file is also
|
||
* undeletable *during* that update (it is the executing image), so cleanup runs
|
||
* at the start of the next update instead, when nothing holds it open. Orphaned
|
||
* `.tmp-update-<timestamp>` staging directories from an interrupted run are
|
||
* swept for the same reason.
|
||
*
|
||
* Best-effort: a locked or already-gone file is skipped, never fatal. Returns
|
||
* the entries removed so tests can assert the sweep.
|
||
*/
|
||
export function pruneUpdateLeftovers(binaryPath: string): string[] {
|
||
const dir = dirname(binaryPath);
|
||
const base = basename(binaryPath);
|
||
const removed: string[] = [];
|
||
|
||
let entries: string[];
|
||
try {
|
||
entries = readdirSync(dir);
|
||
} catch {
|
||
return removed;
|
||
}
|
||
|
||
const now = Date.now();
|
||
for (const entry of entries) {
|
||
// `<binary>.old.<anything>` (e.g. seal-use.exe.old.1727...) and the
|
||
// `.tmp-update-<ts>` staging dirs this command creates. Never the live
|
||
// binary itself: its name has no `.old.` / `tmp-update` marker.
|
||
const isStaleBackup = entry.startsWith(`${base}.old.`);
|
||
const isOrphanStaging = entry.startsWith(".tmp-update-");
|
||
if (!isStaleBackup && !isOrphanStaging) continue;
|
||
|
||
const fullPath = join(dir, entry);
|
||
try {
|
||
if (isOrphanStaging) {
|
||
// A staging dir younger than an hour may belong to an update running
|
||
// right now; deleting it out from under that download would break it.
|
||
// The `.old.` case needs no such gate: on Windows a live image cannot
|
||
// be deleted (the rm throws and is swallowed), and on POSIX no `.old.`
|
||
// file is ever written.
|
||
if (now - statSync(fullPath).mtimeMs < 60 * 60 * 1000) continue;
|
||
}
|
||
rmSync(fullPath, { recursive: true, force: true });
|
||
removed.push(entry);
|
||
} catch {
|
||
// Still locked (its owning process is alive); the next update retries.
|
||
}
|
||
}
|
||
|
||
return removed;
|
||
}
|
||
|
||
/**
|
||
* Installs the Agent Skill by running the newly installed binary as a child process, then reads
|
||
* the file back to prove which version actually landed.
|
||
*
|
||
* The read-back is the point. Nothing about writing the file distinguishes "wrote the target
|
||
* skill" from "wrote my own skill": the previous in-process sync did the latter and still reported
|
||
* success, for several releases. Asserting the version turns silent staleness into a loud failure,
|
||
* and it happens before the command declares the update complete.
|
||
*/
|
||
function installSkillFromInstalledBinary(
|
||
execPath: string,
|
||
targetVersion: string
|
||
): { targetDir?: string; version?: string } {
|
||
const result = spawnSync(execPath, ["skill", "install"], { encoding: "utf8" });
|
||
if (result.status !== 0) {
|
||
throw new Error(
|
||
`Binary updated to v${targetVersion}, but refreshing the Agent Skill failed ` +
|
||
`('${execPath} skill install' exited with ${result.status}). ` +
|
||
`Run 'seal-use skill install' to finish the update.`
|
||
);
|
||
}
|
||
|
||
let targetDir: string | undefined;
|
||
try {
|
||
targetDir = (JSON.parse(result.stdout ?? "") as { targetDir?: string }).targetDir;
|
||
} catch {
|
||
// `skill install` prints JSON; if that ever changes, the read-back below still decides.
|
||
}
|
||
|
||
const version = readInstalledSkillVersion(targetDir ? join(targetDir, "SKILL.md") : undefined);
|
||
if (version !== targetVersion) {
|
||
throw new Error(
|
||
`Binary updated to v${targetVersion}, but the Agent Skill on disk reports ` +
|
||
`${version ?? "no version"}${targetDir ? ` (${targetDir})` : ""}. ` +
|
||
`Run 'seal-use skill install' to finish the update.`
|
||
);
|
||
}
|
||
|
||
return { targetDir, version };
|
||
}
|
||
|
||
function detectPlatform(): "darwin" | "linux" | "windows" {
|
||
if (process.platform === "darwin") return "darwin";
|
||
if (process.platform === "win32") return "windows";
|
||
return "linux";
|
||
}
|
||
|
||
function detectArch(): "arm64" | "x64" {
|
||
return process.arch === "arm64" ? "arm64" : "x64";
|
||
}
|
||
|
||
type GitHubAsset = {
|
||
name: string;
|
||
downloadUrl: string;
|
||
size: number;
|
||
};
|
||
|
||
type GitHubRelease = {
|
||
version: string;
|
||
tagName: string;
|
||
name?: string;
|
||
publishedAt?: string;
|
||
author?: string;
|
||
notes: string;
|
||
htmlUrl: string;
|
||
assets: GitHubAsset[];
|
||
};
|
||
|
||
export function getMirrorMode(): "auto" | "github" | "gitea" {
|
||
const env = (process.env.SEAL_USE_MIRROR || process.env.SEAL_HOME_MIRROR)?.trim().toLowerCase();
|
||
if (env === "github" || env === "gitea") return env;
|
||
if (process.env.CI) return "github";
|
||
return "auto";
|
||
}
|
||
|
||
async function fetchReleasesWithSource(
|
||
repo: string,
|
||
limit = 20
|
||
): Promise<{ releases: GitHubRelease[]; source: "gitea" | "github" | null }> {
|
||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||
const headers: Record<string, string> = {
|
||
"User-Agent": `seal-use/${VERSION}`,
|
||
Accept: "application/vnd.github.v3+json",
|
||
...(token ? { Authorization: `Bearer ${token}` } : {})
|
||
};
|
||
|
||
const mirrorMode = getMirrorMode();
|
||
const urls: string[] = [];
|
||
|
||
// 1. Gitea releases (bypassed in CI / GitHub-only mode)
|
||
if (mirrorMode !== "github") {
|
||
urls.push(
|
||
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`,
|
||
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`
|
||
);
|
||
}
|
||
|
||
// 2. GitHub releases (bypassed in Gitea-only mode)
|
||
if (mirrorMode !== "gitea") {
|
||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||
if (repo !== LEGACY_GITHUB_REPO) {
|
||
urls.push(`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases?per_page=${limit}`);
|
||
}
|
||
}
|
||
|
||
for (const url of urls) {
|
||
try {
|
||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(3000) });
|
||
if (!res.ok) continue;
|
||
const json = (await res.json()) as Array<{
|
||
tag_name?: string;
|
||
name?: string;
|
||
body?: string;
|
||
html_url?: string;
|
||
published_at?: string;
|
||
author?: { login?: string };
|
||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||
}>;
|
||
|
||
if (!Array.isArray(json) || json.length === 0) continue;
|
||
|
||
const list: GitHubRelease[] = [];
|
||
for (const item of json) {
|
||
const tagName = item.tag_name ?? "";
|
||
const version = tagName.replace(/^v/, "");
|
||
if (!version) continue;
|
||
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
|
||
name: a.name,
|
||
downloadUrl: a.browser_download_url,
|
||
size: a.size ?? 0
|
||
}));
|
||
list.push({
|
||
version,
|
||
tagName,
|
||
name: item.name ?? tagName,
|
||
publishedAt: item.published_at ? normalizeBeijingIso(item.published_at) : undefined,
|
||
author: item.author?.login,
|
||
notes: item.body ?? "",
|
||
htmlUrl: item.html_url ?? "",
|
||
assets
|
||
});
|
||
}
|
||
if (list.length > 0) {
|
||
return { releases: list, source: url.includes("git.ying-qing.cn") ? "gitea" : "github" };
|
||
}
|
||
} catch {
|
||
// try next source
|
||
}
|
||
}
|
||
|
||
return { releases: [], source: null };
|
||
}
|
||
|
||
async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
|
||
const { releases } = await fetchReleasesWithSource(repo, limit);
|
||
return releases;
|
||
}
|
||
|
||
async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise<GitHubRelease | undefined> {
|
||
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
|
||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||
const headers: Record<string, string> = {
|
||
"User-Agent": `seal-use/${VERSION}`,
|
||
Accept: "application/vnd.github.v3+json",
|
||
...(token ? { Authorization: `Bearer ${token}` } : {})
|
||
};
|
||
|
||
const mirrorMode = getMirrorMode();
|
||
const urls: string[] = [];
|
||
|
||
// 1. Gitea releases (bypassed in CI / GitHub-only mode)
|
||
if (mirrorMode !== "github") {
|
||
urls.push(
|
||
tag
|
||
? `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`
|
||
: `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`,
|
||
tag
|
||
? `https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`
|
||
: `https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`
|
||
);
|
||
}
|
||
|
||
// 2. GitHub releases (bypassed in Gitea-only mode)
|
||
if (mirrorMode !== "gitea") {
|
||
urls.push(
|
||
tag
|
||
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
|
||
: `https://api.github.com/repos/${repo}/releases/latest`
|
||
);
|
||
if (repo !== LEGACY_GITHUB_REPO) {
|
||
urls.push(
|
||
tag
|
||
? `https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/tags/${tag}`
|
||
: `https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/latest`
|
||
);
|
||
}
|
||
}
|
||
|
||
let fallbackRelease: GitHubRelease | undefined;
|
||
|
||
for (const url of urls) {
|
||
try {
|
||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(3000) });
|
||
if (!res.ok) continue;
|
||
const json = (await res.json()) as {
|
||
tag_name?: string;
|
||
name?: string;
|
||
body?: string;
|
||
html_url?: string;
|
||
published_at?: string;
|
||
author?: { login?: string };
|
||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||
};
|
||
|
||
const tagName = json.tag_name ?? "";
|
||
const version = tagName.replace(/^v/, "");
|
||
if (!version) continue;
|
||
|
||
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
|
||
name: item.name,
|
||
downloadUrl: item.browser_download_url,
|
||
size: item.size ?? 0
|
||
}));
|
||
|
||
const candidateRelease: GitHubRelease = {
|
||
version,
|
||
tagName,
|
||
name: json.name ?? tagName,
|
||
publishedAt: json.published_at ? normalizeBeijingIso(json.published_at) : undefined,
|
||
author: json.author?.login,
|
||
notes: json.body ?? "",
|
||
htmlUrl: json.html_url ?? "",
|
||
assets
|
||
};
|
||
|
||
// If this source already has uploaded assets, return it immediately.
|
||
if (assets.length > 0) {
|
||
return candidateRelease;
|
||
}
|
||
|
||
// Otherwise keep as fallback (in case all sources have no assets)
|
||
if (!fallbackRelease) {
|
||
fallbackRelease = candidateRelease;
|
||
}
|
||
} catch {
|
||
// try next source
|
||
}
|
||
}
|
||
|
||
return fallbackRelease;
|
||
}
|
||
|
||
function isArchiveAsset(name: string): boolean {
|
||
return name.endsWith(".tar.gz") || name.endsWith(".tgz") || name.endsWith(".zip");
|
||
}
|
||
|
||
function isRawBinaryAsset(name: string): boolean {
|
||
return !isArchiveAsset(name) && !name.endsWith(".sha256");
|
||
}
|
||
|
||
/**
|
||
* Picks the release asset for this platform.
|
||
*
|
||
* Prefer the compressed archive, which is roughly a third of the raw binary (25–39 MB against
|
||
* 67–102 MB) — that is the difference between a fast and a slow `seal-use update`, and it matches
|
||
* which asset the Gitea mirror uploads first.
|
||
*
|
||
* Windows still prefers the raw `.exe`: extracting the `.zip` there would depend on an `unzip`
|
||
* binary that stock Windows does not ship. Both are published for every platform, so the other one
|
||
* remains a working fallback.
|
||
*/
|
||
export function matchAssetForPlatform(
|
||
assets: GitHubAsset[],
|
||
platform: "darwin" | "linux" | "windows",
|
||
arch: "arm64" | "x64"
|
||
): GitHubAsset | undefined {
|
||
const platformKeywords: Record<string, string[]> = {
|
||
darwin: ["darwin", "macos", "osx", "apple"],
|
||
linux: ["linux"],
|
||
windows: ["windows", "win32", "win"]
|
||
};
|
||
const archKeywords: Record<string, string[]> = {
|
||
arm64: ["arm64", "aarch64"],
|
||
x64: ["x64", "x86_64", "amd64"]
|
||
};
|
||
|
||
const pKeys = platformKeywords[platform] || [];
|
||
const aKeys = archKeywords[arch] || [];
|
||
|
||
const matched = assets.filter((asset) => {
|
||
const lower = asset.name.toLowerCase();
|
||
const matchesP = pKeys.some((k) => lower.includes(k));
|
||
const matchesA = aKeys.some((k) => lower.includes(k));
|
||
return matchesP && matchesA;
|
||
});
|
||
|
||
// A `.sha256` sidecar matches the platform/arch keywords too, and it is never installable.
|
||
const candidates = matched.filter((asset) => !asset.name.endsWith(".sha256"));
|
||
const archive = candidates.find((asset) => isArchiveAsset(asset.name));
|
||
const directBinary = candidates.find((asset) => isRawBinaryAsset(asset.name));
|
||
|
||
if (platform === "windows") {
|
||
return directBinary ?? archive ?? candidates[0];
|
||
}
|
||
return archive ?? directBinary ?? candidates[0];
|
||
}
|
||
|
||
function logProgress(msg: string) {
|
||
try {
|
||
process.stderr.write(`${msg}\n`);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
|
||
const mirrorMode = getMirrorMode();
|
||
const candidates: string[] = [];
|
||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||
const fileName = assetName || url.split("/").pop() || "";
|
||
|
||
// 1. High-speed Gitea direct mirror (bypassed in CI / GitHub-only mode)
|
||
if (mirrorMode !== "github") {
|
||
if (tag && fileName) {
|
||
candidates.push(
|
||
`https://git.ying-qing.cn/gitea/seal-use/releases/download/${tag}/${fileName}`,
|
||
`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${fileName}`
|
||
);
|
||
}
|
||
if (url.startsWith("https://git.ying-qing.cn")) {
|
||
candidates.push(url);
|
||
}
|
||
}
|
||
|
||
// 2. Fast GitHub CDN proxies and direct GitHub fallback (bypassed in Gitea-only mode)
|
||
if (mirrorMode !== "gitea") {
|
||
if (tag && fileName) {
|
||
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
|
||
if (!process.env.CI) {
|
||
candidates.push(`https://ghfast.top/${ghDirectUrl}`, `https://gh.ddlc.top/${ghDirectUrl}`);
|
||
}
|
||
candidates.push(ghDirectUrl);
|
||
} else if (url.includes("github.com")) {
|
||
if (!process.env.CI) {
|
||
candidates.push(`https://ghfast.top/${url}`, `https://gh.ddlc.top/${url}`);
|
||
}
|
||
candidates.push(url);
|
||
} else {
|
||
candidates.push(url);
|
||
}
|
||
}
|
||
|
||
// Deduplicate candidates
|
||
const uniqueCandidates = Array.from(new Set(candidates));
|
||
|
||
let lastError: Error | undefined;
|
||
const CONNECT_TIMEOUT_MS = 6000; // 6s connection & headers timeout
|
||
const WARMUP_WINDOW_MS = 6000; // 6s initial grace window
|
||
const WARMUP_MIN_BYTES = 300 * 1024; // Must download at least 300 KB within first 6s (otherwise switch)
|
||
const STALL_TIMEOUT_MS = 10000; // 10s completely stalled (0 bytes received) before giving up
|
||
const MAX_TOTAL_TIMEOUT_MS = 180000; // 3m max safety limit
|
||
|
||
for (let i = 0; i < uniqueCandidates.length; i++) {
|
||
const candidate = uniqueCandidates[i]!;
|
||
const controller = new AbortController();
|
||
let abortReason = "";
|
||
const abortWith = (reason: string) => {
|
||
abortReason = reason;
|
||
try {
|
||
controller.abort();
|
||
} catch {
|
||
// ignore
|
||
}
|
||
};
|
||
|
||
let connectTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {
|
||
abortWith("Connection timed out (no response headers within 6s)");
|
||
}, CONNECT_TIMEOUT_MS);
|
||
|
||
let maxTimer: ReturnType<typeof setTimeout> | undefined;
|
||
let warmupTimer: ReturnType<typeof setTimeout> | undefined;
|
||
|
||
try {
|
||
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] Downloading via: ${candidate}`);
|
||
const res = await fetch(candidate, { signal: controller.signal });
|
||
if (connectTimer) {
|
||
clearTimeout(connectTimer);
|
||
connectTimer = undefined;
|
||
}
|
||
|
||
if (!res.ok) {
|
||
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
||
}
|
||
|
||
maxTimer = setTimeout(() => {
|
||
abortWith("Overall download time exceeded 3 minutes");
|
||
}, MAX_TOTAL_TIMEOUT_MS);
|
||
|
||
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
||
const reader = res.body?.getReader();
|
||
if (!reader) {
|
||
const buffer = Buffer.from(await res.arrayBuffer());
|
||
if (buffer.length < 1000) {
|
||
throw new Error(`Downloaded content is suspiciously small (${buffer.length} bytes)`);
|
||
}
|
||
writeFileSync(destPath, buffer);
|
||
logProgress(`✓ Download succeeded (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||
return;
|
||
}
|
||
|
||
const chunks: Uint8Array[] = [];
|
||
let receivedBytes = 0;
|
||
let lastReport = 0;
|
||
|
||
// Initial 6-second warmup speed check: must reach 300KB
|
||
warmupTimer = setTimeout(() => {
|
||
if (receivedBytes < WARMUP_MIN_BYTES) {
|
||
const kb = (receivedBytes / 1024).toFixed(1);
|
||
abortWith(`Initial transfer too slow (${kb} KB < 300 KB in 6s), switching mirror...`);
|
||
}
|
||
}, WARMUP_WINDOW_MS);
|
||
|
||
while (true) {
|
||
// Read next chunk with 10s stall timeout
|
||
const readPromise = reader.read();
|
||
let chunkTimeoutTimer: ReturnType<typeof setTimeout> | undefined;
|
||
const stallPromise = new Promise<never>((_, reject) => {
|
||
chunkTimeoutTimer = setTimeout(() => {
|
||
reject(new Error("Data transfer stalled (no chunk received for 10s)"));
|
||
}, STALL_TIMEOUT_MS);
|
||
});
|
||
|
||
let result: { done: boolean; value?: Uint8Array };
|
||
try {
|
||
result = await Promise.race([readPromise, stallPromise]);
|
||
} finally {
|
||
if (chunkTimeoutTimer) clearTimeout(chunkTimeoutTimer);
|
||
}
|
||
|
||
const { done, value } = result;
|
||
if (done) break;
|
||
|
||
if (value) {
|
||
chunks.push(value);
|
||
receivedBytes += value.length;
|
||
|
||
// Clear warmup timer early if we already passed 300KB
|
||
if (warmupTimer && receivedBytes >= WARMUP_MIN_BYTES) {
|
||
clearTimeout(warmupTimer);
|
||
warmupTimer = undefined;
|
||
}
|
||
|
||
const now = Date.now();
|
||
if (now - lastReport > 200) {
|
||
lastReport = now;
|
||
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
|
||
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
||
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
||
try {
|
||
process.stderr.write(`\r ↳ Progress: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
try {
|
||
process.stderr.write("\n");
|
||
} catch {
|
||
// ignore
|
||
}
|
||
|
||
const completeBuffer = Buffer.concat(chunks);
|
||
if (completeBuffer.length < 1000) {
|
||
throw new Error(`Downloaded content is suspiciously small (${completeBuffer.length} bytes)`);
|
||
}
|
||
writeFileSync(destPath, completeBuffer);
|
||
logProgress(`✓ Download completed successfully (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||
return;
|
||
} catch (err) {
|
||
if (connectTimer) clearTimeout(connectTimer);
|
||
if (warmupTimer) clearTimeout(warmupTimer);
|
||
if (maxTimer) clearTimeout(maxTimer);
|
||
const msg = abortReason || (err instanceof Error ? err.message : String(err));
|
||
lastError = new Error(msg);
|
||
logProgress(`\n ↳ Mirror failed: ${lastError.message}`);
|
||
} finally {
|
||
if (connectTimer) clearTimeout(connectTimer);
|
||
if (warmupTimer) clearTimeout(warmupTimer);
|
||
if (maxTimer) clearTimeout(maxTimer);
|
||
}
|
||
}
|
||
|
||
throw new Error(`Failed to download asset from all mirrors: ${lastError?.message}`);
|
||
}
|
||
|
||
/**
|
||
* Lists every regular file under `dir`.
|
||
*
|
||
* Replaces the previous `find` subprocess: `find` is not available on Windows, so the archive
|
||
* path could not have worked there even once the download succeeded.
|
||
*/
|
||
function listFilesRecursive(dir: string): string[] {
|
||
let entries;
|
||
try {
|
||
entries = readdirSync(dir, { withFileTypes: true });
|
||
} catch {
|
||
return [];
|
||
}
|
||
|
||
const found: string[] = [];
|
||
for (const entry of entries) {
|
||
const full = join(dir, entry.name);
|
||
if (entry.isDirectory()) {
|
||
found.push(...listFilesRecursive(full));
|
||
} else if (entry.isFile()) {
|
||
found.push(full);
|
||
}
|
||
}
|
||
return found;
|
||
}
|
||
|
||
function resolveExtractedBinary(targetDir: string, platform: string, fallback: string): string {
|
||
const expectedName = platform === "windows" ? "seal-use.exe" : "seal-use";
|
||
const files = listFilesRecursive(targetDir);
|
||
return files.find((file) => basename(file) === expectedName) ?? files[0] ?? fallback;
|
||
}
|
||
|
||
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||
if (result.status !== 0) {
|
||
throw new Error(`Failed to extract tar archive: ${result.stderr.toString()}`);
|
||
}
|
||
unlinkSync(archivePath);
|
||
|
||
return resolveExtractedBinary(targetDir, platform, archivePath);
|
||
}
|
||
|
||
function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||
if (result.status !== 0) {
|
||
throw new Error(`Failed to extract zip archive: ${result.stderr.toString()}`);
|
||
}
|
||
unlinkSync(archivePath);
|
||
|
||
return resolveExtractedBinary(targetDir, platform, archivePath);
|
||
}
|
||
|
||
import { compareSemVer, isNewerVersion } from "../../core/semver.js";
|
||
// Re-exported for tests and callers that historically imported from here.
|
||
export { compareSemVer, isNewerVersion };
|
||
|
||
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
|
||
const result = spawnSync(command, args, {
|
||
cwd: options.cwd,
|
||
encoding: "utf8",
|
||
stdio: ["ignore", "pipe", "pipe"]
|
||
});
|
||
|
||
if (result.stdout) console.error(result.stdout.trimEnd());
|
||
if (result.stderr) console.error(result.stderr.trimEnd());
|
||
|
||
if (result.status !== 0) {
|
||
throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`);
|
||
}
|
||
}
|