forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-vscode-version.ts
More file actions
92 lines (73 loc) · 2.27 KB
/
get-vscode-version.ts
File metadata and controls
92 lines (73 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import consola from "consola"
import { VERSION_CACHE_TTL_MS, type VersionCache } from "./version-cache"
export const FALLBACK = "1.104.3"
let cache: VersionCache | undefined
async function fetchFromOfficialApi(): Promise<string> {
const controller = new AbortController()
const timeout = setTimeout(() => {
controller.abort()
}, 5000)
try {
const response = await fetch(
"https://update.code.visualstudio.com/api/releases/stable",
{ signal: controller.signal },
)
const versions = (await response.json()) as Array<string>
if (Array.isArray(versions) && versions.length > 0 && versions[0]) {
return versions[0]
}
throw new Error("Unexpected response shape")
} finally {
clearTimeout(timeout)
}
}
async function fetchFromAur(): Promise<string> {
const controller = new AbortController()
const timeout = setTimeout(() => {
controller.abort()
}, 5000)
try {
const response = await fetch(
"https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=visual-studio-code-bin",
{ signal: controller.signal },
)
const pkgbuild = await response.text()
const match = pkgbuild.match(/pkgver=(\d+\.\d+\.\d+)/)
if (match?.[1]) {
return match[1]
}
throw new Error("Version not found in PKGBUILD")
} finally {
clearTimeout(timeout)
}
}
export async function getVSCodeVersion(): Promise<string> {
if (cache && Date.now() - cache.fetchedAt < VERSION_CACHE_TTL_MS) {
return cache.version
}
let fetched: string | null = null
try {
fetched = await fetchFromOfficialApi()
} catch {
try {
fetched = await fetchFromAur()
} catch {
consola.warn(
"Failed to fetch VS Code version from all sources, using fallback",
)
}
}
const version =
fetched !== null && /^\d+\.\d+\.\d+$/.test(fetched) ? fetched : FALLBACK
if (fetched !== null && version !== FALLBACK) {
// eslint-disable-next-line require-atomic-updates
cache = { version, fetchedAt: Date.now() }
} else if (fetched !== null) {
// Format validation rejected the fetched value
const safeVersion = fetched.slice(0, 40).replaceAll(/[^\x20-\x7E]/g, "?")
consola.warn(
`Invalid version format received: ${safeVersion}, using fallback`,
)
}
return version
}