forked from bristena-op/opencode-session-handoff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto-update.ts
More file actions
294 lines (248 loc) · 8.04 KB
/
auto-update.ts
File metadata and controls
294 lines (248 loc) · 8.04 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
import type { PluginInput } from "@opencode-ai/plugin";
const PACKAGE_NAME = "opencode-session-handoff";
const NPM_REGISTRY_URL = `https://registry.npmjs.org/-/package/${PACKAGE_NAME}/dist-tags`;
const NPM_FETCH_TIMEOUT = 5000;
const BUN_INSTALL_TIMEOUT_MS = 60000;
type PluginClient = PluginInput["client"];
interface UpdateContext {
directory: string;
client: PluginClient;
}
function getConfigDir(): string {
return path.join(os.homedir(), ".config", "opencode");
}
function getConfigPath(): string {
const configDir = getConfigDir();
const jsoncPath = path.join(configDir, "opencode.jsonc");
if (fs.existsSync(jsoncPath)) return jsoncPath;
return path.join(configDir, "opencode.json");
}
function getCurrentVersion(): string | null {
try {
const currentDir = path.dirname(new URL(import.meta.url).pathname);
let dir = currentDir;
for (let i = 0; i < 5; i++) {
const pkgPath = path.join(dir, "package.json");
if (fs.existsSync(pkgPath)) {
const content = fs.readFileSync(pkgPath, "utf-8");
const pkg = JSON.parse(content);
if (pkg.name === PACKAGE_NAME && pkg.version) {
return pkg.version;
}
}
dir = path.dirname(dir);
}
} catch {
return null;
}
return null;
}
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 { latest?: string };
return data.latest ?? null;
} catch {
return null;
} finally {
clearTimeout(timeoutId);
}
}
interface PluginEntryInfo {
entry: string;
isPinned: boolean;
pinnedVersion: string | null;
configPath: string;
}
function findPluginEntry(): PluginEntryInfo | null {
const configPath = getConfigPath();
if (!fs.existsSync(configPath)) return null;
try {
const content = fs.readFileSync(configPath, "utf-8");
const pinnedPattern = new RegExp(`["']${PACKAGE_NAME}@([^"']+)["']`);
const unpinnedPattern = new RegExp(`["']${PACKAGE_NAME}["']`);
const pinnedMatch = content.match(pinnedPattern);
if (pinnedMatch) {
return {
entry: pinnedMatch[0].slice(1, -1),
isPinned: true,
pinnedVersion: pinnedMatch[1],
configPath,
};
}
const unpinnedMatch = content.match(unpinnedPattern);
if (unpinnedMatch) {
return {
entry: unpinnedMatch[0].slice(1, -1),
isPinned: false,
pinnedVersion: null,
configPath,
};
}
} catch {
return null;
}
return null;
}
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) 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)) return false;
const updatedPluginArray = pluginArrayContent.replace(regex, `"${newEntry}"`);
const updatedContent = before + updatedPluginArray + after;
if (updatedContent === content) return false;
fs.writeFileSync(configPath, updatedContent, "utf-8");
return true;
} catch {
return false;
}
}
function removePackageDir(configDir: string): boolean {
const pkgDir = path.join(configDir, "node_modules", PACKAGE_NAME);
if (fs.existsSync(pkgDir)) {
fs.rmSync(pkgDir, { recursive: true, force: true });
return true;
}
return false;
}
function removeFromPackageJson(configDir: string): boolean {
const pkgJsonPath = path.join(configDir, "package.json");
if (!fs.existsSync(pkgJsonPath)) return false;
const content = fs.readFileSync(pkgJsonPath, "utf-8");
const pkgJson = JSON.parse(content);
if (pkgJson.dependencies?.[PACKAGE_NAME]) {
delete pkgJson.dependencies[PACKAGE_NAME];
fs.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2));
return true;
}
return false;
}
function removeFromBunLock(configDir: string): boolean {
const lockPath = path.join(configDir, "bun.lock");
if (!fs.existsSync(lockPath)) return false;
const content = fs.readFileSync(lockPath, "utf-8");
const cleanedContent = content.replace(/,(\s*[}\]])/g, "$1");
const lock = JSON.parse(cleanedContent);
let modified = false;
if (lock.workspaces?.[""]?.dependencies?.[PACKAGE_NAME]) {
delete lock.workspaces[""].dependencies[PACKAGE_NAME];
modified = true;
}
if (lock.packages?.[PACKAGE_NAME]) {
delete lock.packages[PACKAGE_NAME];
modified = true;
}
if (modified) {
fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2));
}
return modified;
}
function invalidatePackage(): boolean {
const configDir = getConfigDir();
try {
removePackageDir(configDir);
removeFromPackageJson(configDir);
removeFromBunLock(configDir);
return true;
} catch {
return false;
}
}
async function runBunInstall(): Promise<boolean> {
try {
const proc = Bun.spawn(["bun", "install"], {
cwd: getConfigDir(),
stdout: "pipe",
stderr: "pipe",
});
const timeoutPromise = new Promise<"timeout">((resolve) =>
setTimeout(() => resolve("timeout"), BUN_INSTALL_TIMEOUT_MS),
);
const exitPromise = proc.exited.then(() => "completed" as const);
const result = await Promise.race([exitPromise, timeoutPromise]);
if (result === "timeout") {
try {
proc.kill();
} catch {
return false;
}
return false;
}
return proc.exitCode === 0;
} catch {
return false;
}
}
async function showToast(client: PluginClient, message: string): Promise<void> {
try {
await client.tui.showToast({ body: { message, variant: "info" } });
} catch {
return;
}
}
async function runUpdateCheck(ctx: UpdateContext): Promise<void> {
const currentVersion = getCurrentVersion();
if (!currentVersion) return;
const latestVersion = await getLatestVersion();
if (!latestVersion) return;
if (currentVersion === latestVersion) return;
const pluginInfo = findPluginEntry();
if (!pluginInfo) return;
if (pluginInfo.isPinned) {
const updated = updatePinnedVersion(pluginInfo.configPath, pluginInfo.entry, latestVersion);
if (!updated) {
await showToast(ctx.client, `session-handoff v${latestVersion} available. Update manually.`);
return;
}
}
invalidatePackage();
const success = await runBunInstall();
if (success) {
await showToast(
ctx.client,
`session-handoff updated: v${currentVersion} → v${latestVersion}. Restart to apply.`,
);
} else {
await showToast(ctx.client, `session-handoff v${latestVersion} available. Restart to apply.`);
}
}
export function createAutoUpdateHook(ctx: UpdateContext) {
let hasChecked = false;
return {
event: async ({ event }: { event: { type: string; properties?: unknown } }): Promise<void> => {
if (event.type !== "session.created") return;
if (hasChecked) return;
const props = event.properties as { info?: { parentID?: string } } | undefined;
if (props?.info?.parentID) return;
hasChecked = true;
setTimeout(() => {
runUpdateCheck(ctx).catch(() => {});
}, 100);
},
};
}