Repository navigation
Expand file tree
/
Copy pathclient-version.ts
More file actions
170 lines (142 loc) · 4.73 KB
/
Copy pathclient-version.ts
File metadata and controls
170 lines (142 loc) · 4.73 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import fs from "node:fs"
import path from "node:path"
import {
FALLBACK_CLIENT_VERSION,
MODEL_CACHE_TTL_MS,
VERSION_CACHE_FILE,
} from "../shared.js"
import { opencodeGlobalCacheDir } from "../context/paths.js"
import { withAbortDeadline } from "../deadline.js"
import { processShared } from "../process-shared.js"
const INSTALL_URL = "https://cursor.com/install"
const REMOTE_TIMEOUT_MS = 5_000
const BUILD_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9A-Za-z][0-9A-Za-z.-]*$/
const CLIENT_VERSION_RE = /^cli-[0-9A-Za-z][0-9A-Za-z._-]*$/
type VersionCache = { version: string; fetchedAt: number }
// Once per process, not per copy of this package the host loads.
const cache = processShared("client-version.v1", (): { resolution?: Promise<string> } => ({}))
export function resetClientVersionCache(): void {
cache.resolution = undefined
}
export function resolveClientVersion(): Promise<string> {
cache.resolution ??= resolve()
return cache.resolution
}
async function resolve(): Promise<string> {
const env = process.env.CURSOR_CLIENT_VERSION?.trim()
if (isClientVersion(env)) return env
const local = discoverLocalVersion()
if (local) return local
return (await resolveRemoteVersion()) ?? FALLBACK_CLIENT_VERSION
}
function isClientVersion(value: unknown): value is string {
return typeof value === "string" && CLIENT_VERSION_RE.test(value)
}
export function cursorAgentVersionsDir(): string | undefined {
const home = process.env.HOME || process.env.USERPROFILE
if (!home) return undefined
switch (process.platform) {
case "linux":
case "darwin":
return path.join(home, ".local", "share", "cursor-agent", "versions")
default:
return undefined
}
}
export function discoverLocalVersion(
dir = cursorAgentVersionsDir(),
): string | undefined {
if (!dir) return undefined
let entries: fs.Dirent[]
try {
entries = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return undefined
}
let newest: { name: string; mtimeMs: number } | undefined
for (const entry of entries) {
if (!entry.isDirectory() || !BUILD_RE.test(entry.name)) continue
try {
const mtimeMs = fs.statSync(path.join(dir, entry.name)).mtimeMs
if (
!newest ||
mtimeMs > newest.mtimeMs ||
(mtimeMs === newest.mtimeMs && entry.name > newest.name)
) {
newest = { name: entry.name, mtimeMs }
}
} catch {
// Directory disappeared during discovery.
}
}
return newest ? `cli-${newest.name}` : undefined
}
export function extractVersionFromInstaller(script: string): string | undefined {
const match = script.match(/downloads\.cursor\.com\/lab\/([^/"'\s]+)\//)
return match && BUILD_RE.test(match[1]) ? match[1] : undefined
}
function versionCachePath(): string {
return path.join(opencodeGlobalCacheDir(), VERSION_CACHE_FILE)
}
function readVersionCache(): VersionCache | undefined {
const file = versionCachePath()
try {
const value = JSON.parse(fs.readFileSync(file, "utf8")) as Record<string, unknown>
if (
!isClientVersion(value.version) ||
typeof value.fetchedAt !== "number" ||
!Number.isFinite(value.fetchedAt)
) {
return undefined
}
return { version: value.version, fetchedAt: value.fetchedAt }
} catch {
return undefined
}
}
function writeVersionCache(cache: VersionCache): void {
const file = versionCachePath()
try {
fs.mkdirSync(path.dirname(file), { recursive: true })
fs.writeFileSync(file, JSON.stringify(cache, null, 2))
} catch {
// Cache writes are optional.
}
}
function isCacheFresh(cache: VersionCache, now = Date.now()): boolean {
const age = now - cache.fetchedAt
return age >= 0 && age < MODEL_CACHE_TTL_MS
}
async function fetchInstallerVersion(): Promise<string | undefined> {
return withAbortDeadline(
REMOTE_TIMEOUT_MS,
() => new Error("Cursor installer version request timed out"),
async (signal) => {
const response = await fetch(INSTALL_URL, { signal })
if (!response.ok) return undefined
const build = extractVersionFromInstaller(await response.text())
return build ? `cli-${build}` : undefined
},
)
}
async function refreshVersionCache(): Promise<void> {
const version = await fetchInstallerVersion()
if (version) writeVersionCache({ version, fetchedAt: Date.now() })
}
async function resolveRemoteVersion(): Promise<string | undefined> {
const cached = readVersionCache()
if (cached && isCacheFresh(cached)) {
void refreshVersionCache().catch(() => {})
return cached.version
}
try {
const version = await fetchInstallerVersion()
if (version) {
writeVersionCache({ version, fetchedAt: Date.now() })
return version
}
} catch {
// Use stale cache or the fallback below.
}
return cached?.version
}