@chandresh726/switchy 1.3.7 → 1.3.9
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/README.md +12 -2
- package/dist/cli.js +1652 -508
- package/dist/cli.js.map +4 -4
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,125 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
// src/cleanup.ts
|
|
8
|
-
import { readdir, rm, stat } from "node:fs/promises";
|
|
9
|
-
import path from "node:path";
|
|
10
|
-
var STABLE_VERSION_PATTERN = /^\d+\.\d+\.\d+$/u;
|
|
11
|
-
var DOWNLOAD_ARCHIVE_PATTERN = /^switchy-(\d+\.\d+\.\d+)-(?:darwin|linux|win32)-(?:arm64|x64)\.tar\.gz$/u;
|
|
12
|
-
var INSTALL_DIRECTORY_PREFIX = ".install-";
|
|
13
|
-
var UPDATE_SNAPSHOT_PREFIX = "update-";
|
|
14
|
-
var RETAINED_UPDATE_SNAPSHOTS = 3;
|
|
15
|
-
async function listEntries(directory) {
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res, err) => function __init() {
|
|
5
|
+
if (err) throw err[0];
|
|
16
6
|
try {
|
|
17
|
-
return
|
|
18
|
-
} catch (
|
|
19
|
-
|
|
20
|
-
throw error;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
async function pruneInstallArtifacts(paths, retainedVersions) {
|
|
24
|
-
const retained = new Set(
|
|
25
|
-
retainedVersions.filter((version) => Boolean(version))
|
|
26
|
-
);
|
|
27
|
-
const result = { versions: [], downloads: [], snapshots: [] };
|
|
28
|
-
for (const entry of await listEntries(paths.versions)) {
|
|
29
|
-
if (!entry.isDirectory() || !STABLE_VERSION_PATTERN.test(entry.name) || retained.has(entry.name)) {
|
|
30
|
-
continue;
|
|
31
|
-
}
|
|
32
|
-
await rm(path.join(paths.versions, entry.name), {
|
|
33
|
-
recursive: true,
|
|
34
|
-
force: true
|
|
35
|
-
});
|
|
36
|
-
result.versions.push(entry.name);
|
|
37
|
-
}
|
|
38
|
-
for (const entry of await listEntries(paths.app)) {
|
|
39
|
-
if (entry.isDirectory() && entry.name.startsWith(INSTALL_DIRECTORY_PREFIX)) {
|
|
40
|
-
await rm(path.join(paths.app, entry.name), { recursive: true, force: true });
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
for (const entry of await listEntries(paths.downloads)) {
|
|
44
|
-
const version = DOWNLOAD_ARCHIVE_PATTERN.exec(entry.name)?.[1];
|
|
45
|
-
if (!entry.isFile() || !version || retained.has(version)) continue;
|
|
46
|
-
await rm(path.join(paths.downloads, entry.name), { force: true });
|
|
47
|
-
result.downloads.push(entry.name);
|
|
7
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
|
+
} catch (e) {
|
|
9
|
+
throw err = [e], e;
|
|
48
10
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
modifiedAt: (await stat(path.join(paths.updateSnapshots, entry.name))).mtimeMs
|
|
55
|
-
}))
|
|
56
|
-
);
|
|
57
|
-
snapshots.sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
58
|
-
for (const snapshot of snapshots.slice(RETAINED_UPDATE_SNAPSHOTS)) {
|
|
59
|
-
await rm(path.join(paths.updateSnapshots, snapshot.name), {
|
|
60
|
-
recursive: true,
|
|
61
|
-
force: true
|
|
62
|
-
});
|
|
63
|
-
result.snapshots.push(snapshot.name);
|
|
64
|
-
}
|
|
65
|
-
return result;
|
|
66
|
-
}
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
67
16
|
|
|
68
17
|
// package.json
|
|
69
|
-
var package_default
|
|
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
|
-
|
|
18
|
+
var package_default;
|
|
19
|
+
var init_package = __esm({
|
|
20
|
+
"package.json"() {
|
|
21
|
+
package_default = {
|
|
22
|
+
name: "@chandresh726/switchy",
|
|
23
|
+
version: "1.3.9",
|
|
24
|
+
description: "Install, run, update, and stop the local-first Switchy application.",
|
|
25
|
+
license: "MIT",
|
|
26
|
+
type: "module",
|
|
27
|
+
bin: {
|
|
28
|
+
switchy: "dist/cli.js"
|
|
29
|
+
},
|
|
30
|
+
files: [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md"
|
|
33
|
+
],
|
|
34
|
+
engines: {
|
|
35
|
+
node: ">=24 <25"
|
|
36
|
+
},
|
|
37
|
+
repository: {
|
|
38
|
+
type: "git",
|
|
39
|
+
url: "git+https://github.com/Chandresh726/Switchy.git",
|
|
40
|
+
directory: "packages/cli"
|
|
41
|
+
},
|
|
42
|
+
homepage: "https://github.com/Chandresh726/Switchy#readme",
|
|
43
|
+
bugs: {
|
|
44
|
+
url: "https://github.com/Chandresh726/Switchy/issues"
|
|
45
|
+
},
|
|
46
|
+
publishConfig: {
|
|
47
|
+
access: "public"
|
|
48
|
+
},
|
|
49
|
+
scripts: {
|
|
50
|
+
build: "node scripts/build.mjs",
|
|
51
|
+
typecheck: "tsc --noEmit -p tsconfig.json",
|
|
52
|
+
prepack: "pnpm build"
|
|
53
|
+
},
|
|
54
|
+
dependencies: {
|
|
55
|
+
tar: "^7.5.22"
|
|
56
|
+
},
|
|
57
|
+
devDependencies: {
|
|
58
|
+
"@types/node": "^24.13.3",
|
|
59
|
+
esbuild: "^0.28.1",
|
|
60
|
+
typescript: "^5.9.3"
|
|
61
|
+
}
|
|
62
|
+
};
|
|
109
63
|
}
|
|
110
|
-
};
|
|
64
|
+
});
|
|
111
65
|
|
|
112
66
|
// src/config.ts
|
|
113
|
-
var CLI_VERSION = package_default.version;
|
|
114
|
-
var DEFAULT_PORT = 6767;
|
|
115
|
-
var DEFAULT_HOSTNAME = "127.0.0.1";
|
|
116
|
-
var GITHUB_REPOSITORY = "Chandresh726/Switchy";
|
|
117
|
-
var RELEASE_MANIFEST_FILE = "switchy-manifest.json";
|
|
118
|
-
var STARTUP_TIMEOUT_MS = 6e4;
|
|
119
|
-
var SHUTDOWN_TIMEOUT_MS = 15e3;
|
|
120
|
-
function resolveApplicationVersion(requestedVersion) {
|
|
121
|
-
return requestedVersion ?? CLI_VERSION;
|
|
122
|
-
}
|
|
123
67
|
function assertSupportedNodeVersion(nodeVersion = process.versions.node) {
|
|
124
68
|
if (!/^24\.\d+\.\d+$/u.test(nodeVersion)) {
|
|
125
69
|
throw new Error(
|
|
@@ -127,21 +71,71 @@ function assertSupportedNodeVersion(nodeVersion = process.versions.node) {
|
|
|
127
71
|
);
|
|
128
72
|
}
|
|
129
73
|
}
|
|
74
|
+
var CLI_VERSION, DEFAULT_PORT, DEFAULT_HOSTNAME, GITHUB_REPOSITORY, RELEASE_MANIFEST_FILE, STARTUP_TIMEOUT_MS, SHUTDOWN_TIMEOUT_MS;
|
|
75
|
+
var init_config = __esm({
|
|
76
|
+
"src/config.ts"() {
|
|
77
|
+
"use strict";
|
|
78
|
+
init_package();
|
|
79
|
+
CLI_VERSION = package_default.version;
|
|
80
|
+
DEFAULT_PORT = 6767;
|
|
81
|
+
DEFAULT_HOSTNAME = "127.0.0.1";
|
|
82
|
+
GITHUB_REPOSITORY = "Chandresh726/Switchy";
|
|
83
|
+
RELEASE_MANIFEST_FILE = "switchy-manifest.json";
|
|
84
|
+
STARTUP_TIMEOUT_MS = 6e4;
|
|
85
|
+
SHUTDOWN_TIMEOUT_MS = 15e3;
|
|
86
|
+
}
|
|
87
|
+
});
|
|
130
88
|
|
|
131
|
-
//
|
|
89
|
+
// ../../lib/runtime/atomic-file.ts
|
|
132
90
|
import { randomUUID } from "node:crypto";
|
|
133
|
-
import {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
91
|
+
import { open, readFile, rename, rm } from "node:fs/promises";
|
|
92
|
+
import path from "node:path";
|
|
93
|
+
async function readJsonFile(filePath) {
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(await readFile(filePath, "utf8"));
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error.code === "ENOENT") return null;
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async function syncDirectory(directory) {
|
|
102
|
+
if (process.platform === "win32") return;
|
|
103
|
+
const handle = await open(directory, "r");
|
|
104
|
+
try {
|
|
105
|
+
await handle.sync();
|
|
106
|
+
} finally {
|
|
107
|
+
await handle.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function writeFileAtomic(filePath, contents) {
|
|
111
|
+
const directory = path.dirname(filePath);
|
|
112
|
+
const temporaryPath = path.join(directory, `.${path.basename(filePath)}.${randomUUID()}.tmp`);
|
|
113
|
+
try {
|
|
114
|
+
const handle = await open(temporaryPath, "wx", 384);
|
|
115
|
+
try {
|
|
116
|
+
await handle.writeFile(contents);
|
|
117
|
+
await handle.sync();
|
|
118
|
+
} finally {
|
|
119
|
+
await handle.close();
|
|
120
|
+
}
|
|
121
|
+
await rename(temporaryPath, filePath);
|
|
122
|
+
await syncDirectory(directory);
|
|
123
|
+
} finally {
|
|
124
|
+
await rm(temporaryPath, { force: true });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function writeJsonFileAtomic(filePath, value) {
|
|
128
|
+
await writeFileAtomic(filePath, `${JSON.stringify(value, null, 2)}
|
|
129
|
+
`);
|
|
130
|
+
}
|
|
131
|
+
var init_atomic_file = __esm({
|
|
132
|
+
"../../lib/runtime/atomic-file.ts"() {
|
|
133
|
+
"use strict";
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// ../../lib/runtime/process-identity.ts
|
|
138
|
+
import os from "node:os";
|
|
145
139
|
function processIsAlive(pid) {
|
|
146
140
|
try {
|
|
147
141
|
process.kill(pid, 0);
|
|
@@ -150,102 +144,319 @@ function processIsAlive(pid) {
|
|
|
150
144
|
return error.code === "EPERM";
|
|
151
145
|
}
|
|
152
146
|
}
|
|
153
|
-
|
|
147
|
+
function predatesCurrentBoot(startedAt) {
|
|
154
148
|
try {
|
|
155
|
-
|
|
156
|
-
await readFile(path2.join(lockPath, LOCK_OWNER_FILE), "utf8")
|
|
157
|
-
);
|
|
158
|
-
if (!Number.isInteger(value.pid) || (value.pid ?? 0) <= 0 || typeof value.token !== "string" || value.token.length === 0) {
|
|
159
|
-
return null;
|
|
160
|
-
}
|
|
161
|
-
return value;
|
|
149
|
+
return Boolean(startedAt && (typeof startedAt === "number" ? startedAt : Date.parse(startedAt)) < Date.now() - os.uptime() * 1e3 - 1e4);
|
|
162
150
|
} catch {
|
|
163
|
-
return
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
var init_process_identity = __esm({
|
|
155
|
+
"../../lib/runtime/process-identity.ts"() {
|
|
156
|
+
"use strict";
|
|
164
157
|
}
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// ../../lib/runtime/file-lock.ts
|
|
161
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
162
|
+
import { mkdir, readFile as readFile2, readdir, rename as rename2, rm as rm2, rmdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
163
|
+
import path2 from "node:path";
|
|
164
|
+
async function removeEmptyDirectory(directory) {
|
|
165
|
+
await rmdir(directory).catch((error) => {
|
|
166
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
|
|
167
|
+
});
|
|
165
168
|
}
|
|
166
|
-
async function
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
169
|
+
async function reclaimStaleLock(lockPath) {
|
|
170
|
+
const names = await readdir(lockPath).catch((error) => {
|
|
171
|
+
if (error.code === "ENOENT") return [];
|
|
172
|
+
throw error;
|
|
173
|
+
});
|
|
174
|
+
const lockStats = await stat(lockPath).catch(() => null);
|
|
175
|
+
if (names.length === 0 && lockStats && Date.now() - lockStats.mtimeMs < INVALID_LOCK_GRACE_MS) return;
|
|
176
|
+
for (const name of names) {
|
|
177
|
+
if (!OWNER_FILE.test(name)) continue;
|
|
178
|
+
const ownerPath = path2.join(lockPath, name);
|
|
179
|
+
const owner = await readFile2(ownerPath, "utf8").then((value) => JSON.parse(value)).catch(() => null);
|
|
180
|
+
const valid = owner && Number.isInteger(owner.pid) && owner.pid > 0;
|
|
181
|
+
const stale = valid ? !processIsAlive(owner.pid) || predatesCurrentBoot(owner.startedAt) : lockStats && Date.now() - lockStats.mtimeMs > INVALID_LOCK_GRACE_MS;
|
|
182
|
+
if (stale) await unlink(ownerPath).catch((error) => {
|
|
183
|
+
if (error.code !== "ENOENT") throw error;
|
|
184
|
+
});
|
|
170
185
|
}
|
|
186
|
+
await removeEmptyDirectory(lockPath);
|
|
171
187
|
}
|
|
172
|
-
async function
|
|
188
|
+
async function removeFile(filePath) {
|
|
173
189
|
try {
|
|
174
|
-
|
|
190
|
+
await unlink(filePath);
|
|
175
191
|
} catch (error) {
|
|
176
|
-
if (error.code === "ENOENT") return
|
|
192
|
+
if (error.code === "ENOENT") return;
|
|
177
193
|
throw error;
|
|
178
194
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
const temporaryPath = path2.join(
|
|
182
|
-
path2.dirname(filePath),
|
|
183
|
-
`.${path2.basename(filePath)}.${randomUUID()}.tmp`
|
|
184
|
-
);
|
|
185
|
-
await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}
|
|
186
|
-
`, {
|
|
187
|
-
mode: 384
|
|
195
|
+
await syncDirectory(path2.dirname(filePath)).catch((error) => {
|
|
196
|
+
if (error.code !== "ENOENT") throw error;
|
|
188
197
|
});
|
|
189
|
-
await rename(temporaryPath, filePath);
|
|
190
|
-
}
|
|
191
|
-
async function removeFile(filePath) {
|
|
192
|
-
await rm2(filePath, { force: true });
|
|
193
198
|
}
|
|
194
|
-
async function withDirectoryLock(lockPath, operation) {
|
|
199
|
+
async function withDirectoryLock(lockPath, operation, { timeoutMs = LOCK_TIMEOUT_MS } = {}) {
|
|
195
200
|
await mkdir(path2.dirname(lockPath), { recursive: true, mode: 448 });
|
|
196
|
-
const
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
+
const token = randomUUID2();
|
|
202
|
+
const ownerName = `owner-${token}.json`;
|
|
203
|
+
const candidate = `${lockPath}.candidate-${token}`;
|
|
204
|
+
await mkdir(candidate, { mode: 448 });
|
|
205
|
+
let acquired = false;
|
|
206
|
+
try {
|
|
207
|
+
await writeFile(path2.join(candidate, ownerName), JSON.stringify({
|
|
208
|
+
pid: process.pid,
|
|
209
|
+
token,
|
|
210
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
211
|
+
}), { mode: 384 });
|
|
212
|
+
const deadline = Date.now() + timeoutMs;
|
|
213
|
+
while (true) {
|
|
201
214
|
try {
|
|
202
|
-
await
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
`,
|
|
206
|
-
{ mode: 384 }
|
|
207
|
-
);
|
|
215
|
+
await rename2(candidate, lockPath);
|
|
216
|
+
acquired = true;
|
|
217
|
+
break;
|
|
208
218
|
} catch (error) {
|
|
209
|
-
|
|
210
|
-
throw error;
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
readLockOwner(lockPath),
|
|
217
|
-
stat2(lockPath).catch(() => null)
|
|
218
|
-
]);
|
|
219
|
-
if (owner && !processIsAlive(owner.pid) || !owner && lockStats && Date.now() - lockStats.mtimeMs > INVALID_LOCK_GRACE_MS) {
|
|
220
|
-
await rm2(lockPath, { recursive: true, force: true });
|
|
221
|
-
continue;
|
|
219
|
+
const code = error.code;
|
|
220
|
+
if (!["EEXIST", "ENOTEMPTY", "EPERM"].includes(code ?? "")) throw error;
|
|
221
|
+
if (code === "EPERM" && !await stat(lockPath).catch(() => null)) throw error;
|
|
222
|
+
await reclaimStaleLock(lockPath);
|
|
223
|
+
if (!await stat(lockPath).catch(() => null)) continue;
|
|
224
|
+
if (Date.now() >= deadline) throw new LockBusyError(`Timed out waiting for ${path2.basename(lockPath)}`);
|
|
225
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
222
226
|
}
|
|
223
|
-
if (Date.now() >= deadline) {
|
|
224
|
-
throw new Error(`Timed out waiting for ${path2.basename(lockPath)}`);
|
|
225
|
-
}
|
|
226
|
-
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
227
227
|
}
|
|
228
|
-
}
|
|
229
|
-
try {
|
|
230
228
|
return await operation();
|
|
231
229
|
} finally {
|
|
232
|
-
|
|
230
|
+
if (acquired) {
|
|
231
|
+
await unlink(path2.join(lockPath, ownerName)).catch((error) => {
|
|
232
|
+
if (error.code !== "ENOENT") throw error;
|
|
233
|
+
});
|
|
234
|
+
await removeEmptyDirectory(lockPath);
|
|
235
|
+
} else {
|
|
236
|
+
await rm2(candidate, { recursive: true, force: true });
|
|
237
|
+
}
|
|
233
238
|
}
|
|
234
239
|
}
|
|
240
|
+
var LOCK_TIMEOUT_MS, INVALID_LOCK_GRACE_MS, OWNER_FILE, LockBusyError;
|
|
241
|
+
var init_file_lock = __esm({
|
|
242
|
+
"../../lib/runtime/file-lock.ts"() {
|
|
243
|
+
"use strict";
|
|
244
|
+
init_atomic_file();
|
|
245
|
+
init_process_identity();
|
|
246
|
+
init_process_identity();
|
|
247
|
+
LOCK_TIMEOUT_MS = 6e4;
|
|
248
|
+
INVALID_LOCK_GRACE_MS = 3e4;
|
|
249
|
+
OWNER_FILE = /^owner(?:-[a-f0-9-]+)?\.json$/u;
|
|
250
|
+
LockBusyError = class extends Error {
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
});
|
|
235
254
|
|
|
236
|
-
// src/
|
|
237
|
-
|
|
255
|
+
// src/files.ts
|
|
256
|
+
var init_files = __esm({
|
|
257
|
+
"src/files.ts"() {
|
|
258
|
+
"use strict";
|
|
259
|
+
init_file_lock();
|
|
260
|
+
init_atomic_file();
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// ../../lib/runtime/lifecycle-state.ts
|
|
238
265
|
import path3 from "node:path";
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
266
|
+
function lifecycleFiles(paths) {
|
|
267
|
+
return {
|
|
268
|
+
preferences: path3.join(paths.runtime, "lifecycle.json"),
|
|
269
|
+
state: path3.join(paths.runtime, "update-state.json"),
|
|
270
|
+
transaction: path3.join(paths.runtime, "update-transaction.json"),
|
|
271
|
+
maintenance: path3.join(paths.runtime, "update-maintenance.json"),
|
|
272
|
+
browser: path3.join(paths.runtime, "browser-heartbeats"),
|
|
273
|
+
request: path3.join(paths.runtime, "update-request.json"),
|
|
274
|
+
requests: path3.join(paths.runtime, "update-requests"),
|
|
275
|
+
updateLock: path3.join(paths.runtime, "update.lock"),
|
|
276
|
+
hostLock: path3.join(paths.runtime, "host.lock"),
|
|
277
|
+
supervisorLock: path3.join(paths.runtime, "supervisor.lock"),
|
|
278
|
+
preferencesLock: path3.join(paths.runtime, "preferences.lock"),
|
|
279
|
+
host: path3.join(paths.app, "host")
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
async function readPreferences(paths) {
|
|
283
|
+
const value = await readJsonFile(lifecycleFiles(paths).preferences);
|
|
284
|
+
if (!value) return { ...DEFAULT_PREFERENCES };
|
|
285
|
+
if (["startAtLogin", "openAtLogin", "automaticUpdates", "running"].some(
|
|
286
|
+
(key) => typeof value[key] !== "boolean"
|
|
287
|
+
) || !Number.isInteger(value.port) || value.port < 1 || value.port > 65535) {
|
|
288
|
+
throw new Error("Switchy startup preferences are invalid");
|
|
289
|
+
}
|
|
290
|
+
return value;
|
|
291
|
+
}
|
|
292
|
+
async function readUpdateState(paths) {
|
|
293
|
+
return { ...DEFAULT_UPDATE_STATE, ...await readJsonFile(lifecycleFiles(paths).state) };
|
|
294
|
+
}
|
|
295
|
+
async function saveUpdateState(paths, changes) {
|
|
296
|
+
const previous = await readUpdateState(paths);
|
|
297
|
+
const next = { ...previous, ...changes };
|
|
298
|
+
if (JSON.stringify(previous) !== JSON.stringify(next)) await writeJsonFileAtomic(lifecycleFiles(paths).state, next);
|
|
299
|
+
}
|
|
300
|
+
function compareVersions(left, right) {
|
|
301
|
+
if (![left, right].every((value) => /^\d+\.\d+\.\d+$/u.test(value))) {
|
|
302
|
+
throw new Error("Invalid stable version");
|
|
303
|
+
}
|
|
304
|
+
const a = left.split(".").map(Number);
|
|
305
|
+
const b = right.split(".").map(Number);
|
|
306
|
+
for (let index = 0; index < 3; index++) {
|
|
307
|
+
if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;
|
|
308
|
+
}
|
|
309
|
+
return 0;
|
|
310
|
+
}
|
|
311
|
+
var DEFAULT_PREFERENCES, DEFAULT_UPDATE_STATE;
|
|
312
|
+
var init_lifecycle_state = __esm({
|
|
313
|
+
"../../lib/runtime/lifecycle-state.ts"() {
|
|
314
|
+
"use strict";
|
|
315
|
+
init_atomic_file();
|
|
316
|
+
init_process_identity();
|
|
317
|
+
DEFAULT_PREFERENCES = {
|
|
318
|
+
startAtLogin: false,
|
|
319
|
+
openAtLogin: false,
|
|
320
|
+
automaticUpdates: false,
|
|
321
|
+
running: true,
|
|
322
|
+
port: 6767
|
|
323
|
+
};
|
|
324
|
+
DEFAULT_UPDATE_STATE = {
|
|
325
|
+
phase: "idle",
|
|
326
|
+
lastCheckedAt: null,
|
|
327
|
+
latestVersion: null,
|
|
328
|
+
failedVersion: null,
|
|
329
|
+
downloadedVersion: null,
|
|
330
|
+
message: null
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
// ../../lib/runtime/update-requests.ts
|
|
336
|
+
import { mkdir as mkdir2, readdir as readdir2 } from "node:fs/promises";
|
|
337
|
+
import path4 from "node:path";
|
|
338
|
+
async function nextUpdateRequest(paths) {
|
|
339
|
+
const directory = lifecycleFiles(paths).requests;
|
|
340
|
+
const names = await readdir2(directory).catch((error) => {
|
|
341
|
+
if (error.code === "ENOENT") return [];
|
|
342
|
+
throw error;
|
|
343
|
+
});
|
|
344
|
+
for (const name of names.filter((name2) => /^\d+-[a-f0-9-]+\.json$/u.test(name2)).sort()) {
|
|
345
|
+
const file = path4.join(directory, name);
|
|
346
|
+
const request = await readJsonFile(file);
|
|
347
|
+
if (request && typeof request.id === "string" && ["check", "download", "install"].includes(request.action) && (request.version === void 0 || /^\d+\.\d+\.\d+$/u.test(request.version))) return { request, file };
|
|
348
|
+
throw new Error("Invalid Switchy update request");
|
|
349
|
+
}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
var init_update_requests = __esm({
|
|
353
|
+
"../../lib/runtime/update-requests.ts"() {
|
|
354
|
+
"use strict";
|
|
355
|
+
init_atomic_file();
|
|
356
|
+
init_lifecycle_state();
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
// src/lifecycle-state.ts
|
|
361
|
+
import path5 from "node:path";
|
|
362
|
+
async function saveUpdateState2(paths, changes) {
|
|
363
|
+
await withDirectoryLock(path5.join(paths.runtime, "update-state.lock"), () => saveUpdateState(paths, changes));
|
|
364
|
+
}
|
|
365
|
+
var init_lifecycle_state2 = __esm({
|
|
366
|
+
"src/lifecycle-state.ts"() {
|
|
367
|
+
"use strict";
|
|
368
|
+
init_lifecycle_state();
|
|
369
|
+
init_files();
|
|
370
|
+
init_lifecycle_state();
|
|
371
|
+
init_atomic_file();
|
|
372
|
+
init_update_requests();
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
// src/logs.ts
|
|
377
|
+
import { open as open2, stat as stat2, truncate, writeFile as writeFile2 } from "node:fs/promises";
|
|
378
|
+
async function rotateLog(file) {
|
|
379
|
+
if (((await stat2(file).catch(() => null))?.size ?? 0) < MAX_LOG_BYTES) return;
|
|
380
|
+
await writeFile2(`${file}.1`, await readLogTail(file), { mode: 384 });
|
|
381
|
+
await truncate(file, 0);
|
|
382
|
+
}
|
|
383
|
+
async function readLogTail(file, lines = 200) {
|
|
384
|
+
const handle = await open2(file, "r").catch((error) => {
|
|
385
|
+
if (error.code === "ENOENT") return null;
|
|
386
|
+
throw error;
|
|
387
|
+
});
|
|
388
|
+
if (!handle) return "";
|
|
242
389
|
try {
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
390
|
+
const { size } = await handle.stat();
|
|
391
|
+
const length = Math.min(size, MAX_TAIL_BYTES);
|
|
392
|
+
const buffer = Buffer.alloc(length);
|
|
393
|
+
await handle.read(buffer, 0, length, size - length);
|
|
394
|
+
const text = buffer.toString("utf8");
|
|
395
|
+
return (size > length ? text.slice(text.indexOf("\n") + 1) : text).trimEnd().split("\n").slice(-lines).join("\n");
|
|
396
|
+
} finally {
|
|
397
|
+
await handle.close();
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
var MAX_LOG_BYTES, MAX_TAIL_BYTES;
|
|
401
|
+
var init_logs = __esm({
|
|
402
|
+
"src/logs.ts"() {
|
|
403
|
+
"use strict";
|
|
404
|
+
MAX_LOG_BYTES = 10 * 1024 * 1024;
|
|
405
|
+
MAX_TAIL_BYTES = 256 * 1024;
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
// src/startup-environment.ts
|
|
410
|
+
import os2 from "node:os";
|
|
411
|
+
import path6 from "node:path";
|
|
412
|
+
function searchPath(paths, saved) {
|
|
413
|
+
const home = os2.homedir();
|
|
414
|
+
return [...new Set([
|
|
415
|
+
lifecycleFiles(paths).host,
|
|
416
|
+
path6.dirname(process.execPath),
|
|
417
|
+
...(process.env.PATH ?? "").split(path6.delimiter),
|
|
418
|
+
...(saved ?? "").split(path6.delimiter),
|
|
419
|
+
...process.platform === "win32" ? [] : [
|
|
420
|
+
path6.join(home, ".local/bin"),
|
|
421
|
+
path6.join(home, ".opencode/bin"),
|
|
422
|
+
"/opt/homebrew/bin",
|
|
423
|
+
"/usr/local/bin",
|
|
424
|
+
"/usr/bin",
|
|
425
|
+
"/bin",
|
|
426
|
+
"/usr/sbin",
|
|
427
|
+
"/sbin"
|
|
428
|
+
]
|
|
429
|
+
].filter((value) => value && path6.isAbsolute(value)))].join(path6.delimiter);
|
|
430
|
+
}
|
|
431
|
+
async function saveStartupEnvironment(paths) {
|
|
432
|
+
const file = path6.join(lifecycleFiles(paths).host, "environment.json");
|
|
433
|
+
const saved = await readJsonFile(file);
|
|
434
|
+
const cliExecutables = { ...saved?.cliExecutables };
|
|
435
|
+
for (const name of EXECUTABLE_VARIABLES) {
|
|
436
|
+
const value = process.env[name]?.trim();
|
|
437
|
+
if (value && path6.isAbsolute(value)) cliExecutables[name] = value;
|
|
247
438
|
}
|
|
439
|
+
await writeJsonFileAtomic(file, { path: searchPath(paths, saved?.path), cliExecutables });
|
|
248
440
|
}
|
|
441
|
+
async function runtimeEnvironment(paths) {
|
|
442
|
+
const saved = await readJsonFile(path6.join(lifecycleFiles(paths).host, "environment.json"));
|
|
443
|
+
return { ...saved?.cliExecutables, ...process.env, PATH: searchPath(paths, saved?.path) };
|
|
444
|
+
}
|
|
445
|
+
var EXECUTABLE_VARIABLES;
|
|
446
|
+
var init_startup_environment = __esm({
|
|
447
|
+
"src/startup-environment.ts"() {
|
|
448
|
+
"use strict";
|
|
449
|
+
init_files();
|
|
450
|
+
init_lifecycle_state2();
|
|
451
|
+
EXECUTABLE_VARIABLES = ["SWITCHY_CODEX_CLI_PATH", "SWITCHY_OPENCODE_CLI_PATH"];
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
// src/process-manager.ts
|
|
456
|
+
import { open as open3 } from "node:fs/promises";
|
|
457
|
+
import path7 from "node:path";
|
|
458
|
+
import { spawn } from "node:child_process";
|
|
459
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
249
460
|
async function readProcessRecord(paths) {
|
|
250
461
|
const record = await readJsonFile(paths.processRecord).catch(() => null);
|
|
251
462
|
if (!record || record.schemaVersion !== 1 || !Number.isInteger(record.pid) || record.pid <= 0 || typeof record.instanceId !== "string" || record.instanceId.length === 0 || !/^\d+\.\d+\.\d+$/u.test(record.version) || record.hostname !== DEFAULT_HOSTNAME || !Number.isInteger(record.port) || record.port < 1 || record.port > 65535 || !Number.isFinite(Date.parse(record.startedAt))) {
|
|
@@ -273,23 +484,20 @@ async function fetchLiveness(record) {
|
|
|
273
484
|
}
|
|
274
485
|
async function getRunningProcess(paths) {
|
|
275
486
|
const record = await readProcessRecord(paths);
|
|
276
|
-
if (!record)
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if (!processIsAlive2(record.pid)) {
|
|
281
|
-
await removeFile(paths.processRecord);
|
|
282
|
-
return null;
|
|
487
|
+
if (!record || predatesCurrentBoot(record.startedAt) || !processIsAlive(record.pid)) return null;
|
|
488
|
+
const live = await fetchLiveness(record);
|
|
489
|
+
if (live && (live.instanceId !== record.instanceId || live.version !== record.version)) {
|
|
490
|
+
throw new Error("The recorded port belongs to another application instance");
|
|
283
491
|
}
|
|
284
|
-
return { record, live
|
|
492
|
+
return { record, live };
|
|
285
493
|
}
|
|
286
494
|
async function waitForExit(pid, timeoutMs) {
|
|
287
495
|
const deadline = Date.now() + timeoutMs;
|
|
288
496
|
while (Date.now() < deadline) {
|
|
289
|
-
if (!
|
|
497
|
+
if (!processIsAlive(pid)) return true;
|
|
290
498
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
291
499
|
}
|
|
292
|
-
return !
|
|
500
|
+
return !processIsAlive(pid);
|
|
293
501
|
}
|
|
294
502
|
async function signalProcessTree(pid, signal) {
|
|
295
503
|
if (process.platform !== "win32") {
|
|
@@ -321,7 +529,7 @@ async function signalProcessTree(pid, signal) {
|
|
|
321
529
|
);
|
|
322
530
|
child.once("error", reject);
|
|
323
531
|
child.once("exit", (code) => {
|
|
324
|
-
if (code === 0 || !
|
|
532
|
+
if (code === 0 || !processIsAlive(pid)) resolve();
|
|
325
533
|
else reject(new Error(`taskkill exited with code ${code}`));
|
|
326
534
|
});
|
|
327
535
|
});
|
|
@@ -347,7 +555,7 @@ async function stopSwitchy(paths, force = false) {
|
|
|
347
555
|
async function waitUntilReady(record) {
|
|
348
556
|
const deadline = Date.now() + STARTUP_TIMEOUT_MS;
|
|
349
557
|
while (Date.now() < deadline) {
|
|
350
|
-
if (!
|
|
558
|
+
if (!processIsAlive(record.pid)) {
|
|
351
559
|
throw new Error("Switchy exited before becoming ready");
|
|
352
560
|
}
|
|
353
561
|
try {
|
|
@@ -355,7 +563,10 @@ async function waitUntilReady(record) {
|
|
|
355
563
|
`http://${record.hostname}:${record.port}/api/health/ready`,
|
|
356
564
|
{ signal: AbortSignal.timeout(2e3) }
|
|
357
565
|
);
|
|
358
|
-
if (response.ok)
|
|
566
|
+
if (response.ok) {
|
|
567
|
+
const live = await fetchLiveness(record);
|
|
568
|
+
if (live?.instanceId === record.instanceId && live.version === record.version) return;
|
|
569
|
+
}
|
|
359
570
|
} catch {
|
|
360
571
|
}
|
|
361
572
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
@@ -367,17 +578,19 @@ async function startSwitchyProcess({
|
|
|
367
578
|
runtimeDirectory,
|
|
368
579
|
version,
|
|
369
580
|
port,
|
|
370
|
-
foreground
|
|
581
|
+
foreground,
|
|
582
|
+
candidate = false
|
|
371
583
|
}) {
|
|
372
|
-
const instanceId =
|
|
584
|
+
const instanceId = randomUUID3();
|
|
373
585
|
const environment = {
|
|
374
|
-
...
|
|
586
|
+
...await runtimeEnvironment(paths),
|
|
587
|
+
...candidate ? { SWITCHY_UPDATE_CANDIDATE: "1" } : { SWITCHY_UPDATE_CANDIDATE: "" },
|
|
375
588
|
NODE_ENV: "production",
|
|
376
589
|
HOSTNAME: DEFAULT_HOSTNAME,
|
|
377
590
|
PORT: String(port),
|
|
378
591
|
SWITCHY_HOME: paths.root,
|
|
379
592
|
SWITCHY_INSTANCE_ID: instanceId,
|
|
380
|
-
SWITCHY_MACOS_NOTIFICATION_HELPER:
|
|
593
|
+
SWITCHY_MACOS_NOTIFICATION_HELPER: path7.join(
|
|
381
594
|
runtimeDirectory,
|
|
382
595
|
"bin",
|
|
383
596
|
"Switchy Notifications.app",
|
|
@@ -387,14 +600,20 @@ async function startSwitchyProcess({
|
|
|
387
600
|
),
|
|
388
601
|
PLAYWRIGHT_BROWSERS_PATH: paths.playwright
|
|
389
602
|
};
|
|
390
|
-
const serverPath =
|
|
391
|
-
|
|
603
|
+
const serverPath = path7.join(runtimeDirectory, "server.js");
|
|
604
|
+
if (!foreground) await rotateLog(paths.logFile);
|
|
605
|
+
const logHandle = foreground ? null : await open3(paths.logFile, "a", 384);
|
|
392
606
|
const child = spawn(process.execPath, [serverPath], {
|
|
393
607
|
cwd: runtimeDirectory,
|
|
394
|
-
detached:
|
|
608
|
+
detached: true,
|
|
395
609
|
env: environment,
|
|
396
610
|
stdio: foreground ? "inherit" : ["ignore", logHandle.fd, logHandle.fd]
|
|
397
611
|
});
|
|
612
|
+
const exited = new Promise((resolve, reject) => {
|
|
613
|
+
child.once("error", reject);
|
|
614
|
+
child.once("exit", (code) => code === 0 || code === null ? resolve() : reject(new Error(`Switchy exited with code ${code}`)));
|
|
615
|
+
});
|
|
616
|
+
void exited.catch(() => void 0);
|
|
398
617
|
await logHandle?.close();
|
|
399
618
|
if (!child.pid) throw new Error("Switchy did not return a process ID");
|
|
400
619
|
const record = {
|
|
@@ -406,23 +625,31 @@ async function startSwitchyProcess({
|
|
|
406
625
|
port,
|
|
407
626
|
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
408
627
|
};
|
|
409
|
-
await writeJsonFileAtomic(paths.processRecord, record);
|
|
410
|
-
if (foreground) {
|
|
411
|
-
await new Promise((resolve, reject) => {
|
|
412
|
-
child.once("error", reject);
|
|
413
|
-
child.once("exit", (code) => {
|
|
414
|
-
if (code === 0 || code === null) resolve();
|
|
415
|
-
else reject(new Error(`Switchy exited with code ${code}`));
|
|
416
|
-
});
|
|
417
|
-
}).finally(() => removeFile(paths.processRecord));
|
|
418
|
-
return record;
|
|
419
|
-
}
|
|
420
|
-
child.unref();
|
|
421
628
|
try {
|
|
629
|
+
await writeJsonFileAtomic(paths.processRecord, record);
|
|
630
|
+
if (foreground) {
|
|
631
|
+
const terminate = () => {
|
|
632
|
+
void signalProcessTree(record.pid, "SIGTERM").catch(console.error);
|
|
633
|
+
};
|
|
634
|
+
process.once("SIGINT", terminate);
|
|
635
|
+
process.once("SIGTERM", terminate);
|
|
636
|
+
const completion = exited.finally(async () => {
|
|
637
|
+
process.removeListener("SIGINT", terminate);
|
|
638
|
+
process.removeListener("SIGTERM", terminate);
|
|
639
|
+
await withDirectoryLock(paths.startLock, async () => {
|
|
640
|
+
const current = await readProcessRecord(paths);
|
|
641
|
+
if (current?.instanceId === record.instanceId) await removeFile(paths.processRecord);
|
|
642
|
+
});
|
|
643
|
+
});
|
|
644
|
+
void completion.catch(() => void 0);
|
|
645
|
+
foregroundProcesses.set(record.instanceId, completion);
|
|
646
|
+
} else {
|
|
647
|
+
child.unref();
|
|
648
|
+
}
|
|
422
649
|
await waitUntilReady(record);
|
|
423
650
|
return record;
|
|
424
651
|
} catch (error) {
|
|
425
|
-
if (
|
|
652
|
+
if (processIsAlive(record.pid)) {
|
|
426
653
|
await signalProcessTree(record.pid, "SIGTERM");
|
|
427
654
|
if (!await waitForExit(record.pid, SHUTDOWN_TIMEOUT_MS)) {
|
|
428
655
|
await signalProcessTree(record.pid, "SIGKILL");
|
|
@@ -438,82 +665,50 @@ async function startSwitchyProcess({
|
|
|
438
665
|
throw error;
|
|
439
666
|
}
|
|
440
667
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
if (override && !path4.isAbsolute(override)) {
|
|
449
|
-
throw new Error("SWITCHY_HOME must be an absolute path");
|
|
668
|
+
async function waitForForegroundExit(record) {
|
|
669
|
+
const completion = foregroundProcesses.get(record.instanceId);
|
|
670
|
+
if (!completion) return;
|
|
671
|
+
try {
|
|
672
|
+
await completion;
|
|
673
|
+
} finally {
|
|
674
|
+
foregroundProcesses.delete(record.instanceId);
|
|
450
675
|
}
|
|
451
|
-
const root = override ? path4.normalize(override) : path4.join(os.homedir(), ".switchy");
|
|
452
|
-
const data = path4.join(root, "data");
|
|
453
|
-
const app = path4.join(root, "app");
|
|
454
|
-
const runtime = path4.join(root, "runtime");
|
|
455
|
-
const logs = path4.join(root, "logs");
|
|
456
|
-
const cache = path4.join(root, "cache");
|
|
457
|
-
return {
|
|
458
|
-
root,
|
|
459
|
-
data,
|
|
460
|
-
productionData: path4.join(data, "production"),
|
|
461
|
-
app,
|
|
462
|
-
versions: path4.join(app, "versions"),
|
|
463
|
-
currentVersion: path4.join(app, "current.json"),
|
|
464
|
-
runtime,
|
|
465
|
-
processRecord: path4.join(runtime, "process.json"),
|
|
466
|
-
installLock: path4.join(runtime, "install.lock"),
|
|
467
|
-
startLock: path4.join(runtime, "start.lock"),
|
|
468
|
-
logs,
|
|
469
|
-
logFile: path4.join(logs, "switchy.log"),
|
|
470
|
-
cache,
|
|
471
|
-
downloads: path4.join(cache, "downloads"),
|
|
472
|
-
playwright: path4.join(cache, "playwright"),
|
|
473
|
-
updateSnapshots: path4.join(root, "update-snapshots")
|
|
474
|
-
};
|
|
475
676
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
paths.playwright,
|
|
487
|
-
paths.updateSnapshots
|
|
488
|
-
]) {
|
|
489
|
-
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
677
|
+
var foregroundProcesses;
|
|
678
|
+
var init_process_manager = __esm({
|
|
679
|
+
"src/process-manager.ts"() {
|
|
680
|
+
"use strict";
|
|
681
|
+
init_config();
|
|
682
|
+
init_files();
|
|
683
|
+
init_lifecycle_state2();
|
|
684
|
+
init_logs();
|
|
685
|
+
init_startup_environment();
|
|
686
|
+
foregroundProcesses = /* @__PURE__ */ new Map();
|
|
490
687
|
}
|
|
491
|
-
}
|
|
688
|
+
});
|
|
492
689
|
|
|
493
|
-
// src/
|
|
494
|
-
import {
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
690
|
+
// src/preferences.ts
|
|
691
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
692
|
+
async function saveRuntimePreference(paths, changes) {
|
|
693
|
+
await withDirectoryLock(lifecycleFiles(paths).preferencesLock, async () => {
|
|
694
|
+
await writeJsonFileAtomic(lifecycleFiles(paths).preferences, { ...await readPreferences(paths), ...changes });
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
async function setRunningPreference(paths, running, port) {
|
|
698
|
+
await saveRuntimePreference(paths, { running, ...port === void 0 ? {} : { port } });
|
|
699
|
+
}
|
|
700
|
+
async function requestRuntimeStop(paths) {
|
|
701
|
+
await saveRuntimePreference(paths, { running: false, stopToken: randomUUID4() });
|
|
702
|
+
}
|
|
703
|
+
var init_preferences = __esm({
|
|
704
|
+
"src/preferences.ts"() {
|
|
705
|
+
"use strict";
|
|
706
|
+
init_files();
|
|
707
|
+
init_lifecycle_state2();
|
|
708
|
+
}
|
|
709
|
+
});
|
|
508
710
|
|
|
509
711
|
// src/platform.ts
|
|
510
|
-
var SUPPORTED_TARGETS = [
|
|
511
|
-
"darwin-arm64",
|
|
512
|
-
"linux-arm64",
|
|
513
|
-
"linux-x64",
|
|
514
|
-
"win32-x64"
|
|
515
|
-
];
|
|
516
|
-
var supportedTargets = new Set(SUPPORTED_TARGETS);
|
|
517
712
|
function isSupportedTarget(target) {
|
|
518
713
|
return supportedTargets.has(target);
|
|
519
714
|
}
|
|
@@ -524,19 +719,44 @@ function currentTarget(platform = process.platform, architecture = process.arch)
|
|
|
524
719
|
}
|
|
525
720
|
return target;
|
|
526
721
|
}
|
|
722
|
+
var SUPPORTED_TARGETS, supportedTargets;
|
|
723
|
+
var init_platform = __esm({
|
|
724
|
+
"src/platform.ts"() {
|
|
725
|
+
"use strict";
|
|
726
|
+
SUPPORTED_TARGETS = [
|
|
727
|
+
"darwin-arm64",
|
|
728
|
+
"linux-arm64",
|
|
729
|
+
"linux-x64",
|
|
730
|
+
"win32-x64"
|
|
731
|
+
];
|
|
732
|
+
supportedTargets = new Set(SUPPORTED_TARGETS);
|
|
733
|
+
}
|
|
734
|
+
});
|
|
527
735
|
|
|
528
736
|
// src/release.ts
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
737
|
+
import { createHash, randomUUID as randomUUID5 } from "node:crypto";
|
|
738
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
739
|
+
import {
|
|
740
|
+
cp,
|
|
741
|
+
mkdir as mkdir3,
|
|
742
|
+
readFile as readFile3,
|
|
743
|
+
rename as rename3,
|
|
744
|
+
rm as rm3,
|
|
745
|
+
stat as stat3
|
|
746
|
+
} from "node:fs/promises";
|
|
747
|
+
import { Readable, Transform } from "node:stream";
|
|
748
|
+
import { pipeline } from "node:stream/promises";
|
|
749
|
+
import path8 from "node:path";
|
|
750
|
+
import { extract } from "tar";
|
|
751
|
+
function notificationRuntimeFiles(target) {
|
|
752
|
+
if (!target.startsWith("darwin-")) return [];
|
|
753
|
+
return [
|
|
754
|
+
"bin/Switchy Notifications.app/Contents/Info.plist",
|
|
535
755
|
MACOS_NOTIFIER_EXECUTABLE
|
|
536
756
|
];
|
|
537
757
|
}
|
|
538
758
|
function assertStableVersion(version) {
|
|
539
|
-
if (!
|
|
759
|
+
if (!STABLE_VERSION_PATTERN.test(version)) {
|
|
540
760
|
throw new Error(`Invalid stable Switchy version: ${version}`);
|
|
541
761
|
}
|
|
542
762
|
return version;
|
|
@@ -545,13 +765,13 @@ function releaseManifestUrl(version) {
|
|
|
545
765
|
return process.env.SWITCHY_MANIFEST_URL ?? `https://github.com/${GITHUB_REPOSITORY}/releases/download/v${version}/${RELEASE_MANIFEST_FILE}`;
|
|
546
766
|
}
|
|
547
767
|
function assertReleaseArtifact(value) {
|
|
548
|
-
if (typeof value !== "object" || value === null || typeof value.file !== "string" ||
|
|
768
|
+
if (typeof value !== "object" || value === null || typeof value.file !== "string" || path8.basename(value.file) !== value.file || !/^switchy-\d+\.\d+\.\d+-(?:darwin|linux|win32)-(?:arm64|x64)\.tar\.gz$/u.test(value.file) || typeof value.sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(value.sha256) || typeof value.size !== "number" || !Number.isSafeInteger(value.size) || value.size <= 0 || value.size > 1e9) {
|
|
549
769
|
throw new Error("Release manifest contains an invalid artifact");
|
|
550
770
|
}
|
|
551
771
|
return value;
|
|
552
772
|
}
|
|
553
773
|
function parseReleaseManifest(value) {
|
|
554
|
-
if (typeof value !== "object" || value === null || value.schemaVersion !== 1 || typeof value.version !== "string" || !
|
|
774
|
+
if (typeof value !== "object" || value === null || value.schemaVersion !== 1 || typeof value.version !== "string" || !STABLE_VERSION_PATTERN.test(value.version) || typeof value.publishedAt !== "string" || typeof value.nodeVersion !== "string" || typeof value.artifacts !== "object" || value.artifacts === null) {
|
|
555
775
|
throw new Error("Release manifest is invalid");
|
|
556
776
|
}
|
|
557
777
|
const manifest = value;
|
|
@@ -654,13 +874,13 @@ async function validateRuntimeDirectory(runtimeDirectory, version, target) {
|
|
|
654
874
|
"switchy-runtime.json",
|
|
655
875
|
...platformFiles
|
|
656
876
|
]) {
|
|
657
|
-
const fileStats = await stat3(
|
|
877
|
+
const fileStats = await stat3(path8.join(runtimeDirectory, relativePath)).catch(() => null);
|
|
658
878
|
if (!fileStats?.isFile()) {
|
|
659
879
|
throw new Error(`Runtime is missing ${relativePath}`);
|
|
660
880
|
}
|
|
661
881
|
}
|
|
662
882
|
if (platformFiles.length > 0) {
|
|
663
|
-
const helper = await stat3(
|
|
883
|
+
const helper = await stat3(path8.join(runtimeDirectory, MACOS_NOTIFIER_EXECUTABLE));
|
|
664
884
|
if ((helper.mode & 73) === 0) {
|
|
665
885
|
throw new Error("Runtime native notification helper is not executable");
|
|
666
886
|
}
|
|
@@ -668,8 +888,8 @@ async function validateRuntimeDirectory(runtimeDirectory, version, target) {
|
|
|
668
888
|
let metadata;
|
|
669
889
|
try {
|
|
670
890
|
metadata = JSON.parse(
|
|
671
|
-
await
|
|
672
|
-
|
|
891
|
+
await readFile3(
|
|
892
|
+
path8.join(runtimeDirectory, "switchy-runtime.json"),
|
|
673
893
|
"utf8"
|
|
674
894
|
)
|
|
675
895
|
);
|
|
@@ -683,7 +903,7 @@ async function validateRuntimeDirectory(runtimeDirectory, version, target) {
|
|
|
683
903
|
async function installRuntimeUnlocked(version, paths) {
|
|
684
904
|
assertStableVersion(version);
|
|
685
905
|
const target = currentTarget();
|
|
686
|
-
const versionDirectory =
|
|
906
|
+
const versionDirectory = path8.join(paths.versions, version);
|
|
687
907
|
if ((await stat3(versionDirectory).catch(() => null))?.isDirectory()) {
|
|
688
908
|
try {
|
|
689
909
|
await validateRuntimeDirectory(versionDirectory, version, target);
|
|
@@ -693,15 +913,15 @@ async function installRuntimeUnlocked(version, paths) {
|
|
|
693
913
|
}
|
|
694
914
|
}
|
|
695
915
|
const localRuntime = process.env.SWITCHY_RUNTIME_SOURCE?.trim();
|
|
696
|
-
const temporaryDirectory =
|
|
916
|
+
const temporaryDirectory = path8.join(
|
|
697
917
|
paths.app,
|
|
698
|
-
`.install-${version}-${
|
|
918
|
+
`.install-${version}-${randomUUID5()}`
|
|
699
919
|
);
|
|
700
920
|
await rm3(temporaryDirectory, { recursive: true, force: true });
|
|
701
921
|
await mkdir3(temporaryDirectory, { recursive: true, mode: 448 });
|
|
702
922
|
try {
|
|
703
923
|
if (localRuntime) {
|
|
704
|
-
await cp(
|
|
924
|
+
await cp(path8.resolve(localRuntime), temporaryDirectory, {
|
|
705
925
|
recursive: true,
|
|
706
926
|
verbatimSymlinks: true
|
|
707
927
|
});
|
|
@@ -711,7 +931,7 @@ async function installRuntimeUnlocked(version, paths) {
|
|
|
711
931
|
if (!artifact) {
|
|
712
932
|
throw new Error(`Release ${version} does not support ${target}`);
|
|
713
933
|
}
|
|
714
|
-
const archivePath =
|
|
934
|
+
const archivePath = path8.join(paths.downloads, artifact.file);
|
|
715
935
|
const artifactUrl = new URL(artifact.file, manifestUrl).toString();
|
|
716
936
|
const existing = await stat3(archivePath).catch(() => null);
|
|
717
937
|
const cachedArchiveIsValid = existing?.size === artifact.size && await sha256(archivePath) === artifact.sha256;
|
|
@@ -737,7 +957,7 @@ async function installRuntimeUnlocked(version, paths) {
|
|
|
737
957
|
});
|
|
738
958
|
}
|
|
739
959
|
await validateRuntimeDirectory(temporaryDirectory, version, target);
|
|
740
|
-
await
|
|
960
|
+
await rename3(temporaryDirectory, versionDirectory);
|
|
741
961
|
return versionDirectory;
|
|
742
962
|
} catch (error) {
|
|
743
963
|
await rm3(temporaryDirectory, { recursive: true, force: true });
|
|
@@ -749,19 +969,99 @@ async function installRuntime(version, paths) {
|
|
|
749
969
|
return installRuntimeUnlocked(version, paths);
|
|
750
970
|
});
|
|
751
971
|
}
|
|
752
|
-
async function setCurrentVersion(paths, version) {
|
|
972
|
+
async function setCurrentVersion(paths, version, previousVersion) {
|
|
973
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
753
974
|
const value = {
|
|
754
975
|
schemaVersion: 1,
|
|
755
976
|
version,
|
|
756
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
977
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
978
|
+
previousVersion: previousVersion !== void 0 ? previousVersion : current?.version !== version ? current?.version ?? null : current.previousVersion ?? null
|
|
757
979
|
};
|
|
758
980
|
await writeJsonFileAtomic(paths.currentVersion, value);
|
|
759
981
|
}
|
|
982
|
+
var STABLE_VERSION_PATTERN, MACOS_NOTIFIER_EXECUTABLE;
|
|
983
|
+
var init_release = __esm({
|
|
984
|
+
"src/release.ts"() {
|
|
985
|
+
"use strict";
|
|
986
|
+
init_config();
|
|
987
|
+
init_files();
|
|
988
|
+
init_platform();
|
|
989
|
+
STABLE_VERSION_PATTERN = /^\d+\.\d+\.\d+$/u;
|
|
990
|
+
MACOS_NOTIFIER_EXECUTABLE = "bin/Switchy Notifications.app/Contents/MacOS/SwitchyNotifier";
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
|
|
994
|
+
// src/cleanup.ts
|
|
995
|
+
import { readdir as readdir3, rm as rm4, stat as stat4 } from "node:fs/promises";
|
|
996
|
+
import path9 from "node:path";
|
|
997
|
+
async function listEntries(directory) {
|
|
998
|
+
try {
|
|
999
|
+
return await readdir3(directory, { withFileTypes: true });
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
if (error.code === "ENOENT") return [];
|
|
1002
|
+
throw error;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
async function pruneInstallArtifacts(paths, retainedVersions) {
|
|
1006
|
+
const retained = new Set(
|
|
1007
|
+
retainedVersions.filter((version) => Boolean(version))
|
|
1008
|
+
);
|
|
1009
|
+
const result = { versions: [], downloads: [], snapshots: [] };
|
|
1010
|
+
for (const entry of await listEntries(paths.versions)) {
|
|
1011
|
+
if (!entry.isDirectory() || !STABLE_VERSION_PATTERN2.test(entry.name) || retained.has(entry.name)) {
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
await rm4(path9.join(paths.versions, entry.name), {
|
|
1015
|
+
recursive: true,
|
|
1016
|
+
force: true
|
|
1017
|
+
});
|
|
1018
|
+
result.versions.push(entry.name);
|
|
1019
|
+
}
|
|
1020
|
+
for (const entry of await listEntries(paths.app)) {
|
|
1021
|
+
if (entry.isDirectory() && entry.name.startsWith(INSTALL_DIRECTORY_PREFIX)) {
|
|
1022
|
+
await rm4(path9.join(paths.app, entry.name), { recursive: true, force: true });
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
for (const entry of await listEntries(paths.downloads)) {
|
|
1026
|
+
const version = DOWNLOAD_ARCHIVE_PATTERN.exec(entry.name)?.[1];
|
|
1027
|
+
if (!entry.isFile() || !version || retained.has(version)) continue;
|
|
1028
|
+
await rm4(path9.join(paths.downloads, entry.name), { force: true });
|
|
1029
|
+
result.downloads.push(entry.name);
|
|
1030
|
+
}
|
|
1031
|
+
const snapshots = await Promise.all(
|
|
1032
|
+
(await listEntries(paths.updateSnapshots)).filter(
|
|
1033
|
+
(entry) => entry.isDirectory() && entry.name.startsWith(UPDATE_SNAPSHOT_PREFIX)
|
|
1034
|
+
).map(async (entry) => ({
|
|
1035
|
+
name: entry.name,
|
|
1036
|
+
modifiedAt: (await stat4(path9.join(paths.updateSnapshots, entry.name))).mtimeMs
|
|
1037
|
+
}))
|
|
1038
|
+
);
|
|
1039
|
+
snapshots.sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
1040
|
+
for (const snapshot of snapshots.slice(RETAINED_UPDATE_SNAPSHOTS)) {
|
|
1041
|
+
await rm4(path9.join(paths.updateSnapshots, snapshot.name), {
|
|
1042
|
+
recursive: true,
|
|
1043
|
+
force: true
|
|
1044
|
+
});
|
|
1045
|
+
result.snapshots.push(snapshot.name);
|
|
1046
|
+
}
|
|
1047
|
+
return result;
|
|
1048
|
+
}
|
|
1049
|
+
var STABLE_VERSION_PATTERN2, DOWNLOAD_ARCHIVE_PATTERN, INSTALL_DIRECTORY_PREFIX, UPDATE_SNAPSHOT_PREFIX, RETAINED_UPDATE_SNAPSHOTS;
|
|
1050
|
+
var init_cleanup = __esm({
|
|
1051
|
+
"src/cleanup.ts"() {
|
|
1052
|
+
"use strict";
|
|
1053
|
+
STABLE_VERSION_PATTERN2 = /^\d+\.\d+\.\d+$/u;
|
|
1054
|
+
DOWNLOAD_ARCHIVE_PATTERN = /^switchy-(\d+\.\d+\.\d+)-(?:darwin|linux|win32)-(?:arm64|x64)\.tar\.gz$/u;
|
|
1055
|
+
INSTALL_DIRECTORY_PREFIX = ".install-";
|
|
1056
|
+
UPDATE_SNAPSHOT_PREFIX = "update-";
|
|
1057
|
+
RETAINED_UPDATE_SNAPSHOTS = 3;
|
|
1058
|
+
}
|
|
1059
|
+
});
|
|
760
1060
|
|
|
761
1061
|
// src/runtime.ts
|
|
762
1062
|
import { spawn as spawn2 } from "node:child_process";
|
|
763
|
-
import { cp as cp2, mkdir as mkdir4,
|
|
764
|
-
import
|
|
1063
|
+
import { cp as cp2, mkdir as mkdir4, open as open4, readdir as readdir4, stat as stat5 } from "node:fs/promises";
|
|
1064
|
+
import path10 from "node:path";
|
|
765
1065
|
async function run(executable, args, options) {
|
|
766
1066
|
await new Promise((resolve, reject) => {
|
|
767
1067
|
const child = spawn2(executable, args, {
|
|
@@ -769,30 +1069,44 @@ async function run(executable, args, options) {
|
|
|
769
1069
|
env: options.env,
|
|
770
1070
|
stdio: ["ignore", "pipe", "pipe"]
|
|
771
1071
|
});
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
1072
|
+
let output = Buffer.alloc(0);
|
|
1073
|
+
const collect = (chunk) => {
|
|
1074
|
+
output = Buffer.concat([output, chunk]).subarray(-64 * 1024);
|
|
1075
|
+
};
|
|
1076
|
+
child.stdout.on("data", collect);
|
|
1077
|
+
child.stderr.on("data", collect);
|
|
1078
|
+
let timedOut = false;
|
|
1079
|
+
const timeout = setTimeout(() => {
|
|
1080
|
+
timedOut = true;
|
|
1081
|
+
child.kill("SIGKILL");
|
|
1082
|
+
}, 10 * 6e4);
|
|
1083
|
+
child.once("error", () => clearTimeout(timeout));
|
|
775
1084
|
child.once("error", reject);
|
|
776
1085
|
child.once("close", (code) => {
|
|
1086
|
+
clearTimeout(timeout);
|
|
1087
|
+
if (timedOut) {
|
|
1088
|
+
reject(new Error(`${path10.basename(executable)} timed out after 10 minutes`));
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
777
1091
|
if (code === 0) {
|
|
778
1092
|
resolve();
|
|
779
1093
|
return;
|
|
780
1094
|
}
|
|
781
|
-
const
|
|
782
|
-
if (
|
|
783
|
-
reject(new Error(`${
|
|
1095
|
+
const message = output.toString("utf8").trim();
|
|
1096
|
+
if (message) console.error(message);
|
|
1097
|
+
reject(new Error(`${path10.basename(executable)} exited with code ${code}`));
|
|
784
1098
|
});
|
|
785
1099
|
});
|
|
786
1100
|
}
|
|
787
1101
|
async function ensurePlaywrightBrowser(runtimeDirectory, paths) {
|
|
788
1102
|
if (process.env.SWITCHY_SKIP_BROWSER_INSTALL === "1") return;
|
|
789
|
-
const cliPath =
|
|
1103
|
+
const cliPath = path10.join(
|
|
790
1104
|
runtimeDirectory,
|
|
791
1105
|
"node_modules",
|
|
792
1106
|
"playwright",
|
|
793
1107
|
"cli.js"
|
|
794
1108
|
);
|
|
795
|
-
if (!(await
|
|
1109
|
+
if (!(await stat5(cliPath).catch(() => null))?.isFile()) {
|
|
796
1110
|
throw new Error("The packaged runtime is missing the Playwright installer");
|
|
797
1111
|
}
|
|
798
1112
|
await run(process.execPath, [cliPath, "install", "chromium"], {
|
|
@@ -806,193 +1120,977 @@ async function ensurePlaywrightBrowser(runtimeDirectory, paths) {
|
|
|
806
1120
|
async function runDatabaseMigration(runtimeDirectory, paths) {
|
|
807
1121
|
await run(
|
|
808
1122
|
process.execPath,
|
|
809
|
-
[
|
|
1123
|
+
[path10.join(runtimeDirectory, "bin", "migrate.cjs")],
|
|
810
1124
|
{
|
|
811
1125
|
cwd: runtimeDirectory,
|
|
812
1126
|
env: {
|
|
813
1127
|
...process.env,
|
|
814
1128
|
NODE_ENV: "production",
|
|
815
|
-
SWITCHY_HOME: paths.root
|
|
1129
|
+
SWITCHY_HOME: paths.root,
|
|
1130
|
+
SWITCHY_MIGRATION_PARENT_PID: String(process.pid)
|
|
816
1131
|
}
|
|
817
1132
|
}
|
|
818
1133
|
);
|
|
819
1134
|
}
|
|
820
1135
|
async function createUpdateSnapshot(paths, fromVersion, toVersion) {
|
|
821
|
-
if (!(await
|
|
1136
|
+
if (!(await stat5(paths.productionData).catch(() => null))?.isDirectory()) {
|
|
822
1137
|
return null;
|
|
823
1138
|
}
|
|
824
1139
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/gu, "-");
|
|
825
|
-
const snapshotDirectory =
|
|
1140
|
+
const snapshotDirectory = path10.join(
|
|
826
1141
|
paths.updateSnapshots,
|
|
827
1142
|
`update-${fromVersion}-to-${toVersion}-${timestamp}`
|
|
828
1143
|
);
|
|
829
1144
|
await mkdir4(snapshotDirectory, { recursive: true, mode: 448 });
|
|
830
|
-
await cp2(paths.productionData,
|
|
1145
|
+
await cp2(paths.productionData, path10.join(snapshotDirectory, "production"), {
|
|
831
1146
|
recursive: true
|
|
832
1147
|
});
|
|
833
|
-
await
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
`,
|
|
841
|
-
{ mode: 384 }
|
|
842
|
-
);
|
|
1148
|
+
await syncTree(path10.join(snapshotDirectory, "production"));
|
|
1149
|
+
await writeJsonFileAtomic(path10.join(snapshotDirectory, "update.json"), {
|
|
1150
|
+
fromVersion,
|
|
1151
|
+
toVersion,
|
|
1152
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1153
|
+
});
|
|
1154
|
+
await syncDirectory(paths.updateSnapshots);
|
|
843
1155
|
return snapshotDirectory;
|
|
844
1156
|
}
|
|
1157
|
+
async function syncTree(directory) {
|
|
1158
|
+
for (const entry of await readdir4(directory, { withFileTypes: true })) {
|
|
1159
|
+
const file = path10.join(directory, entry.name);
|
|
1160
|
+
if (entry.isDirectory()) await syncTree(file);
|
|
1161
|
+
else if (entry.isFile()) {
|
|
1162
|
+
const handle = await open4(file, "r");
|
|
1163
|
+
try {
|
|
1164
|
+
await handle.sync();
|
|
1165
|
+
} finally {
|
|
1166
|
+
await handle.close();
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
await syncDirectory(directory);
|
|
1171
|
+
}
|
|
1172
|
+
var init_runtime = __esm({
|
|
1173
|
+
"src/runtime.ts"() {
|
|
1174
|
+
"use strict";
|
|
1175
|
+
init_lifecycle_state2();
|
|
1176
|
+
init_files();
|
|
1177
|
+
}
|
|
1178
|
+
});
|
|
845
1179
|
|
|
846
|
-
// src/
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
1180
|
+
// src/updater.ts
|
|
1181
|
+
import { cp as cp3, readdir as readdir5, rename as rename4, rm as rm5, stat as stat6 } from "node:fs/promises";
|
|
1182
|
+
import path11 from "node:path";
|
|
1183
|
+
async function appRequest(paths, route, method = "GET") {
|
|
1184
|
+
const running = await getRunningProcess(paths);
|
|
1185
|
+
if (!running?.live || running.live.instanceId !== running.record.instanceId) {
|
|
1186
|
+
throw new Error("Cannot verify the running Switchy instance");
|
|
1187
|
+
}
|
|
1188
|
+
return fetch(`http://127.0.0.1:${running.record.port}/api/lifecycle/${route}`, {
|
|
1189
|
+
method,
|
|
1190
|
+
headers: { "X-Switchy-Request": "true" },
|
|
1191
|
+
signal: AbortSignal.timeout(1e4)
|
|
1192
|
+
});
|
|
851
1193
|
}
|
|
852
|
-
async function
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
await
|
|
860
|
-
|
|
861
|
-
() => startCommandUnlocked({ paths, version, port, foreground })
|
|
862
|
-
);
|
|
1194
|
+
async function applicationIsIdle(paths) {
|
|
1195
|
+
if (!await getRunningProcess(paths)) return true;
|
|
1196
|
+
const response = await appRequest(paths, "activity");
|
|
1197
|
+
if (response.status === 404) {
|
|
1198
|
+
throw new Error("This older Switchy version needs a one-time stopped upgrade. Run switchy stop, then switchy update.");
|
|
1199
|
+
}
|
|
1200
|
+
if (!response.ok) throw new Error("Could not check active Switchy work");
|
|
1201
|
+
const result = await response.json();
|
|
1202
|
+
return result.idle === true;
|
|
863
1203
|
}
|
|
864
|
-
async function
|
|
865
|
-
paths
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
})
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
);
|
|
875
|
-
return;
|
|
1204
|
+
async function browsersAreOpen(paths) {
|
|
1205
|
+
const directory = lifecycleFiles(paths).browser;
|
|
1206
|
+
const files = await readdir5(directory).catch((error) => {
|
|
1207
|
+
if (error.code === "ENOENT") return [];
|
|
1208
|
+
throw error;
|
|
1209
|
+
});
|
|
1210
|
+
for (const file of files) {
|
|
1211
|
+
const filePath = path11.join(directory, file);
|
|
1212
|
+
const info = await stat6(filePath).catch(() => null);
|
|
1213
|
+
if (info && Date.now() - info.mtimeMs < 9e4) return true;
|
|
1214
|
+
await rm5(filePath, { force: true });
|
|
876
1215
|
}
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
const
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1216
|
+
return false;
|
|
1217
|
+
}
|
|
1218
|
+
async function assertNoOtherRuntimes(paths) {
|
|
1219
|
+
const directory = path11.join(paths.runtime, "coordination");
|
|
1220
|
+
const files = await readdir5(directory).catch((error) => {
|
|
1221
|
+
if (error.code === "ENOENT") return [];
|
|
1222
|
+
throw error;
|
|
1223
|
+
});
|
|
1224
|
+
for (const file of files.filter((name) => /^\.switchy-runtime-.*\.json$/u.test(name))) {
|
|
1225
|
+
const lock = await readJsonFile(path11.join(directory, file));
|
|
1226
|
+
if (!lock || !Number.isInteger(lock.pid) || lock.pid <= 0) throw new Error("Cannot verify application shutdown");
|
|
1227
|
+
if (predatesCurrentBoot(lock.startedAt)) continue;
|
|
1228
|
+
try {
|
|
1229
|
+
process.kill(lock.pid, 0);
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
if (error.code === "ESRCH") continue;
|
|
1232
|
+
throw error;
|
|
1233
|
+
}
|
|
1234
|
+
throw new Error("Another Switchy runtime is using local data");
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
async function restoreSnapshot(paths, transaction) {
|
|
1238
|
+
if (!transaction.snapshot) throw new Error("Update recovery snapshot is missing");
|
|
1239
|
+
const expected = path11.resolve(paths.updateSnapshots);
|
|
1240
|
+
const snapshot = path11.resolve(transaction.snapshot);
|
|
1241
|
+
if (path11.dirname(snapshot) !== expected) throw new Error("Invalid update recovery snapshot path");
|
|
1242
|
+
const original = path11.join(snapshot, "production");
|
|
1243
|
+
if (!(await stat6(original)).isDirectory()) throw new Error("Update recovery snapshot is missing");
|
|
1244
|
+
const staging = path11.join(paths.data, ".update-restore");
|
|
1245
|
+
const failed = path11.join(paths.data, ".update-failed");
|
|
1246
|
+
await rm5(staging, { recursive: true, force: true });
|
|
1247
|
+
await cp3(original, staging, { recursive: true });
|
|
1248
|
+
await syncTree(staging);
|
|
1249
|
+
await rm5(failed, { recursive: true, force: true });
|
|
1250
|
+
if (await stat6(paths.productionData).catch(() => null)) await rename4(paths.productionData, failed);
|
|
1251
|
+
await rename4(staging, paths.productionData);
|
|
1252
|
+
await syncDirectory(paths.data);
|
|
1253
|
+
await rm5(failed, { recursive: true, force: true });
|
|
1254
|
+
}
|
|
1255
|
+
async function recoverInterruptedUpdate(paths) {
|
|
1256
|
+
return withDirectoryLock(path11.join(paths.runtime, "migration.lock"), () => recoverUpdate(paths));
|
|
1257
|
+
}
|
|
1258
|
+
async function recoverUpdate(paths) {
|
|
1259
|
+
const files = lifecycleFiles(paths);
|
|
1260
|
+
const transaction = await readJsonFile(files.transaction);
|
|
1261
|
+
if (!transaction) {
|
|
1262
|
+
await removeFile(files.maintenance);
|
|
1263
|
+
return false;
|
|
1264
|
+
}
|
|
1265
|
+
if (transaction.fromVersion !== null && !/^\d+\.\d+\.\d+$/u.test(transaction.fromVersion) || !/^\d+\.\d+\.\d+$/u.test(transaction.toVersion) || !["prepared", "stopped", "snapshot", "starting", "committed"].includes(transaction.stage)) {
|
|
1266
|
+
throw new Error("Invalid update recovery record");
|
|
1267
|
+
}
|
|
1268
|
+
if (transaction.stage === "committed") {
|
|
1269
|
+
await saveUpdateState2(paths, { phase: "idle", failedVersion: null, downloadedVersion: null, message: null });
|
|
1270
|
+
await removeFile(files.transaction);
|
|
1271
|
+
await removeFile(files.maintenance);
|
|
1272
|
+
return false;
|
|
1273
|
+
}
|
|
1274
|
+
const running = await getRunningProcess(paths);
|
|
1275
|
+
if (running) await stopSwitchy(paths);
|
|
1276
|
+
await assertNoOtherRuntimes(paths);
|
|
1277
|
+
if (transaction.stage === "snapshot" || transaction.stage === "starting") {
|
|
1278
|
+
if (transaction.snapshot) await restoreSnapshot(paths, transaction);
|
|
1279
|
+
else if (transaction.hadData === false) await rm5(paths.productionData, { recursive: true, force: true });
|
|
1280
|
+
else throw new Error("Update recovery snapshot is missing");
|
|
1281
|
+
}
|
|
1282
|
+
if (transaction.fromVersion) await setCurrentVersion(paths, transaction.fromVersion, transaction.previousVersion ?? null);
|
|
1283
|
+
else await removeFile(paths.currentVersion);
|
|
1284
|
+
await saveUpdateState2(paths, {
|
|
1285
|
+
phase: "failed",
|
|
1286
|
+
failedVersion: transaction.toVersion,
|
|
1287
|
+
message: "The update did not complete. Switchy restored the previous version."
|
|
1288
|
+
});
|
|
1289
|
+
await removeFile(files.transaction);
|
|
1290
|
+
await removeFile(files.maintenance);
|
|
1291
|
+
return true;
|
|
1292
|
+
}
|
|
1293
|
+
async function downloadUpdate(paths, version) {
|
|
1294
|
+
return withUpdateLock(paths, () => prepareUpdate(paths, version));
|
|
1295
|
+
}
|
|
1296
|
+
async function prepareUpdate(paths, version) {
|
|
1297
|
+
const staged = (await readUpdateState(paths)).downloadedVersion === version;
|
|
1298
|
+
if (!staged) await saveUpdateState2(paths, { phase: "downloading", message: null });
|
|
1299
|
+
const directory = await installRuntime(version, paths);
|
|
1300
|
+
if (!(await stat6(path11.join(directory, "bin/lifecycle.cjs")).catch(() => null))?.isFile()) {
|
|
1301
|
+
throw new Error("The candidate runtime is missing lifecycle support");
|
|
1302
|
+
}
|
|
1303
|
+
const metadata = await readJsonFile(path11.join(directory, "switchy-runtime.json"));
|
|
1304
|
+
if (metadata?.lifecycleProtocol !== 2) throw new Error("This release does not support safe managed updates. Choose a current release.");
|
|
1305
|
+
if (!staged) {
|
|
1306
|
+
await ensurePlaywrightBrowser(directory, paths);
|
|
1307
|
+
await saveUpdateState2(paths, { phase: "ready", downloadedVersion: version, message: null });
|
|
1308
|
+
}
|
|
1309
|
+
return directory;
|
|
1310
|
+
}
|
|
1311
|
+
async function installUpdate(paths, version, manual, options = {}) {
|
|
1312
|
+
return withUpdateLock(paths, async () => {
|
|
1313
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
1314
|
+
if (current && compareVersions(version, current.version) <= 0) return false;
|
|
1315
|
+
const preferences = await readPreferences(paths);
|
|
1316
|
+
if (!await applicationIsIdle(paths) || !manual && await browsersAreOpen(paths)) {
|
|
1317
|
+
await saveUpdateState2(paths, { phase: "waiting", message: "Waiting for active work to finish and Switchy tabs to close." });
|
|
1318
|
+
return false;
|
|
1319
|
+
}
|
|
1320
|
+
const directory = await prepareUpdate(paths, version);
|
|
1321
|
+
return withDirectoryLock(paths.startLock, async () => {
|
|
1322
|
+
await recoverInterruptedUpdate(paths);
|
|
1323
|
+
const selected = await readJsonFile(paths.currentVersion);
|
|
1324
|
+
if (selected && compareVersions(version, selected.version) <= 0) return false;
|
|
1325
|
+
const latestPreferences = await readPreferences(paths);
|
|
1326
|
+
if (preferences.stopToken !== latestPreferences.stopToken || preferences.running && !latestPreferences.running || !manual && (!latestPreferences.automaticUpdates || await browsersAreOpen(paths))) return false;
|
|
1327
|
+
return activateRuntime(paths, directory, version, selected, options);
|
|
1328
|
+
});
|
|
890
1329
|
});
|
|
1330
|
+
}
|
|
1331
|
+
async function activateRuntime(paths, directory, version, current, options) {
|
|
1332
|
+
const files = lifecycleFiles(paths);
|
|
1333
|
+
await writeJsonFileAtomic(files.maintenance, { startedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
891
1334
|
try {
|
|
892
|
-
|
|
1335
|
+
if (!await applicationIsIdle(paths)) {
|
|
1336
|
+
await saveUpdateState2(paths, { phase: "waiting", message: "Waiting for active work to finish." });
|
|
1337
|
+
return false;
|
|
1338
|
+
}
|
|
1339
|
+
const running = await getRunningProcess(paths);
|
|
1340
|
+
const transaction = {
|
|
1341
|
+
fromVersion: current?.version ?? null,
|
|
1342
|
+
toVersion: version,
|
|
1343
|
+
snapshot: null,
|
|
1344
|
+
previousVersion: current?.previousVersion ?? null,
|
|
1345
|
+
hadData: (await stat6(paths.productionData).catch(() => null))?.isDirectory() ?? false,
|
|
1346
|
+
port: options.port ?? running?.record.port ?? (await readPreferences(paths)).port,
|
|
1347
|
+
stage: "prepared"
|
|
1348
|
+
};
|
|
1349
|
+
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1350
|
+
await saveUpdateState2(paths, { phase: "installing", message: "Switchy is updating\u2026" });
|
|
1351
|
+
if (running) await stopSwitchy(paths);
|
|
1352
|
+
await assertNoOtherRuntimes(paths);
|
|
1353
|
+
transaction.stage = "stopped";
|
|
1354
|
+
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1355
|
+
if (transaction.hadData) {
|
|
1356
|
+
transaction.snapshot = await createUpdateSnapshot(paths, current?.version ?? "unmanaged", version);
|
|
1357
|
+
if (!transaction.snapshot) throw new Error("Cannot update without a recovery snapshot");
|
|
1358
|
+
}
|
|
1359
|
+
transaction.stage = "snapshot";
|
|
1360
|
+
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1361
|
+
await runDatabaseMigration(directory, paths);
|
|
1362
|
+
transaction.stage = "starting";
|
|
1363
|
+
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1364
|
+
await startSwitchyProcess({
|
|
893
1365
|
paths,
|
|
894
|
-
runtimeDirectory,
|
|
895
|
-
version
|
|
896
|
-
port,
|
|
897
|
-
foreground
|
|
1366
|
+
runtimeDirectory: directory,
|
|
1367
|
+
version,
|
|
1368
|
+
port: transaction.port,
|
|
1369
|
+
foreground: options.foreground ?? false,
|
|
1370
|
+
candidate: true
|
|
898
1371
|
});
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
);
|
|
1372
|
+
const live = await getRunningProcess(paths);
|
|
1373
|
+
const identity = live && await fetchLiveness(live.record);
|
|
1374
|
+
if (!identity || identity.version !== version || identity.instanceId !== live?.record.instanceId) {
|
|
1375
|
+
throw new Error("Updated application identity did not match");
|
|
903
1376
|
}
|
|
1377
|
+
await setCurrentVersion(paths, version, current?.version ?? null);
|
|
1378
|
+
await setRunningPreference(paths, !options.foreground, transaction.port);
|
|
1379
|
+
transaction.stage = "committed";
|
|
1380
|
+
await writeJsonFileAtomic(files.transaction, transaction);
|
|
1381
|
+
await saveUpdateState2(paths, { phase: "idle", failedVersion: null, downloadedVersion: null, message: null });
|
|
1382
|
+
await removeFile(files.transaction);
|
|
1383
|
+
await pruneInstallArtifacts(paths, [version, current?.version ?? null]).catch((error) => {
|
|
1384
|
+
console.warn("Could not prune old update artifacts:", error);
|
|
1385
|
+
});
|
|
1386
|
+
return true;
|
|
1387
|
+
} catch (error) {
|
|
1388
|
+
await recoverInterruptedUpdate(paths);
|
|
1389
|
+
if (current && !await getRunningProcess(paths)) {
|
|
1390
|
+
await startSwitchyProcess({
|
|
1391
|
+
paths,
|
|
1392
|
+
runtimeDirectory: path11.join(paths.versions, current.version),
|
|
1393
|
+
version: current.version,
|
|
1394
|
+
port: options.port ?? (await readPreferences(paths)).port,
|
|
1395
|
+
foreground: false
|
|
1396
|
+
});
|
|
1397
|
+
}
|
|
1398
|
+
throw error;
|
|
904
1399
|
} finally {
|
|
905
|
-
await
|
|
1400
|
+
if (!await readJsonFile(files.transaction)) await removeFile(files.maintenance);
|
|
906
1401
|
}
|
|
907
1402
|
}
|
|
908
|
-
function
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1403
|
+
async function withUpdateLock(paths, operation) {
|
|
1404
|
+
return withDirectoryLock(lifecycleFiles(paths).updateLock, async () => {
|
|
1405
|
+
try {
|
|
1406
|
+
return await operation();
|
|
1407
|
+
} catch (error) {
|
|
1408
|
+
await saveUpdateState2(paths, { phase: "failed", message: "Could not update Switchy. Check the lifecycle log for details." }).catch((stateError) => console.error("Could not record update failure:", stateError));
|
|
1409
|
+
throw error;
|
|
1410
|
+
}
|
|
1411
|
+
});
|
|
915
1412
|
}
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1413
|
+
var init_updater = __esm({
|
|
1414
|
+
"src/updater.ts"() {
|
|
1415
|
+
"use strict";
|
|
1416
|
+
init_cleanup();
|
|
1417
|
+
init_files();
|
|
1418
|
+
init_lifecycle_state2();
|
|
1419
|
+
init_process_manager();
|
|
1420
|
+
init_preferences();
|
|
1421
|
+
init_release();
|
|
1422
|
+
init_runtime();
|
|
1423
|
+
}
|
|
1424
|
+
});
|
|
1425
|
+
|
|
1426
|
+
// src/controller.ts
|
|
1427
|
+
import path12 from "node:path";
|
|
1428
|
+
async function startRuntime(paths, options = {}) {
|
|
1429
|
+
const stopToken = (await readPreferences(paths)).stopToken;
|
|
1430
|
+
await withDirectoryLock(paths.startLock, () => recoverInterruptedUpdate(paths));
|
|
1431
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
1432
|
+
const version = assertStableVersion(options.version ?? current?.version ?? CLI_VERSION);
|
|
1433
|
+
const port = options.port ?? (await readPreferences(paths)).port;
|
|
1434
|
+
if (!current || version !== current.version) {
|
|
1435
|
+
const installed = await installUpdate(paths, version, true, { port, foreground: options.foreground });
|
|
1436
|
+
if (!installed) throw new Error("Version change deferred. Wait for active work to finish. Downgrades are not supported.");
|
|
1437
|
+
}
|
|
1438
|
+
return withDirectoryLock(paths.startLock, async () => {
|
|
1439
|
+
if ((await readPreferences(paths)).stopToken !== stopToken) throw new Error("Start cancelled by a stop request.");
|
|
1440
|
+
const selected = await readJsonFile(paths.currentVersion);
|
|
1441
|
+
if (!selected) throw new Error("Switchy has no installed runtime");
|
|
1442
|
+
const running = await getRunningProcess(paths);
|
|
1443
|
+
if (running && !running.live) throw new Error("Switchy is unresponsive. Inspect logs or run stop --force before starting again.");
|
|
1444
|
+
if (running && options.foreground && current?.version === version) throw new Error("Stop the running app before starting in foreground mode.");
|
|
1445
|
+
const record = running?.record ?? await startSwitchyProcess({
|
|
1446
|
+
paths,
|
|
1447
|
+
runtimeDirectory: path12.join(paths.versions, selected.version),
|
|
1448
|
+
version: selected.version,
|
|
1449
|
+
port,
|
|
1450
|
+
foreground: options.foreground ?? false
|
|
1451
|
+
});
|
|
1452
|
+
await setRunningPreference(paths, !options.foreground, record.port);
|
|
1453
|
+
return record;
|
|
922
1454
|
});
|
|
923
1455
|
}
|
|
924
|
-
async function
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
1456
|
+
async function stopRuntime(paths, force = false) {
|
|
1457
|
+
await requestRuntimeStop(paths);
|
|
1458
|
+
return withDirectoryLock(paths.startLock, async () => {
|
|
1459
|
+
await requestRuntimeStop(paths);
|
|
1460
|
+
return stopSwitchy(paths, force);
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
async function reconcileRuntime(paths) {
|
|
1464
|
+
return withDirectoryLock(paths.startLock, async () => {
|
|
1465
|
+
await recoverInterruptedUpdate(paths);
|
|
1466
|
+
const preferences = await readPreferences(paths);
|
|
1467
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
1468
|
+
if (!preferences.running || !current) return null;
|
|
1469
|
+
const running = await getRunningProcess(paths);
|
|
1470
|
+
if (running) return running.record;
|
|
1471
|
+
return startSwitchyProcess({
|
|
1472
|
+
paths,
|
|
1473
|
+
runtimeDirectory: path12.join(paths.versions, current.version),
|
|
1474
|
+
version: current.version,
|
|
1475
|
+
port: preferences.port,
|
|
1476
|
+
foreground: false
|
|
1477
|
+
});
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
async function restartRuntime(paths) {
|
|
1481
|
+
await requestRuntimeStop(paths);
|
|
1482
|
+
return withDirectoryLock(paths.startLock, async () => {
|
|
1483
|
+
await requestRuntimeStop(paths);
|
|
1484
|
+
await recoverInterruptedUpdate(paths);
|
|
1485
|
+
await stopSwitchy(paths);
|
|
1486
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
1487
|
+
if (!current) throw new Error("Switchy is not installed. Run switchy start first.");
|
|
1488
|
+
const preferences = await readPreferences(paths);
|
|
1489
|
+
const record = await startSwitchyProcess({
|
|
1490
|
+
paths,
|
|
1491
|
+
runtimeDirectory: path12.join(paths.versions, current.version),
|
|
1492
|
+
version: current.version,
|
|
1493
|
+
port: preferences.port,
|
|
1494
|
+
foreground: false
|
|
1495
|
+
});
|
|
1496
|
+
await setRunningPreference(paths, true, record.port);
|
|
1497
|
+
return record;
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
var init_controller = __esm({
|
|
1501
|
+
"src/controller.ts"() {
|
|
1502
|
+
"use strict";
|
|
1503
|
+
init_config();
|
|
1504
|
+
init_files();
|
|
1505
|
+
init_lifecycle_state2();
|
|
1506
|
+
init_process_manager();
|
|
1507
|
+
init_preferences();
|
|
1508
|
+
init_release();
|
|
1509
|
+
init_updater();
|
|
1510
|
+
}
|
|
1511
|
+
});
|
|
1512
|
+
|
|
1513
|
+
// src/paths.ts
|
|
1514
|
+
import { mkdir as mkdir5 } from "node:fs/promises";
|
|
1515
|
+
import os3 from "node:os";
|
|
1516
|
+
import path13 from "node:path";
|
|
1517
|
+
function getSwitchyPaths(configuredRoot = process.env.SWITCHY_HOME) {
|
|
1518
|
+
const override = configuredRoot?.trim();
|
|
1519
|
+
if (override && !path13.isAbsolute(override)) {
|
|
1520
|
+
throw new Error("SWITCHY_HOME must be an absolute path");
|
|
1521
|
+
}
|
|
1522
|
+
const root = override ? path13.normalize(override) : path13.join(os3.homedir(), ".switchy");
|
|
1523
|
+
const data = path13.join(root, "data");
|
|
1524
|
+
const app = path13.join(root, "app");
|
|
1525
|
+
const runtime = path13.join(root, "runtime");
|
|
1526
|
+
const logs = path13.join(root, "logs");
|
|
1527
|
+
const cache = path13.join(root, "cache");
|
|
1528
|
+
return {
|
|
1529
|
+
root,
|
|
1530
|
+
data,
|
|
1531
|
+
productionData: path13.join(data, "production"),
|
|
1532
|
+
app,
|
|
1533
|
+
versions: path13.join(app, "versions"),
|
|
1534
|
+
currentVersion: path13.join(app, "current.json"),
|
|
1535
|
+
runtime,
|
|
1536
|
+
processRecord: path13.join(runtime, "process.json"),
|
|
1537
|
+
installLock: path13.join(runtime, "install.lock"),
|
|
1538
|
+
startLock: path13.join(runtime, "start.lock"),
|
|
1539
|
+
logs,
|
|
1540
|
+
logFile: path13.join(logs, "switchy.log"),
|
|
1541
|
+
cache,
|
|
1542
|
+
downloads: path13.join(cache, "downloads"),
|
|
1543
|
+
playwright: path13.join(cache, "playwright"),
|
|
1544
|
+
updateSnapshots: path13.join(root, "update-snapshots")
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
async function ensureSwitchyDirectories(paths) {
|
|
1548
|
+
for (const directory of [
|
|
1549
|
+
paths.root,
|
|
1550
|
+
paths.data,
|
|
1551
|
+
paths.app,
|
|
1552
|
+
paths.versions,
|
|
1553
|
+
paths.runtime,
|
|
1554
|
+
paths.logs,
|
|
1555
|
+
paths.cache,
|
|
1556
|
+
paths.downloads,
|
|
1557
|
+
paths.playwright,
|
|
1558
|
+
paths.updateSnapshots
|
|
1559
|
+
]) {
|
|
1560
|
+
await mkdir5(directory, { recursive: true, mode: 448 });
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
var init_paths = __esm({
|
|
1564
|
+
"src/paths.ts"() {
|
|
1565
|
+
"use strict";
|
|
1566
|
+
}
|
|
1567
|
+
});
|
|
1568
|
+
|
|
1569
|
+
// src/startup.ts
|
|
1570
|
+
import { execFile, spawn as spawn3 } from "node:child_process";
|
|
1571
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
1572
|
+
import { chmod, copyFile, link, mkdir as mkdir6, open as open5, readFile as readFile4, rename as rename5, rm as rm6, stat as stat7 } from "node:fs/promises";
|
|
1573
|
+
import os4 from "node:os";
|
|
1574
|
+
import path14 from "node:path";
|
|
1575
|
+
import { promisify } from "node:util";
|
|
1576
|
+
function escapeXml(value) {
|
|
1577
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
1578
|
+
}
|
|
1579
|
+
function startupPlist(paths, executable = path14.join(lifecycleFiles(paths).host, "node")) {
|
|
1580
|
+
const host = lifecycleFiles(paths).host;
|
|
1581
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1582
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1583
|
+
<plist version="1.0"><dict>
|
|
1584
|
+
<key>Label</key><string>${LABEL}</string>
|
|
1585
|
+
<key>ProgramArguments</key><array><string>${escapeXml(executable)}</string><string>${escapeXml(path14.join(host, "supervisor.cjs"))}</string><string>--login</string></array>
|
|
1586
|
+
<key>EnvironmentVariables</key><dict><key>SWITCHY_HOME</key><string>${escapeXml(paths.root)}</string></dict>
|
|
1587
|
+
<key>RunAtLoad</key><true/>
|
|
1588
|
+
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
|
1589
|
+
<key>ThrottleInterval</key><integer>30</integer>
|
|
1590
|
+
<key>StandardOutPath</key><string>${escapeXml(path14.join(paths.logs, "lifecycle.log"))}</string>
|
|
1591
|
+
<key>StandardErrorPath</key><string>${escapeXml(path14.join(paths.logs, "lifecycle.log"))}</string>
|
|
1592
|
+
</dict></plist>
|
|
1593
|
+
`;
|
|
1594
|
+
}
|
|
1595
|
+
async function hostNode(paths) {
|
|
1596
|
+
const metadata = await readJsonFile(path14.join(lifecycleFiles(paths).host, "node.json"));
|
|
1597
|
+
if (!metadata || !/^node-24\.\d+\.\d+(?:\.exe)?$/u.test(metadata.file)) throw new Error("Switchy manager Node metadata is invalid");
|
|
1598
|
+
return metadata;
|
|
1599
|
+
}
|
|
1600
|
+
async function installHost(paths, runtimeDirectory) {
|
|
1601
|
+
if (!(await stat7(path14.join(runtimeDirectory, "bin/lifecycle.cjs")).catch(() => null))?.isFile()) return false;
|
|
1602
|
+
return withDirectoryLock(lifecycleFiles(paths).hostLock, async () => {
|
|
1603
|
+
const host = lifecycleFiles(paths).host;
|
|
1604
|
+
await mkdir6(host, { recursive: true, mode: 448 });
|
|
1605
|
+
const previous = await readJsonFile(path14.join(host, "node.json"));
|
|
1606
|
+
const version = previous && compareVersions(previous.version, process.versions.node) > 0 ? previous.version : process.versions.node;
|
|
1607
|
+
const file = `node-${version}${process.platform === "win32" ? ".exe" : ""}`;
|
|
1608
|
+
const node = path14.join(host, file);
|
|
1609
|
+
if (!(await stat7(node).catch(() => null))?.isFile()) {
|
|
1610
|
+
if (version !== process.versions.node) throw new Error("The managed Node executable is missing. Start with the newer Node 24 version to restore it.");
|
|
1611
|
+
const temporary = `${node}.${randomUUID6()}.tmp`;
|
|
1612
|
+
try {
|
|
1613
|
+
await copyFile(process.execPath, temporary);
|
|
1614
|
+
await chmod(temporary, 448);
|
|
1615
|
+
const handle = await open5(temporary, "r");
|
|
1616
|
+
try {
|
|
1617
|
+
await handle.sync();
|
|
1618
|
+
} finally {
|
|
1619
|
+
await handle.close();
|
|
1620
|
+
}
|
|
1621
|
+
await rename5(temporary, node);
|
|
1622
|
+
} finally {
|
|
1623
|
+
await rm6(temporary, { force: true });
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
const alias = path14.join(host, process.platform === "win32" ? "node.exe" : "node");
|
|
1627
|
+
if (previous?.file !== file || !await stat7(alias).catch(() => null)) {
|
|
1628
|
+
const temporary = `${alias}.${randomUUID6()}.tmp`;
|
|
1629
|
+
try {
|
|
1630
|
+
await link(node, temporary);
|
|
1631
|
+
await rename5(temporary, alias);
|
|
1632
|
+
} catch (error) {
|
|
1633
|
+
if (!["EPERM", "EBUSY", "EACCES"].includes(error.code ?? "") || !await stat7(alias).catch(() => null)) throw error;
|
|
1634
|
+
} finally {
|
|
1635
|
+
await rm6(temporary, { force: true });
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
await writeJsonFileAtomic(path14.join(host, "node.json"), { file, version });
|
|
1639
|
+
await writeFileAtomic(path14.join(host, "supervisor.cjs"), SUPERVISOR);
|
|
1640
|
+
await saveStartupEnvironment(paths);
|
|
1641
|
+
return true;
|
|
1642
|
+
});
|
|
1643
|
+
}
|
|
1644
|
+
async function startHost(paths) {
|
|
1645
|
+
const host = lifecycleFiles(paths).host;
|
|
1646
|
+
const log = await open5(path14.join(paths.logs, "lifecycle.log"), "a", 384);
|
|
1647
|
+
const node = await hostNode(paths);
|
|
1648
|
+
const child = spawn3(
|
|
1649
|
+
path14.join(host, node.file),
|
|
1650
|
+
[path14.join(host, "supervisor.cjs")],
|
|
1651
|
+
{
|
|
1652
|
+
detached: true,
|
|
1653
|
+
stdio: ["ignore", log.fd, log.fd],
|
|
1654
|
+
windowsHide: true,
|
|
1655
|
+
env: { ...await runtimeEnvironment(paths), SWITCHY_HOME: paths.root }
|
|
1656
|
+
}
|
|
1657
|
+
);
|
|
1658
|
+
await new Promise((resolve, reject) => {
|
|
1659
|
+
child.once("spawn", resolve);
|
|
1660
|
+
child.once("error", reject);
|
|
1661
|
+
}).finally(() => log.close());
|
|
1662
|
+
child.unref();
|
|
1663
|
+
}
|
|
1664
|
+
async function setStartupRegistration(paths, enabled) {
|
|
1665
|
+
if (process.platform !== "darwin") {
|
|
1666
|
+
if (enabled) throw new Error("Start at sign-in is currently supported on macOS");
|
|
930
1667
|
return;
|
|
931
1668
|
}
|
|
932
|
-
const
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1669
|
+
const file = path14.join(os4.homedir(), "Library/LaunchAgents", `${LABEL}.plist`);
|
|
1670
|
+
await mkdir6(path14.dirname(file), { recursive: true, mode: 448 });
|
|
1671
|
+
const existingRegistration = await readFile4(file, "utf8").catch(() => "");
|
|
1672
|
+
if (existingRegistration && !existingRegistration.includes(`<string>${escapeXml(paths.root)}</string>`)) {
|
|
1673
|
+
throw new Error("Another Switchy installation owns the startup item");
|
|
1674
|
+
}
|
|
1675
|
+
if (enabled) {
|
|
1676
|
+
const node = await hostNode(paths);
|
|
1677
|
+
await writeFileAtomic(file, startupPlist(paths, path14.join(lifecycleFiles(paths).host, node.file)));
|
|
1678
|
+
} else {
|
|
1679
|
+
await rm6(file, { force: true });
|
|
1680
|
+
const uid = process.getuid?.();
|
|
1681
|
+
if (uid !== void 0) {
|
|
1682
|
+
await execute("/bin/launchctl", ["disable", `gui/${uid}/${LABEL}`]).catch(() => void 0);
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
if (enabled) {
|
|
1686
|
+
const uid = process.getuid?.();
|
|
1687
|
+
if (uid !== void 0) await execute("/bin/launchctl", ["enable", `gui/${uid}/${LABEL}`]);
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
var execute, LABEL, SUPERVISOR;
|
|
1691
|
+
var init_startup = __esm({
|
|
1692
|
+
"src/startup.ts"() {
|
|
1693
|
+
"use strict";
|
|
1694
|
+
init_files();
|
|
1695
|
+
init_startup_environment();
|
|
1696
|
+
init_lifecycle_state2();
|
|
1697
|
+
execute = promisify(execFile);
|
|
1698
|
+
LABEL = "com.switchy.lifecycle";
|
|
1699
|
+
SUPERVISOR = `const fs = require('node:fs');
|
|
1700
|
+
const path = require('node:path');
|
|
1701
|
+
const { spawn } = require('node:child_process');
|
|
1702
|
+
const root = process.env.SWITCHY_HOME;
|
|
1703
|
+
let login = process.argv.includes('--login');
|
|
1704
|
+
let child;
|
|
1705
|
+
let stopping = false;
|
|
1706
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
|
|
1707
|
+
stopping = true;
|
|
1708
|
+
if (child) child.kill('SIGTERM'); else process.exit(0);
|
|
1709
|
+
});
|
|
1710
|
+
function start() {
|
|
1711
|
+
let current;
|
|
1712
|
+
try { current = JSON.parse(fs.readFileSync(path.join(root, 'app/current.json'), 'utf8')); }
|
|
1713
|
+
catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
1714
|
+
if (!/^\\d+\\.\\d+\\.\\d+$/.test(current.version)) throw Error('Invalid installed version');
|
|
1715
|
+
const worker = path.join(root, 'app/versions', current.version, 'bin/lifecycle.cjs');
|
|
1716
|
+
if (!fs.existsSync(worker)) return;
|
|
1717
|
+
const metadata = JSON.parse(fs.readFileSync(path.join(root, 'app/host/node.json'), 'utf8'));
|
|
1718
|
+
child = spawn(path.join(root, 'app/host', metadata.file), [worker, login ? 'serve-login' : 'serve'], {
|
|
1719
|
+
env: { ...process.env, SWITCHY_HOME: root }, stdio: 'inherit', windowsHide: true
|
|
1720
|
+
});
|
|
1721
|
+
child.once('error', error => { console.error('Switchy lifecycle:', error.message); process.exitCode = 1; });
|
|
1722
|
+
child.once('exit', code => {
|
|
1723
|
+
child = undefined;
|
|
1724
|
+
if (stopping || code === 20) return;
|
|
1725
|
+
login = false;
|
|
1726
|
+
if (code === 21) start();
|
|
1727
|
+
else setTimeout(start, 30000);
|
|
1728
|
+
});
|
|
937
1729
|
}
|
|
938
|
-
|
|
1730
|
+
start();
|
|
1731
|
+
`;
|
|
1732
|
+
}
|
|
1733
|
+
});
|
|
1734
|
+
|
|
1735
|
+
// src/lifecycle-manager.ts
|
|
1736
|
+
import { readdir as readdir6, rename as rename6 } from "node:fs/promises";
|
|
1737
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
1738
|
+
import path15 from "node:path";
|
|
1739
|
+
async function configureLifecycle(paths, changes) {
|
|
1740
|
+
await withDirectoryLock(lifecycleFiles(paths).preferencesLock, async () => {
|
|
1741
|
+
const running = await getRunningProcess(paths);
|
|
1742
|
+
const preferences = {
|
|
1743
|
+
...await readPreferences(paths),
|
|
1744
|
+
...changes,
|
|
1745
|
+
...running ? { port: running.record.port } : {}
|
|
1746
|
+
};
|
|
1747
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
1748
|
+
if (!current || !await installHost(paths, path15.join(paths.versions, current.version))) {
|
|
1749
|
+
throw new Error("Install a Switchy release with startup support first");
|
|
1750
|
+
}
|
|
1751
|
+
await setStartupRegistration(paths, preferences.startAtLogin);
|
|
1752
|
+
await writeJsonFileAtomic(lifecycleFiles(paths).preferences, preferences);
|
|
1753
|
+
});
|
|
1754
|
+
await startHost(paths);
|
|
1755
|
+
}
|
|
1756
|
+
async function lifecycleTick(login = false) {
|
|
939
1757
|
const paths = getSwitchyPaths();
|
|
1758
|
+
const files = lifecycleFiles(paths);
|
|
940
1759
|
await ensureSwitchyDirectories(paths);
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1760
|
+
if (login) {
|
|
1761
|
+
if (!(await readPreferences(paths)).startAtLogin) return false;
|
|
1762
|
+
await setRunningPreference(paths, true);
|
|
1763
|
+
}
|
|
1764
|
+
const record = await reconcileRuntime(paths);
|
|
1765
|
+
if (!record) return false;
|
|
1766
|
+
const preferences = await readPreferences(paths);
|
|
1767
|
+
const current = { version: record.version };
|
|
1768
|
+
if (login && preferences.openAtLogin) {
|
|
1769
|
+
const { openCommand: openCommand2 } = await Promise.resolve().then(() => (init_commands(), commands_exports));
|
|
1770
|
+
await openCommand2();
|
|
1771
|
+
}
|
|
1772
|
+
const queued = await nextUpdateRequest(paths);
|
|
1773
|
+
const legacy = queued ? null : await takeLegacyRequest(files.request);
|
|
1774
|
+
const request = queued?.request ?? legacy?.request ?? null;
|
|
1775
|
+
const acknowledge = async () => {
|
|
1776
|
+
const file = queued?.file ?? legacy?.file;
|
|
1777
|
+
if (file) await removeFile(file);
|
|
1778
|
+
};
|
|
1779
|
+
const state = await readUpdateState(paths);
|
|
1780
|
+
const due = !state.lastCheckedAt || Date.now() - Date.parse(state.lastCheckedAt) >= 6 * 60 * 6e4;
|
|
1781
|
+
try {
|
|
1782
|
+
let latest = request?.version ?? state.latestVersion;
|
|
1783
|
+
if (request?.action === "check" || request && !latest || preferences.automaticUpdates && due && !request?.version) {
|
|
1784
|
+
await saveUpdateState2(paths, { phase: "checking", lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString(), message: null });
|
|
1785
|
+
latest = await resolveLatestStableVersion();
|
|
1786
|
+
await saveUpdateState2(paths, {
|
|
1787
|
+
latestVersion: latest,
|
|
1788
|
+
phase: compareVersions(latest, current.version) > 0 ? "available" : "idle"
|
|
958
1789
|
});
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
1790
|
+
if (request?.action === "check") await acknowledge();
|
|
1791
|
+
}
|
|
1792
|
+
if (request?.action === "download" && latest && compareVersions(latest, current.version) > 0) {
|
|
1793
|
+
await downloadUpdate(paths, latest);
|
|
1794
|
+
await acknowledge();
|
|
1795
|
+
return true;
|
|
1796
|
+
}
|
|
1797
|
+
if (latest && compareVersions(latest, current.version) > 0 && (request?.action === "install" || preferences.automaticUpdates && state.failedVersion !== latest && (state.phase !== "failed" || due))) {
|
|
1798
|
+
if (request?.action === "install" || latest.split(".")[0] === current.version.split(".")[0]) {
|
|
1799
|
+
const installed = await installUpdate(paths, latest, request?.action === "install");
|
|
1800
|
+
if (installed && request) await acknowledge();
|
|
1801
|
+
} else {
|
|
1802
|
+
await saveUpdateState2(paths, { phase: "available", message: "A major update is available. Download it from System Info." });
|
|
962
1803
|
}
|
|
963
|
-
throw error;
|
|
964
1804
|
}
|
|
965
|
-
|
|
1805
|
+
if (request && latest && compareVersions(latest, current.version) <= 0) await acknowledge();
|
|
1806
|
+
} catch (error) {
|
|
1807
|
+
console.error("Switchy update check failed:", error);
|
|
1808
|
+
await saveUpdateState2(paths, { phase: "failed", message: "Could not update Switchy. Check the lifecycle log for details." });
|
|
1809
|
+
if (request) await acknowledge();
|
|
1810
|
+
}
|
|
1811
|
+
return true;
|
|
966
1812
|
}
|
|
967
|
-
async function
|
|
1813
|
+
async function takeLegacyRequest(file) {
|
|
1814
|
+
const pending = (await readdir6(path15.dirname(file))).filter((name) => name.startsWith(`${path15.basename(file)}.`) && name.endsWith(".claimed")).sort()[0];
|
|
1815
|
+
if (pending) {
|
|
1816
|
+
const claimed2 = path15.join(path15.dirname(file), pending);
|
|
1817
|
+
return { file: claimed2, request: await readJsonFile(claimed2) };
|
|
1818
|
+
}
|
|
1819
|
+
const claimed = `${file}.${randomUUID7()}.claimed`;
|
|
1820
|
+
try {
|
|
1821
|
+
await rename6(file, claimed);
|
|
1822
|
+
} catch (error) {
|
|
1823
|
+
if (error.code === "ENOENT") return null;
|
|
1824
|
+
throw error;
|
|
1825
|
+
}
|
|
1826
|
+
return { file: claimed, request: await readJsonFile(claimed) };
|
|
1827
|
+
}
|
|
1828
|
+
var init_lifecycle_manager = __esm({
|
|
1829
|
+
"src/lifecycle-manager.ts"() {
|
|
1830
|
+
"use strict";
|
|
1831
|
+
init_files();
|
|
1832
|
+
init_lifecycle_state2();
|
|
1833
|
+
init_paths();
|
|
1834
|
+
init_process_manager();
|
|
1835
|
+
init_release();
|
|
1836
|
+
init_startup();
|
|
1837
|
+
init_controller();
|
|
1838
|
+
init_preferences();
|
|
1839
|
+
init_updater();
|
|
1840
|
+
}
|
|
1841
|
+
});
|
|
1842
|
+
|
|
1843
|
+
// src/lifecycle-daemon.ts
|
|
1844
|
+
import { watch } from "node:fs";
|
|
1845
|
+
import { mkdir as mkdir7 } from "node:fs/promises";
|
|
1846
|
+
async function serveLifecycle(login) {
|
|
968
1847
|
const paths = getSwitchyPaths();
|
|
969
|
-
|
|
970
|
-
|
|
1848
|
+
await ensureSwitchyDirectories(paths);
|
|
1849
|
+
const files = lifecycleFiles(paths);
|
|
1850
|
+
await mkdir7(files.requests, { recursive: true, mode: 448 });
|
|
1851
|
+
try {
|
|
1852
|
+
return await withDirectoryLock(files.supervisorLock, async () => {
|
|
1853
|
+
const initial = await readJsonFile(paths.currentVersion);
|
|
1854
|
+
let stopping = false;
|
|
1855
|
+
let dirty = false;
|
|
1856
|
+
let wake;
|
|
1857
|
+
const notify = () => {
|
|
1858
|
+
dirty = true;
|
|
1859
|
+
wake?.();
|
|
1860
|
+
};
|
|
1861
|
+
const stop = () => {
|
|
1862
|
+
stopping = true;
|
|
1863
|
+
notify();
|
|
1864
|
+
};
|
|
1865
|
+
process.once("SIGINT", stop);
|
|
1866
|
+
process.once("SIGTERM", stop);
|
|
1867
|
+
const watchers = [watch(paths.runtime, (_, name) => {
|
|
1868
|
+
if (["lifecycle.json", "update-request.json", "update-requests", "process.json"].includes(String(name))) notify();
|
|
1869
|
+
}), watch(files.requests, notify)];
|
|
1870
|
+
for (const watcher of watchers) watcher.on("error", (error) => console.warn("Switchy lifecycle watch:", error.message));
|
|
1871
|
+
try {
|
|
1872
|
+
let lastError = null;
|
|
1873
|
+
while (!stopping) {
|
|
1874
|
+
try {
|
|
1875
|
+
if (!await lifecycleTick(login)) return 20;
|
|
1876
|
+
login = false;
|
|
1877
|
+
lastError = null;
|
|
1878
|
+
await rotateLog(paths.logFile);
|
|
1879
|
+
await rotateLog(`${paths.logs}/lifecycle.log`);
|
|
1880
|
+
} catch (error) {
|
|
1881
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1882
|
+
if (message !== lastError) console.error("Switchy lifecycle:", message);
|
|
1883
|
+
lastError = message;
|
|
1884
|
+
}
|
|
1885
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
1886
|
+
if (!current) return 20;
|
|
1887
|
+
if (current.version !== initial?.version) return 21;
|
|
1888
|
+
const node = await readJsonFile(`${files.host}/node.json`);
|
|
1889
|
+
if (node && node.version !== process.versions.node) return 21;
|
|
1890
|
+
if (!dirty && !stopping) await new Promise((resolve) => {
|
|
1891
|
+
const timer = setTimeout(resolve, 3e4);
|
|
1892
|
+
wake = () => {
|
|
1893
|
+
clearTimeout(timer);
|
|
1894
|
+
resolve();
|
|
1895
|
+
};
|
|
1896
|
+
});
|
|
1897
|
+
wake = void 0;
|
|
1898
|
+
dirty = false;
|
|
1899
|
+
}
|
|
1900
|
+
return 20;
|
|
1901
|
+
} finally {
|
|
1902
|
+
for (const watcher of watchers) watcher.close();
|
|
1903
|
+
process.removeListener("SIGINT", stop);
|
|
1904
|
+
process.removeListener("SIGTERM", stop);
|
|
1905
|
+
}
|
|
1906
|
+
}, { timeoutMs: 0 });
|
|
1907
|
+
} catch (error) {
|
|
1908
|
+
if (error instanceof LockBusyError) return 20;
|
|
971
1909
|
throw error;
|
|
972
|
-
}
|
|
973
|
-
const lines = contents.trimEnd().split("\n");
|
|
974
|
-
console.log(lines.slice(-200).join("\n"));
|
|
1910
|
+
}
|
|
975
1911
|
}
|
|
976
|
-
|
|
1912
|
+
var init_lifecycle_daemon = __esm({
|
|
1913
|
+
"src/lifecycle-daemon.ts"() {
|
|
1914
|
+
"use strict";
|
|
1915
|
+
init_files();
|
|
1916
|
+
init_lifecycle_manager();
|
|
1917
|
+
init_lifecycle_state2();
|
|
1918
|
+
init_paths();
|
|
1919
|
+
init_logs();
|
|
1920
|
+
}
|
|
1921
|
+
});
|
|
1922
|
+
|
|
1923
|
+
// src/lifecycle.ts
|
|
1924
|
+
async function prepareLifecycleHost(paths, runtimeDirectory) {
|
|
1925
|
+
if (process.env.SWITCHY_DISABLE_LIFECYCLE === "1") return;
|
|
1926
|
+
if (!await installHost(paths, runtimeDirectory)) return;
|
|
1927
|
+
const preferences = await readPreferences(paths);
|
|
1928
|
+
if (preferences.startAtLogin) await setStartupRegistration(paths, true);
|
|
1929
|
+
await startHost(paths);
|
|
1930
|
+
}
|
|
1931
|
+
async function lifecycleCommand(action) {
|
|
1932
|
+
const paths = getSwitchyPaths();
|
|
1933
|
+
await ensureSwitchyDirectories(paths);
|
|
1934
|
+
if (action === "serve" || action === "serve-login") {
|
|
1935
|
+
process.exitCode = await serveLifecycle(action === "serve-login");
|
|
1936
|
+
} else if (action === "tick" || action === "login") {
|
|
1937
|
+
if (!await lifecycleTick(action === "login")) process.exitCode = 20;
|
|
1938
|
+
} else if (action === "enable" || action === "disable") {
|
|
1939
|
+
await configureLifecycle(paths, { startAtLogin: action === "enable" });
|
|
1940
|
+
console.log(`Start at sign-in ${action === "enable" ? "enabled" : "disabled"}.`);
|
|
1941
|
+
} else if (action === "status") {
|
|
1942
|
+
console.log(JSON.stringify({ preferences: await readPreferences(paths), update: await readUpdateState(paths) }, null, 2));
|
|
1943
|
+
} else if (action === "configure") {
|
|
1944
|
+
const input = JSON.parse(process.argv[3] ?? "{}");
|
|
1945
|
+
const allowed = ["startAtLogin", "openAtLogin", "automaticUpdates"];
|
|
1946
|
+
if (Object.entries(input).some(([key, value]) => !allowed.includes(key) || typeof value !== "boolean")) {
|
|
1947
|
+
throw new Error("Invalid lifecycle preferences");
|
|
1948
|
+
}
|
|
1949
|
+
await configureLifecycle(paths, input);
|
|
1950
|
+
} else {
|
|
1951
|
+
throw new Error("Use startup enable, disable, or status");
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
var init_lifecycle = __esm({
|
|
1955
|
+
"src/lifecycle.ts"() {
|
|
1956
|
+
"use strict";
|
|
1957
|
+
init_lifecycle_daemon();
|
|
1958
|
+
init_lifecycle_manager();
|
|
1959
|
+
init_lifecycle_state2();
|
|
1960
|
+
init_paths();
|
|
1961
|
+
init_startup();
|
|
1962
|
+
}
|
|
1963
|
+
});
|
|
1964
|
+
|
|
1965
|
+
// src/commands.ts
|
|
1966
|
+
var commands_exports = {};
|
|
1967
|
+
__export(commands_exports, {
|
|
1968
|
+
doctorCommand: () => doctorCommand,
|
|
1969
|
+
logsCommand: () => logsCommand,
|
|
1970
|
+
openCommand: () => openCommand,
|
|
1971
|
+
restartCommand: () => restartCommand,
|
|
1972
|
+
startCommand: () => startCommand,
|
|
1973
|
+
statusCommand: () => statusCommand,
|
|
1974
|
+
stopCommand: () => stopCommand,
|
|
1975
|
+
updateCommand: () => updateCommand,
|
|
1976
|
+
versionCommand: () => versionCommand
|
|
1977
|
+
});
|
|
1978
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
1979
|
+
import path16 from "node:path";
|
|
1980
|
+
async function startCommand(options = {}) {
|
|
1981
|
+
const paths = getSwitchyPaths();
|
|
1982
|
+
await ensureSwitchyDirectories(paths);
|
|
1983
|
+
const record = await startRuntime(paths, options);
|
|
1984
|
+
if (options.foreground) {
|
|
1985
|
+
await waitForForegroundExit(record);
|
|
1986
|
+
} else {
|
|
1987
|
+
await prepareLifecycleHost(paths, path16.join(paths.versions, record.version));
|
|
1988
|
+
console.log(`Switchy ${record.version} is running at http://${record.hostname}:${record.port}`);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
async function stopCommand(force = false) {
|
|
1992
|
+
const paths = getSwitchyPaths();
|
|
1993
|
+
await ensureSwitchyDirectories(paths);
|
|
1994
|
+
console.log(await stopRuntime(paths, force) ? "Switchy stopped." : "Switchy is not running.");
|
|
1995
|
+
}
|
|
1996
|
+
async function restartCommand() {
|
|
1997
|
+
const paths = getSwitchyPaths();
|
|
1998
|
+
await ensureSwitchyDirectories(paths);
|
|
1999
|
+
const record = await restartRuntime(paths);
|
|
2000
|
+
await prepareLifecycleHost(paths, path16.join(paths.versions, record.version));
|
|
2001
|
+
console.log(`Switchy ${record.version} restarted at http://${record.hostname}:${record.port}`);
|
|
2002
|
+
}
|
|
2003
|
+
async function readStatus() {
|
|
977
2004
|
const paths = getSwitchyPaths();
|
|
978
2005
|
const running = await getRunningProcess(paths);
|
|
979
|
-
|
|
980
|
-
const
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
2006
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
2007
|
+
const status = {
|
|
2008
|
+
status: running ? running.live ? "running" : "unresponsive" : "stopped",
|
|
2009
|
+
cliVersion: CLI_VERSION,
|
|
2010
|
+
installedVersion: current?.version ?? null,
|
|
2011
|
+
previousVersion: current?.previousVersion ?? null,
|
|
2012
|
+
nodeVersion: process.versions.node,
|
|
2013
|
+
pid: running?.record.pid ?? null,
|
|
2014
|
+
url: running ? `http://${running.record.hostname}:${running.record.port}` : null
|
|
2015
|
+
};
|
|
2016
|
+
return status;
|
|
2017
|
+
}
|
|
2018
|
+
async function statusCommand(json = false) {
|
|
2019
|
+
const status = await readStatus();
|
|
2020
|
+
if (json) console.log(JSON.stringify(status, null, 2));
|
|
2021
|
+
else {
|
|
2022
|
+
console.log(`Switchy${status.pid ? ` ${status.installedVersion}` : ""} is ${status.status}.`);
|
|
2023
|
+
if (status.pid) console.log(`URL: ${status.url}
|
|
2024
|
+
PID: ${status.pid}`);
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
async function doctorCommand() {
|
|
2028
|
+
const paths = getSwitchyPaths();
|
|
2029
|
+
const issues = {};
|
|
2030
|
+
const inspect = async (name, read) => {
|
|
2031
|
+
try {
|
|
2032
|
+
return await read();
|
|
2033
|
+
} catch (error) {
|
|
2034
|
+
issues[name] = error instanceof Error ? error.message : String(error);
|
|
2035
|
+
return null;
|
|
2036
|
+
}
|
|
2037
|
+
};
|
|
2038
|
+
const [status, record, preferences, update, managedNode] = await Promise.all([
|
|
2039
|
+
inspect("process", readStatus),
|
|
2040
|
+
inspect("record", () => readProcessRecord(paths)),
|
|
2041
|
+
inspect("preferences", () => readPreferences(paths)),
|
|
2042
|
+
inspect("update", () => readUpdateState(paths)),
|
|
2043
|
+
inspect("managedNode", () => readJsonFile(path16.join(paths.app, "host/node.json")))
|
|
2044
|
+
]);
|
|
2045
|
+
console.log(JSON.stringify({
|
|
2046
|
+
...status,
|
|
2047
|
+
cliVersion: CLI_VERSION,
|
|
2048
|
+
home: paths.root,
|
|
2049
|
+
preferences,
|
|
2050
|
+
update,
|
|
2051
|
+
managedNode,
|
|
2052
|
+
issues,
|
|
2053
|
+
recordedPid: record?.pid ?? null,
|
|
2054
|
+
applicationLog: paths.logFile,
|
|
2055
|
+
lifecycleLog: path16.join(paths.logs, "lifecycle.log")
|
|
2056
|
+
}, null, 2));
|
|
2057
|
+
}
|
|
2058
|
+
async function updateCommand(action = "install") {
|
|
2059
|
+
const paths = getSwitchyPaths();
|
|
2060
|
+
await ensureSwitchyDirectories(paths);
|
|
2061
|
+
const staged = (await readUpdateState(paths)).downloadedVersion;
|
|
2062
|
+
if (action === "apply" && !staged) throw new Error("No update is downloaded. Run switchy update --download first.");
|
|
2063
|
+
const latestVersion = action === "apply" ? staged : await resolveLatestStableVersion();
|
|
2064
|
+
const current = await readJsonFile(paths.currentVersion);
|
|
2065
|
+
await saveUpdateState2(paths, { latestVersion, lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
2066
|
+
if (current && compareVersions(latestVersion, current.version) <= 0) {
|
|
2067
|
+
await saveUpdateState2(paths, { phase: "idle", message: null });
|
|
2068
|
+
console.log(`Switchy ${current.version} is already current.`);
|
|
2069
|
+
} else if (action === "check") {
|
|
2070
|
+
await saveUpdateState2(paths, { phase: "available", message: null });
|
|
2071
|
+
console.log(`Switchy ${latestVersion} is available.`);
|
|
2072
|
+
} else if (action === "download") {
|
|
2073
|
+
await downloadUpdate(paths, latestVersion);
|
|
2074
|
+
console.log(`Downloaded Switchy ${latestVersion}. Run switchy update --apply to install.`);
|
|
2075
|
+
} else if (await installUpdate(paths, latestVersion, true)) {
|
|
2076
|
+
await prepareLifecycleHost(paths, path16.join(paths.versions, latestVersion));
|
|
2077
|
+
console.log(`Updated to Switchy ${latestVersion}.`);
|
|
989
2078
|
} else {
|
|
990
|
-
|
|
991
|
-
args = [url];
|
|
2079
|
+
console.log("Update deferred. Wait for active work to finish and try again.");
|
|
992
2080
|
}
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
2081
|
+
}
|
|
2082
|
+
async function logsCommand() {
|
|
2083
|
+
console.log(await readLogTail(getSwitchyPaths().logFile));
|
|
2084
|
+
}
|
|
2085
|
+
async function openCommand() {
|
|
2086
|
+
const running = await getRunningProcess(getSwitchyPaths());
|
|
2087
|
+
if (!running?.live) throw new Error("Switchy is not running or is unresponsive");
|
|
2088
|
+
const url = `http://${running.record.hostname}:${running.record.port}`;
|
|
2089
|
+
const [executable, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
2090
|
+
const child = spawn4(executable, args, { detached: true, stdio: "ignore" });
|
|
2091
|
+
await new Promise((resolve, reject) => {
|
|
2092
|
+
child.once("spawn", resolve);
|
|
2093
|
+
child.once("error", reject);
|
|
996
2094
|
});
|
|
997
2095
|
child.unref();
|
|
998
2096
|
console.log(url);
|
|
@@ -1000,58 +2098,99 @@ async function openCommand() {
|
|
|
1000
2098
|
function versionCommand() {
|
|
1001
2099
|
console.log(CLI_VERSION);
|
|
1002
2100
|
}
|
|
2101
|
+
var init_commands = __esm({
|
|
2102
|
+
"src/commands.ts"() {
|
|
2103
|
+
"use strict";
|
|
2104
|
+
init_config();
|
|
2105
|
+
init_controller();
|
|
2106
|
+
init_files();
|
|
2107
|
+
init_lifecycle();
|
|
2108
|
+
init_lifecycle_state2();
|
|
2109
|
+
init_logs();
|
|
2110
|
+
init_paths();
|
|
2111
|
+
init_process_manager();
|
|
2112
|
+
init_release();
|
|
2113
|
+
init_updater();
|
|
2114
|
+
}
|
|
2115
|
+
});
|
|
1003
2116
|
|
|
1004
|
-
// src/
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
2117
|
+
// src/arguments.ts
|
|
2118
|
+
var OPTIONS = {
|
|
2119
|
+
start: { "--port": "value", "--app-version": "value", "--foreground": "flag" },
|
|
2120
|
+
stop: { "--force": "flag" },
|
|
2121
|
+
restart: {},
|
|
2122
|
+
status: { "--json": "flag" },
|
|
2123
|
+
doctor: {},
|
|
2124
|
+
update: { "--check": "flag", "--download": "flag", "--apply": "flag" },
|
|
2125
|
+
startup: {},
|
|
2126
|
+
logs: {},
|
|
2127
|
+
open: {},
|
|
2128
|
+
version: {},
|
|
2129
|
+
help: {}
|
|
2130
|
+
};
|
|
2131
|
+
function parseArguments(args) {
|
|
2132
|
+
const command = args[0] ?? "help";
|
|
2133
|
+
if (args.includes("--help") || args.includes("-h")) return { command: "help", values: /* @__PURE__ */ new Map(), startup: "status" };
|
|
2134
|
+
const selected = command === "--version" || command === "-v" ? "version" : command;
|
|
2135
|
+
const options = Object.hasOwn(OPTIONS, selected) ? OPTIONS[selected] : void 0;
|
|
2136
|
+
if (!options) throw new Error(`Unknown command: ${command}`);
|
|
2137
|
+
const values = /* @__PURE__ */ new Map();
|
|
2138
|
+
let startup = "status";
|
|
2139
|
+
for (let index = 1; index < args.length; index++) {
|
|
2140
|
+
const name = args[index];
|
|
2141
|
+
if (selected === "startup" && index === 1 && ["enable", "disable", "status"].includes(name)) {
|
|
2142
|
+
startup = name;
|
|
2143
|
+
continue;
|
|
2144
|
+
}
|
|
2145
|
+
const kind = Object.hasOwn(options, name) ? options[name] : void 0;
|
|
2146
|
+
if (!kind) throw new Error(`Unknown option for ${selected}: ${name}`);
|
|
2147
|
+
if (values.has(name)) throw new Error(`Duplicate option: ${name}`);
|
|
2148
|
+
if (kind === "value") {
|
|
2149
|
+
const value = args[++index];
|
|
2150
|
+
if (!value || value.startsWith("-")) throw new Error(`${name} requires a value`);
|
|
2151
|
+
values.set(name, value);
|
|
2152
|
+
} else values.set(name, true);
|
|
1011
2153
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
const value = optionValue(args, "--port");
|
|
1016
|
-
if (!value) return void 0;
|
|
1017
|
-
const port = Number(value);
|
|
1018
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
2154
|
+
if (selected === "update" && values.size > 1) throw new Error("Choose one update action: --check, --download, or --apply");
|
|
2155
|
+
const port = values.get("--port");
|
|
2156
|
+
if (typeof port === "string" && (!/^\d+$/u.test(port) || Number(port) < 1 || Number(port) > 65535)) {
|
|
1019
2157
|
throw new Error("--port must be an integer between 1 and 65535");
|
|
1020
2158
|
}
|
|
1021
|
-
return
|
|
2159
|
+
return { command: selected, values, startup };
|
|
1022
2160
|
}
|
|
1023
|
-
function printHelp() {
|
|
1024
|
-
console.log(`Switchy CLI
|
|
1025
2161
|
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
switchy update
|
|
1031
|
-
switchy logs
|
|
1032
|
-
switchy open
|
|
1033
|
-
switchy version`);
|
|
1034
|
-
}
|
|
2162
|
+
// src/cli.ts
|
|
2163
|
+
init_commands();
|
|
2164
|
+
init_config();
|
|
2165
|
+
init_lifecycle();
|
|
1035
2166
|
async function main() {
|
|
1036
2167
|
assertSupportedNodeVersion();
|
|
1037
|
-
const
|
|
1038
|
-
const command = args[0] ?? "help";
|
|
2168
|
+
const { command, values, startup } = parseArguments(process.argv.slice(2));
|
|
1039
2169
|
switch (command) {
|
|
1040
2170
|
case "start":
|
|
1041
2171
|
await startCommand({
|
|
1042
|
-
version:
|
|
1043
|
-
port:
|
|
1044
|
-
foreground:
|
|
2172
|
+
version: values.get("--app-version"),
|
|
2173
|
+
port: values.has("--port") ? Number(values.get("--port")) : void 0,
|
|
2174
|
+
foreground: values.has("--foreground")
|
|
1045
2175
|
});
|
|
1046
2176
|
break;
|
|
1047
2177
|
case "stop":
|
|
1048
|
-
await stopCommand(
|
|
2178
|
+
await stopCommand(values.has("--force"));
|
|
2179
|
+
break;
|
|
2180
|
+
case "restart":
|
|
2181
|
+
await restartCommand();
|
|
1049
2182
|
break;
|
|
1050
2183
|
case "status":
|
|
1051
|
-
await statusCommand();
|
|
2184
|
+
await statusCommand(values.has("--json"));
|
|
2185
|
+
break;
|
|
2186
|
+
case "doctor":
|
|
2187
|
+
await doctorCommand();
|
|
2188
|
+
break;
|
|
2189
|
+
case "startup":
|
|
2190
|
+
await lifecycleCommand(startup);
|
|
1052
2191
|
break;
|
|
1053
2192
|
case "update":
|
|
1054
|
-
await updateCommand();
|
|
2193
|
+
await updateCommand(values.has("--check") ? "check" : values.has("--download") ? "download" : values.has("--apply") ? "apply" : "install");
|
|
1055
2194
|
break;
|
|
1056
2195
|
case "logs":
|
|
1057
2196
|
await logsCommand();
|
|
@@ -1060,17 +2199,22 @@ async function main() {
|
|
|
1060
2199
|
await openCommand();
|
|
1061
2200
|
break;
|
|
1062
2201
|
case "version":
|
|
1063
|
-
case "--version":
|
|
1064
|
-
case "-v":
|
|
1065
2202
|
versionCommand();
|
|
1066
2203
|
break;
|
|
1067
|
-
case "help":
|
|
1068
|
-
case "--help":
|
|
1069
|
-
case "-h":
|
|
1070
|
-
printHelp();
|
|
1071
|
-
break;
|
|
1072
2204
|
default:
|
|
1073
|
-
|
|
2205
|
+
console.log(`Switchy CLI
|
|
2206
|
+
|
|
2207
|
+
Usage:
|
|
2208
|
+
switchy start [--port ${DEFAULT_PORT}] [--foreground] [--app-version <version>]
|
|
2209
|
+
switchy stop [--force]
|
|
2210
|
+
switchy restart
|
|
2211
|
+
switchy status [--json]
|
|
2212
|
+
switchy doctor
|
|
2213
|
+
switchy update [--check | --download | --apply]
|
|
2214
|
+
switchy startup enable|disable|status
|
|
2215
|
+
switchy logs
|
|
2216
|
+
switchy open
|
|
2217
|
+
switchy version`);
|
|
1074
2218
|
}
|
|
1075
2219
|
}
|
|
1076
2220
|
main().catch((error) => {
|