@codelia/cli 0.1.86 → 0.1.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-VNP4GLGX.js +66 -0
- package/dist/chunk-BFVVMMRM.js +202 -0
- package/dist/chunk-PG452V5E.js +45 -0
- package/dist/chunk-QYWLK4HY.js +156 -0
- package/dist/chunk-S7OVJIGV.js +1052 -0
- package/dist/index.cjs +3243 -1564
- package/dist/index.js +48 -1575
- package/dist/launch-OTCP4VZR.js +9 -0
- package/dist/launcher-TKAK6K4J.js +19 -0
- package/dist/mcp-GB4CGP6K.js +699 -0
- package/dist/prompt-mode-BYUIUSIO.js +705 -0
- package/dist/session-2EB4JKFW.js +52 -0
- package/dist/update-SEBHPMUD.js +124 -0
- package/package.json +10 -10
|
@@ -0,0 +1,1052 @@
|
|
|
1
|
+
// src/update/semver.ts
|
|
2
|
+
import { isValidUpdateChannel } from "@codelia/config-loader";
|
|
3
|
+
var MAX_VERSION_LENGTH = 128;
|
|
4
|
+
var SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
|
|
5
|
+
var NUMERIC_ID_RE = /^(0|[1-9]\d*)$/;
|
|
6
|
+
var parseVersion = (value) => {
|
|
7
|
+
if (typeof value !== "string") return null;
|
|
8
|
+
const trimmed = value.trim();
|
|
9
|
+
if (trimmed.length === 0 || trimmed.length > MAX_VERSION_LENGTH) return null;
|
|
10
|
+
const match = SEMVER_RE.exec(trimmed);
|
|
11
|
+
if (!match) return null;
|
|
12
|
+
const major = Number.parseInt(match[1], 10);
|
|
13
|
+
const minor = Number.parseInt(match[2], 10);
|
|
14
|
+
const patch = Number.parseInt(match[3], 10);
|
|
15
|
+
if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
const prerelease = [];
|
|
19
|
+
if (match[4]) {
|
|
20
|
+
for (const part of match[4].split(".")) {
|
|
21
|
+
if (NUMERIC_ID_RE.test(part)) {
|
|
22
|
+
const num = Number.parseInt(part, 10);
|
|
23
|
+
if (!Number.isSafeInteger(num)) return null;
|
|
24
|
+
prerelease.push(num);
|
|
25
|
+
} else if (/^0\d+$/.test(part)) {
|
|
26
|
+
return null;
|
|
27
|
+
} else {
|
|
28
|
+
prerelease.push(part);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { major, minor, patch, prerelease, raw: trimmed };
|
|
33
|
+
};
|
|
34
|
+
var isValidVersion = (value) => parseVersion(value) !== null;
|
|
35
|
+
var compareVersions = (a, b) => {
|
|
36
|
+
const left = parseVersion(a);
|
|
37
|
+
const right = parseVersion(b);
|
|
38
|
+
if (!left || !right) return null;
|
|
39
|
+
for (const [l, r] of [
|
|
40
|
+
[left.major, right.major],
|
|
41
|
+
[left.minor, right.minor],
|
|
42
|
+
[left.patch, right.patch]
|
|
43
|
+
]) {
|
|
44
|
+
if (l !== r) return l > r ? 1 : -1;
|
|
45
|
+
}
|
|
46
|
+
const lp = left.prerelease;
|
|
47
|
+
const rp = right.prerelease;
|
|
48
|
+
if (lp.length === 0 && rp.length === 0) return 0;
|
|
49
|
+
if (lp.length === 0) return 1;
|
|
50
|
+
if (rp.length === 0) return -1;
|
|
51
|
+
const len = Math.min(lp.length, rp.length);
|
|
52
|
+
for (let i = 0; i < len; i += 1) {
|
|
53
|
+
const li = lp[i];
|
|
54
|
+
const ri = rp[i];
|
|
55
|
+
if (li === ri) continue;
|
|
56
|
+
const lNum = typeof li === "number";
|
|
57
|
+
const rNum = typeof ri === "number";
|
|
58
|
+
if (lNum && rNum) return li > ri ? 1 : -1;
|
|
59
|
+
if (lNum !== rNum) return lNum ? -1 : 1;
|
|
60
|
+
return String(li) > String(ri) ? 1 : -1;
|
|
61
|
+
}
|
|
62
|
+
if (lp.length === rp.length) return 0;
|
|
63
|
+
return lp.length > rp.length ? 1 : -1;
|
|
64
|
+
};
|
|
65
|
+
var isNewerVersion = (candidate, current) => compareVersions(candidate, current) === 1;
|
|
66
|
+
var inferChannelFromVersion = (version) => {
|
|
67
|
+
const parsed = parseVersion(version);
|
|
68
|
+
const first = parsed?.prerelease[0];
|
|
69
|
+
if (typeof first === "string" && isValidUpdateChannel(first)) {
|
|
70
|
+
return first;
|
|
71
|
+
}
|
|
72
|
+
return "latest";
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// src/update/launcher-entry.ts
|
|
76
|
+
import { spawn } from "child_process";
|
|
77
|
+
import fsSync from "fs";
|
|
78
|
+
import path from "path";
|
|
79
|
+
var UPDATE_REEXEC_ENV = "CODELIA_UPDATE_REEXEC";
|
|
80
|
+
var DEFAULT_LAUNCHER_ENTRY = path.join("dist", "index.cjs");
|
|
81
|
+
var readInstalledVersion = (packageRoot) => {
|
|
82
|
+
try {
|
|
83
|
+
const manifest = JSON.parse(
|
|
84
|
+
fsSync.readFileSync(path.join(packageRoot, "package.json"), "utf8")
|
|
85
|
+
);
|
|
86
|
+
return manifest.name === "@codelia/cli" && isValidVersion(manifest.version) ? manifest.version : null;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
var reexecLauncher = (options) => new Promise((resolve) => {
|
|
92
|
+
const child = spawn(process.execPath, [options.entry, ...options.args], {
|
|
93
|
+
stdio: "inherit",
|
|
94
|
+
env: options.env
|
|
95
|
+
});
|
|
96
|
+
child.on("error", () => resolve(null));
|
|
97
|
+
child.on("exit", (code, signal) => resolve(signal ? 1 : code ?? 1));
|
|
98
|
+
});
|
|
99
|
+
var launcherEntry = (packageRoot) => {
|
|
100
|
+
const fallback = path.join(packageRoot, DEFAULT_LAUNCHER_ENTRY);
|
|
101
|
+
let bin;
|
|
102
|
+
try {
|
|
103
|
+
bin = JSON.parse(
|
|
104
|
+
fsSync.readFileSync(path.join(packageRoot, "package.json"), "utf8")
|
|
105
|
+
).bin;
|
|
106
|
+
} catch {
|
|
107
|
+
return fallback;
|
|
108
|
+
}
|
|
109
|
+
const relative = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null ? bin.codelia : void 0;
|
|
110
|
+
if (typeof relative !== "string" || relative.length === 0) return fallback;
|
|
111
|
+
const entry = path.resolve(packageRoot, relative);
|
|
112
|
+
const inside = path.relative(packageRoot, entry);
|
|
113
|
+
if (inside.startsWith("..") || path.isAbsolute(inside)) return fallback;
|
|
114
|
+
return fsSync.existsSync(entry) ? entry : fallback;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// src/update/registry.ts
|
|
118
|
+
import { createHash } from "crypto";
|
|
119
|
+
var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org";
|
|
120
|
+
var CLI_PACKAGE_NAME = "@codelia/cli";
|
|
121
|
+
var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
|
|
122
|
+
var MAX_REGISTRY_RESPONSE_BYTES = 256 * 1024;
|
|
123
|
+
var normalizeRegistryUrl = (raw) => {
|
|
124
|
+
const candidate = (raw ?? "").trim() || DEFAULT_REGISTRY_URL;
|
|
125
|
+
let parsed;
|
|
126
|
+
try {
|
|
127
|
+
parsed = new URL(candidate);
|
|
128
|
+
} catch {
|
|
129
|
+
throw new Error("Invalid npm registry URL");
|
|
130
|
+
}
|
|
131
|
+
if (parsed.protocol !== "https:") {
|
|
132
|
+
throw new Error("Registry URL must use https");
|
|
133
|
+
}
|
|
134
|
+
if (parsed.username || parsed.password) {
|
|
135
|
+
throw new Error("Registry URL must not include embedded credentials");
|
|
136
|
+
}
|
|
137
|
+
const pathname = parsed.pathname.replace(/\/+$/, "");
|
|
138
|
+
return `${parsed.origin}${pathname}`;
|
|
139
|
+
};
|
|
140
|
+
var resolveRegistryUrl = (env = process.env) => normalizeRegistryUrl(env.CODELIA_UPDATE_REGISTRY ?? env.npm_config_registry);
|
|
141
|
+
var computeRegistryId = (registryUrl) => createHash("sha256").update(registryUrl).digest("hex");
|
|
142
|
+
var readBoundedText = async (response, maxBytes) => {
|
|
143
|
+
const declaredLength = response.headers.get("content-length");
|
|
144
|
+
if (declaredLength) {
|
|
145
|
+
const parsedLength = Number.parseInt(declaredLength, 10);
|
|
146
|
+
if (Number.isFinite(parsedLength) && parsedLength > maxBytes) {
|
|
147
|
+
throw new Error("Registry response exceeded maximum allowed size");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (!response.body) {
|
|
151
|
+
const text = await response.text();
|
|
152
|
+
if (Buffer.byteLength(text, "utf8") > maxBytes) {
|
|
153
|
+
throw new Error("Registry response exceeded maximum allowed size");
|
|
154
|
+
}
|
|
155
|
+
return text;
|
|
156
|
+
}
|
|
157
|
+
const reader = response.body.getReader();
|
|
158
|
+
const chunks = [];
|
|
159
|
+
let total = 0;
|
|
160
|
+
try {
|
|
161
|
+
for (; ; ) {
|
|
162
|
+
const { done, value } = await reader.read();
|
|
163
|
+
if (done) break;
|
|
164
|
+
if (!value) continue;
|
|
165
|
+
total += value.byteLength;
|
|
166
|
+
if (total > maxBytes) {
|
|
167
|
+
await reader.cancel();
|
|
168
|
+
throw new Error("Registry response exceeded maximum allowed size");
|
|
169
|
+
}
|
|
170
|
+
chunks.push(value);
|
|
171
|
+
}
|
|
172
|
+
} finally {
|
|
173
|
+
reader.releaseLock();
|
|
174
|
+
}
|
|
175
|
+
return Buffer.concat(chunks, total).toString("utf8");
|
|
176
|
+
};
|
|
177
|
+
var fetchLatestVersion = async (options) => {
|
|
178
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
179
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
180
|
+
const controller = new AbortController();
|
|
181
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
182
|
+
const onAbort = () => controller.abort();
|
|
183
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
184
|
+
try {
|
|
185
|
+
const endpoint = `${options.registryUrl}/-/package/${encodeURIComponent(CLI_PACKAGE_NAME)}/dist-tags`;
|
|
186
|
+
const response = await fetchImpl(endpoint, {
|
|
187
|
+
method: "GET",
|
|
188
|
+
headers: { accept: "application/json" },
|
|
189
|
+
redirect: "error",
|
|
190
|
+
signal: controller.signal
|
|
191
|
+
});
|
|
192
|
+
if (!response.ok) {
|
|
193
|
+
throw new Error(`Registry returned HTTP ${response.status}`);
|
|
194
|
+
}
|
|
195
|
+
const raw = await readBoundedText(response, MAX_REGISTRY_RESPONSE_BYTES);
|
|
196
|
+
let parsed;
|
|
197
|
+
try {
|
|
198
|
+
parsed = JSON.parse(raw);
|
|
199
|
+
} catch {
|
|
200
|
+
throw new Error("Registry returned invalid JSON");
|
|
201
|
+
}
|
|
202
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
203
|
+
throw new Error("Registry dist-tags response was not an object");
|
|
204
|
+
}
|
|
205
|
+
const version = parsed[options.channel];
|
|
206
|
+
if (!isValidVersion(version)) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
`Registry dist-tag "${options.channel}" has no valid semver version`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
return version;
|
|
212
|
+
} finally {
|
|
213
|
+
clearTimeout(timer);
|
|
214
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
// src/update/state.ts
|
|
219
|
+
import { randomBytes } from "crypto";
|
|
220
|
+
import { promises as fs } from "fs";
|
|
221
|
+
import path2 from "path";
|
|
222
|
+
import { setTimeout as delay } from "timers/promises";
|
|
223
|
+
import { isValidUpdateChannel as isValidUpdateChannel2 } from "@codelia/config-loader";
|
|
224
|
+
import { openSqlite } from "@codelia/storage";
|
|
225
|
+
var resolveUpdatePaths = (cacheDir) => {
|
|
226
|
+
const dir = path2.join(cacheDir, "update");
|
|
227
|
+
return {
|
|
228
|
+
dir,
|
|
229
|
+
stateFile: path2.join(dir, "state.json"),
|
|
230
|
+
noticesDir: path2.join(dir, "notices")
|
|
231
|
+
};
|
|
232
|
+
};
|
|
233
|
+
var resolveInstallApplyLockFile = (canonicalPackageRoot) => path2.join(
|
|
234
|
+
path2.dirname(path2.dirname(canonicalPackageRoot)),
|
|
235
|
+
".codelia-update.lock.sqlite"
|
|
236
|
+
);
|
|
237
|
+
var MAX_STATE_BYTES = 64 * 1024;
|
|
238
|
+
var MAX_MESSAGE_LENGTH = 300;
|
|
239
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
240
|
+
var isTimestamp = (value) => typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
|
|
241
|
+
var clampMessage = (value) => {
|
|
242
|
+
const singleLine = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
|
|
243
|
+
return singleLine.length > MAX_MESSAGE_LENGTH ? `${singleLine.slice(0, MAX_MESSAGE_LENGTH - 1)}\u2026` : singleLine;
|
|
244
|
+
};
|
|
245
|
+
var parseUpdateState = (value) => {
|
|
246
|
+
const state = { version: 1 };
|
|
247
|
+
if (!isRecord(value) || value.version !== 1) return state;
|
|
248
|
+
if (isTimestamp(value.last_check_at)) {
|
|
249
|
+
state.last_check_at = value.last_check_at;
|
|
250
|
+
}
|
|
251
|
+
if (typeof value.last_check_ok === "boolean") {
|
|
252
|
+
state.last_check_ok = value.last_check_ok;
|
|
253
|
+
}
|
|
254
|
+
if (typeof value.last_check_error === "string") {
|
|
255
|
+
state.last_check_error = clampMessage(value.last_check_error);
|
|
256
|
+
}
|
|
257
|
+
if (typeof value.channel === "string" && isValidUpdateChannel2(value.channel)) {
|
|
258
|
+
state.channel = value.channel;
|
|
259
|
+
}
|
|
260
|
+
if (typeof value.registry_id === "string" && /^[0-9a-f]{64}$/.test(value.registry_id)) {
|
|
261
|
+
state.registry_id = value.registry_id;
|
|
262
|
+
}
|
|
263
|
+
if (value.configured_channel === null || typeof value.configured_channel === "string" && isValidUpdateChannel2(value.configured_channel)) {
|
|
264
|
+
state.configured_channel = value.configured_channel;
|
|
265
|
+
}
|
|
266
|
+
if (isValidVersion(value.latest_version)) {
|
|
267
|
+
state.latest_version = value.latest_version;
|
|
268
|
+
}
|
|
269
|
+
if (isValidVersion(value.checked_version)) {
|
|
270
|
+
state.checked_version = value.checked_version;
|
|
271
|
+
}
|
|
272
|
+
if (isRecord(value.apply_failure) && isValidVersion(value.apply_failure.version) && isTimestamp(value.apply_failure.at) && typeof value.apply_failure.message === "string") {
|
|
273
|
+
state.apply_failure = {
|
|
274
|
+
version: value.apply_failure.version,
|
|
275
|
+
at: value.apply_failure.at,
|
|
276
|
+
message: clampMessage(value.apply_failure.message),
|
|
277
|
+
...value.apply_failure.unmanaged === true ? { unmanaged: true } : {}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
if (isRecord(value.applied) && isValidVersion(value.applied.from) && isValidVersion(value.applied.to) && isTimestamp(value.applied.at)) {
|
|
281
|
+
state.applied = {
|
|
282
|
+
from: value.applied.from,
|
|
283
|
+
to: value.applied.to,
|
|
284
|
+
at: value.applied.at
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
return state;
|
|
288
|
+
};
|
|
289
|
+
var readUpdateState = async (file) => {
|
|
290
|
+
try {
|
|
291
|
+
const info = await fs.lstat(file);
|
|
292
|
+
if (!info.isFile() || info.size > MAX_STATE_BYTES) return { version: 1 };
|
|
293
|
+
return parseUpdateState(JSON.parse(await fs.readFile(file, "utf8")));
|
|
294
|
+
} catch {
|
|
295
|
+
return { version: 1 };
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
var writeJsonAtomic = async (file, value) => {
|
|
299
|
+
await fs.mkdir(path2.dirname(file), { recursive: true });
|
|
300
|
+
const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
301
|
+
try {
|
|
302
|
+
await fs.writeFile(temp, `${JSON.stringify(value, null, 2)}
|
|
303
|
+
`, {
|
|
304
|
+
mode: 384,
|
|
305
|
+
flag: "wx"
|
|
306
|
+
});
|
|
307
|
+
await fs.rename(temp, file);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
await fs.rm(temp, { force: true });
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
var writeUpdateState = (file, state) => writeJsonAtomic(file, state);
|
|
314
|
+
var isSqliteBusyError = (error) => ["SQLITE_BUSY", "SQLITE_LOCKED"].includes(
|
|
315
|
+
error?.code ?? ""
|
|
316
|
+
);
|
|
317
|
+
var tryWithSqliteLock = async (lockFile, timeoutMs, action) => {
|
|
318
|
+
await fs.mkdir(path2.dirname(lockFile), { recursive: true, mode: 448 });
|
|
319
|
+
const db = await openSqlite(lockFile);
|
|
320
|
+
try {
|
|
321
|
+
db.exec("PRAGMA busy_timeout = 0");
|
|
322
|
+
const deadline = performance.now() + timeoutMs;
|
|
323
|
+
for (; ; ) {
|
|
324
|
+
try {
|
|
325
|
+
db.exec("BEGIN IMMEDIATE");
|
|
326
|
+
break;
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (!isSqliteBusyError(error)) throw error;
|
|
329
|
+
if (performance.now() >= deadline) {
|
|
330
|
+
return { acquired: false };
|
|
331
|
+
}
|
|
332
|
+
await delay(15);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
const value = await action();
|
|
337
|
+
db.exec("COMMIT");
|
|
338
|
+
return { acquired: true, value };
|
|
339
|
+
} catch (error) {
|
|
340
|
+
try {
|
|
341
|
+
db.exec("ROLLBACK");
|
|
342
|
+
} catch {
|
|
343
|
+
}
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
} finally {
|
|
347
|
+
db.close();
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
var withLockedUpdateState = async (file, action) => {
|
|
351
|
+
const result = await tryWithSqliteLock(
|
|
352
|
+
`${file}.lock.sqlite`,
|
|
353
|
+
5e3,
|
|
354
|
+
async () => action(await readUpdateState(file))
|
|
355
|
+
);
|
|
356
|
+
if (!result.acquired) {
|
|
357
|
+
throw new Error("Timed out waiting for update state lock");
|
|
358
|
+
}
|
|
359
|
+
return result.value;
|
|
360
|
+
};
|
|
361
|
+
var mutateUpdateState = (file, mutate) => withLockedUpdateState(file, async (state) => {
|
|
362
|
+
const next = mutate(state);
|
|
363
|
+
await writeUpdateState(file, next);
|
|
364
|
+
return next;
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
// src/update/apply.ts
|
|
368
|
+
import { execFile } from "child_process";
|
|
369
|
+
import fsSync2 from "fs";
|
|
370
|
+
import path3 from "path";
|
|
371
|
+
var APPLY_LOCK_WAIT_MS = 250;
|
|
372
|
+
var NPM_PREFIX_TIMEOUT_MS = 1e4;
|
|
373
|
+
var NPM_INSTALL_TIMEOUT_MS = 12e4;
|
|
374
|
+
var defaultRunner = ({ command, args, env, timeoutMs }) => new Promise((resolve) => {
|
|
375
|
+
execFile(
|
|
376
|
+
command,
|
|
377
|
+
args,
|
|
378
|
+
{
|
|
379
|
+
env,
|
|
380
|
+
timeout: timeoutMs,
|
|
381
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
382
|
+
encoding: "utf8",
|
|
383
|
+
windowsHide: true
|
|
384
|
+
},
|
|
385
|
+
(error, stdout, stderr) => {
|
|
386
|
+
if (!error) {
|
|
387
|
+
resolve({ code: 0, stdout, stderr });
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
const exitCode = typeof error.code === "number" ? error.code : 1;
|
|
391
|
+
resolve({
|
|
392
|
+
code: exitCode,
|
|
393
|
+
stdout: stdout ?? "",
|
|
394
|
+
stderr: stderr || error.message
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
);
|
|
398
|
+
});
|
|
399
|
+
var canonicalDir = (target) => {
|
|
400
|
+
const resolved = path3.resolve(target);
|
|
401
|
+
try {
|
|
402
|
+
return fsSync2.realpathSync(resolved);
|
|
403
|
+
} catch {
|
|
404
|
+
return resolved;
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
var summarizeStderr = (stderr, fallback) => {
|
|
408
|
+
const lines = stderr.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
409
|
+
const npmErr = lines.find(
|
|
410
|
+
(l) => l.startsWith("npm error") || l.startsWith("npm ERR!")
|
|
411
|
+
);
|
|
412
|
+
return clampMessage(npmErr ?? lines.at(-1) ?? fallback);
|
|
413
|
+
};
|
|
414
|
+
var applyUpdate = async (options) => {
|
|
415
|
+
const env = options.env ?? process.env;
|
|
416
|
+
const runner = options.runner ?? defaultRunner;
|
|
417
|
+
const now = options.now ?? Date.now;
|
|
418
|
+
if (options.method.kind !== "npm-global" || !options.method.prefix || !options.method.autoApply.supported) {
|
|
419
|
+
return {
|
|
420
|
+
status: "failed",
|
|
421
|
+
message: options.method.autoApply.supported ? "Unsupported installation layout" : options.method.autoApply.reason,
|
|
422
|
+
unmanaged: true
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
const npmPath = options.method.autoApply.npmPath;
|
|
426
|
+
const expectedPrefix = canonicalDir(options.method.prefix);
|
|
427
|
+
const applyLockFile = resolveInstallApplyLockFile(
|
|
428
|
+
canonicalDir(options.method.packageRoot)
|
|
429
|
+
);
|
|
430
|
+
const locked = await tryWithSqliteLock(
|
|
431
|
+
applyLockFile,
|
|
432
|
+
APPLY_LOCK_WAIT_MS,
|
|
433
|
+
async () => {
|
|
434
|
+
const onDisk = readInstalledVersion(options.method.packageRoot);
|
|
435
|
+
if (onDisk && onDisk !== options.from) {
|
|
436
|
+
return { status: "changed", installed: onDisk };
|
|
437
|
+
}
|
|
438
|
+
const currentState = await readUpdateState(options.paths.stateFile);
|
|
439
|
+
if (currentState.latest_version && (compareVersions(currentState.latest_version, options.to) ?? 0) !== 0) {
|
|
440
|
+
return { status: "superseded" };
|
|
441
|
+
}
|
|
442
|
+
if (!isNewerVersion(options.to, options.from)) {
|
|
443
|
+
return { status: "changed", installed: options.from };
|
|
444
|
+
}
|
|
445
|
+
let registryUrl;
|
|
446
|
+
try {
|
|
447
|
+
registryUrl = resolveRegistryUrl(env);
|
|
448
|
+
} catch (error) {
|
|
449
|
+
const message = clampMessage(
|
|
450
|
+
error instanceof Error ? error.message : String(error)
|
|
451
|
+
);
|
|
452
|
+
return { status: "failed", message };
|
|
453
|
+
}
|
|
454
|
+
const npmEnv = {
|
|
455
|
+
...env,
|
|
456
|
+
npm_config_registry: registryUrl,
|
|
457
|
+
npm_config_update_notifier: "false"
|
|
458
|
+
};
|
|
459
|
+
const failAndRecord = async (message, unmanaged) => {
|
|
460
|
+
await recordApplyFailure(
|
|
461
|
+
options.paths.stateFile,
|
|
462
|
+
options.to,
|
|
463
|
+
message,
|
|
464
|
+
now,
|
|
465
|
+
unmanaged
|
|
466
|
+
);
|
|
467
|
+
return unmanaged ? { status: "failed", message, unmanaged } : { status: "failed", message };
|
|
468
|
+
};
|
|
469
|
+
const prefixProbe = await runner({
|
|
470
|
+
command: npmPath,
|
|
471
|
+
args: ["prefix", "-g"],
|
|
472
|
+
env: npmEnv,
|
|
473
|
+
timeoutMs: NPM_PREFIX_TIMEOUT_MS
|
|
474
|
+
});
|
|
475
|
+
if (prefixProbe.code !== 0) {
|
|
476
|
+
return failAndRecord(
|
|
477
|
+
summarizeStderr(prefixProbe.stderr, "npm prefix check failed")
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
const reportedPrefix = canonicalDir(prefixProbe.stdout.trim());
|
|
481
|
+
if (reportedPrefix !== expectedPrefix) {
|
|
482
|
+
return failAndRecord(
|
|
483
|
+
"npm global prefix does not match installation prefix",
|
|
484
|
+
true
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
const install = await runner({
|
|
488
|
+
command: npmPath,
|
|
489
|
+
args: [
|
|
490
|
+
"install",
|
|
491
|
+
"-g",
|
|
492
|
+
"--prefix",
|
|
493
|
+
expectedPrefix,
|
|
494
|
+
"--no-audit",
|
|
495
|
+
"--no-fund",
|
|
496
|
+
`${CLI_PACKAGE_NAME}@${options.to}`
|
|
497
|
+
],
|
|
498
|
+
env: npmEnv,
|
|
499
|
+
timeoutMs: NPM_INSTALL_TIMEOUT_MS
|
|
500
|
+
});
|
|
501
|
+
if (install.code !== 0) {
|
|
502
|
+
return failAndRecord(
|
|
503
|
+
summarizeStderr(
|
|
504
|
+
install.stderr,
|
|
505
|
+
`npm install exited with status ${install.code}`
|
|
506
|
+
)
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
const verified = readInstalledVersion(options.method.packageRoot);
|
|
510
|
+
if (verified !== options.to) {
|
|
511
|
+
return failAndRecord(
|
|
512
|
+
verified ? `Expected version ${options.to} after install, found ${verified}` : `Could not verify installed version ${options.to} after install`
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
const appliedAt = new Date(now()).toISOString();
|
|
516
|
+
await mutateUpdateState(options.paths.stateFile, (state) => {
|
|
517
|
+
const next = {
|
|
518
|
+
...state,
|
|
519
|
+
version: 1,
|
|
520
|
+
applied: { from: options.from, to: options.to, at: appliedAt }
|
|
521
|
+
};
|
|
522
|
+
delete next.apply_failure;
|
|
523
|
+
return next;
|
|
524
|
+
}).catch(() => void 0);
|
|
525
|
+
return { status: "installed", from: options.from, to: options.to };
|
|
526
|
+
}
|
|
527
|
+
);
|
|
528
|
+
if (!locked.acquired) {
|
|
529
|
+
return { status: "deferred" };
|
|
530
|
+
}
|
|
531
|
+
return locked.value;
|
|
532
|
+
};
|
|
533
|
+
var recordApplyFailure = async (stateFile, version, message, now, unmanaged) => {
|
|
534
|
+
const at = new Date(now()).toISOString();
|
|
535
|
+
await mutateUpdateState(stateFile, (state) => ({
|
|
536
|
+
...state,
|
|
537
|
+
version: 1,
|
|
538
|
+
apply_failure: {
|
|
539
|
+
version,
|
|
540
|
+
at,
|
|
541
|
+
message: clampMessage(message),
|
|
542
|
+
...unmanaged ? { unmanaged: true } : {}
|
|
543
|
+
}
|
|
544
|
+
})).catch(() => void 0);
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
// src/update/check.ts
|
|
548
|
+
var CHECK_SUCCESS_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
549
|
+
var CHECK_FAILURE_TTL_MS = 60 * 60 * 1e3;
|
|
550
|
+
var resolveEffectiveChannel = (currentVersion, configuredChannel) => configuredChannel ?? inferChannelFromVersion(currentVersion);
|
|
551
|
+
var isMatchingCheckScope = (state, scope) => state.registry_id === scope.registryId && state.channel === scope.channel && state.configured_channel === scope.configuredChannel;
|
|
552
|
+
var shouldCheckNow = (state, options) => {
|
|
553
|
+
const now = options.now ?? Date.now();
|
|
554
|
+
const effectiveChannel = resolveEffectiveChannel(
|
|
555
|
+
options.currentVersion,
|
|
556
|
+
options.configuredChannel
|
|
557
|
+
);
|
|
558
|
+
if (!isMatchingCheckScope(state, {
|
|
559
|
+
channel: effectiveChannel,
|
|
560
|
+
configuredChannel: options.configuredChannel,
|
|
561
|
+
registryId: options.registryId
|
|
562
|
+
}) || state.checked_version !== options.currentVersion) {
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
if (!state.last_check_at) return true;
|
|
566
|
+
const lastMs = Date.parse(state.last_check_at);
|
|
567
|
+
if (!Number.isFinite(lastMs)) return true;
|
|
568
|
+
const ttl = state.last_check_ok === true ? CHECK_SUCCESS_TTL_MS : CHECK_FAILURE_TTL_MS;
|
|
569
|
+
return now - lastMs >= ttl;
|
|
570
|
+
};
|
|
571
|
+
var runRegistryCheck = async (options) => {
|
|
572
|
+
const now = options.now ?? Date.now;
|
|
573
|
+
const channel = resolveEffectiveChannel(
|
|
574
|
+
options.currentVersion,
|
|
575
|
+
options.configuredChannel
|
|
576
|
+
);
|
|
577
|
+
let registryUrl;
|
|
578
|
+
try {
|
|
579
|
+
registryUrl = resolveRegistryUrl(options.env);
|
|
580
|
+
} catch (error) {
|
|
581
|
+
const message = clampMessage(
|
|
582
|
+
error instanceof Error ? error.message : String(error)
|
|
583
|
+
);
|
|
584
|
+
return { status: "failed", channel, message };
|
|
585
|
+
}
|
|
586
|
+
const regId = computeRegistryId(registryUrl);
|
|
587
|
+
const checkedAt = new Date(now()).toISOString();
|
|
588
|
+
try {
|
|
589
|
+
const latest = await fetchLatestVersion({
|
|
590
|
+
registryUrl,
|
|
591
|
+
channel,
|
|
592
|
+
fetchImpl: options.fetchImpl,
|
|
593
|
+
signal: options.signal
|
|
594
|
+
});
|
|
595
|
+
await mutateUpdateState(options.paths.stateFile, (state) => {
|
|
596
|
+
const next = {
|
|
597
|
+
...state,
|
|
598
|
+
version: 1,
|
|
599
|
+
last_check_at: checkedAt,
|
|
600
|
+
last_check_ok: true,
|
|
601
|
+
channel,
|
|
602
|
+
registry_id: regId,
|
|
603
|
+
configured_channel: options.configuredChannel,
|
|
604
|
+
latest_version: latest,
|
|
605
|
+
checked_version: options.currentVersion
|
|
606
|
+
};
|
|
607
|
+
delete next.last_check_error;
|
|
608
|
+
if (next.apply_failure && next.apply_failure.version !== latest) {
|
|
609
|
+
delete next.apply_failure;
|
|
610
|
+
}
|
|
611
|
+
return next;
|
|
612
|
+
});
|
|
613
|
+
if (isNewerVersion(latest, options.currentVersion)) {
|
|
614
|
+
return { status: "update_available", channel, latest };
|
|
615
|
+
}
|
|
616
|
+
return { status: "up_to_date", channel, latest };
|
|
617
|
+
} catch (error) {
|
|
618
|
+
if (options.signal?.aborted) {
|
|
619
|
+
return { status: "aborted", channel };
|
|
620
|
+
}
|
|
621
|
+
const message = clampMessage(
|
|
622
|
+
error instanceof Error ? error.message : String(error)
|
|
623
|
+
);
|
|
624
|
+
await mutateUpdateState(options.paths.stateFile, (state) => {
|
|
625
|
+
const scopeChanged = !isMatchingCheckScope(state, {
|
|
626
|
+
channel,
|
|
627
|
+
configuredChannel: options.configuredChannel,
|
|
628
|
+
registryId: regId
|
|
629
|
+
});
|
|
630
|
+
const next = {
|
|
631
|
+
...state,
|
|
632
|
+
version: 1,
|
|
633
|
+
last_check_at: checkedAt,
|
|
634
|
+
last_check_ok: false,
|
|
635
|
+
last_check_error: message,
|
|
636
|
+
channel,
|
|
637
|
+
registry_id: regId,
|
|
638
|
+
configured_channel: options.configuredChannel,
|
|
639
|
+
checked_version: options.currentVersion
|
|
640
|
+
};
|
|
641
|
+
if (scopeChanged) {
|
|
642
|
+
delete next.latest_version;
|
|
643
|
+
delete next.apply_failure;
|
|
644
|
+
}
|
|
645
|
+
return next;
|
|
646
|
+
}).catch(() => void 0);
|
|
647
|
+
return { status: "failed", channel, message };
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
// src/update/install-method.ts
|
|
652
|
+
import fsSync3 from "fs";
|
|
653
|
+
import path4 from "path";
|
|
654
|
+
var isSafeExecutable = (candidate, platform) => {
|
|
655
|
+
try {
|
|
656
|
+
fsSync3.accessSync(candidate, fsSync3.constants.X_OK);
|
|
657
|
+
const real = fsSync3.realpathSync(candidate);
|
|
658
|
+
const info = fsSync3.statSync(real);
|
|
659
|
+
if (!info.isFile()) return false;
|
|
660
|
+
if (platform !== "win32" && typeof process.geteuid === "function") {
|
|
661
|
+
const euid = process.geteuid();
|
|
662
|
+
if (info.uid !== 0 && info.uid !== euid) return false;
|
|
663
|
+
if ((info.mode & 18) !== 0) return false;
|
|
664
|
+
const parentInfo = fsSync3.statSync(path4.dirname(real));
|
|
665
|
+
if (parentInfo.uid !== 0 && parentInfo.uid !== euid) return false;
|
|
666
|
+
if ((parentInfo.mode & 18) !== 0) return false;
|
|
667
|
+
}
|
|
668
|
+
return true;
|
|
669
|
+
} catch {
|
|
670
|
+
return false;
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
var resolveNpmBinary = (env = process.env) => {
|
|
674
|
+
const platform = process.platform;
|
|
675
|
+
const names = platform === "win32" ? ["npm.cmd", "npm.exe"] : ["npm"];
|
|
676
|
+
const candidates = [];
|
|
677
|
+
const execDir = path4.dirname(process.execPath);
|
|
678
|
+
if (path4.isAbsolute(execDir)) {
|
|
679
|
+
for (const name of names) {
|
|
680
|
+
candidates.push(path4.join(execDir, name));
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const rawPath = env.PATH ?? env.Path ?? "";
|
|
684
|
+
for (const entry of rawPath.split(path4.delimiter)) {
|
|
685
|
+
const dir = entry.trim();
|
|
686
|
+
if (!dir || !path4.isAbsolute(dir)) continue;
|
|
687
|
+
for (const name of names) {
|
|
688
|
+
candidates.push(path4.join(dir, name));
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
const seen = /* @__PURE__ */ new Set();
|
|
692
|
+
for (const candidate of candidates) {
|
|
693
|
+
if (seen.has(candidate)) continue;
|
|
694
|
+
seen.add(candidate);
|
|
695
|
+
if (isSafeExecutable(candidate, platform)) {
|
|
696
|
+
return candidate;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return null;
|
|
700
|
+
};
|
|
701
|
+
var isWritableDir = (dir) => {
|
|
702
|
+
try {
|
|
703
|
+
fsSync3.accessSync(dir, fsSync3.constants.W_OK);
|
|
704
|
+
return true;
|
|
705
|
+
} catch {
|
|
706
|
+
return false;
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
var splitSegments = (target) => path4.normalize(target).split(path4.sep).filter(Boolean);
|
|
710
|
+
var hasMatchingBinLink = (prefix, packageRoot, platform) => {
|
|
711
|
+
const binCandidate = platform === "win32" ? path4.join(prefix, "codelia.cmd") : path4.join(prefix, "bin", "codelia");
|
|
712
|
+
if (!fsSync3.existsSync(binCandidate)) return false;
|
|
713
|
+
if (platform === "win32") return true;
|
|
714
|
+
try {
|
|
715
|
+
const resolvedBin = fsSync3.realpathSync(binCandidate);
|
|
716
|
+
const resolvedRoot = fsSync3.realpathSync(packageRoot);
|
|
717
|
+
const rel = path4.relative(resolvedRoot, resolvedBin);
|
|
718
|
+
return !rel.startsWith("..") && !path4.isAbsolute(rel);
|
|
719
|
+
} catch {
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
var unsupportedInstall = (kind, packageRoot, reason, prefix) => ({
|
|
724
|
+
kind,
|
|
725
|
+
packageRoot,
|
|
726
|
+
...prefix ? { prefix } : {},
|
|
727
|
+
autoApply: { supported: false, reason }
|
|
728
|
+
});
|
|
729
|
+
var EXTERNAL_MANAGER_MATCHERS = [
|
|
730
|
+
{
|
|
731
|
+
kind: "development",
|
|
732
|
+
reason: "source checkout",
|
|
733
|
+
match: (segments) => !segments.includes("node_modules")
|
|
734
|
+
},
|
|
735
|
+
{
|
|
736
|
+
kind: "homebrew",
|
|
737
|
+
reason: "managed by Homebrew",
|
|
738
|
+
match: (segments) => segments.includes("Cellar")
|
|
739
|
+
},
|
|
740
|
+
{
|
|
741
|
+
kind: "nix",
|
|
742
|
+
reason: "managed by Nix/Guix store",
|
|
743
|
+
match: (segments) => segments[0] === "nix" && segments[1] === "store" || segments[0] === "gnu" && segments[1] === "store"
|
|
744
|
+
},
|
|
745
|
+
{
|
|
746
|
+
kind: "npx",
|
|
747
|
+
reason: "ephemeral npx cache",
|
|
748
|
+
match: (_segments, lower) => lower.includes("_npx")
|
|
749
|
+
},
|
|
750
|
+
{
|
|
751
|
+
kind: "pnpm",
|
|
752
|
+
reason: "managed by pnpm",
|
|
753
|
+
match: (_segments, lower) => lower.includes(".pnpm") || lower.includes("pnpm")
|
|
754
|
+
},
|
|
755
|
+
{
|
|
756
|
+
kind: "bun",
|
|
757
|
+
reason: "managed by Bun",
|
|
758
|
+
match: (_segments, lower) => lower.includes(".bun")
|
|
759
|
+
},
|
|
760
|
+
{
|
|
761
|
+
kind: "yarn",
|
|
762
|
+
reason: "managed by Yarn",
|
|
763
|
+
match: (_segments, lower) => lower.includes("yarn")
|
|
764
|
+
},
|
|
765
|
+
{
|
|
766
|
+
kind: "volta",
|
|
767
|
+
reason: "managed by Volta",
|
|
768
|
+
match: (_segments, lower) => lower.includes(".volta")
|
|
769
|
+
},
|
|
770
|
+
{
|
|
771
|
+
kind: "mise",
|
|
772
|
+
reason: "managed by mise",
|
|
773
|
+
match: (_segments, lower) => lower.includes("mise") && lower.includes("installs") && lower.includes("npm")
|
|
774
|
+
}
|
|
775
|
+
];
|
|
776
|
+
var detectInstallMethod = (options) => {
|
|
777
|
+
const platform = options.platform ?? process.platform;
|
|
778
|
+
const env = options.env ?? process.env;
|
|
779
|
+
const resolveNpm = options.resolveNpm ?? resolveNpmBinary;
|
|
780
|
+
let packageRoot = path4.resolve(options.packageRoot);
|
|
781
|
+
try {
|
|
782
|
+
packageRoot = fsSync3.realpathSync(packageRoot);
|
|
783
|
+
} catch {
|
|
784
|
+
}
|
|
785
|
+
const segments = splitSegments(packageRoot);
|
|
786
|
+
const lowerSegments = segments.map((s) => s.toLowerCase());
|
|
787
|
+
for (const matcher of EXTERNAL_MANAGER_MATCHERS) {
|
|
788
|
+
if (matcher.match(segments, lowerSegments)) {
|
|
789
|
+
return unsupportedInstall(matcher.kind, packageRoot, matcher.reason);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
const scopeDir = path4.dirname(packageRoot);
|
|
793
|
+
const nodeModulesDir = path4.dirname(scopeDir);
|
|
794
|
+
if (path4.basename(packageRoot) !== "cli" || path4.basename(scopeDir) !== "@codelia" || path4.basename(nodeModulesDir) !== "node_modules") {
|
|
795
|
+
return unsupportedInstall(
|
|
796
|
+
"unknown",
|
|
797
|
+
packageRoot,
|
|
798
|
+
"unrecognized package layout"
|
|
799
|
+
);
|
|
800
|
+
}
|
|
801
|
+
const parentOfNodeModules = path4.dirname(nodeModulesDir);
|
|
802
|
+
const prefix = platform === "win32" ? parentOfNodeModules : path4.basename(parentOfNodeModules) === "lib" ? path4.dirname(parentOfNodeModules) : null;
|
|
803
|
+
if (!prefix || !hasMatchingBinLink(prefix, packageRoot, platform)) {
|
|
804
|
+
return unsupportedInstall(
|
|
805
|
+
"local",
|
|
806
|
+
packageRoot,
|
|
807
|
+
"project-local installation"
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
const npmPath = resolveNpm(env);
|
|
811
|
+
if (!npmPath) {
|
|
812
|
+
return unsupportedInstall(
|
|
813
|
+
"npm-global",
|
|
814
|
+
packageRoot,
|
|
815
|
+
"npm executable not found",
|
|
816
|
+
prefix
|
|
817
|
+
);
|
|
818
|
+
}
|
|
819
|
+
if (!isWritableDir(nodeModulesDir) || !isWritableDir(scopeDir)) {
|
|
820
|
+
return unsupportedInstall(
|
|
821
|
+
"npm-global",
|
|
822
|
+
packageRoot,
|
|
823
|
+
"install directory is not writable",
|
|
824
|
+
prefix
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
return {
|
|
828
|
+
kind: "npm-global",
|
|
829
|
+
packageRoot,
|
|
830
|
+
prefix,
|
|
831
|
+
autoApply: { supported: true, npmPath }
|
|
832
|
+
};
|
|
833
|
+
};
|
|
834
|
+
var buildUpdateCommand = (method, target) => {
|
|
835
|
+
const spec = `${CLI_PACKAGE_NAME}@${target.channel}`;
|
|
836
|
+
switch (method.kind) {
|
|
837
|
+
case "npm-global":
|
|
838
|
+
return `npm install -g ${spec}`;
|
|
839
|
+
case "pnpm":
|
|
840
|
+
return `pnpm add -g ${spec}`;
|
|
841
|
+
case "bun":
|
|
842
|
+
return `bun add -g ${spec}`;
|
|
843
|
+
case "yarn":
|
|
844
|
+
return `yarn global add ${spec}`;
|
|
845
|
+
case "volta":
|
|
846
|
+
return `volta install ${spec}`;
|
|
847
|
+
case "homebrew":
|
|
848
|
+
return "brew upgrade codelia";
|
|
849
|
+
case "local":
|
|
850
|
+
return `npm install ${spec}`;
|
|
851
|
+
case "development":
|
|
852
|
+
case "nix":
|
|
853
|
+
case "mise":
|
|
854
|
+
case "npx":
|
|
855
|
+
case "unknown":
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
|
|
860
|
+
// src/update/notices.ts
|
|
861
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
862
|
+
import fsSync4, { promises as fs2 } from "fs";
|
|
863
|
+
import path5 from "path";
|
|
864
|
+
var UPDATE_NOTICE_FILE_ENV = "CODELIA_UPDATE_NOTICE_FILE";
|
|
865
|
+
var STALE_NOTICE_AGE_MS = 60 * 60 * 1e3;
|
|
866
|
+
var commandHint = (command) => command ? `Update with: ${command}` : "Update using the package manager that installed Codelia.";
|
|
867
|
+
var buildStartupNotices = (state, options) => {
|
|
868
|
+
const notices = [];
|
|
869
|
+
if (options.reexecFrom && options.reexecFrom !== options.currentVersion) {
|
|
870
|
+
notices.push(
|
|
871
|
+
`Updated Codelia ${options.reexecFrom} -> ${options.currentVersion}.`
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
if (options.mode === "off") return notices;
|
|
875
|
+
const latest = state.latest_version;
|
|
876
|
+
if (!latest || !isNewerVersion(latest, options.currentVersion)) {
|
|
877
|
+
return notices;
|
|
878
|
+
}
|
|
879
|
+
const channel = state.channel ?? "latest";
|
|
880
|
+
const command = options.method ? buildUpdateCommand(options.method, { version: latest, channel }) : null;
|
|
881
|
+
if (state.apply_failure && state.apply_failure.version === latest) {
|
|
882
|
+
const hint = state.apply_failure.unmanaged ? commandHint(null) : commandHint(command);
|
|
883
|
+
notices.push(
|
|
884
|
+
`Automatic update to ${latest} failed (${state.apply_failure.message}). ${hint}`
|
|
885
|
+
);
|
|
886
|
+
return notices;
|
|
887
|
+
}
|
|
888
|
+
if (options.mode === "notify" || !options.method?.autoApply.supported) {
|
|
889
|
+
const hint = options.method?.autoApply.supported ? "Run `codelia update` to install." : commandHint(command);
|
|
890
|
+
notices.push(
|
|
891
|
+
`Update available: ${options.currentVersion} -> ${latest}. ${hint}`
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
return notices;
|
|
895
|
+
};
|
|
896
|
+
var writeStartupNoticeFile = async (paths, notices) => {
|
|
897
|
+
if (notices.length === 0) return null;
|
|
898
|
+
await fs2.mkdir(paths.noticesDir, { recursive: true, mode: 448 });
|
|
899
|
+
void cleanupStaleNotices(paths.noticesDir);
|
|
900
|
+
const file = path5.join(
|
|
901
|
+
paths.noticesDir,
|
|
902
|
+
`notice-${process.pid}-${randomBytes2(4).toString("hex")}.json`
|
|
903
|
+
);
|
|
904
|
+
await writeJsonAtomic(file, { notices: [...notices] });
|
|
905
|
+
return file;
|
|
906
|
+
};
|
|
907
|
+
var removeNoticeFileSync = (file) => {
|
|
908
|
+
if (!file) return;
|
|
909
|
+
try {
|
|
910
|
+
fsSync4.rmSync(file, { force: true });
|
|
911
|
+
} catch {
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
var cleanupStaleNotices = async (dir) => {
|
|
915
|
+
try {
|
|
916
|
+
const cutoff = Date.now() - STALE_NOTICE_AGE_MS;
|
|
917
|
+
const entries = await fs2.readdir(dir);
|
|
918
|
+
for (const entry of entries) {
|
|
919
|
+
if (!entry.startsWith("notice-") || !entry.endsWith(".json")) continue;
|
|
920
|
+
const full = path5.join(dir, entry);
|
|
921
|
+
const stat = await fs2.lstat(full).catch(() => null);
|
|
922
|
+
if (stat?.isFile() && stat.mtimeMs < cutoff) {
|
|
923
|
+
await fs2.rm(full, { force: true }).catch(() => void 0);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
} catch {
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
|
|
930
|
+
// src/update/settings.ts
|
|
931
|
+
import { promises as fs3 } from "fs";
|
|
932
|
+
import {
|
|
933
|
+
isValidUpdateChannel as isValidUpdateChannel3,
|
|
934
|
+
parseUpdateMode
|
|
935
|
+
} from "@codelia/config-loader";
|
|
936
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
937
|
+
var isCiEnvironment = (env) => {
|
|
938
|
+
const ci = (env.CI ?? "").trim().toLowerCase();
|
|
939
|
+
if (ci === "1" || ci === "true" || ci === "yes") return true;
|
|
940
|
+
return Boolean(
|
|
941
|
+
env.GITHUB_ACTIONS || env.GITLAB_CI || env.BUILDKITE || env.CIRCLECI || env.JENKINS_URL
|
|
942
|
+
);
|
|
943
|
+
};
|
|
944
|
+
var parseEnvMode = (raw) => {
|
|
945
|
+
if (raw === void 0) return {};
|
|
946
|
+
const normalized = raw.trim().toLowerCase();
|
|
947
|
+
if (normalized === "") return {};
|
|
948
|
+
if (normalized === "0" || normalized === "false" || normalized === "off") {
|
|
949
|
+
return { value: "off" };
|
|
950
|
+
}
|
|
951
|
+
if (normalized === "1" || normalized === "true" || normalized === "auto") {
|
|
952
|
+
return { value: "auto" };
|
|
953
|
+
}
|
|
954
|
+
if (normalized === "notify") {
|
|
955
|
+
return { value: "notify" };
|
|
956
|
+
}
|
|
957
|
+
return { invalid: true };
|
|
958
|
+
};
|
|
959
|
+
var readGlobalUpdateConfig = async (configFile) => {
|
|
960
|
+
const warnings = [];
|
|
961
|
+
let rawText;
|
|
962
|
+
try {
|
|
963
|
+
rawText = await fs3.readFile(configFile, "utf8");
|
|
964
|
+
} catch {
|
|
965
|
+
return { warnings };
|
|
966
|
+
}
|
|
967
|
+
let parsed;
|
|
968
|
+
try {
|
|
969
|
+
parsed = JSON.parse(rawText);
|
|
970
|
+
} catch {
|
|
971
|
+
return { warnings };
|
|
972
|
+
}
|
|
973
|
+
if (!isRecord2(parsed) || !isRecord2(parsed.update)) {
|
|
974
|
+
return { warnings };
|
|
975
|
+
}
|
|
976
|
+
const update = parsed.update;
|
|
977
|
+
let mode;
|
|
978
|
+
if (update.mode !== void 0) {
|
|
979
|
+
mode = parseUpdateMode(update.mode);
|
|
980
|
+
if (!mode) {
|
|
981
|
+
warnings.push(
|
|
982
|
+
`Ignoring invalid update.mode in ${configFile} (expected "auto", "notify", or "off").`
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
let channel;
|
|
987
|
+
if (update.channel !== void 0) {
|
|
988
|
+
if (typeof update.channel === "string" && isValidUpdateChannel3(update.channel)) {
|
|
989
|
+
channel = update.channel;
|
|
990
|
+
} else {
|
|
991
|
+
warnings.push(
|
|
992
|
+
`Ignoring invalid update.channel in ${configFile} (expected an npm dist-tag name).`
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
return { mode, channel, warnings };
|
|
997
|
+
};
|
|
998
|
+
var resolveUpdateSettings = async (options) => {
|
|
999
|
+
const env = options.env ?? process.env;
|
|
1000
|
+
const fromConfig = await readGlobalUpdateConfig(options.configFile);
|
|
1001
|
+
const warnings = [...fromConfig.warnings];
|
|
1002
|
+
const envMode = parseEnvMode(env.CODELIA_AUTO_UPDATE);
|
|
1003
|
+
if (envMode.invalid) {
|
|
1004
|
+
warnings.push(
|
|
1005
|
+
`Ignoring invalid CODELIA_AUTO_UPDATE=${env.CODELIA_AUTO_UPDATE} (expected "auto", "notify", or "off").`
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
let channel = fromConfig.channel ?? null;
|
|
1009
|
+
if (env.CODELIA_UPDATE_CHANNEL !== void 0) {
|
|
1010
|
+
const trimmed = env.CODELIA_UPDATE_CHANNEL.trim();
|
|
1011
|
+
if (trimmed.length === 0) {
|
|
1012
|
+
channel = null;
|
|
1013
|
+
} else if (isValidUpdateChannel3(trimmed)) {
|
|
1014
|
+
channel = trimmed;
|
|
1015
|
+
} else {
|
|
1016
|
+
warnings.push(
|
|
1017
|
+
`Ignoring invalid CODELIA_UPDATE_CHANNEL=${env.CODELIA_UPDATE_CHANNEL}.`
|
|
1018
|
+
);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
let mode = envMode.value ?? fromConfig.mode ?? "notify";
|
|
1022
|
+
if (!options.interactive || isCiEnvironment(env)) {
|
|
1023
|
+
mode = "off";
|
|
1024
|
+
}
|
|
1025
|
+
return { mode, channel, warnings };
|
|
1026
|
+
};
|
|
1027
|
+
|
|
1028
|
+
export {
|
|
1029
|
+
isValidVersion,
|
|
1030
|
+
compareVersions,
|
|
1031
|
+
isNewerVersion,
|
|
1032
|
+
UPDATE_REEXEC_ENV,
|
|
1033
|
+
reexecLauncher,
|
|
1034
|
+
launcherEntry,
|
|
1035
|
+
resolveRegistryUrl,
|
|
1036
|
+
computeRegistryId,
|
|
1037
|
+
resolveUpdatePaths,
|
|
1038
|
+
readUpdateState,
|
|
1039
|
+
applyUpdate,
|
|
1040
|
+
resolveEffectiveChannel,
|
|
1041
|
+
isMatchingCheckScope,
|
|
1042
|
+
shouldCheckNow,
|
|
1043
|
+
runRegistryCheck,
|
|
1044
|
+
detectInstallMethod,
|
|
1045
|
+
buildUpdateCommand,
|
|
1046
|
+
UPDATE_NOTICE_FILE_ENV,
|
|
1047
|
+
commandHint,
|
|
1048
|
+
buildStartupNotices,
|
|
1049
|
+
writeStartupNoticeFile,
|
|
1050
|
+
removeNoticeFileSync,
|
|
1051
|
+
resolveUpdateSettings
|
|
1052
|
+
};
|