refactor(cli): split commands/update.ts into update/{index,releases}.ts

releases.ts carries the GitHub/Gitea release infrastructure (types,
listing, mirrored download, archive extraction, semver compare);
index.ts keeps handleUpdateCommand and re-exports the previously
public members so update.test.ts stays source-compatible.
Verbatim code moves, no behavior change: tsc clean, 316 tests pass.
This commit is contained in:
gitea committed 2026-10-04 14:12:03 +08:00
1 parent 6f1f2623a3
commit c8450b9908
4 files changed
+510 -471

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ import {
normalizeRepo,
isValidRepo,
type GitHubAsset,
} from "./update.js";
} from "./update/index.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
@@ -1,18 +1,32 @@
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { isCompiledBinary, resolveAppRoot } from "../../packaging/runtime.js";
import { syncGlobalSkillIfPresent } from "../../packaging/embedded-skill.js";
import { loadGlobalConfig } from "../../core/config/loader.js";
import { VERSION } from "../../version.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js";
const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
export type UpdateSourcePreference = "auto" | "github" | "gitea";
import { isCompiledBinary, resolveAppRoot } from "../../../packaging/runtime.js";
import { syncGlobalSkillIfPresent } from "../../../packaging/embedded-skill.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
import { VERSION } from "../../../version.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../../types.js";
import {
compareSemVer,
detectArch,
detectPlatform,
downloadFile,
extractTarGz,
extractZip,
fetchGitHubRelease,
fetchGitHubReleases,
isNewerVersion,
isValidRepo,
matchAssetForPlatform,
normalizeRepo,
DEFAULT_GITHUB_REPO,
GITHUB_REPO_ENV,
type GitHubAsset,
type GitHubRelease,
type UpdateSourcePreference,
} from "./releases.js";
export type UpdateOptions = {
checkOnly?: boolean;
@@ -24,16 +38,22 @@ export type UpdateOptions = {
sourcePreference: UpdateSourcePreference;
};
export function normalizeRepo(raw: string): string {
let repo = raw.trim();
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
return repo;
}
export function isValidRepo(repo: string): boolean {
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
}
// 维持模块级兼容导出:测试与外部此前均从 "./update.js" 导入这些成员。
export {
compareSemVer,
downloadFile,
fetchGitHubRelease,
fetchGitHubReleases,
isValidRepo,
isNewerVersion,
matchAssetForPlatform,
normalizeRepo,
DEFAULT_GITHUB_REPO,
GITHUB_REPO_ENV,
type GitHubAsset,
type GitHubRelease,
type UpdateSourcePreference,
} from "./releases.js";
export async function handleUpdateCommand(
parsed: CliParsedArgs,
@@ -512,452 +532,6 @@ export async function handleUpdateCommand(
}
}
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";
}
export type GitHubAsset = {
name: string;
downloadUrl: string;
size: number;
};
export type GitHubRelease = {
version: string;
tagName: string;
name?: string;
publishedAt?: string;
author?: string;
notes: string;
htmlUrl: string;
assets: GitHubAsset[];
};
export async function fetchGitHubReleases(
repo: string,
limit = 20,
sourcePreference: UpdateSourcePreference = "auto"
): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
const urls: string[] = [];
if (sourcePreference === "github") {
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
} else if (sourcePreference === "gitea") {
if (allowGitea) {
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
}
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
} else {
if (allowGitea) {
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
}
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
}
let fallbackList: GitHubRelease[] = [];
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
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,
author: item.author?.login,
notes: item.body ?? "",
htmlUrl: item.html_url ?? "",
assets,
});
}
if (list.length > 0) {
if (list.some((r) => r.assets.length > 0)) {
return list;
}
if (fallbackList.length === 0) {
fallbackList = list;
}
}
} catch {
// try next source
}
}
return fallbackList;
}
export async function fetchGitHubRelease(
repo: string,
targetVersion?: string,
sourcePreference: UpdateSourcePreference = "auto"
): 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": `hose-use/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
const urls: string[] = [];
const giteaTagUrl = tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
const githubTagUrl = tag
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
: `https://api.github.com/repos/${repo}/releases/latest`;
if (sourcePreference === "github") {
urls.push(githubTagUrl);
} else if (sourcePreference === "gitea") {
if (allowGitea) urls.push(giteaTagUrl);
urls.push(githubTagUrl);
} else {
if (allowGitea) urls.push(giteaTagUrl);
urls.push(githubTagUrl);
}
let fallbackRelease: GitHubRelease | undefined;
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
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,
author: json.author?.login,
notes: json.body ?? "",
htmlUrl: json.html_url ?? "",
assets,
};
if (assets.length > 0) {
return candidateRelease;
}
if (!fallbackRelease) {
fallbackRelease = candidateRelease;
}
} catch {
// try next source
}
}
return fallbackRelease;
}
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", "win64", ".exe"],
};
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;
});
// Prefer compressed archives (.tar.gz / .zip) over raw binary for faster downloads (25MB vs 65MB+)
const archive = matched.find(
(asset) =>
asset.name.endsWith(".tar.gz") ||
asset.name.endsWith(".tgz") ||
asset.name.endsWith(".zip")
);
if (archive) return archive;
// Fallback to direct raw binary if available
const directBinary = matched.find(
(asset) =>
!asset.name.endsWith(".tar.gz") &&
!asset.name.endsWith(".tgz") &&
!asset.name.endsWith(".zip") &&
!asset.name.endsWith(".sha256")
);
return directBinary || matched[0];
}
function logProgress(msg: string) {
try {
process.stderr.write(`${msg}\n`);
} catch {
// ignore
}
}
export async function downloadFile(
url: string,
destPath: string,
tagName?: string,
assetName?: string,
repo: string = DEFAULT_GITHUB_REPO,
sourcePreference: UpdateSourcePreference = "auto"
) {
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
const fileName = assetName || url.split("/").pop() || "";
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
// 1. High-speed Gitea direct mirror first (only for default official repo)
if (allowGitea) {
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
}
}
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
if (sourcePreference !== "gitea") {
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
}
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
if (sourcePreference !== "gitea") {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://ghproxy.net/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(`https://mirror.ghproxy.com/${url}`);
}
candidates.push(url);
} else {
candidates.push(url);
}
const uniqueCandidates = Array.from(new Set(candidates));
let lastError: Error | undefined;
for (let i = 0; i < uniqueCandidates.length; i++) {
const candidate = uniqueCandidates[i]!;
try {
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
const reqHeaders: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token && candidate.includes("github.com")) {
reqHeaders["Authorization"] = `Bearer ${token}`;
}
const res = await fetch(candidate, {
headers: reqHeaders,
signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
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(`下载文件异常(大小仅 ${buffer.length} 字节)`);
}
writeFileSync(destPath, buffer);
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
}
const chunks: Uint8Array[] = [];
let receivedBytes = 0;
let lastReport = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
chunks.push(value);
receivedBytes += value.length;
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 ↳ 进度: ${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(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
}
writeFileSync(destPath, completeBuffer);
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
logProgress(` ↳ 节点失败: ${lastError.message}`);
}
}
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
}
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(`解压 tar 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
// Exact match for hose-use or hose-use.exe
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
const platformBinary = files.find((f) => {
const base = f.split("/").pop() || "";
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
});
if (platformBinary) return platformBinary;
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || 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(`解压 zip 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
const platformBinary = files.find((f) => {
const base = f.split("/").pop() || "";
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
});
if (platformBinary) return platformBinary;
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
}
export function compareSemVer(v1: string, v2: string): number {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b) return 1;
if (a < b) return -1;
}
return 0;
}
export function isNewerVersion(latest: string, current: string): boolean {
return compareSemVer(latest, current) > 0;
}
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd,
+465
View File
@@ -0,0 +1,465 @@
import { unlinkSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { VERSION } from "../../../version.js";
export const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
export const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
export type UpdateSourcePreference = "auto" | "github" | "gitea";
export function normalizeRepo(raw: string): string {
let repo = raw.trim();
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
return repo;
}
export function isValidRepo(repo: string): boolean {
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
}
export function detectPlatform(): "darwin" | "linux" | "windows" {
if (process.platform === "darwin") return "darwin";
if (process.platform === "win32") return "windows";
return "linux";
}
export function detectArch(): "arm64" | "x64" {
return process.arch === "arm64" ? "arm64" : "x64";
}
export type GitHubAsset = {
name: string;
downloadUrl: string;
size: number;
};
export type GitHubRelease = {
version: string;
tagName: string;
name?: string;
publishedAt?: string;
author?: string;
notes: string;
htmlUrl: string;
assets: GitHubAsset[];
};
export async function fetchGitHubReleases(
repo: string,
limit = 20,
sourcePreference: UpdateSourcePreference = "auto"
): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
const urls: string[] = [];
if (sourcePreference === "github") {
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
} else if (sourcePreference === "gitea") {
if (allowGitea) {
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
}
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
} else {
if (allowGitea) {
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
}
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
}
let fallbackList: GitHubRelease[] = [];
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
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,
author: item.author?.login,
notes: item.body ?? "",
htmlUrl: item.html_url ?? "",
assets,
});
}
if (list.length > 0) {
if (list.some((r) => r.assets.length > 0)) {
return list;
}
if (fallbackList.length === 0) {
fallbackList = list;
}
}
} catch {
// try next source
}
}
return fallbackList;
}
export async function fetchGitHubRelease(
repo: string,
targetVersion?: string,
sourcePreference: UpdateSourcePreference = "auto"
): 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": `hose-use/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
const urls: string[] = [];
const giteaTagUrl = tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
const githubTagUrl = tag
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
: `https://api.github.com/repos/${repo}/releases/latest`;
if (sourcePreference === "github") {
urls.push(githubTagUrl);
} else if (sourcePreference === "gitea") {
if (allowGitea) urls.push(giteaTagUrl);
urls.push(githubTagUrl);
} else {
if (allowGitea) urls.push(giteaTagUrl);
urls.push(githubTagUrl);
}
let fallbackRelease: GitHubRelease | undefined;
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
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,
author: json.author?.login,
notes: json.body ?? "",
htmlUrl: json.html_url ?? "",
assets,
};
if (assets.length > 0) {
return candidateRelease;
}
if (!fallbackRelease) {
fallbackRelease = candidateRelease;
}
} catch {
// try next source
}
}
return fallbackRelease;
}
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", "win64", ".exe"],
};
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;
});
// Prefer compressed archives (.tar.gz / .zip) over raw binary for faster downloads (25MB vs 65MB+)
const archive = matched.find(
(asset) =>
asset.name.endsWith(".tar.gz") ||
asset.name.endsWith(".tgz") ||
asset.name.endsWith(".zip")
);
if (archive) return archive;
// Fallback to direct raw binary if available
const directBinary = matched.find(
(asset) =>
!asset.name.endsWith(".tar.gz") &&
!asset.name.endsWith(".tgz") &&
!asset.name.endsWith(".zip") &&
!asset.name.endsWith(".sha256")
);
return directBinary || matched[0];
}
function logProgress(msg: string) {
try {
process.stderr.write(`${msg}\n`);
} catch {
// ignore
}
}
export async function downloadFile(
url: string,
destPath: string,
tagName?: string,
assetName?: string,
repo: string = DEFAULT_GITHUB_REPO,
sourcePreference: UpdateSourcePreference = "auto"
) {
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
const fileName = assetName || url.split("/").pop() || "";
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
// 1. High-speed Gitea direct mirror first (only for default official repo)
if (allowGitea) {
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
}
}
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
if (sourcePreference !== "gitea") {
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
}
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
if (sourcePreference !== "gitea") {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://ghproxy.net/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(`https://mirror.ghproxy.com/${url}`);
}
candidates.push(url);
} else {
candidates.push(url);
}
const uniqueCandidates = Array.from(new Set(candidates));
let lastError: Error | undefined;
for (let i = 0; i < uniqueCandidates.length; i++) {
const candidate = uniqueCandidates[i]!;
try {
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
const reqHeaders: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token && candidate.includes("github.com")) {
reqHeaders["Authorization"] = `Bearer ${token}`;
}
const res = await fetch(candidate, {
headers: reqHeaders,
signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
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(`下载文件异常(大小仅 ${buffer.length} 字节)`);
}
writeFileSync(destPath, buffer);
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
}
const chunks: Uint8Array[] = [];
let receivedBytes = 0;
let lastReport = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
chunks.push(value);
receivedBytes += value.length;
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 ↳ 进度: ${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(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
}
writeFileSync(destPath, completeBuffer);
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
logProgress(` ↳ 节点失败: ${lastError.message}`);
}
}
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
}
export 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(`解压 tar 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
// Exact match for hose-use or hose-use.exe
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
const platformBinary = files.find((f) => {
const base = f.split("/").pop() || "";
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
});
if (platformBinary) return platformBinary;
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
}
export 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(`解压 zip 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
const platformBinary = files.find((f) => {
const base = f.split("/").pop() || "";
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
});
if (platformBinary) return platformBinary;
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
}
export function compareSemVer(v1: string, v2: string): number {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b) return 1;
if (a < b) return -1;
}
return 0;
}
export function isNewerVersion(latest: string, current: string): boolean {
return compareSemVer(latest, current) > 0;
}
+1 -1
View File
@@ -8,7 +8,7 @@ import { handleMenuCommand } from "./commands/menu.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleProbeCommand } from "./commands/probe.js";
import { handleMcpCommand } from "./commands/mcp.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleUpdateCommand } from "./commands/update/index.js";
import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill.js";
import { handleContactCommand } from "./commands/contact.js";