示例工程 56-auto-update
56-auto-update/demo-01-feed-parse/feed.ts
type Candidate = { version: string; url: string; notes: string };
function compareVersions(a: string, b: string): number {
const left = a.split(".").map((part) => Number(part) || 0);
const right = b.split(".").map((part) => Number(part) || 0);
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
const l = left[index] ?? 0;
const r = right[index] ?? 0;
if (l !== r) return l - r;
}
return 0;
}
function pickLatest(candidates: Candidate[]): Candidate {
const sorted = [...candidates].sort((a, b) =>
compareVersions(a.version, b.version),
);
const latest = sorted.at(-1);
if (!latest) throw new Error("EMPTY_FEED");
return latest;
}
const macFeed = JSON.stringify({
releases: [
{
version: "1.9.0",
updateTo: { url: "https://updates.example.com/1.9.0.zip" },
releaseNotes: "旧版本",
},
{
version: "1.10.0",
updateTo: { url: "https://updates.example.com/1.10.0.zip" },
releaseNotes: "新版本",
},
],
});
const winFeed = [
"aaaa App-2.0.0-full.nupkg 100",
"bbbb App-2.0.0-delta.nupkg 20",
"cccc App-1.9.0-full.nupkg 90",
].join("\n");
const macLatest = pickLatest(
(
JSON.parse(macFeed) as { releases: Array<Record<string, unknown>> }
).releases.map((row) => {
const updateTo = row.updateTo as { url?: string } | undefined;
return {
version: String(row.version),
url: updateTo?.url ?? "",
notes: String(row.releaseNotes ?? ""),
};
}),
);
const winVersions = winFeed
.split(/\r?\n/)
.map((line) => /App-(\d+\.\d+\.\d+)-(?:full|delta)\.nupkg/.exec(line)?.[1])
.filter((value): value is string => Boolean(value));
const winLatest = pickLatest(
winVersions.map((version) => ({
version,
url: `https://updates.example.com/App-${version}-full.nupkg`,
notes: "win",
})),
);
const decide = (current: string, latest: string) =>
compareVersions(latest, current) > 0 ? "update" : "none";
const ok =
macLatest.version === "1.10.0" &&
winLatest.version === "2.0.0" &&
decide("1.0.0", macLatest.version) === "update" &&
decide("2.0.0", winLatest.version) === "none" &&
compareVersions("1.10.0", "1.9.0") > 0;
console.log(
JSON.stringify({
evt: "smoke",
ok,
macLatest,
winLatest,
decisions: {
current1: decide("1.0.0", macLatest.version),
current2: decide("2.0.0", winLatest.version),
},
}),
);