forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-copilot-chat-version.ts
More file actions
82 lines (68 loc) · 2.35 KB
/
get-copilot-chat-version.ts
File metadata and controls
82 lines (68 loc) · 2.35 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
import consola from "consola"
import { VERSION_CACHE_TTL_MS, type VersionCache } from "./version-cache"
export const FALLBACK = "0.26.7"
let cache: VersionCache | undefined
async function fetchFromMarketplace(): Promise<string> {
const controller = new AbortController()
const timeout = setTimeout(() => {
controller.abort()
}, 5000)
try {
const response = await fetch(
"https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json;api-version=3.0-preview.1",
},
body: JSON.stringify({
filters: [
{
criteria: [{ filterType: 7, value: "GitHub.copilot-chat" }],
},
],
flags: 529,
}),
signal: controller.signal,
},
)
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
const data = (await response.json()) as any
const parsed: unknown =
data?.results?.[0]?.extensions?.[0]?.versions?.[0]?.version
/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
if (typeof parsed !== "string" || !parsed) {
throw new Error("Unexpected response shape")
}
return parsed
} finally {
clearTimeout(timeout)
}
}
export async function getCopilotChatVersion(): Promise<string> {
if (cache && Date.now() - cache.fetchedAt < VERSION_CACHE_TTL_MS) {
return cache.version
}
let fetched: string | null = null
try {
fetched = await fetchFromMarketplace()
} catch {
consola.warn(
"Failed to fetch Copilot Chat version from Marketplace, 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
}