Repository navigation
Expand file tree
/
Copy pathfront.mjs
More file actions
executable file
·422 lines (400 loc) · 22.3 KB
/
Copy pathfront.mjs
File metadata and controls
executable file
·422 lines (400 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/env node
/* PinDeck: the front, which is what `pindeck` starts.
pindeck [deck-dir | deck.html] [--port 5180] [--provider claude|codex] [--model <name>] [--asset-root <dir>]
pindeck login [deck-dir | deck.html]
pindeck export <deck> --out <dir> [--size WxH] [--fragments last|each] [--json]
pindeck layout <deck> [--json]
export and layout run without the front or the editor (lib/headless.mjs). One port and one login for several decks. Each deck that is open runs its own deck server (server.mjs, on
a private port of 127.0.0.1 with a token of its own) and is reached here as /d/<deck key>/: the front logs
the browser in, then passes each request on with that deck's token. A deck starts when it is first asked
for (from the editor's deck menu, or a bookmark), so its chat, Claude session and undo stay while it is
open, and Claude can go on working in one deck while you edit another. A deck with no editor open for
PINDECK_IDLE_MS (30 minutes) is closed; it opens again when asked for.
The menu lists the decks in the start folder and the asset roots, and in their folders one level down
(lib/deck-list.mjs). Only those can be opened: there is no free path entry. */
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { isSupportedPlatform, detectCapabilities, publicCapabilities, parsePort } from "./lib/capabilities.mjs";
import { deckTarget, homeDir, homeWarning } from "./lib/deck-target.mjs";
import { goodHost, LOGIN_PAGE, createLogin, openOnEnter } from "./lib/login.mjs";
import { listDecks } from "./lib/deck-list.mjs";
import { assetRoots } from "./lib/asset-roots.mjs";
import { registerServer, printLogin } from "./lib/servers.mjs";
import { USAGE } from "./lib/usage.mjs";
const EDITOR_DIR = path.dirname(fileURLToPath(import.meta.url));
const SERVER = path.join(EDITOR_DIR, "server.mjs");
const HOME_DIR = homeDir();
const IDLE_MS = Number(process.env.PINDECK_IDLE_MS) || 30 * 60000;
const argv = process.argv.slice(2);
/* pindeck export and pindeck layout: without the editor, a server or a backend (lib/headless.mjs) */
if (argv[0] === "export" || argv[0] === "layout") {
const { runHeadless } = await import("./lib/headless.mjs");
process.exit(await runHeadless(argv[0], argv.slice(1)));
}
if (argv.includes("--help") || argv.includes("-h")) { console.log(USAGE); process.exit(0); }
const opt = (name, dflt) => { const i = argv.indexOf(name); return i >= 0 ? argv.splice(i, 2)[1] : dflt; };
const portArg = opt("--port", process.env.PORT || 5180);
const PASS = []; // what every deck server gets: the backend and the asset roots
for (const name of ["--provider", "--model"]) { const v = opt(name); if (v !== undefined) PASS.push(name, v); }
const assetArgs = [];
for (let a; (a = opt("--asset-root")) !== undefined;) { assetArgs.push(a); PASS.push("--asset-root", a); }
let PORT = parsePort(portArg); // the port actually bound once listening (--port 0 picks a free one)
if (PORT === null) { console.error(`Invalid port "${portArg}": use a number from 1 to 65535.\n\n${USAGE}`); process.exit(2); }
if (!isSupportedPlatform(process.platform)) {
const { showPlatformNotice } = await import("./lib/platform-notice.mjs");
await showPlatformNotice(PORT);
process.exit(0);
}
/* pindeck login: a new one-time login link from the PinDeck that serves the deck (see lib/servers.mjs), asked
with the token in its server file (readable only by this user). With a deck, the link opens that deck. */
if (argv[0] === "login") await printLogin(HOME_DIR, argv[1] ? deckTarget(argv[1]) : null);
/* The start deck, and the folders whose decks the menu offers. A folder without index.html opens the list
of its decks; if it has none, its deck server says why, as for any deck that cannot be opened. */
const homeNote = homeWarning(HOME_DIR);
if (homeNote) console.warn(homeNote);
const START = deckTarget(argv[0] || process.cwd());
if (process.env.CLAUDE_MODEL) // PinDeck 2 read it
console.warn(`CLAUDE_MODEL is not used by PinDeck 3: choose the model in the editor's model menu, or start with --model ${process.env.CLAUDE_MODEL}.`);
let fileConfig = {};
try { fileConfig = JSON.parse(fs.readFileSync(path.join(HOME_DIR, "config.json"), "utf8")); } catch {}
if (!fileConfig || typeof fileConfig !== "object" || Array.isArray(fileConfig)) fileConfig = {}; // the deck server says why
// a missing asset root stops the start, before anything is written; one that goes later lists nothing
const givenRoots = assetRoots(assetArgs, fileConfig);
if (givenRoots.missing.length) { console.error(`Asset root ${givenRoots.missing[0]} is not a folder.\n\n${USAGE}`); process.exit(2); }
const ROOTS = [...new Set([START.dir, ...givenRoots.roots])];
const decksNow = () => listDecks(ROOTS);
const chooser = !START.named && !fs.existsSync(path.join(START.dir, START.file)) && decksNow().some((d) => !d.problem);
const TOKEN = crypto.randomBytes(16).toString("hex");
let ORIGIN = `http://127.0.0.1:${PORT}`; // set again from the bound port once listening
const { loginCode, loginUrl, authed, login } = createLogin({ token: TOKEN, port: () => PORT, origin: () => ORIGIN });
const CAPS = detectCapabilities();
/* ---- Deck servers -------------------------------------------------------------------------------- */
const decks = new Map(); // key -> { key, dir, file, label, proc, url, token, ready, exited, sse, last }
const labelOf = (d) => (d.file === "index.html" ? path.basename(d.dir) : d.file);
let quitting = false;
/* Its output goes to this terminal, each line marked with the deck. hold(l): keep the line back for now */
function forward(stream, label, to, keep, hold = () => false) {
let rest = "";
const put = (l) => { keep?.(l + "\n"); if (!hold(l)) to.write(`[${label}] ${l}\n`); };
stream.on("data", (chunk) => {
const lines = (rest + chunk).split("\n");
rest = lines.pop();
lines.forEach(put);
});
stream.on("end", () => { if (rest) put(rest); });
}
/* The deck's server, started once: the promise resolves when it listens, or rejects with what it printed.
The start deck's complaints are printed by the front as they are, like those of PinDeck before the front. */
function openDeck(entry, start = false) {
const known = decks.get(entry.key);
if (known) return known.ready;
const d = { key: entry.key, dir: entry.dir, file: entry.file, label: labelOf(entry), sse: 0, last: Date.now() };
decks.set(d.key, d);
// its own process group: Ctrl+C reaches the front only, which then ends every deck once
d.proc = spawn(process.execPath, [SERVER, entry.file === "index.html" ? entry.dir : path.join(entry.dir, entry.file),
"--port", "0", ...PASS], { env: { ...process.env, PINDECK_FRONT: "1", PINDECK_FRONT_URL: ORIGIN },
stdio: ["ignore", "pipe", "pipe", "ipc"], detached: true });
// what it says before it listens: its reason if it stops; the start deck's warnings once it runs
let said = "";
const held = [];
forward(d.proc.stdout, d.label, process.stdout);
forward(d.proc.stderr, d.label, process.stderr, (l) => { if (!d.url) said = (said + l).slice(-20000); },
(l) => start && !d.url && held.push(l));
d.exited = new Promise((r) => d.proc.once("exit", r));
d.ready = new Promise((resolve, reject) => {
d.proc.on("message", (m) => {
if (!m?.ready) return;
Object.assign(d, { url: m.ready.url, token: m.ready.token });
for (const l of held.splice(0)) console.error(l); // a start that went ahead anyway, as PinDeck said it before the front
if (!start) console.log(`[${d.label}] opened: ${path.join(d.dir, d.file)}`);
resolve(d);
});
d.proc.once("exit", (code, signal) => {
if (decks.get(d.key) === d) decks.delete(d.key);
if (d.url && !quitting) console.log(`[${d.label}] closed`);
reject(Object.assign(new Error(said.trim() || `The deck server stopped (${code ?? signal}).`), { exitCode: code || 1 }));
});
});
d.ready.catch(() => {});
return d.ready;
}
function stopDeck(d) {
try { d.proc.kill("SIGTERM"); } catch {}
}
/* A deck with no editor open (no event stream) and nothing to do for IDLE_MS is closed */
setInterval(async () => {
for (const d of decks.values()) {
if (!d.url || d.sse > 0 || Date.now() - d.last < IDLE_MS) continue;
try {
const res = await fetch(`${d.url}/api/status`, { headers: { "x-editor-token": d.token } });
const st = await res.json();
if (st.busy || d.sse > 0 || Date.now() - d.last < IDLE_MS) continue;
} catch { continue; }
console.log(`[${d.label}] no editor open for ${Math.round(IDLE_MS / 60000)} min: closing it (it opens again when asked for)`);
stopDeck(d);
}
}, Math.min(60000, IDLE_MS / 2)).unref();
/* The request, without the front's cookie and with the deck's token, to the deck's server; the answer
streamed back (event streams, media ranges and large uploads included) */
function proxy(req, res, d, rest, anonymous = false) {
d.last = Date.now();
// the deck's pages keep the browser's host: on localhost (Present) the deck server leaves out the sandbox
const headers = { ...req.headers, host: anonymous ? req.headers.host : new URL(d.url).host, ...(anonymous ? {} : { "x-editor-token": d.token }) };
if (anonymous) delete headers["x-editor-token"];
delete headers.cookie;
delete headers.origin; // checked here against the front's address; the deck server checks its own
const up = http.request(d.url + rest, { method: req.method, headers }, (r) => {
res.writeHead(r.statusCode, r.headers);
r.pipe(res);
// the deck server stopped mid-answer (an event stream, say): end ours too, or the browser waits forever
r.on("aborted", () => res.destroy());
r.on("error", () => res.destroy());
});
up.on("error", () => { if (!res.headersSent) page(res, 502, "This deck stopped answering", "Reload the page to open it again."); else res.destroy(); });
if (rest.split("?")[0] === "/api/events") {
d.sse++;
res.on("close", () => { d.sse--; d.last = Date.now(); });
}
res.on("close", () => { if (!res.writableFinished) up.destroy(); });
req.pipe(up);
}
/* ---- One event stream per browser -------------------------------------------------------------------
Browsers open at most 6 connections to one host and port, and each editor tab held one open for its deck's
events: a sixth tab never loaded. The tabs of a browser share one stream through a shared worker
(public/events-worker.js): GET /events?stream=<id> holds it, POST /events/subscribe adds a tab's deck (the
front opens that deck's events on its server and passes them on, marked with the tab) or removes it. If a
deck server stops, the deck is opened again and the tab gets its state afresh (its "hello"). */
const streams = new Map(); // stream id -> { res, tabs: Map(tab -> { stop() }) }
function eventStream(res, id) {
streams.get(id)?.res.end(); // the worker reconnected: its old stream is done
const st = { res, tabs: new Map() };
streams.set(id, st);
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
res.write("event: ready\ndata: {}\n\n");
const ping = setInterval(() => res.write(": ping\n\n"), 20000);
res.on("close", () => {
clearInterval(ping);
if (streams.get(id) === st) streams.delete(id);
for (const t of st.tabs.values()) t.stop();
});
}
function follow(st, tab, key) {
let stopped = false, up = null, tries = 0;
const send = (type, raw) => {
if (!stopped && !st.res.writableEnded) st.res.write(`event: deck\ndata: {"tab":${JSON.stringify(tab)},"type":${JSON.stringify(type)},"data":${raw}}\n\n`);
};
const retry = () => {
if (stopped || quitting) return;
if (++tries > 20) return send("gone", JSON.stringify({ error: "The deck stopped answering. Reload the page." }));
setTimeout(connect, Math.min(5000, 200 * tries));
};
async function connect() {
if (stopped || quitting) return;
let d = decks.get(key);
try {
if (!d) {
const entry = START.key === key && !chooser ? { key, dir: START.dir, file: START.file } : decksNow().find((e) => e.key === key);
if (!entry || entry.problem) return send("gone", JSON.stringify({ error: entry?.problem || "This deck is not in the deck folder or an asset root (any more)." }));
d = entry;
}
d = await openDeck(d);
} catch (e) { return send("gone", JSON.stringify({ error: e.message })); }
if (stopped) return;
up = http.get(d.url + "/api/events", { headers: { "x-editor-token": d.token } }, (r) => {
if (r.statusCode !== 200) { r.resume(); return retry(); }
d.sse++;
tries = 0;
let buf = "", ended = false;
r.setEncoding("utf8");
r.on("data", (chunk) => {
buf += chunk;
for (let i; (i = buf.indexOf("\n\n")) >= 0;) {
const block = buf.slice(0, i);
buf = buf.slice(i + 2);
const type = /^event: (.*)$/m.exec(block)?.[1], data = /^data: (.*)$/m.exec(block)?.[1];
if (type && data) send(type, data);
}
});
const end = () => {
if (ended) return;
ended = true;
d.sse--;
d.last = Date.now();
if (!stopped) { send("gone", "{}"); retry(); }
};
r.on("end", end); r.on("aborted", end); r.on("error", end); r.on("close", end);
});
up.on("error", retry);
}
connect();
return { stop() { stopped = true; up?.destroy(); } };
}
async function readJson(req) {
let s = "";
req.setEncoding("utf8");
for await (const c of req) { s += c; if (s.length > 10000) throw new Error("body too large"); }
return s ? JSON.parse(s) : {};
}
/* ---- HTTP ------------------------------------------------------------------------------------- */
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c]));
const text = (res, code, s) => { res.writeHead(code, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }); res.end(s); };
const json = (res, code, o) => { res.writeHead(code, { "content-type": "application/json", "cache-control": "no-store" }); res.end(JSON.stringify(o)); };
function page(res, code, title, body) {
res.writeHead(code, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
res.end(`<!doctype html><meta charset="utf-8"><title>${esc(title)} · PinDeck</title>
<link rel="icon" href="/editor/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/editor/front.css">
<main class="front"><h1>${esc(title)}</h1>${body}</main>`);
}
/* The decks for the menu (and the start page without a start deck), with which are open and working */
const deckList = () => decksNow().map((e) => ({ key: e.key, rel: e.rel, root: e.root, problem: e.problem,
open: !!decks.get(e.key)?.url }));
function chooserPage(res) {
const list = deckList(), groups = new Map(ROOTS.map((r) => [r, list.filter((d) => d.root === r)]).filter(([, l]) => l.length));
const body = [...groups].map(([root, list]) => `<h2>${esc(root)}</h2><ul>${list.map((d) => d.problem
? `<li class="off" title="${esc(d.problem)}">${esc(d.rel)}<small>${esc(d.problem)}</small></li>`
: `<li><a href="/d/${esc(d.key)}/">${esc(d.rel)}</a>${d.open ? " <small>open</small>" : ""}</li>`).join("")}</ul>`).join("");
page(res, 200, "Decks", body || "<p>No decks here.</p>");
}
const MIME = { html: "text/html; charset=utf-8", css: "text/css; charset=utf-8", js: "text/javascript; charset=utf-8",
svg: "image/svg+xml", png: "image/png" };
function serveEditorFile(res, rel) {
const base = path.join(EDITOR_DIR, "public");
const f = path.resolve(base, "." + path.posix.normalize("/" + decodeURIComponent(rel)));
if (!f.startsWith(base + path.sep)) return text(res, 403, "Forbidden");
fs.readFile(f, (err, data) => {
if (err) return text(res, 404, "Not found");
res.writeHead(200, { "content-type": MIME[path.extname(f).slice(1)] || "application/octet-stream", "cache-control": "no-store" });
res.end(data);
});
}
const server = http.createServer(async (req, res) => {
const host = String(req.headers.host || "").toLowerCase();
if (!goodHost(host)) return text(res, 403, "Bad host");
try {
const url = new URL(req.url, ORIGIN);
const p = url.pathname;
if (req.method === "GET" && p === "/login") return login(res, url, host);
// the editor's own scripts and styles hold nothing secret; the deck page loads bridge.js from here
if (req.method === "GET" && p.startsWith("/editor/")) return serveEditorFile(res, p.slice(8));
/* A deck's pages and files under /d/<deck>/v/<token>/: asked for by the deck itself, which runs sandboxed
without the login cookie (see VIEW in server.mjs). Passed on without the token, so the deck server's own
check of the path is all they get; only to a deck that is open, so they never start one. */
const view = /^\/d\/([\w.-]+)(\/v\/.*)$/.exec(p);
if (view && !authed(req)) {
const d = decks.get(view[1]);
if (!d?.url || (req.method !== "GET" && req.method !== "HEAD")) return text(res, 403, "Not logged in");
return proxy(req, res, d, view[2] + url.search, true);
}
if (!authed(req)) {
if (req.method === "GET" && /^\/(d\/[^/]+\/(index\.html)?)?$/.test(p)) {
res.writeHead(403, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
return res.end(LOGIN_PAGE);
}
return text(res, 403, "Not logged in");
}
const origin = req.headers.origin;
if (req.method === "POST" && origin && origin.toLowerCase() !== `http://${host}`) return text(res, 403, "Bad origin");
if (p === "/") {
if (chooser) return chooserPage(res);
res.writeHead(302, { location: `/d/${START.key}/`, "cache-control": "no-store" });
return res.end();
}
if (p === "/api/ping") return json(res, 200, { ok: true, front: true });
if (p === "/api/login-link") return json(res, 200, { url: loginUrl(loginCode(3600000), url.searchParams.get("next") || "/") });
if (p === "/api/decks") return json(res, 200, { decks: deckList() });
if (p === "/events" && req.method === "GET") {
const id = url.searchParams.get("stream") || "";
return /^[\w-]{8,64}$/.test(id) ? eventStream(res, id) : text(res, 400, "Bad stream");
}
if (p === "/events/subscribe" && req.method === "POST") {
const b = await readJson(req);
const st = streams.get(String(b.stream));
const tab = String(b.tab || "");
if (!st || !/^\d{1,9}$/.test(tab)) return json(res, 404, { error: "No such stream." });
st.tabs.get(tab)?.stop();
st.tabs.delete(tab);
if (b.on && /^[\w.-]+$/.test(String(b.deck))) st.tabs.set(tab, follow(st, tab, String(b.deck)));
return json(res, 200, {});
}
const m = /^\/d\/([\w.-]+)(\/.*)?$/.exec(p);
if (!m) return text(res, 404, "Not found");
if (!m[2]) {
res.writeHead(301, { location: `/d/${m[1]}/${url.search}` });
return res.end();
}
let d = decks.get(m[1]);
if (!d) {
// only a deck from the list, and only one PinDeck can open
const entry = START.key === m[1] && !chooser ? { key: START.key, dir: START.dir, file: START.file }
: decksNow().find((e) => e.key === m[1]);
if (!entry) return page(res, 404, "No such deck", `<p>It is not in the deck folder or an asset root (any more).</p><p><a href="/">All decks</a></p>`);
if (entry.problem) return page(res, 409, "PinDeck cannot open this deck", `<p>${esc(entry.problem)}</p><p><a href="/">All decks</a></p>`);
d = entry;
}
try { d = await openDeck(d); }
catch (e) { return page(res, 502, "PinDeck could not open this deck", `<pre>${esc(e.message)}</pre><p><a href="/">All decks</a></p>`); }
return proxy(req, res, d, m[2] + url.search);
} catch (e) {
const bad = e instanceof SyntaxError || e instanceof URIError || e.message === "body too large";
if (!res.headersSent) text(res, bad ? 400 : 500, String(e.message || e));
}
});
/* ---- Start ----------------------------------------------------------------------------------------
The port is bound first, then the start deck opens (its server checks it before writing anything). If it
cannot, the front says why and stops: as before the front, nothing is written. */
let removeServerInfo = () => {};
function writeServerInfo() {
fs.mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 });
removeServerInfo = registerServer(HOME_DIR, { url: ORIGIN, token: TOKEN, deckDir: START.dir, front: true });
}
let listening = false;
server.on("error", (e) => {
if (listening) return console.error(e);
console.error(e.code === "EADDRINUSE"
? `Port ${PORT} is in use (another PinDeck, or an SSH tunnel?). Choose another with --port, the same on both ends of a tunnel.`
: `Cannot listen on 127.0.0.1:${PORT}: ${e.message}`);
process.exit(1);
});
server.listen(PORT, "127.0.0.1", async () => {
listening = true;
PORT = server.address().port;
ORIGIN = `http://127.0.0.1:${PORT}`;
if (!chooser) {
try { await openDeck({ key: START.key, dir: START.dir, file: START.file }, true); }
catch (e) {
console.error(e.message.replace(/\n+$/, ""));
process.exit(e.exitCode); // 2 for a bad argument, as the deck server says
}
}
writeServerInfo();
console.log(`PinDeck: ${loginUrl(loginCode(3600000))}`);
console.log(" (a one-time login link, valid for an hour; for a new one: pindeck login)");
openOnEnter(() => loginUrl(loginCode(3600000)));
console.log(chooser ? `Decks: ${START.dir}` : `Deck: ${START.dir}`);
console.log(`Server: ${CAPS.label}`);
for (const [name, c] of Object.entries(publicCapabilities(CAPS)))
if (c && c.available === false) console.log(` ${name}: off (${c.reason})`);
});
/* Ctrl+C or SIGTERM: every deck ends as it does on its own (its assistant gets end of input; at most 6 s),
then the front. A second Ctrl+C ends them at once. */
async function quit() {
if (quitting) {
for (const d of decks.values()) try { process.kill(-d.proc.pid, "SIGKILL"); } catch {}
process.exit(1);
}
quitting = true;
server.close();
server.closeAllConnections?.();
removeServerInfo();
const all = [...decks.values()];
all.forEach(stopDeck);
await Promise.race([Promise.all(all.map((d) => d.exited)), new Promise((r) => setTimeout(r, 7000))]);
for (const d of all) if (d.proc.exitCode === null && d.proc.signalCode === null) try { process.kill(-d.proc.pid, "SIGKILL"); } catch {}
process.exit(0);
}
process.on("SIGINT", quit);
process.on("SIGTERM", quit);