@anhlp/alp-cli 0.0.1-beta.8 → 0.0.1-beta.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/dist/acp/main.js +1 -1
- package/dist/acp.js +180 -82
- package/dist/{alp-web → alp-dashboard}/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/{alp-web/assets/TerminalPanel-BbYa_Xkd.js → alp-dashboard/assets/TerminalPanel-BSjqIfNr.js} +1 -1
- package/dist/{alp-web/assets/index-DOJh89Ik.js → alp-dashboard/assets/index-CZFfSOIE.js} +5 -5
- package/dist/{alp-web → alp-dashboard}/index.html +1 -1
- package/dist/{alp-web.js → alp-dashboard.js} +349 -306
- package/dist/alpd.js +1308 -1271
- package/dist/backup.js +1 -1
- package/dist/build-manifest.json +14 -5
- package/dist/cli.js +4 -3
- package/dist/daemon.d.ts +1 -1
- package/dist/daemon.js +6 -6
- package/dist/dashboard-migrate.d.ts +31 -0
- package/dist/dashboard-migrate.js +127 -0
- package/dist/dashboard-service.d.ts +69 -0
- package/dist/{web-service.js → dashboard-service.js} +30 -32
- package/dist/desktop.d.ts +56 -0
- package/dist/desktop.js +91 -0
- package/dist/interfaces.d.ts +2 -2
- package/dist/interfaces.js +133 -43
- package/dist/paths.d.ts +6 -1
- package/dist/paths.js +4 -2
- package/dist/roles.d.ts +5 -5
- package/dist/self-update.d.ts +2 -1
- package/dist/self-update.js +7 -1
- package/dist/sessions.d.ts +0 -1
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +6 -4
- package/package.json +6 -6
- package/src/cli.js +3 -2
- package/src/daemon.js +7 -6
- package/src/dashboard-migrate.js +152 -0
- package/src/{web-service.js → dashboard-service.js} +54 -48
- package/src/desktop.js +122 -0
- package/src/interfaces.js +170 -61
- package/src/paths.js +9 -3
- package/src/roles.js +4 -4
- package/src/self-update.js +10 -2
- package/src/sessions.js +0 -2
- package/src/usage.js +6 -4
- package/dist/web-service.d.ts +0 -56
- /package/dist/{alp-web → alp-dashboard}/alp-boundary.json +0 -0
- /package/dist/{alp-web → alp-dashboard}/apple-touch-icon.png +0 -0
- /package/dist/{alp-web → alp-dashboard}/assets/TerminalPanel-DLuoa74B.css +0 -0
- /package/dist/{alp-web → alp-dashboard}/assets/highlighter-BnicKQ_d.js +0 -0
- /package/dist/{alp-web → alp-dashboard}/assets/index-DwqDSiIi.css +0 -0
- /package/dist/{alp-web → alp-dashboard}/favicon-attention.svg +0 -0
- /package/dist/{alp-web → alp-dashboard}/favicon-running.svg +0 -0
- /package/dist/{alp-web → alp-dashboard}/favicon.svg +0 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmod, link, lstat, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { migrateDashboardSettings } from '@anhlp/alp-core/user-settings';
|
|
5
|
+
import { DASHBOARD, LEGACY_WEB, refusal, serviceOwner, stopService } from './dashboard-service.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The move from `alp web` (0.0.1-beta.8 and earlier) to `alp dashboard` (t-81b0.5), run by every
|
|
9
|
+
* `alp dashboard` command before it reads or starts anything. An install keeps its token, its port
|
|
10
|
+
* and its enabled/disabled setting:
|
|
11
|
+
*
|
|
12
|
+
* 1. alp web still running under `integrations/web.lock` (or the Paseo integration from before its
|
|
13
|
+
* own rename, which held the same lock) is stopped, with the same proofs `alp dashboard --stop`
|
|
14
|
+
* uses; a holder that cannot be proven is left running and nothing below is moved, since it
|
|
15
|
+
* may still write the old files.
|
|
16
|
+
* 2. `<home>/web/` (alp web's credential store) becomes `<home>/dashboard/`.
|
|
17
|
+
* 3. `<home>/web.json` written by alp web (`app: 'alp-web'`) becomes `<home>/dashboard.json`, keeping
|
|
18
|
+
* its token and credential id; one without `app` is the Paseo integration's identity and is left
|
|
19
|
+
* for the service to carry into paseo.json, as before.
|
|
20
|
+
* 4. `logs/integrations/alp-web.log` becomes `alp-dashboard.log`.
|
|
21
|
+
* 5. settings.json: `web.enabled`, `web.port` and `web.permissions` move to `dashboard.*`
|
|
22
|
+
* (`web.relay`, Paseo's, stays); see migrateDashboardSettings.
|
|
23
|
+
*
|
|
24
|
+
* Every step only moves an old name onto a missing new one, so a second run does nothing and a home
|
|
25
|
+
* that has both keeps the new one untouched (the old one is reported, never merged or deleted).
|
|
26
|
+
* Steps that race another `alp dashboard` lose cleanly: a rename or link that finds its source gone
|
|
27
|
+
* or its target present is skipped.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** @param {string} file */
|
|
31
|
+
const exists = file => lstat(file).then(() => true, () => false);
|
|
32
|
+
/** A file's JSON, or undefined when it is missing or not JSON. @param {string} file */
|
|
33
|
+
const readJson = file => readFile(file, 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
|
|
34
|
+
/** @param {unknown} error */
|
|
35
|
+
const code = error => /** @type {any} */ (error)?.code;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {string} home
|
|
39
|
+
* @param {{ strict?: boolean }} [options] strict: a legacy holder alp cannot stop is an error (a start
|
|
40
|
+
* would otherwise lose its port to it); without it, it is reported and the files are left alone.
|
|
41
|
+
* @returns {Promise<{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }>}
|
|
42
|
+
* held: a legacy holder alp would not stop is still running (only without strict).
|
|
43
|
+
*/
|
|
44
|
+
export async function migrateDashboard(home, { strict = false } = {}) {
|
|
45
|
+
/** @type {{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }} */
|
|
46
|
+
const report = { moved: [], kept: [], warnings: [] };
|
|
47
|
+
|
|
48
|
+
// 1. The service from before the rename.
|
|
49
|
+
const owner = await serviceOwner(home, LEGACY_WEB);
|
|
50
|
+
if ('pid' in owner || (owner.alive && owner.kind === 'transient')) {
|
|
51
|
+
try { report.stopped = await stopService(home, 30_000, LEGACY_WEB); }
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (strict) throw error;
|
|
54
|
+
report.warnings.push(/** @type {any} */ (error)?.message ?? String(error));
|
|
55
|
+
report.held = true;
|
|
56
|
+
return report;
|
|
57
|
+
}
|
|
58
|
+
} else if (owner.alive) {
|
|
59
|
+
const message = `${refusal(home, LEGACY_WEB)} (${owner.reason}); stop it, then run the command again`;
|
|
60
|
+
if (strict) throw new Error(message);
|
|
61
|
+
report.warnings.push(message);
|
|
62
|
+
report.held = true;
|
|
63
|
+
return report;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 2. The credential store.
|
|
67
|
+
const oldStore = path.join(home, 'web');
|
|
68
|
+
const newStore = path.join(home, 'dashboard');
|
|
69
|
+
if (await exists(path.join(oldStore, 'credentials.json'))) {
|
|
70
|
+
if (await exists(newStore)) report.kept.push(oldStore);
|
|
71
|
+
else {
|
|
72
|
+
try { await rename(oldStore, newStore); report.moved.push(`${oldStore} -> ${newStore}`); }
|
|
73
|
+
catch (error) { if (!['ENOENT', 'EEXIST', 'ENOTEMPTY'].includes(code(error))) throw error; }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 3. What the service published.
|
|
78
|
+
const oldInfo = path.join(home, LEGACY_WEB.info);
|
|
79
|
+
const newInfo = path.join(home, DASHBOARD.info);
|
|
80
|
+
const published = await readJson(oldInfo);
|
|
81
|
+
if (published?.app === LEGACY_WEB.app) {
|
|
82
|
+
// The same token in dashboard.json: this file was already carried (by an earlier or a concurrent
|
|
83
|
+
// run, or a crash after the link), so the old one is only a copy.
|
|
84
|
+
const carriedAlready = async () => typeof published.token === 'string' && published.token !== '' && (await readJson(newInfo))?.token === published.token;
|
|
85
|
+
const removeOld = () => unlink(oldInfo).catch(error => { if (code(error) !== 'ENOENT') throw error; });
|
|
86
|
+
if (await exists(newInfo)) {
|
|
87
|
+
if (await carriedAlready()) await removeOld();
|
|
88
|
+
else report.kept.push(oldInfo);
|
|
89
|
+
} else {
|
|
90
|
+
// Only what the next start reuses; the old pid, port and URL died with the old service.
|
|
91
|
+
const carried = { version: published.version, app: DASHBOARD.app, token: published.token, credentialId: published.credentialId };
|
|
92
|
+
const temporary = `${newInfo}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
93
|
+
try {
|
|
94
|
+
await writeFile(temporary, `${JSON.stringify(carried)}\n`, { mode: 0o600, flag: 'wx' });
|
|
95
|
+
await chmod(temporary, 0o600);
|
|
96
|
+
// A link never replaces: a dashboard.json written meanwhile wins, and the old file is
|
|
97
|
+
// removed only when that one carries the same token.
|
|
98
|
+
const linked = await link(temporary, newInfo).then(() => true, error => { if (code(error) !== 'EEXIST') throw error; return false; });
|
|
99
|
+
if (linked) { report.moved.push(`${oldInfo} -> ${newInfo}`); await removeOld(); }
|
|
100
|
+
else if (await carriedAlready()) await removeOld();
|
|
101
|
+
else report.kept.push(oldInfo);
|
|
102
|
+
} finally { await unlink(temporary).catch(() => {}); }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 4. The service's log.
|
|
107
|
+
const logs = path.join(home, 'logs', 'integrations');
|
|
108
|
+
const oldLog = path.join(logs, 'alp-web.log');
|
|
109
|
+
const newLog = path.join(logs, 'alp-dashboard.log');
|
|
110
|
+
if (await exists(oldLog) && !(await exists(newLog))) {
|
|
111
|
+
await rename(oldLog, newLog).then(() => report.moved.push(`${oldLog} -> ${newLog}`), error => { if (code(error) !== 'ENOENT') throw error; });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 5. Settings. A file alp cannot rewrite (invalid, read-only) is still obeyed: dashboardSettings
|
|
115
|
+
// reads `web.*` where `dashboard.*` is not set.
|
|
116
|
+
try {
|
|
117
|
+
const settings = await migrateDashboardSettings(home);
|
|
118
|
+
for (const key of settings.moved) report.moved.push(`settings.json web.${key} -> dashboard.${key}`);
|
|
119
|
+
for (const key of settings.conflicts) report.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
report.warnings.push(`settings.json was not migrated (web.* is still read): ${/** @type {any} */ (error)?.message ?? error}`);
|
|
122
|
+
}
|
|
123
|
+
return report;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* What a home still has under the names from before the rename, without changing anything (for
|
|
128
|
+
* `alp dashboard --status`): `pending` the next `alp dashboard` moves, `kept` it leaves because the
|
|
129
|
+
* new name exists, and the legacy service if one runs.
|
|
130
|
+
* @param {string} home
|
|
131
|
+
* @returns {Promise<{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }>}
|
|
132
|
+
*/
|
|
133
|
+
export async function legacyLeftovers(home) {
|
|
134
|
+
/** @type {{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }} */
|
|
135
|
+
const result = { pending: [], kept: [] };
|
|
136
|
+
const owner = await serviceOwner(home, LEGACY_WEB);
|
|
137
|
+
if ('pid' in owner) result.legacy = { pid: owner.pid };
|
|
138
|
+
else if (owner.alive) result.legacy = { reason: owner.reason };
|
|
139
|
+
const place = async (/** @type {string} */ old, /** @type {string} */ current) => (await exists(current) ? result.kept : result.pending).push(old);
|
|
140
|
+
if (await exists(path.join(home, 'web', 'credentials.json'))) await place(path.join(home, 'web'), path.join(home, 'dashboard'));
|
|
141
|
+
const published = await readJson(path.join(home, LEGACY_WEB.info));
|
|
142
|
+
if (published?.app === LEGACY_WEB.app) await place(path.join(home, LEGACY_WEB.info), path.join(home, DASHBOARD.info));
|
|
143
|
+
const logs = path.join(home, 'logs', 'integrations');
|
|
144
|
+
if (await exists(path.join(logs, 'alp-web.log'))) await place(path.join(logs, 'alp-web.log'), path.join(logs, 'alp-dashboard.log'));
|
|
145
|
+
const settings = await readJson(path.join(home, 'settings.json'));
|
|
146
|
+
for (const key of ['enabled', 'port', 'permissions']) {
|
|
147
|
+
if (settings?.web?.[key] === undefined) continue;
|
|
148
|
+
if (settings?.dashboard?.[key] !== undefined) result.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
|
|
149
|
+
else result.pending.push(`settings.json web.${key}`);
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
@@ -10,11 +10,15 @@ import { distributionEntry } from './paths.js';
|
|
|
10
10
|
import { selfEntry } from '@anhlp/alp-core/packaged';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* The CLI's side of alp-
|
|
14
|
-
* process owns its lock, and how to stop that process safely.
|
|
13
|
+
* The CLI's side of alp-dashboard (packages/cli/src/dashboard), the service behind `alp dashboard`:
|
|
14
|
+
* where it is, which process owns its lock, and how to stop that process safely. The same proofs
|
|
15
|
+
* apply to what ran under the names from before the rename (t-81b0.5): `integrations/web.lock` and
|
|
16
|
+
* `web.json`, held by alp web of 0.0.1-beta.8 or earlier, or by the Paseo integration from before
|
|
17
|
+
* its own rename.
|
|
15
18
|
*
|
|
16
|
-
* Only a process proven to be the one that took
|
|
17
|
-
* with SIGTERM (the CLI's own `--rotate` child aside, which it may time out): the lock and
|
|
19
|
+
* Only a process proven to be the one that took the service's lock is ever signalled, and only
|
|
20
|
+
* with SIGTERM (the CLI's own `--rotate` child aside, which it may time out): the lock and the
|
|
21
|
+
* service's `<name>.json` name the same pid, both files are the user's, the lock is
|
|
18
22
|
* from this boot, the pid answers signal 0 (so it is the user's own process), and that process
|
|
19
23
|
* started no later than the lock was written (so the pid was not reused). Anything else is reported
|
|
20
24
|
* and left alone. A stopped owner releases the lock; one that died holding it leaves it to the next
|
|
@@ -24,15 +28,25 @@ import { selfEntry } from '@anhlp/alp-core/packaged';
|
|
|
24
28
|
const execFileAsync = promisify(execFile);
|
|
25
29
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
26
30
|
|
|
27
|
-
/** The alp-
|
|
28
|
-
export function
|
|
29
|
-
const entry = fileURLToPath(distributionEntry('alp-
|
|
30
|
-
if (!existsSync(entry)) throw new Error(`alp
|
|
31
|
+
/** The alp-dashboard service script beside this CLI; a clear error when this CLI was built without it. */
|
|
32
|
+
export function dashboardScript() {
|
|
33
|
+
const entry = fileURLToPath(distributionEntry('alp-dashboard.js'));
|
|
34
|
+
if (!existsSync(entry)) throw new Error(`alp dashboard is not built: ${entry} is missing. Build the CLI (npm run build in the ALP checkout) or reinstall ALP.`);
|
|
31
35
|
return entry;
|
|
32
36
|
}
|
|
33
37
|
|
|
34
|
-
/** What starts alp-
|
|
35
|
-
export const
|
|
38
|
+
/** What starts alp-dashboard: its script under Node (named through app/current in the ALP bundle). */
|
|
39
|
+
export const dashboardEntry = () => selfEntry(dashboardScript());
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @typedef {{ lock: string, info: string, app: string, what: string }} Service
|
|
43
|
+
* The integration lock's name, the file the service publishes, the `app` it writes there, and what
|
|
44
|
+
* messages call it.
|
|
45
|
+
*/
|
|
46
|
+
/** @type {Service} */
|
|
47
|
+
export const DASHBOARD = Object.freeze({ lock: 'dashboard', info: 'dashboard.json', app: 'alp-dashboard', what: 'alp dashboard' });
|
|
48
|
+
/** alp web as 0.0.1-beta.8 and earlier ran it (and, before that, the Paseo integration). @type {Service} */
|
|
49
|
+
export const LEGACY_WEB = Object.freeze({ lock: 'web', info: 'web.json', app: 'alp-web', what: 'alp web from before its rename to alp dashboard' });
|
|
36
50
|
|
|
37
51
|
const readJson = async file => JSON.parse(await readFile(file, 'utf8'));
|
|
38
52
|
|
|
@@ -50,20 +64,20 @@ async function processTimes(pid) {
|
|
|
50
64
|
}
|
|
51
65
|
|
|
52
66
|
/**
|
|
53
|
-
* The process that owns
|
|
54
|
-
* whether waiting can help: `transient` (an owner still starting has not published
|
|
67
|
+
* The process that owns `service`'s lock, if it is proven safe to stop; else why not. `kind` says
|
|
68
|
+
* whether waiting can help: `transient` (an owner still starting has not published its file yet),
|
|
55
69
|
* `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
|
|
56
70
|
* `unknown` (it cannot be proven either way, for example without ps or on Windows).
|
|
57
71
|
*
|
|
58
72
|
* The reuse proof compares the lock's creation time with the process's start from ps: when
|
|
59
73
|
* `startedUptime` is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
|
|
60
74
|
* For legacy locks, wall-clock `startedAt` is compared.
|
|
61
|
-
* @param {string} home
|
|
75
|
+
* @param {string} home @param {Service} [service]
|
|
62
76
|
* @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
|
|
63
77
|
*/
|
|
64
|
-
export async function
|
|
65
|
-
const lockFile = path.join(home, 'integrations',
|
|
66
|
-
const infoFile = path.join(home,
|
|
78
|
+
export async function serviceOwner(home, service = DASHBOARD) {
|
|
79
|
+
const lockFile = path.join(home, 'integrations', `${service.lock}.lock`);
|
|
80
|
+
const infoFile = path.join(home, service.info);
|
|
67
81
|
let lock, lockInfo;
|
|
68
82
|
try { lockInfo = await lstat(lockFile); lock = await readJson(lockFile); } catch { return { reason: `${lockFile} is missing or unreadable`, alive: false }; }
|
|
69
83
|
if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== 'number' || !Number.isFinite(Date.parse(lock.startedAt))) {
|
|
@@ -89,7 +103,7 @@ export async function webOwner(home) {
|
|
|
89
103
|
? (Math.floor(os.uptime()) - times.elapsed) > lock.startedUptime + 2
|
|
90
104
|
: times.started > Date.parse(lock.startedAt) + 2_000;
|
|
91
105
|
if (isReused) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, 'foreign');
|
|
92
|
-
// The lock's owner;
|
|
106
|
+
// The lock's owner; its published file must name it too (an owner still starting has not written it yet).
|
|
93
107
|
let info, infoStat;
|
|
94
108
|
try { infoStat = await lstat(infoFile); info = await readJson(infoFile); } catch { return refuse(`${infoFile} is missing or unreadable`, 'transient'); }
|
|
95
109
|
if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, 'transient');
|
|
@@ -111,53 +125,45 @@ async function terminate(pid, what, timeoutMs = 20_000) {
|
|
|
111
125
|
throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1000} s of SIGTERM; stop it, then run the command again`);
|
|
112
126
|
}
|
|
113
127
|
|
|
114
|
-
/** Whether `web.json` is alp-web's own (the pre-rename Paseo integration wrote it without `app`). */
|
|
115
|
-
const isAlpWeb = app => app === 'alp-web';
|
|
116
128
|
const PASEO_BEFORE_RENAME = 'The Paseo integration from before its rename';
|
|
117
129
|
|
|
118
|
-
/**
|
|
119
|
-
|
|
120
|
-
* web.json has no `app: 'alp-web'`), so alp-web can take the lock and web.port. Returns the pid it
|
|
121
|
-
* stopped. A process that cannot be proven to be that integration is left alone.
|
|
122
|
-
* @param {string} home
|
|
123
|
-
*/
|
|
124
|
-
export async function stopPreRenamePaseo(home) {
|
|
125
|
-
const owner = await webOwner(home);
|
|
126
|
-
if (!('pid' in owner) || isAlpWeb(owner.app)) return undefined;
|
|
127
|
-
await terminate(owner.pid, PASEO_BEFORE_RENAME);
|
|
128
|
-
return owner.pid;
|
|
129
|
-
}
|
|
130
|
+
/** What a proven owner of `service`'s lock is, by the `app` its file names. @param {Service} service @param {unknown} app */
|
|
131
|
+
const ownerName = (service, app) => app === service.app || service === DASHBOARD ? service.what : PASEO_BEFORE_RENAME;
|
|
130
132
|
|
|
131
133
|
/**
|
|
132
|
-
* Stops whatever runs as
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
134
|
+
* Stops whatever runs as `service` (alp dashboard; for LEGACY_WEB, alp web from before the rename or
|
|
135
|
+
* the Paseo integration from before its own), waiting up to `timeoutMs` for a starting owner to
|
|
136
|
+
* publish what proves it. Resolves with the pid it stopped, or undefined once no live process owns
|
|
137
|
+
* the lock; refuses at once an owner that is foreign or cannot be proven.
|
|
138
|
+
* @param {string} home @param {number} [timeoutMs] @param {Service} [service]
|
|
136
139
|
*/
|
|
137
|
-
export async function
|
|
140
|
+
export async function stopService(home, timeoutMs = 30_000, service = DASHBOARD) {
|
|
138
141
|
const deadline = Date.now() + timeoutMs;
|
|
139
142
|
for (;;) {
|
|
140
|
-
const owner = await
|
|
141
|
-
if ('pid' in owner) { await terminate(owner.pid,
|
|
143
|
+
const owner = await serviceOwner(home, service);
|
|
144
|
+
if ('pid' in owner) { await terminate(owner.pid, ownerName(service, owner.app)); return owner.pid; }
|
|
142
145
|
if (!owner.alive) return undefined;
|
|
143
146
|
// Only an owner still starting can become provable; waiting changes nothing else.
|
|
144
|
-
if (owner.kind !== 'transient' || Date.now() >= deadline) throw new Error(`${refusal(home)} (${owner.reason}); stop it, then run the command again`);
|
|
147
|
+
if (owner.kind !== 'transient' || Date.now() >= deadline) throw new Error(`${refusal(home, service)} (${owner.reason}); stop it, then run the command again`);
|
|
145
148
|
await sleep(200);
|
|
146
149
|
}
|
|
147
150
|
}
|
|
148
151
|
|
|
149
|
-
/** The opening of the message for a
|
|
150
|
-
export function refusal(home) {
|
|
151
|
-
|
|
152
|
+
/** The opening of the message for a lock held by a process alp would not stop. @param {string} home @param {Service} [service] */
|
|
153
|
+
export function refusal(home, service = DASHBOARD) {
|
|
154
|
+
const lock = path.join(home, 'integrations', `${service.lock}.lock`);
|
|
155
|
+
return service === DASHBOARD
|
|
156
|
+
? `${lock} is held by a process that alp cannot prove is alp dashboard, so it was left running`
|
|
157
|
+
: `${lock} is held by a process that alp cannot prove is ${service.what} or the Paseo integration from before its rename, so it was left running`;
|
|
152
158
|
}
|
|
153
159
|
|
|
154
160
|
/**
|
|
155
|
-
* Probes whether the published
|
|
161
|
+
* Probes whether the published dashboard URL is live and answering requests.
|
|
156
162
|
* Accepts only loopback HTTP/HTTPS addresses.
|
|
157
163
|
* @param {string | undefined} url
|
|
158
164
|
* @param {number} [timeoutMs]
|
|
159
165
|
*/
|
|
160
|
-
export async function
|
|
166
|
+
export async function isDashboardReady(url, timeoutMs = 1_000) {
|
|
161
167
|
if (typeof url !== 'string' || !url) return false;
|
|
162
168
|
try {
|
|
163
169
|
const parsed = new URL(url);
|
|
@@ -171,7 +177,7 @@ export async function isWebReady(url, timeoutMs = 1_000) {
|
|
|
171
177
|
}
|
|
172
178
|
|
|
173
179
|
/**
|
|
174
|
-
* Whether
|
|
180
|
+
* Whether the published file is genuinely claimed by a live alp-dashboard process.
|
|
175
181
|
* If the process is proven foreign (e.g. a reused PID or from another boot) or
|
|
176
182
|
* the URL does not answer HTTP requests, it is never claimed.
|
|
177
183
|
* @param {any} published
|
|
@@ -179,8 +185,8 @@ export async function isWebReady(url, timeoutMs = 1_000) {
|
|
|
179
185
|
* @param {any} held
|
|
180
186
|
* @param {number} [timeoutMs]
|
|
181
187
|
*/
|
|
182
|
-
export async function
|
|
183
|
-
if (published?.app !==
|
|
188
|
+
export async function isServiceClaimed(published, lockPid, held, timeoutMs = 1_000) {
|
|
189
|
+
if (published?.app !== DASHBOARD.app || published.pid !== lockPid) return false;
|
|
184
190
|
if (held?.kind === 'foreign') return false;
|
|
185
|
-
return
|
|
191
|
+
return isDashboardReady(published.url, timeoutMs);
|
|
186
192
|
}
|
package/src/desktop.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { UsageError } from './usage.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* alp desktop (t-81b0.5): opens ALP's desktop app (apps/desktop, an Electron shell for macOS). The
|
|
9
|
+
* app is looked for, in order:
|
|
10
|
+
* 1. ALP.app in /Applications, then in ~/Applications (macOS), opened with `open`. Only a bundle
|
|
11
|
+
* whose CFBundleIdentifier is DESKTOP_BUNDLE_ID counts: another app of that name (an older ALP
|
|
12
|
+
* desktop app, say) is skipped with a one-line message and the lookup goes on;
|
|
13
|
+
* 2. a checkout named by ALP_DESKTOP_CHECKOUT (the repository root, or its apps/desktop), whose
|
|
14
|
+
* app is built (`bun install && bun run build` in apps/desktop), run with its own Electron;
|
|
15
|
+
* 3. neither: how to get it, and exit 1.
|
|
16
|
+
* Nothing secret passes here: the app asks `alp dashboard --print` for its address itself.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The bundle id of the packaged app (apps/desktop/electron-builder.yml, appId). */
|
|
20
|
+
export const DESKTOP_BUNDLE_ID = 'com.anhlp.alp.shell';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The CFBundleIdentifier of the app bundle at `app`, or undefined when it cannot be read. An XML
|
|
24
|
+
* Info.plist (what electron-builder writes) is read directly; any other form through plutil.
|
|
25
|
+
* @param {string} app
|
|
26
|
+
* @returns {Promise<string | undefined>}
|
|
27
|
+
*/
|
|
28
|
+
export async function readBundleId(app) {
|
|
29
|
+
const plist = path.join(app, 'Contents', 'Info.plist');
|
|
30
|
+
const text = await readFile(plist, 'utf8').catch(() => undefined);
|
|
31
|
+
if (text === undefined) return undefined;
|
|
32
|
+
if (text.trimStart().startsWith('<')) {
|
|
33
|
+
const match = /<key>CFBundleIdentifier<\/key>\s*<string>([^<]*)<\/string>/.exec(text);
|
|
34
|
+
return match ? match[1].trim() : undefined;
|
|
35
|
+
}
|
|
36
|
+
return new Promise(resolve => {
|
|
37
|
+
execFile('/usr/bin/plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', plist], (error, stdout) => resolve(error ? undefined : stdout.trim() || undefined));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {string} file */
|
|
42
|
+
const isDirectory = file => stat(file).then(info => info.isDirectory(), () => false);
|
|
43
|
+
/** @param {string} file */
|
|
44
|
+
const isFile = file => stat(file).then(info => info.isFile(), () => false);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The desktop app's directory in a checkout: `dir` itself or `dir/apps/desktop`, whichever holds the
|
|
48
|
+
* package named alp-desktop.
|
|
49
|
+
* @param {string} dir
|
|
50
|
+
*/
|
|
51
|
+
async function desktopPackage(dir) {
|
|
52
|
+
for (const candidate of [path.join(dir, 'apps', 'desktop'), dir]) {
|
|
53
|
+
const manifest = await readFile(path.join(candidate, 'package.json'), 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
|
|
54
|
+
if (manifest?.name === 'alp-desktop') return candidate;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Where the app is and how to start it. Exported for tests.
|
|
61
|
+
* `onSkip` hears about each ALP.app passed over because its bundle id is not DESKTOP_BUNDLE_ID.
|
|
62
|
+
* @param {{ platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv, applications?: string[], onSkip?: (message: string) => void }} [options]
|
|
63
|
+
* @returns {Promise<{ kind: 'app', app: string, command: string, args: string[] }
|
|
64
|
+
* | { kind: 'checkout', dir: string, command: string, args: string[] }
|
|
65
|
+
* | { kind: 'missing', reason?: string }>}
|
|
66
|
+
*/
|
|
67
|
+
export async function resolveDesktop({ platform = process.platform, home = os.homedir(), env = process.env, applications, onSkip = () => {} } = {}) {
|
|
68
|
+
if (platform === 'darwin') {
|
|
69
|
+
for (const directory of applications ?? ['/Applications', path.join(home, 'Applications')]) {
|
|
70
|
+
const app = path.join(directory, 'ALP.app');
|
|
71
|
+
if (!(await isDirectory(app))) continue;
|
|
72
|
+
const id = await readBundleId(app);
|
|
73
|
+
if (id === DESKTOP_BUNDLE_ID) return { kind: 'app', app, command: 'open', args: [app] };
|
|
74
|
+
onSkip(`Skipped ${app}: its bundle id is ${id ? JSON.stringify(id) : 'unreadable'}, not ${DESKTOP_BUNDLE_ID} (ALP's desktop app).`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const checkout = env.ALP_DESKTOP_CHECKOUT;
|
|
78
|
+
if (!checkout) return { kind: 'missing' };
|
|
79
|
+
const dir = await desktopPackage(path.resolve(checkout));
|
|
80
|
+
if (!dir) return { kind: 'missing', reason: `ALP_DESKTOP_CHECKOUT=${checkout} is not an ALP checkout: neither it nor its apps/desktop holds the alp-desktop package.` };
|
|
81
|
+
const electron = path.join(dir, 'node_modules', '.bin', platform === 'win32' ? 'electron.cmd' : 'electron');
|
|
82
|
+
if (!(await isFile(electron)) || !(await isFile(path.join(dir, 'dist', 'main.cjs')))) {
|
|
83
|
+
return { kind: 'missing', reason: `The desktop app in ${dir} is not built: run \`bun install && bun run build\` there, then run alp desktop again.` };
|
|
84
|
+
}
|
|
85
|
+
return { kind: 'checkout', dir, command: electron, args: [dir] };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const INSTRUCTIONS = `ALP's desktop app is not installed.
|
|
89
|
+
- Put ALP.app in /Applications (or ~/Applications), or
|
|
90
|
+
- point ALP_DESKTOP_CHECKOUT at an ALP checkout whose apps/desktop is built:
|
|
91
|
+
cd <checkout>/apps/desktop && bun install && bun run build
|
|
92
|
+
ALP_DESKTOP_CHECKOUT=<checkout> alp desktop
|
|
93
|
+
Meanwhile, \`alp dashboard\` opens ALP in your browser.`;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* @param {string[]} args
|
|
97
|
+
* @param {{ resolve?: typeof resolveDesktop, launch?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void> }} [deps]
|
|
98
|
+
*/
|
|
99
|
+
export async function desktopCommand(args, { resolve = resolveDesktop, launch = start } = {}) {
|
|
100
|
+
if (args.length) throw new UsageError();
|
|
101
|
+
const found = await resolve({ onSkip: message => console.error(message) });
|
|
102
|
+
if (found.kind === 'missing') {
|
|
103
|
+
if (found.reason) console.error(found.reason);
|
|
104
|
+
console.error(INSTRUCTIONS);
|
|
105
|
+
process.exitCode = 1;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const env = { ...process.env };
|
|
109
|
+
// An agent's shell (and Electron's own tools) may set it; Electron would then run as plain Node.
|
|
110
|
+
delete env.ELECTRON_RUN_AS_NODE;
|
|
111
|
+
await launch(found.command, found.args, env);
|
|
112
|
+
console.log(found.kind === 'app' ? `Opened ${found.app}.` : `Started the desktop app from ${found.dir}.`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Starts `command` detached, resolving once it spawned. @param {string} command @param {string[]} args @param {NodeJS.ProcessEnv} env */
|
|
116
|
+
function start(command, args, env) {
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true, env });
|
|
119
|
+
child.once('error', reject);
|
|
120
|
+
child.once('spawn', () => { child.unref(); resolve(); });
|
|
121
|
+
});
|
|
122
|
+
}
|