@chandresh726/switchy 1.3.15 → 1.3.18
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/cli.js +254 -128
- package/dist/cli.js.map +4 -4
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -20,7 +20,7 @@ var init_package = __esm({
|
|
|
20
20
|
"package.json"() {
|
|
21
21
|
package_default = {
|
|
22
22
|
name: "@chandresh726/switchy",
|
|
23
|
-
version: "1.3.
|
|
23
|
+
version: "1.3.18",
|
|
24
24
|
description: "Install, run, update, and stop the local-first Switchy application.",
|
|
25
25
|
license: "MIT",
|
|
26
26
|
type: "module",
|
|
@@ -328,7 +328,9 @@ var init_lifecycle_state = __esm({
|
|
|
328
328
|
latestVersion: null,
|
|
329
329
|
failedVersion: null,
|
|
330
330
|
downloadedVersion: null,
|
|
331
|
-
message: null
|
|
331
|
+
message: null,
|
|
332
|
+
progress: null,
|
|
333
|
+
timings: {}
|
|
332
334
|
};
|
|
333
335
|
}
|
|
334
336
|
});
|
|
@@ -844,23 +846,188 @@ async function requestRuntimeStop(paths) {
|
|
|
844
846
|
}
|
|
845
847
|
|
|
846
848
|
// src/release.ts
|
|
847
|
-
|
|
848
|
-
init_files();
|
|
849
|
-
import { createHash, randomUUID as randomUUID5 } from "node:crypto";
|
|
850
|
-
import { createReadStream, createWriteStream } from "node:fs";
|
|
849
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
851
850
|
import {
|
|
852
851
|
cp,
|
|
853
852
|
mkdir as mkdir3,
|
|
854
853
|
readFile as readFile3,
|
|
855
|
-
rename as
|
|
856
|
-
rm as
|
|
857
|
-
stat as
|
|
854
|
+
rename as rename4,
|
|
855
|
+
rm as rm4,
|
|
856
|
+
stat as stat4
|
|
858
857
|
} from "node:fs/promises";
|
|
859
|
-
import { Readable, Transform } from "node:stream";
|
|
860
|
-
import { pipeline } from "node:stream/promises";
|
|
861
858
|
import path8 from "node:path";
|
|
862
859
|
import { extract } from "tar";
|
|
863
860
|
|
|
861
|
+
// src/download.ts
|
|
862
|
+
init_config();
|
|
863
|
+
init_files();
|
|
864
|
+
import { createHash } from "node:crypto";
|
|
865
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
866
|
+
import { rename as rename3, rm as rm3, stat as stat3 } from "node:fs/promises";
|
|
867
|
+
import { Readable, Transform } from "node:stream";
|
|
868
|
+
import { pipeline } from "node:stream/promises";
|
|
869
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
870
|
+
|
|
871
|
+
// src/update-progress.ts
|
|
872
|
+
init_lifecycle_state2();
|
|
873
|
+
function updateProgressReporter(paths) {
|
|
874
|
+
return async (progress, durationMs) => {
|
|
875
|
+
const state = await readUpdateState(paths);
|
|
876
|
+
await saveUpdateState2(paths, {
|
|
877
|
+
progress,
|
|
878
|
+
...durationMs === void 0 ? {} : { timings: { ...state.timings, [progress.stage]: Math.round(durationMs) } }
|
|
879
|
+
});
|
|
880
|
+
};
|
|
881
|
+
}
|
|
882
|
+
async function trackUpdateStage(stage, report, operation) {
|
|
883
|
+
await report?.({ stage });
|
|
884
|
+
const started = performance.now();
|
|
885
|
+
try {
|
|
886
|
+
return await operation();
|
|
887
|
+
} finally {
|
|
888
|
+
await report?.({ stage }, performance.now() - started);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// src/download.ts
|
|
893
|
+
var RetryableDownloadError = class extends Error {
|
|
894
|
+
constructor(message, retryAfter = 0) {
|
|
895
|
+
super(message);
|
|
896
|
+
this.retryAfter = retryAfter;
|
|
897
|
+
}
|
|
898
|
+
retryAfter;
|
|
899
|
+
};
|
|
900
|
+
function retryable(error) {
|
|
901
|
+
if (error instanceof RetryableDownloadError) return true;
|
|
902
|
+
if (!(error instanceof Error)) return false;
|
|
903
|
+
const code = error.code;
|
|
904
|
+
return error.name === "AbortError" || error.name === "TimeoutError" || error instanceof TypeError && /fetch|terminated/iu.test(error.message) || Boolean(code && /^(?:ECONNRESET|ETIMEDOUT|EPIPE|ENETUNREACH|EAI_AGAIN|ERR_STREAM_PREMATURE_CLOSE|UND_ERR_.*)$/u.test(code));
|
|
905
|
+
}
|
|
906
|
+
async function digest(file) {
|
|
907
|
+
const hash = createHash("sha256");
|
|
908
|
+
for await (const chunk of createReadStream(file)) hash.update(chunk);
|
|
909
|
+
return hash.digest("hex");
|
|
910
|
+
}
|
|
911
|
+
async function downloadVerifiedArchive(identity, destination, report) {
|
|
912
|
+
const partial = `${destination}.part`;
|
|
913
|
+
const record = `${partial}.json`;
|
|
914
|
+
const discard = async () => {
|
|
915
|
+
await Promise.all([rm3(partial, { force: true }), rm3(record, { force: true })]);
|
|
916
|
+
};
|
|
917
|
+
const cached = await stat3(destination).catch(() => null);
|
|
918
|
+
if (cached?.size === identity.size && await trackUpdateStage("verify", report, () => digest(destination)) === identity.sha256) return;
|
|
919
|
+
await rm3(destination, { force: true });
|
|
920
|
+
const saved = await readJsonFile(record);
|
|
921
|
+
if (!saved || saved.url !== identity.url || saved.size !== identity.size || saved.sha256 !== identity.sha256) await discard();
|
|
922
|
+
const deadline = Date.now() + 3e5;
|
|
923
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
924
|
+
let response;
|
|
925
|
+
let metadata = await readJsonFile(record);
|
|
926
|
+
let offset = (await stat3(partial).catch(() => null))?.size ?? 0;
|
|
927
|
+
if (offset > identity.size) {
|
|
928
|
+
await discard();
|
|
929
|
+
offset = 0;
|
|
930
|
+
metadata = null;
|
|
931
|
+
}
|
|
932
|
+
try {
|
|
933
|
+
if (offset === identity.size) {
|
|
934
|
+
if (await trackUpdateStage("verify", report, () => digest(partial)) !== identity.sha256) throw new Error("Runtime checksum verification failed");
|
|
935
|
+
await rename3(partial, destination);
|
|
936
|
+
await rm3(record, { force: true });
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
const remaining = deadline - Date.now();
|
|
940
|
+
if (remaining <= 0) throw new RetryableDownloadError("Runtime download timed out");
|
|
941
|
+
response = await fetch(identity.url, {
|
|
942
|
+
headers: {
|
|
943
|
+
"User-Agent": `switchy-cli/${CLI_VERSION}`,
|
|
944
|
+
"Accept-Encoding": "identity",
|
|
945
|
+
...offset > 0 ? { Range: `bytes=${offset}-`, ...metadata?.validator ? { "If-Range": metadata.validator } : {} } : {}
|
|
946
|
+
},
|
|
947
|
+
redirect: "follow",
|
|
948
|
+
signal: AbortSignal.timeout(remaining)
|
|
949
|
+
});
|
|
950
|
+
const cancel = () => response?.body?.cancel().catch(() => {
|
|
951
|
+
});
|
|
952
|
+
if (response.status === 429 || response.status >= 500) {
|
|
953
|
+
await cancel();
|
|
954
|
+
const value = response.headers.get("retry-after");
|
|
955
|
+
const retryAfter = value === null ? 0 : /^\d+$/u.test(value) ? Number(value) * 1e3 : Date.parse(value) - Date.now();
|
|
956
|
+
throw new RetryableDownloadError(`Runtime download failed with ${response.status}`, Number.isFinite(retryAfter) ? Math.max(0, Math.min(3e4, retryAfter)) : 0);
|
|
957
|
+
}
|
|
958
|
+
if (response.status === 416 && offset > 0) {
|
|
959
|
+
await cancel();
|
|
960
|
+
await discard();
|
|
961
|
+
throw new RetryableDownloadError("Restarting an unavailable download range");
|
|
962
|
+
}
|
|
963
|
+
if (![200, 206].includes(response.status) || !response.body) {
|
|
964
|
+
await cancel();
|
|
965
|
+
throw new Error(`Runtime download failed with ${response.status}`);
|
|
966
|
+
}
|
|
967
|
+
if (response.status === 200) offset = 0;
|
|
968
|
+
const range = response.headers.get("content-range");
|
|
969
|
+
if (response.status === 206 && range !== `bytes ${offset}-${identity.size - 1}/${identity.size}`) {
|
|
970
|
+
await cancel();
|
|
971
|
+
throw new Error("Runtime download returned an invalid byte range");
|
|
972
|
+
}
|
|
973
|
+
const length = response.headers.get("content-length");
|
|
974
|
+
if (length !== null && Number(length) !== identity.size - offset) {
|
|
975
|
+
await cancel();
|
|
976
|
+
throw new Error("Runtime download size does not match the release manifest");
|
|
977
|
+
}
|
|
978
|
+
const etag = response.headers.get("etag");
|
|
979
|
+
const validator = etag && !etag.startsWith("W/") ? etag : response.headers.get("last-modified") ?? void 0;
|
|
980
|
+
await writeJsonFileAtomic(record, { ...identity, validator });
|
|
981
|
+
const hash = createHash("sha256");
|
|
982
|
+
if (offset > 0) for await (const chunk of createReadStream(partial)) hash.update(chunk);
|
|
983
|
+
let downloaded = offset;
|
|
984
|
+
let lastReported = 0;
|
|
985
|
+
await report?.({ stage: "download", completedBytes: downloaded, totalBytes: identity.size });
|
|
986
|
+
const meter = new Transform({
|
|
987
|
+
transform(chunk, _encoding, callback) {
|
|
988
|
+
downloaded += chunk.length;
|
|
989
|
+
if (downloaded > identity.size) {
|
|
990
|
+
callback(new Error("Runtime download exceeded its declared size"));
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
hash.update(chunk);
|
|
994
|
+
if (report && Date.now() - lastReported >= 1e3) {
|
|
995
|
+
lastReported = Date.now();
|
|
996
|
+
report({ stage: "download", completedBytes: downloaded, totalBytes: identity.size }).then(() => callback(null, chunk), callback);
|
|
997
|
+
} else callback(null, chunk);
|
|
998
|
+
}
|
|
999
|
+
});
|
|
1000
|
+
await pipeline(
|
|
1001
|
+
Readable.fromWeb(response.body),
|
|
1002
|
+
meter,
|
|
1003
|
+
createWriteStream(partial, { flags: offset > 0 ? "a" : "w", mode: 384 })
|
|
1004
|
+
);
|
|
1005
|
+
if (downloaded !== identity.size) throw new RetryableDownloadError("Runtime download was interrupted");
|
|
1006
|
+
await trackUpdateStage("verify", report, async () => {
|
|
1007
|
+
if (hash.digest("hex") !== identity.sha256) throw new Error("Runtime checksum verification failed");
|
|
1008
|
+
});
|
|
1009
|
+
await rename3(partial, destination);
|
|
1010
|
+
await rm3(record, { force: true });
|
|
1011
|
+
return;
|
|
1012
|
+
} catch (error) {
|
|
1013
|
+
await response?.body?.cancel().catch(() => {
|
|
1014
|
+
});
|
|
1015
|
+
if (!retryable(error)) {
|
|
1016
|
+
await discard();
|
|
1017
|
+
throw error;
|
|
1018
|
+
}
|
|
1019
|
+
const backoff = error instanceof RetryableDownloadError ? error.retryAfter : 0;
|
|
1020
|
+
const wait = Math.max(backoff, 250 * 2 ** attempt + Math.random() * 100);
|
|
1021
|
+
if (attempt === 2 || Date.now() + wait >= deadline) throw error;
|
|
1022
|
+
await delay(wait);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// src/release.ts
|
|
1028
|
+
init_config();
|
|
1029
|
+
init_files();
|
|
1030
|
+
|
|
864
1031
|
// src/platform.ts
|
|
865
1032
|
var SUPPORTED_TARGETS = [
|
|
866
1033
|
"darwin-arm64",
|
|
@@ -959,47 +1126,6 @@ async function resolveLatestStableVersion() {
|
|
|
959
1126
|
}
|
|
960
1127
|
return tagName.slice(1);
|
|
961
1128
|
}
|
|
962
|
-
async function sha256(filePath) {
|
|
963
|
-
const hash = createHash("sha256");
|
|
964
|
-
for await (const chunk of createReadStream(filePath)) {
|
|
965
|
-
hash.update(chunk);
|
|
966
|
-
}
|
|
967
|
-
return hash.digest("hex");
|
|
968
|
-
}
|
|
969
|
-
async function downloadFile(url, destination, expectedSize) {
|
|
970
|
-
const response = await fetch(url, {
|
|
971
|
-
headers: { "User-Agent": `switchy-cli/${CLI_VERSION}` },
|
|
972
|
-
redirect: "follow",
|
|
973
|
-
signal: AbortSignal.timeout(3e5)
|
|
974
|
-
});
|
|
975
|
-
if (!response.ok || !response.body) {
|
|
976
|
-
throw new Error(`Runtime download failed with ${response.status}`);
|
|
977
|
-
}
|
|
978
|
-
const contentLengthHeader = response.headers.get("content-length");
|
|
979
|
-
const contentLength = Number(contentLengthHeader);
|
|
980
|
-
if (contentLengthHeader !== null && Number.isFinite(contentLength) && contentLength !== expectedSize) {
|
|
981
|
-
throw new Error("Runtime download size does not match the release manifest");
|
|
982
|
-
}
|
|
983
|
-
let downloadedSize = 0;
|
|
984
|
-
const sizeLimit = new Transform({
|
|
985
|
-
transform(chunk, _encoding, callback) {
|
|
986
|
-
downloadedSize += chunk.length;
|
|
987
|
-
if (downloadedSize > expectedSize) {
|
|
988
|
-
callback(new Error("Runtime download exceeded its declared size"));
|
|
989
|
-
return;
|
|
990
|
-
}
|
|
991
|
-
callback(null, chunk);
|
|
992
|
-
}
|
|
993
|
-
});
|
|
994
|
-
await pipeline(
|
|
995
|
-
Readable.fromWeb(response.body),
|
|
996
|
-
sizeLimit,
|
|
997
|
-
createWriteStream(destination, { mode: 384 })
|
|
998
|
-
);
|
|
999
|
-
if (downloadedSize !== expectedSize) {
|
|
1000
|
-
throw new Error("Runtime download size does not match the release manifest");
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
1129
|
async function validateRuntimeDirectory(runtimeDirectory, version, target) {
|
|
1004
1130
|
const platformFiles = notificationRuntimeFiles(target);
|
|
1005
1131
|
for (const relativePath of [
|
|
@@ -1009,13 +1135,13 @@ async function validateRuntimeDirectory(runtimeDirectory, version, target) {
|
|
|
1009
1135
|
"switchy-runtime.json",
|
|
1010
1136
|
...platformFiles
|
|
1011
1137
|
]) {
|
|
1012
|
-
const fileStats = await
|
|
1138
|
+
const fileStats = await stat4(path8.join(runtimeDirectory, relativePath)).catch(() => null);
|
|
1013
1139
|
if (!fileStats?.isFile()) {
|
|
1014
1140
|
throw new Error(`Runtime is missing ${relativePath}`);
|
|
1015
1141
|
}
|
|
1016
1142
|
}
|
|
1017
1143
|
if (platformFiles.length > 0) {
|
|
1018
|
-
const helper = await
|
|
1144
|
+
const helper = await stat4(path8.join(runtimeDirectory, MACOS_NOTIFIER_EXECUTABLE));
|
|
1019
1145
|
if ((helper.mode & 73) === 0) {
|
|
1020
1146
|
throw new Error("Runtime native notification helper is not executable");
|
|
1021
1147
|
}
|
|
@@ -1035,16 +1161,16 @@ async function validateRuntimeDirectory(runtimeDirectory, version, target) {
|
|
|
1035
1161
|
throw new Error("Runtime metadata does not match this installation");
|
|
1036
1162
|
}
|
|
1037
1163
|
}
|
|
1038
|
-
async function installRuntimeUnlocked(version, paths) {
|
|
1164
|
+
async function installRuntimeUnlocked(version, paths, report) {
|
|
1039
1165
|
assertStableVersion(version);
|
|
1040
1166
|
const target = currentTarget();
|
|
1041
1167
|
const versionDirectory = path8.join(paths.versions, version);
|
|
1042
|
-
if ((await
|
|
1168
|
+
if ((await stat4(versionDirectory).catch(() => null))?.isDirectory()) {
|
|
1043
1169
|
try {
|
|
1044
1170
|
await validateRuntimeDirectory(versionDirectory, version, target);
|
|
1045
1171
|
return versionDirectory;
|
|
1046
1172
|
} catch {
|
|
1047
|
-
await
|
|
1173
|
+
await rm4(versionDirectory, { recursive: true, force: true });
|
|
1048
1174
|
}
|
|
1049
1175
|
}
|
|
1050
1176
|
const localRuntime = process.env.SWITCHY_RUNTIME_SOURCE?.trim();
|
|
@@ -1052,7 +1178,7 @@ async function installRuntimeUnlocked(version, paths) {
|
|
|
1052
1178
|
paths.app,
|
|
1053
1179
|
`.install-${version}-${randomUUID5()}`
|
|
1054
1180
|
);
|
|
1055
|
-
await
|
|
1181
|
+
await rm4(temporaryDirectory, { recursive: true, force: true });
|
|
1056
1182
|
await mkdir3(temporaryDirectory, { recursive: true, mode: 448 });
|
|
1057
1183
|
try {
|
|
1058
1184
|
if (localRuntime) {
|
|
@@ -1068,40 +1194,29 @@ async function installRuntimeUnlocked(version, paths) {
|
|
|
1068
1194
|
}
|
|
1069
1195
|
const archivePath = path8.join(paths.downloads, artifact.file);
|
|
1070
1196
|
const artifactUrl = new URL(artifact.file, manifestUrl).toString();
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
} catch (error) {
|
|
1078
|
-
await rm3(archivePath, { force: true });
|
|
1079
|
-
throw error;
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
const downloadedArchive = await stat3(archivePath).catch(() => null);
|
|
1083
|
-
if (downloadedArchive?.size !== artifact.size || await sha256(archivePath) !== artifact.sha256) {
|
|
1084
|
-
await rm3(archivePath, { force: true });
|
|
1085
|
-
throw new Error("Runtime checksum verification failed");
|
|
1086
|
-
}
|
|
1087
|
-
await extract({
|
|
1197
|
+
await trackUpdateStage("download", report, () => downloadVerifiedArchive({
|
|
1198
|
+
url: artifactUrl,
|
|
1199
|
+
size: artifact.size,
|
|
1200
|
+
sha256: artifact.sha256
|
|
1201
|
+
}, archivePath, report));
|
|
1202
|
+
await trackUpdateStage("extract", report, () => extract({
|
|
1088
1203
|
cwd: temporaryDirectory,
|
|
1089
1204
|
file: archivePath,
|
|
1090
1205
|
preservePaths: false,
|
|
1091
1206
|
strict: true
|
|
1092
|
-
});
|
|
1207
|
+
}));
|
|
1093
1208
|
}
|
|
1094
1209
|
await validateRuntimeDirectory(temporaryDirectory, version, target);
|
|
1095
|
-
await
|
|
1210
|
+
await rename4(temporaryDirectory, versionDirectory);
|
|
1096
1211
|
return versionDirectory;
|
|
1097
1212
|
} catch (error) {
|
|
1098
|
-
await
|
|
1213
|
+
await rm4(temporaryDirectory, { recursive: true, force: true });
|
|
1099
1214
|
throw error;
|
|
1100
1215
|
}
|
|
1101
1216
|
}
|
|
1102
|
-
async function installRuntime(version, paths) {
|
|
1217
|
+
async function installRuntime(version, paths, report) {
|
|
1103
1218
|
return withDirectoryLock(paths.installLock, async () => {
|
|
1104
|
-
return installRuntimeUnlocked(version, paths);
|
|
1219
|
+
return installRuntimeUnlocked(version, paths, report);
|
|
1105
1220
|
});
|
|
1106
1221
|
}
|
|
1107
1222
|
async function setCurrentVersion(paths, version, previousVersion) {
|
|
@@ -1116,14 +1231,15 @@ async function setCurrentVersion(paths, version, previousVersion) {
|
|
|
1116
1231
|
}
|
|
1117
1232
|
|
|
1118
1233
|
// src/updater.ts
|
|
1119
|
-
import {
|
|
1234
|
+
import { constants as constants2 } from "node:fs";
|
|
1235
|
+
import { cp as cp3, readdir as readdir5, rename as rename5, rm as rm6, stat as stat7 } from "node:fs/promises";
|
|
1120
1236
|
import path11 from "node:path";
|
|
1121
1237
|
|
|
1122
1238
|
// src/cleanup.ts
|
|
1123
|
-
import { readdir as readdir3, rm as
|
|
1239
|
+
import { readdir as readdir3, rm as rm5, stat as stat5 } from "node:fs/promises";
|
|
1124
1240
|
import path9 from "node:path";
|
|
1125
1241
|
var STABLE_VERSION_PATTERN2 = /^\d+\.\d+\.\d+$/u;
|
|
1126
|
-
var DOWNLOAD_ARCHIVE_PATTERN = /^switchy-(\d+\.\d+\.\d+)-(?:darwin|linux|win32)-(?:arm64|x64)\.tar\.gz
|
|
1242
|
+
var DOWNLOAD_ARCHIVE_PATTERN = /^switchy-(\d+\.\d+\.\d+)-(?:darwin|linux|win32)-(?:arm64|x64)\.tar\.gz(?:\.part(?:\.json)?)?$/u;
|
|
1127
1243
|
var INSTALL_DIRECTORY_PREFIX = ".install-";
|
|
1128
1244
|
var UPDATE_SNAPSHOT_PREFIX = "update-";
|
|
1129
1245
|
var RETAINED_UPDATE_SNAPSHOTS = 3;
|
|
@@ -1144,7 +1260,7 @@ async function pruneInstallArtifacts(paths, retainedVersions) {
|
|
|
1144
1260
|
if (!entry.isDirectory() || !STABLE_VERSION_PATTERN2.test(entry.name) || retained.has(entry.name)) {
|
|
1145
1261
|
continue;
|
|
1146
1262
|
}
|
|
1147
|
-
await
|
|
1263
|
+
await rm5(path9.join(paths.versions, entry.name), {
|
|
1148
1264
|
recursive: true,
|
|
1149
1265
|
force: true
|
|
1150
1266
|
});
|
|
@@ -1152,13 +1268,13 @@ async function pruneInstallArtifacts(paths, retainedVersions) {
|
|
|
1152
1268
|
}
|
|
1153
1269
|
for (const entry of await listEntries(paths.app)) {
|
|
1154
1270
|
if (entry.isDirectory() && entry.name.startsWith(INSTALL_DIRECTORY_PREFIX)) {
|
|
1155
|
-
await
|
|
1271
|
+
await rm5(path9.join(paths.app, entry.name), { recursive: true, force: true });
|
|
1156
1272
|
}
|
|
1157
1273
|
}
|
|
1158
1274
|
for (const entry of await listEntries(paths.downloads)) {
|
|
1159
1275
|
const version = DOWNLOAD_ARCHIVE_PATTERN.exec(entry.name)?.[1];
|
|
1160
1276
|
if (!entry.isFile() || !version || retained.has(version)) continue;
|
|
1161
|
-
await
|
|
1277
|
+
await rm5(path9.join(paths.downloads, entry.name), { force: true });
|
|
1162
1278
|
result.downloads.push(entry.name);
|
|
1163
1279
|
}
|
|
1164
1280
|
const snapshots = await Promise.all(
|
|
@@ -1166,12 +1282,12 @@ async function pruneInstallArtifacts(paths, retainedVersions) {
|
|
|
1166
1282
|
(entry) => entry.isDirectory() && entry.name.startsWith(UPDATE_SNAPSHOT_PREFIX)
|
|
1167
1283
|
).map(async (entry) => ({
|
|
1168
1284
|
name: entry.name,
|
|
1169
|
-
modifiedAt: (await
|
|
1285
|
+
modifiedAt: (await stat5(path9.join(paths.updateSnapshots, entry.name))).mtimeMs
|
|
1170
1286
|
}))
|
|
1171
1287
|
);
|
|
1172
1288
|
snapshots.sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
1173
1289
|
for (const snapshot of snapshots.slice(RETAINED_UPDATE_SNAPSHOTS)) {
|
|
1174
|
-
await
|
|
1290
|
+
await rm5(path9.join(paths.updateSnapshots, snapshot.name), {
|
|
1175
1291
|
recursive: true,
|
|
1176
1292
|
force: true
|
|
1177
1293
|
});
|
|
@@ -1189,7 +1305,8 @@ init_process_manager();
|
|
|
1189
1305
|
init_lifecycle_state2();
|
|
1190
1306
|
init_files();
|
|
1191
1307
|
import { spawn as spawn2 } from "node:child_process";
|
|
1192
|
-
import {
|
|
1308
|
+
import { constants } from "node:fs";
|
|
1309
|
+
import { cp as cp2, mkdir as mkdir4, open as open4, readdir as readdir4, stat as stat6 } from "node:fs/promises";
|
|
1193
1310
|
import path10 from "node:path";
|
|
1194
1311
|
async function run(executable, args, options) {
|
|
1195
1312
|
await new Promise((resolve, reject) => {
|
|
@@ -1235,10 +1352,13 @@ async function ensurePlaywrightBrowser(runtimeDirectory, paths) {
|
|
|
1235
1352
|
"playwright",
|
|
1236
1353
|
"cli.js"
|
|
1237
1354
|
);
|
|
1238
|
-
if (!(await
|
|
1355
|
+
if (!(await stat6(cliPath).catch(() => null))?.isFile()) {
|
|
1239
1356
|
throw new Error("The packaged runtime is missing the Playwright installer");
|
|
1240
1357
|
}
|
|
1241
|
-
await
|
|
1358
|
+
const metadata = await readJsonFile(path10.join(runtimeDirectory, "switchy-runtime.json"));
|
|
1359
|
+
const args = [cliPath, "install", "chromium"];
|
|
1360
|
+
if (metadata?.browserMode === "headless-shell") args.push("--only-shell");
|
|
1361
|
+
await run(process.execPath, args, {
|
|
1242
1362
|
cwd: runtimeDirectory,
|
|
1243
1363
|
env: {
|
|
1244
1364
|
...process.env,
|
|
@@ -1262,7 +1382,7 @@ async function runDatabaseMigration(runtimeDirectory, paths) {
|
|
|
1262
1382
|
);
|
|
1263
1383
|
}
|
|
1264
1384
|
async function createUpdateSnapshot(paths, fromVersion, toVersion) {
|
|
1265
|
-
if (!(await
|
|
1385
|
+
if (!(await stat6(paths.productionData).catch(() => null))?.isDirectory()) {
|
|
1266
1386
|
return null;
|
|
1267
1387
|
}
|
|
1268
1388
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/gu, "-");
|
|
@@ -1272,7 +1392,8 @@ async function createUpdateSnapshot(paths, fromVersion, toVersion) {
|
|
|
1272
1392
|
);
|
|
1273
1393
|
await mkdir4(snapshotDirectory, { recursive: true, mode: 448 });
|
|
1274
1394
|
await cp2(paths.productionData, path10.join(snapshotDirectory, "production"), {
|
|
1275
|
-
recursive: true
|
|
1395
|
+
recursive: true,
|
|
1396
|
+
mode: constants.COPYFILE_FICLONE
|
|
1276
1397
|
});
|
|
1277
1398
|
await syncTree(path10.join(snapshotDirectory, "production"));
|
|
1278
1399
|
await writeJsonFileAtomic(path10.join(snapshotDirectory, "update.json"), {
|
|
@@ -1329,9 +1450,9 @@ async function browsersAreOpen(paths) {
|
|
|
1329
1450
|
});
|
|
1330
1451
|
for (const file of files) {
|
|
1331
1452
|
const filePath = path11.join(directory, file);
|
|
1332
|
-
const info = await
|
|
1453
|
+
const info = await stat7(filePath).catch(() => null);
|
|
1333
1454
|
if (info && Date.now() - info.mtimeMs < 9e4) return true;
|
|
1334
|
-
await
|
|
1455
|
+
await rm6(filePath, { force: true });
|
|
1335
1456
|
}
|
|
1336
1457
|
return false;
|
|
1337
1458
|
}
|
|
@@ -1360,17 +1481,17 @@ async function restoreSnapshot(paths, transaction) {
|
|
|
1360
1481
|
const snapshot = path11.resolve(transaction.snapshot);
|
|
1361
1482
|
if (path11.dirname(snapshot) !== expected) throw new Error("Invalid update recovery snapshot path");
|
|
1362
1483
|
const original = path11.join(snapshot, "production");
|
|
1363
|
-
if (!(await
|
|
1484
|
+
if (!(await stat7(original)).isDirectory()) throw new Error("Update recovery snapshot is missing");
|
|
1364
1485
|
const staging = path11.join(paths.data, ".update-restore");
|
|
1365
1486
|
const failed = path11.join(paths.data, ".update-failed");
|
|
1366
|
-
await
|
|
1367
|
-
await cp3(original, staging, { recursive: true });
|
|
1487
|
+
await rm6(staging, { recursive: true, force: true });
|
|
1488
|
+
await cp3(original, staging, { recursive: true, mode: constants2.COPYFILE_FICLONE });
|
|
1368
1489
|
await syncTree(staging);
|
|
1369
|
-
await
|
|
1370
|
-
if (await
|
|
1371
|
-
await
|
|
1490
|
+
await rm6(failed, { recursive: true, force: true });
|
|
1491
|
+
if (await stat7(paths.productionData).catch(() => null)) await rename5(paths.productionData, failed);
|
|
1492
|
+
await rename5(staging, paths.productionData);
|
|
1372
1493
|
await syncDirectory(paths.data);
|
|
1373
|
-
await
|
|
1494
|
+
await rm6(failed, { recursive: true, force: true });
|
|
1374
1495
|
}
|
|
1375
1496
|
async function recoverInterruptedUpdate(paths) {
|
|
1376
1497
|
return withDirectoryLock(path11.join(paths.runtime, "migration.lock"), () => recoverUpdate(paths));
|
|
@@ -1396,7 +1517,7 @@ async function recoverUpdate(paths) {
|
|
|
1396
1517
|
await assertNoOtherRuntimes(paths);
|
|
1397
1518
|
if (transaction.stage === "snapshot" || transaction.stage === "starting") {
|
|
1398
1519
|
if (transaction.snapshot) await restoreSnapshot(paths, transaction);
|
|
1399
|
-
else if (transaction.hadData === false) await
|
|
1520
|
+
else if (transaction.hadData === false) await rm6(paths.productionData, { recursive: true, force: true });
|
|
1400
1521
|
else throw new Error("Update recovery snapshot is missing");
|
|
1401
1522
|
}
|
|
1402
1523
|
if (transaction.fromVersion) await setCurrentVersion(paths, transaction.fromVersion, transaction.previousVersion ?? null);
|
|
@@ -1415,16 +1536,17 @@ async function downloadUpdate(paths, version) {
|
|
|
1415
1536
|
}
|
|
1416
1537
|
async function prepareUpdate(paths, version) {
|
|
1417
1538
|
const staged = (await readUpdateState(paths)).downloadedVersion === version;
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1539
|
+
const report = updateProgressReporter(paths);
|
|
1540
|
+
if (!staged) await saveUpdateState2(paths, { phase: "downloading", message: null, progress: null, timings: {} });
|
|
1541
|
+
const directory = await installRuntime(version, paths, report);
|
|
1542
|
+
if (!(await stat7(path11.join(directory, "bin/lifecycle.cjs")).catch(() => null))?.isFile()) {
|
|
1421
1543
|
throw new Error("The candidate runtime is missing lifecycle support");
|
|
1422
1544
|
}
|
|
1423
1545
|
const metadata = await readJsonFile(path11.join(directory, "switchy-runtime.json"));
|
|
1424
1546
|
if (metadata?.lifecycleProtocol !== 2) throw new Error("This release does not support safe managed updates. Choose a current release.");
|
|
1425
1547
|
if (!staged) {
|
|
1426
|
-
await ensurePlaywrightBrowser(directory, paths);
|
|
1427
|
-
await saveUpdateState2(paths, { phase: "ready", downloadedVersion: version, message: null });
|
|
1548
|
+
await trackUpdateStage("browser", report, () => ensurePlaywrightBrowser(directory, paths));
|
|
1549
|
+
await saveUpdateState2(paths, { phase: "ready", downloadedVersion: version, message: null, progress: null });
|
|
1428
1550
|
}
|
|
1429
1551
|
return directory;
|
|
1430
1552
|
}
|
|
@@ -1433,11 +1555,12 @@ async function installUpdate(paths, version, manual, options = {}) {
|
|
|
1433
1555
|
const current = await readJsonFile(paths.currentVersion);
|
|
1434
1556
|
if (current && compareVersions(version, current.version) <= 0) return false;
|
|
1435
1557
|
const preferences = await readPreferences(paths);
|
|
1558
|
+
if (!manual && !preferences.automaticUpdates) return false;
|
|
1559
|
+
const directory = await prepareUpdate(paths, version);
|
|
1436
1560
|
if (!await applicationIsIdle(paths) || !manual && await browsersAreOpen(paths)) {
|
|
1437
1561
|
await saveUpdateState2(paths, { phase: "waiting", message: "Waiting for active work to finish and Switchy tabs to close." });
|
|
1438
1562
|
return false;
|
|
1439
1563
|
}
|
|
1440
|
-
const directory = await prepareUpdate(paths, version);
|
|
1441
1564
|
return withDirectoryLock(paths.startLock, async () => {
|
|
1442
1565
|
await recoverInterruptedUpdate(paths);
|
|
1443
1566
|
const selected = await readJsonFile(paths.currentVersion);
|
|
@@ -1450,6 +1573,7 @@ async function installUpdate(paths, version, manual, options = {}) {
|
|
|
1450
1573
|
}
|
|
1451
1574
|
async function activateRuntime(paths, directory, version, current, options) {
|
|
1452
1575
|
const files = lifecycleFiles(paths);
|
|
1576
|
+
const report = updateProgressReporter(paths);
|
|
1453
1577
|
await writeJsonFileAtomic(files.maintenance, { startedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
1454
1578
|
try {
|
|
1455
1579
|
if (!await applicationIsIdle(paths)) {
|
|
@@ -1462,7 +1586,7 @@ async function activateRuntime(paths, directory, version, current, options) {
|
|
|
1462
1586
|
toVersion: version,
|
|
1463
1587
|
snapshot: null,
|
|
1464
1588
|
previousVersion: current?.previousVersion ?? null,
|
|
1465
|
-
hadData: (await
|
|
1589
|
+
hadData: (await stat7(paths.productionData).catch(() => null))?.isDirectory() ?? false,
|
|
1466
1590
|
port: options.port ?? running?.record.port ?? (await readPreferences(paths)).port,
|
|
1467
1591
|
stage: "prepared"
|
|
1468
1592
|
};
|
|
@@ -1473,22 +1597,22 @@ async function activateRuntime(paths, directory, version, current, options) {
|
|
|
1473
1597
|
transaction.stage = "stopped";
|
|
1474
1598
|
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1475
1599
|
if (transaction.hadData) {
|
|
1476
|
-
transaction.snapshot = await createUpdateSnapshot(paths, current?.version ?? "unmanaged", version);
|
|
1600
|
+
transaction.snapshot = await trackUpdateStage("snapshot", report, () => createUpdateSnapshot(paths, current?.version ?? "unmanaged", version));
|
|
1477
1601
|
if (!transaction.snapshot) throw new Error("Cannot update without a recovery snapshot");
|
|
1478
1602
|
}
|
|
1479
1603
|
transaction.stage = "snapshot";
|
|
1480
1604
|
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1481
|
-
await runDatabaseMigration(directory, paths);
|
|
1605
|
+
await trackUpdateStage("migrate", report, () => runDatabaseMigration(directory, paths));
|
|
1482
1606
|
transaction.stage = "starting";
|
|
1483
1607
|
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1484
|
-
await startSwitchyProcess({
|
|
1608
|
+
await trackUpdateStage("start", report, () => startSwitchyProcess({
|
|
1485
1609
|
paths,
|
|
1486
1610
|
runtimeDirectory: directory,
|
|
1487
1611
|
version,
|
|
1488
1612
|
port: transaction.port,
|
|
1489
1613
|
foreground: options.foreground ?? false,
|
|
1490
1614
|
candidate: true
|
|
1491
|
-
});
|
|
1615
|
+
}));
|
|
1492
1616
|
const live = await getRunningProcess(paths);
|
|
1493
1617
|
const identity = live && await fetchLiveness(live.record);
|
|
1494
1618
|
if (!identity || identity.version !== version || identity.instanceId !== live?.record.instanceId) {
|
|
@@ -1498,11 +1622,13 @@ async function activateRuntime(paths, directory, version, current, options) {
|
|
|
1498
1622
|
await setRunningPreference(paths, !options.foreground, transaction.port);
|
|
1499
1623
|
transaction.stage = "committed";
|
|
1500
1624
|
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1501
|
-
await saveUpdateState2(paths, { phase: "idle", failedVersion: null, downloadedVersion: null, message: null });
|
|
1625
|
+
await saveUpdateState2(paths, { phase: "idle", failedVersion: null, downloadedVersion: null, message: null, progress: null });
|
|
1502
1626
|
await removeFile(files.transaction);
|
|
1503
|
-
await
|
|
1627
|
+
await removeFile(files.maintenance);
|
|
1628
|
+
await trackUpdateStage("cleanup", report, () => pruneInstallArtifacts(paths, [version, current?.version ?? null])).catch((error) => {
|
|
1504
1629
|
console.warn("Could not prune old update artifacts:", error);
|
|
1505
1630
|
});
|
|
1631
|
+
await saveUpdateState2(paths, { progress: null });
|
|
1506
1632
|
return true;
|
|
1507
1633
|
} catch (error) {
|
|
1508
1634
|
await recoverInterruptedUpdate(paths);
|
|
@@ -1616,7 +1742,7 @@ import { mkdir as mkdir7 } from "node:fs/promises";
|
|
|
1616
1742
|
|
|
1617
1743
|
// src/lifecycle-manager.ts
|
|
1618
1744
|
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
1619
|
-
import { readdir as readdir6, rename as
|
|
1745
|
+
import { readdir as readdir6, rename as rename7 } from "node:fs/promises";
|
|
1620
1746
|
import path15 from "node:path";
|
|
1621
1747
|
init_files();
|
|
1622
1748
|
init_lifecycle_state2();
|
|
@@ -1629,7 +1755,7 @@ init_startup_environment();
|
|
|
1629
1755
|
init_lifecycle_state2();
|
|
1630
1756
|
import { execFile, spawn as spawn3 } from "node:child_process";
|
|
1631
1757
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
1632
|
-
import { chmod, copyFile, link, mkdir as mkdir6, open as open5, readFile as readFile4, rename as
|
|
1758
|
+
import { chmod, copyFile, link, mkdir as mkdir6, open as open5, readFile as readFile4, rename as rename6, rm as rm7, stat as stat8 } from "node:fs/promises";
|
|
1633
1759
|
import os4 from "node:os";
|
|
1634
1760
|
import path14 from "node:path";
|
|
1635
1761
|
import { promisify } from "node:util";
|
|
@@ -1693,7 +1819,7 @@ async function hostNode(paths) {
|
|
|
1693
1819
|
return metadata;
|
|
1694
1820
|
}
|
|
1695
1821
|
async function installHost(paths, runtimeDirectory) {
|
|
1696
|
-
if (!(await
|
|
1822
|
+
if (!(await stat8(path14.join(runtimeDirectory, "bin/lifecycle.cjs")).catch(() => null))?.isFile()) return false;
|
|
1697
1823
|
return withDirectoryLock(lifecycleFiles(paths).hostLock, async () => {
|
|
1698
1824
|
const host = lifecycleFiles(paths).host;
|
|
1699
1825
|
await mkdir6(host, { recursive: true, mode: 448 });
|
|
@@ -1701,7 +1827,7 @@ async function installHost(paths, runtimeDirectory) {
|
|
|
1701
1827
|
const version = previous && compareVersions(previous.version, process.versions.node) > 0 ? previous.version : process.versions.node;
|
|
1702
1828
|
const file = `node-${version}${process.platform === "win32" ? ".exe" : ""}`;
|
|
1703
1829
|
const node = path14.join(host, file);
|
|
1704
|
-
if (!(await
|
|
1830
|
+
if (!(await stat8(node).catch(() => null))?.isFile()) {
|
|
1705
1831
|
if (version !== process.versions.node) throw new Error("The managed Node executable is missing. Start with the newer Node 24 version to restore it.");
|
|
1706
1832
|
const temporary = `${node}.${randomUUID6()}.tmp`;
|
|
1707
1833
|
try {
|
|
@@ -1713,21 +1839,21 @@ async function installHost(paths, runtimeDirectory) {
|
|
|
1713
1839
|
} finally {
|
|
1714
1840
|
await handle.close();
|
|
1715
1841
|
}
|
|
1716
|
-
await
|
|
1842
|
+
await rename6(temporary, node);
|
|
1717
1843
|
} finally {
|
|
1718
|
-
await
|
|
1844
|
+
await rm7(temporary, { force: true });
|
|
1719
1845
|
}
|
|
1720
1846
|
}
|
|
1721
1847
|
const alias = path14.join(host, process.platform === "win32" ? "node.exe" : "node");
|
|
1722
|
-
if (previous?.file !== file || !await
|
|
1848
|
+
if (previous?.file !== file || !await stat8(alias).catch(() => null)) {
|
|
1723
1849
|
const temporary = `${alias}.${randomUUID6()}.tmp`;
|
|
1724
1850
|
try {
|
|
1725
1851
|
await link(node, temporary);
|
|
1726
|
-
await
|
|
1852
|
+
await rename6(temporary, alias);
|
|
1727
1853
|
} catch (error) {
|
|
1728
|
-
if (!["EPERM", "EBUSY", "EACCES"].includes(error.code ?? "") || !await
|
|
1854
|
+
if (!["EPERM", "EBUSY", "EACCES"].includes(error.code ?? "") || !await stat8(alias).catch(() => null)) throw error;
|
|
1729
1855
|
} finally {
|
|
1730
|
-
await
|
|
1856
|
+
await rm7(temporary, { force: true });
|
|
1731
1857
|
}
|
|
1732
1858
|
}
|
|
1733
1859
|
await writeJsonFileAtomic(path14.join(host, "node.json"), { file, version });
|
|
@@ -1771,7 +1897,7 @@ async function setStartupRegistration(paths, enabled) {
|
|
|
1771
1897
|
const node = await hostNode(paths);
|
|
1772
1898
|
await writeFileAtomic(file, startupPlist(paths, path14.join(lifecycleFiles(paths).host, node.file)));
|
|
1773
1899
|
} else {
|
|
1774
|
-
await
|
|
1900
|
+
await rm7(file, { force: true });
|
|
1775
1901
|
const uid = process.getuid?.();
|
|
1776
1902
|
if (uid !== void 0) {
|
|
1777
1903
|
await execute("/bin/launchctl", ["disable", `gui/${uid}/${LABEL}`]).catch(() => void 0);
|
|
@@ -1866,7 +1992,7 @@ async function takeLegacyRequest(file) {
|
|
|
1866
1992
|
}
|
|
1867
1993
|
const claimed = `${file}.${randomUUID7()}.claimed`;
|
|
1868
1994
|
try {
|
|
1869
|
-
await
|
|
1995
|
+
await rename7(file, claimed);
|
|
1870
1996
|
} catch (error) {
|
|
1871
1997
|
if (error.code === "ENOENT") return null;
|
|
1872
1998
|
throw error;
|