omnitrix 0.0.0-stage → 0.5.0

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.
@@ -0,0 +1,188 @@
1
+ // Starts the dashboard in the background once, finds it again later, and opens at most one tab for it.
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import { dashboardFile } from './dashboard.js';
5
+ import { homeDir, processAlive } from './store.js';
6
+ import { VERSION } from './version.js';
7
+ export const DEFAULT_PORT = 4590;
8
+ // a page retries a lost stream every 2 s (see "retry" in dashboard.ts), so 3.5 s covers one retry and a slow start
9
+ const RECONNECT_WAIT_MS = 3500;
10
+ async function ask(port, what, timeoutMs = 1500) {
11
+ try {
12
+ const res = await fetch(`http://127.0.0.1:${port}${what}`, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error' });
13
+ if (!res.ok)
14
+ return undefined;
15
+ return (await res.json());
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /** Whatever answers on this port as an omnitrix dashboard, if anything does. */
22
+ export async function ping(port) {
23
+ const p = await ask(port, '/api/ping');
24
+ return p?.omnitrix && typeof p.version === 'string' && Number.isInteger(p.pid) ? { version: p.version, pid: p.pid, viewers: Number(p.viewers) || 0 } : undefined;
25
+ }
26
+ /** Opens a page in the default browser. */
27
+ export function openBrowser(url) {
28
+ const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
29
+ spawnSync(cmd, args, { stdio: 'ignore', windowsHide: true });
30
+ }
31
+ function recorded(port) {
32
+ try {
33
+ return JSON.parse(fs.readFileSync(dashboardFile(port), 'utf8'));
34
+ }
35
+ catch {
36
+ return {};
37
+ }
38
+ }
39
+ /** True when this port is served by a dashboard that this omnitrix home started: its record names the same process. */
40
+ async function ours(port) {
41
+ const p = await ping(port);
42
+ return p && recorded(port).pid === p.pid ? p : undefined;
43
+ }
44
+ /** Stop the process that answered on the port as `pid`, and only that one. */
45
+ async function stopProcess(port, pid) {
46
+ if ((await ping(port))?.pid !== pid)
47
+ return false;
48
+ try {
49
+ process.kill(pid);
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ for (let i = 0; i < 50 && processAlive(pid); i++)
55
+ await new Promise((r) => setTimeout(r, 100));
56
+ if (recorded(port).pid === pid)
57
+ fs.rmSync(dashboardFile(port), { force: true });
58
+ return true;
59
+ }
60
+ /** Stop the background dashboard on a port, if this omnitrix home started one there. */
61
+ export async function stopDashboard(port = DEFAULT_PORT) {
62
+ const p = await ours(port);
63
+ if (!p) {
64
+ // a record of a server that is gone is only litter
65
+ if (recorded(port).pid !== undefined && (await ping(port)) === undefined)
66
+ fs.rmSync(dashboardFile(port), { force: true });
67
+ return false;
68
+ }
69
+ return stopProcess(port, p.pid);
70
+ }
71
+ /** The address of a running dashboard started from this omnitrix home, checked by asking it. */
72
+ export async function runningDashboard() {
73
+ let names = [];
74
+ try {
75
+ names = fs.readdirSync(homeDir()).filter((n) => /^dashboard-\d+\.json$/.test(n));
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ for (const name of names) {
81
+ const port = Number(/\d+/.exec(name)[0]);
82
+ if (await ours(port))
83
+ return `http://127.0.0.1:${port}`;
84
+ }
85
+ return null;
86
+ }
87
+ /** True when version `a` ("0.1.26") comes before version `b`. */
88
+ export function olderVersion(a, b) {
89
+ const pa = a.split('.').map(Number);
90
+ const pb = b.split('.').map(Number);
91
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
92
+ const x = pa[i] ?? 0;
93
+ const y = pb[i] ?? 0;
94
+ if (!Number.isFinite(x) || !Number.isFinite(y))
95
+ return false;
96
+ if (x !== y)
97
+ return x < y;
98
+ }
99
+ return false;
100
+ }
101
+ /**
102
+ * Run when omnitrix starts. Each background dashboard from this omnitrix home is replaced when it runs an
103
+ * older version, since installing an update does not stop it, and started again when its process ended
104
+ * without `omnitrix dashboard --stop`, which removes the record. No tab opens; open pages reconnect by
105
+ * themselves. A newer dashboard is left alone, so an older omnitrix cannot turn it back.
106
+ */
107
+ export async function refreshDashboards(opts = {}) {
108
+ let names = [];
109
+ try {
110
+ names = fs.readdirSync(homeDir()).filter((n) => /^dashboard-\d+\.json$/.test(n));
111
+ }
112
+ catch {
113
+ return [];
114
+ }
115
+ const refreshed = [];
116
+ for (const name of names) {
117
+ const port = Number(/\d+/.exec(name)[0]);
118
+ const p = await ping(port);
119
+ const pid = recorded(port).pid;
120
+ if (p ? pid !== p.pid || !olderVersion(p.version, VERSION) : !Number.isInteger(pid) || processAlive(pid))
121
+ continue;
122
+ try {
123
+ await ensureDashboard({ port, cli: opts.cli, open: false });
124
+ refreshed.push(port);
125
+ }
126
+ catch {
127
+ // `omnitrix dashboard` reports what is wrong, such as another program on the port
128
+ }
129
+ }
130
+ return refreshed;
131
+ }
132
+ // A short-lived launcher starts the dashboard and exits at once. A program that closes its helpers on
133
+ // Windows closes their whole process tree, detached children included, and the dashboard would go with
134
+ // it. Its arguments arrive through argv, never as program text.
135
+ const LAUNCHER = "require('node:child_process').spawn(process.execPath,process.argv.slice(1),{detached:true,stdio:'ignore',windowsHide:true}).unref()";
136
+ /**
137
+ * Make sure a dashboard of this version runs on the port, starting one in the background if needed, and
138
+ * open a tab unless a page is already open or one was opened moments ago. Running this twice starts
139
+ * nothing twice.
140
+ */
141
+ export async function ensureDashboard(opts = {}) {
142
+ const port = opts.port ?? DEFAULT_PORT;
143
+ const url = `http://127.0.0.1:${port}`;
144
+ let running = await ping(port);
145
+ // After an upgrade the old version gives way. Exactly the process that answered is stopped, so a new
146
+ // server started meanwhile by another `omnitrix init` is never stopped by mistake.
147
+ if (running && running.version !== VERSION) {
148
+ // only a dashboard this data folder started gives way; one from another folder belongs to someone else's setup
149
+ if (recorded(port).pid !== running.pid)
150
+ throw new Error(`port ${port} is used by an omnitrix dashboard (${running.version}) of another omnitrix data folder; stop it from there, or choose another port with --port`);
151
+ await stopProcess(port, running.pid);
152
+ running = await ping(port);
153
+ if (running && running.version !== VERSION)
154
+ throw new Error(`an older omnitrix dashboard on port ${port} could not be stopped; stop it, then try again`);
155
+ }
156
+ // this version answering without our record is some other program, or a dashboard of another omnitrix home
157
+ if (running && !(await ours(port)))
158
+ throw new Error(`port ${port} is used by another program; choose another with --port`);
159
+ let started = false;
160
+ if (!running) {
161
+ const cli = opts.cli ?? process.argv[1];
162
+ const args = [cli, 'dashboard', '--serve', '--port', String(port)];
163
+ const child = spawn(process.execPath, process.platform === 'win32' ? ['-e', LAUNCHER, ...args] : args, { detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
164
+ child.unref();
165
+ for (let i = 0; i < 80 && !running; i++) {
166
+ await new Promise((r) => setTimeout(r, 100));
167
+ running = await ours(port);
168
+ }
169
+ if (!running)
170
+ throw new Error(`the dashboard did not start; port ${port} may be used by another program, such as an older dashboard still running in a terminal (choose another with --port)`);
171
+ started = true;
172
+ // Pages that were open before a restart come back on their own within about two seconds; give them
173
+ // the time, or a tab would open beside them.
174
+ for (let i = 0; i < RECONNECT_WAIT_MS / 250 && running.viewers === 0; i++) {
175
+ await new Promise((r) => setTimeout(r, 250));
176
+ running = (await ping(port)) ?? running;
177
+ }
178
+ }
179
+ let opened = false;
180
+ if (opts.open !== false) {
181
+ const claim = await ask(port, '/api/claim-open');
182
+ if (claim?.open) {
183
+ (opts.open ?? openBrowser)(url);
184
+ opened = true;
185
+ }
186
+ }
187
+ return { url, started, opened };
188
+ }