forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchecker.ts
More file actions
261 lines (225 loc) · 8.23 KB
/
Copy pathchecker.ts
File metadata and controls
261 lines (225 loc) · 8.23 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import type { NpmDistTags, OpencodeConfig, PackageJson, UpdateCheckResult } from "./types";
import {
PACKAGE_NAME,
NPM_REGISTRY_URL,
NPM_FETCH_TIMEOUT,
INSTALLED_PACKAGE_JSON,
USER_OPENCODE_CONFIG,
USER_OPENCODE_CONFIG_JSONC,
} from "./constants";
import { logAutoUpdate } from "./logging";
export function isLocalDevMode(directory: string): boolean {
return getLocalDevPath(directory) !== null;
}
function stripJsonComments(json: string): string {
return json
.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m: string, g: string | undefined) => (g ? "" : m))
.replace(/,(\s*[}\]])/g, "$1");
}
function getConfigPaths(directory: string): string[] {
return [
path.join(directory, ".opencode", "opencode.json"),
path.join(directory, ".opencode", "opencode.jsonc"),
path.join(directory, ".opencode.json"),
USER_OPENCODE_CONFIG,
USER_OPENCODE_CONFIG_JSONC,
];
}
export function getLocalDevPath(directory: string): string | null {
for (const configPath of getConfigPaths(directory)) {
try {
if (!fs.existsSync(configPath)) continue;
const content = fs.readFileSync(configPath, "utf-8");
const config = JSON.parse(stripJsonComments(content)) as OpencodeConfig;
const plugins = config.plugin ?? [];
for (const entry of plugins) {
if (entry.startsWith("file://") && entry.includes(PACKAGE_NAME)) {
try {
return fileURLToPath(entry);
} catch {
return entry.replace("file://", "");
}
}
}
} catch {
continue;
}
}
return null;
}
function findPackageJsonUp(startPath: string): string | null {
try {
const stat = fs.statSync(startPath);
let dir = stat.isDirectory() ? startPath : path.dirname(startPath);
for (let i = 0; i < 10; i++) {
const pkgPath = path.join(dir, "package.json");
if (fs.existsSync(pkgPath)) {
try {
const content = fs.readFileSync(pkgPath, "utf-8");
const pkg = JSON.parse(content) as PackageJson;
if (pkg.name === PACKAGE_NAME) return pkgPath;
} catch {
continue;
}
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
return null;
}
return null;
}
export function getLocalDevVersion(directory: string): string | null {
const localPath = getLocalDevPath(directory);
if (!localPath) return null;
try {
const pkgPath = findPackageJsonUp(localPath);
if (!pkgPath) return null;
const content = fs.readFileSync(pkgPath, "utf-8");
const pkg = JSON.parse(content) as PackageJson;
return pkg.version ?? null;
} catch {
return null;
}
}
export interface PluginEntryInfo {
entry: string;
isPinned: boolean;
pinnedVersion: string | null;
configPath: string;
}
export function findPluginEntry(directory: string): PluginEntryInfo | null {
for (const configPath of getConfigPaths(directory)) {
try {
if (!fs.existsSync(configPath)) continue;
const content = fs.readFileSync(configPath, "utf-8");
const config = JSON.parse(stripJsonComments(content)) as OpencodeConfig;
const plugins = config.plugin ?? [];
for (const entry of plugins) {
if (entry === PACKAGE_NAME) {
return { entry, isPinned: false, pinnedVersion: null, configPath };
}
if (entry.startsWith(`${PACKAGE_NAME}@`)) {
const pinnedVersion = entry.slice(PACKAGE_NAME.length + 1);
const isPinned = pinnedVersion !== "latest";
return { entry, isPinned, pinnedVersion: isPinned ? pinnedVersion : null, configPath };
}
if (entry.startsWith("file://") && entry.includes(PACKAGE_NAME)) {
return { entry, isPinned: false, pinnedVersion: null, configPath };
}
}
} catch {
continue;
}
}
return null;
}
export function getCachedVersion(): string | null {
try {
if (fs.existsSync(INSTALLED_PACKAGE_JSON)) {
const content = fs.readFileSync(INSTALLED_PACKAGE_JSON, "utf-8");
const pkg = JSON.parse(content) as PackageJson;
if (pkg.version) return pkg.version;
}
} catch {
return null;
}
try {
const currentDir = path.dirname(fileURLToPath(import.meta.url));
const pkgPath = findPackageJsonUp(currentDir);
if (pkgPath) {
const content = fs.readFileSync(pkgPath, "utf-8");
const pkg = JSON.parse(content) as PackageJson;
if (pkg.version) return pkg.version;
}
} catch (err) {
logAutoUpdate(`Failed to resolve version from current directory: ${err}`);
}
return null;
}
export function updatePinnedVersion(configPath: string, oldEntry: string, newVersion: string): boolean {
try {
const content = fs.readFileSync(configPath, "utf-8");
const newEntry = `${PACKAGE_NAME}@${newVersion}`;
const pluginMatch = content.match(/"plugin"\s*:\s*\[/);
if (!pluginMatch || pluginMatch.index === undefined) {
logAutoUpdate(`No "plugin" array found in ${configPath}`);
return false;
}
const startIdx = pluginMatch.index + pluginMatch[0].length;
let bracketCount = 1;
let endIdx = startIdx;
for (let i = startIdx; i < content.length && bracketCount > 0; i++) {
if (content[i] === "[") bracketCount++;
else if (content[i] === "]") bracketCount--;
endIdx = i;
}
const before = content.slice(0, startIdx);
const pluginArrayContent = content.slice(startIdx, endIdx);
const after = content.slice(endIdx);
const escapedOldEntry = oldEntry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`["']${escapedOldEntry}["']`);
if (!regex.test(pluginArrayContent)) {
logAutoUpdate(`Entry "${oldEntry}" not found in plugin array of ${configPath}`);
return false;
}
const updatedPluginArray = pluginArrayContent.replace(regex, `"${newEntry}"`);
const updatedContent = before + updatedPluginArray + after;
if (updatedContent === content) {
logAutoUpdate(`No changes made to ${configPath}`);
return false;
}
fs.writeFileSync(configPath, updatedContent, "utf-8");
logAutoUpdate(`Updated ${configPath}: ${oldEntry} → ${newEntry}`);
return true;
} catch (err) {
console.error(`[auto-update-checker] Failed to update config file ${configPath}:`, err);
return false;
}
}
export async function getLatestVersion(): Promise<string | null> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), NPM_FETCH_TIMEOUT);
try {
const response = await fetch(NPM_REGISTRY_URL, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
if (!response.ok) return null;
const data = (await response.json()) as NpmDistTags;
return data.latest ?? null;
} catch {
return null;
} finally {
clearTimeout(timeoutId);
}
}
export async function checkForUpdate(directory: string): Promise<UpdateCheckResult> {
if (isLocalDevMode(directory)) {
logAutoUpdate("Local dev mode detected, skipping update check");
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: true, isPinned: false };
}
const pluginInfo = findPluginEntry(directory);
if (!pluginInfo) {
logAutoUpdate("Plugin not found in config");
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: false, isPinned: false };
}
const currentVersion = getCachedVersion() ?? pluginInfo.pinnedVersion;
if (!currentVersion) {
logAutoUpdate("No version found (cached or pinned)");
return { needsUpdate: false, currentVersion: null, latestVersion: null, isLocalDev: false, isPinned: pluginInfo.isPinned };
}
const latestVersion = await getLatestVersion();
if (!latestVersion) {
logAutoUpdate("Failed to fetch latest version");
return { needsUpdate: false, currentVersion, latestVersion: null, isLocalDev: false, isPinned: pluginInfo.isPinned };
}
const needsUpdate = currentVersion !== latestVersion;
logAutoUpdate(`Current: ${currentVersion}, Latest: ${latestVersion}, NeedsUpdate: ${needsUpdate}`);
return { needsUpdate, currentVersion, latestVersion, isLocalDev: false, isPinned: pluginInfo.isPinned };
}