cliprobe 1.9.0 → 1.11.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.
package/dist/cli.js CHANGED
@@ -1,2755 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
- import { execFile, execFileSync, spawn } from "node:child_process";
4
- import { accessSync, closeSync, constants, existsSync, lstatSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
- import { delimiter, dirname, join, resolve, sep } from "node:path";
6
- import { tmpdir } from "node:os";
7
- import { randomUUID } from "node:crypto";
2
+ import { C as shellJoin, D as onInterrupt, E as handleInterrupts, S as MAX_TIMEOUT_MS, T as safe, _ as CONFIG_FILE, b as ProbeError, d as describeAccept, f as mainProbe, h as VERSION, l as prepare, m as planFromConfig, n as FORMAT_NAMES, o as execute, p as planFromArgs, r as isFormat, s as exitCodeFor, t as FORMATS, u as DEFAULT_TIMEOUT_MS, v as loadConfig, w as shellSplit, x as UsageError } from "./report-6mELXFtT.js";
3
+ import { accessSync, constants, existsSync, lstatSync, readlinkSync, realpathSync, rmSync, statSync } from "node:fs";
4
+ import { dirname, resolve, sep } from "node:path";
8
5
  import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises";
9
- // src/core/interrupt.ts
10
- const cleanups = /* @__PURE__ */ new Set();
11
- /** Registers `cleanup` until the returned function is called. */
12
- function onInterrupt(cleanup) {
13
- cleanups.add(cleanup);
14
- return () => {
15
- cleanups.delete(cleanup);
16
- };
17
- }
18
- /** Runs every registered cleanup, newest first, so processes die before their directories go. */
19
- function runInterruptCleanups() {
20
- const pending = [...cleanups].reverse();
21
- cleanups.clear();
22
- for (const cleanup of pending) try {
23
- cleanup();
24
- } catch {}
25
- }
26
- /** The signals that stop cliprobe and how a shell reports each: 128 plus its number. */
27
- const INTERRUPT_SIGNALS = /* @__PURE__ */ new Map([
28
- ["SIGHUP", 129],
29
- ["SIGINT", 130],
30
- ["SIGTERM", 143]
31
- ]);
32
- /**
33
- * On SIGINT, SIGTERM or SIGHUP: cleans up, then dies by the same signal, so the
34
- * shell or CI runner sees 130, 143 or 129 as for any other program.
35
- */
36
- function handleInterrupts(target = process) {
37
- const signals = [...INTERRUPT_SIGNALS.keys()];
38
- for (const [signal, code] of INTERRUPT_SIGNALS) target.once(signal, () => {
39
- runInterruptCleanups();
40
- for (const s of signals) target.removeAllListeners(s);
41
- try {
42
- target.kill(target.pid, signal);
43
- } catch {
44
- target.exit(code);
45
- }
46
- });
47
- }
48
- // src/core/group.ts
49
- const isGone = (state) => state.startsWith("Z") || state.startsWith("X");
50
- /** Fields of a /proc/<pid>/stat line; the name may hold spaces and parentheses. */
51
- function parseProcStat(line) {
52
- const open = line.indexOf("(");
53
- const close = line.lastIndexOf(")");
54
- const fields = line.slice(close + 1).trim().split(" ");
55
- return {
56
- name: line.slice(open + 1, close),
57
- state: fields[0] ?? "",
58
- ppid: Number(fields[1] ?? ""),
59
- pgid: Number(fields[2] ?? ""),
60
- start: fields[19] ?? ""
61
- };
62
- }
63
- /** Every running process, without zombies, read from `<root>`. */
64
- function tableFromProc(root = "/proc", keep = () => true) {
65
- const table = [];
66
- for (const entry of readdirSync(root)) {
67
- if (!/^\d+$/.test(entry)) continue;
68
- try {
69
- const stat = parseProcStat(readFileSync(`${root}/${entry}/stat`, "utf8"));
70
- if (isGone(stat.state) || !keep(stat)) continue;
71
- const cmdline = readFileSync(`${root}/${entry}/cmdline`, "utf8").split("\0").filter(Boolean).join(" ");
72
- table.push({
73
- pid: Number(entry),
74
- ppid: stat.ppid,
75
- pgid: stat.pgid,
76
- start: stat.start,
77
- command: cmdline || stat.name
78
- });
79
- } catch {}
80
- }
81
- return table.sort((a, b) => a.pid - b.pid);
82
- }
83
- /** lstart is the only start time macOS ps gives; LC_ALL=C keeps its format fixed. */
84
- const PS_ARGS = [
85
- "-A",
86
- "-o",
87
- "pid=,ppid=,pgid=,lstart=,stat=,args="
88
- ];
89
- const PS_ENV = {
90
- ...process.env,
91
- LC_ALL: "C"
92
- };
93
- const PS_LINE = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+(\S+)\s+(.*)$/;
94
- /** Running processes from `ps -A -o pid=,ppid=,pgid=,lstart=,stat=,args=` output. */
95
- function parsePsTable(out) {
96
- const table = [];
97
- for (const line of out.split("\n")) {
98
- const m = PS_LINE.exec(line);
99
- if (!m || isGone(m[5] ?? "")) continue;
100
- table.push({
101
- pid: Number(m[1]),
102
- ppid: Number(m[2]),
103
- pgid: Number(m[3]),
104
- start: m[4] ?? "",
105
- command: (m[6] ?? "").trim()
106
- });
107
- }
108
- return table.sort((a, b) => a.pid - b.pid);
109
- }
110
- /**
111
- * A snapshot of every running process, read at once: from /proc on Linux, from
112
- * ps elsewhere. `platform` and `ps` are parameters so tests can take the ps path
113
- * on Linux and see it fail.
114
- */
115
- function processTable(platform = process.platform, ps = "ps") {
116
- if (platform === "linux") return tableFromProc();
117
- try {
118
- return parsePsTable(execFileSync(ps, PS_ARGS, {
119
- encoding: "utf8",
120
- env: PS_ENV
121
- }));
122
- } catch {
123
- return [];
124
- }
125
- }
126
- /** processTable() without blocking: on macOS, ps takes a few milliseconds. */
127
- function processTableAsync(platform = process.platform, ps = "ps") {
128
- if (platform === "linux") return Promise.resolve(tableFromProc());
129
- return new Promise((resolve) => {
130
- execFile(ps, PS_ARGS, {
131
- encoding: "utf8",
132
- env: PS_ENV
133
- }, (error, out) => {
134
- resolve(error ? [] : parsePsTable(out));
135
- });
136
- });
137
- }
138
- /**
139
- * What one run started, followed by parent PID as well as by process group: a
140
- * child in its own group or session (Node's `detached`, setsid, daemons) leaves
141
- * the program's group, and once the program exits it is reparented, so only a
142
- * snapshot taken while the program runs links it to the program.
143
- */
144
- var ProcessTree = class {
145
- #root;
146
- #groups;
147
- /** Descendants seen so far, by PID, with their start time. */
148
- #seen = /* @__PURE__ */ new Map();
149
- /**
150
- * @param root the program's PID
151
- * @param groups the process groups whose members belong to the run, read
152
- * each time: the program's own, and the one under a pseudo-terminal
153
- */
154
- constructor(root, groups) {
155
- this.#root = root;
156
- this.#groups = groups;
157
- }
158
- /** Once the program has exited and been reaped, its PID may belong to another process. */
159
- programExited() {
160
- this.#root = void 0;
161
- }
162
- /** Records the program's descendants from a snapshot taken while it runs. */
163
- record(table) {
164
- for (const p of this.running(table)) this.#seen.set(p.pid, p.start);
165
- }
166
- /**
167
- * The run's processes in `table`: the program, the members of its groups,
168
- * the descendants recorded earlier (the same PID and start time), and
169
- * everything below any of them. cliprobe itself is never one of them.
170
- */
171
- running(table) {
172
- const groups = new Set(this.#groups());
173
- const found = /* @__PURE__ */ new Map();
174
- const candidates = table.filter((p) => p.pid !== 1 && p.pid !== process.pid);
175
- for (const p of candidates) if (p.pid === this.#root || groups.has(p.pgid) || this.#seen.has(p.pid) && this.#seen.get(p.pid) === p.start) found.set(p.pid, p);
176
- let grew = true;
177
- while (grew) {
178
- grew = false;
179
- for (const p of candidates) if (!found.has(p.pid) && found.has(p.ppid)) {
180
- found.set(p.pid, p);
181
- grew = true;
182
- }
183
- }
184
- return [...found.values()].sort((a, b) => a.pid - b.pid);
185
- }
186
- };
187
- /**
188
- * SIGKILLs the given processes, the run's groups, and every group that one of
189
- * the processes leads, so what they started after the snapshot goes too.
190
- */
191
- function killAll(processes, groups) {
192
- const targets = new Set(groups.map((g) => -g));
193
- for (const p of processes) {
194
- targets.add(p.pid);
195
- if (p.pgid === p.pid) targets.add(-p.pid);
196
- }
197
- targets.delete(-process.pid);
198
- targets.delete(process.pid);
199
- targets.delete(-1);
200
- targets.delete(1);
201
- targets.delete(0);
202
- for (const target of targets) try {
203
- process.kill(target, "SIGKILL");
204
- } catch {}
205
- }
206
- // src/core/sandbox.ts
207
- /** A minimal environment: no tokens or config from the caller's shell. */
208
- function sandbox() {
209
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-"));
210
- return {
211
- dir,
212
- env: {
213
- PATH: process.env["PATH"] ?? "/usr/bin:/bin",
214
- LANG: process.env["LANG"] ?? "C.UTF-8",
215
- HOME: dir,
216
- TMPDIR: dir,
217
- TERM: "dumb",
218
- CI: "1",
219
- NO_UPDATE_NOTIFIER: "1"
220
- }
221
- };
222
- }
223
- // src/core/which.ts
224
- function isExecutableFile(path) {
225
- try {
226
- accessSync(path, constants.X_OK);
227
- return statSync(path).isFile();
228
- } catch {
229
- return false;
230
- }
231
- }
232
- /**
233
- * Where `command` would be found, as spawn() looks for it: a path with a slash
234
- * as given, otherwise each PATH entry in turn (an empty entry is the current
235
- * directory). Under a PTY, a missing command is only a line of shell output, so
236
- * the terminal checks ask first.
237
- */
238
- function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
239
- if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
240
- for (const dir of path.split(delimiter)) {
241
- const candidate = join(dir || ".", command);
242
- if (isExecutableFile(candidate)) return candidate;
243
- }
244
- }
245
- /** The first bytes of a file, or nothing when it can't be read (execute-only, say). */
246
- function head(path, bytes = 512) {
247
- let fd;
248
- try {
249
- fd = openSync(path, "r");
250
- const buffer = Buffer.alloc(bytes);
251
- return buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0));
252
- } catch {
253
- return Buffer.alloc(0);
254
- } finally {
255
- if (fd !== void 0) closeSync(fd);
256
- }
257
- }
258
- /** Why the interpreter named on a `#!` line can't run, if it can't. */
259
- function interpreterProblem(command, file, path) {
260
- const start = head(file, 256);
261
- if (start.subarray(0, 2).toString("latin1") !== "#!") return void 0;
262
- const [interpreter = "", first] = (start.toString("utf8").slice(2).split("\n")[0] ?? "").trim().split(/[ \t]+/);
263
- if (interpreter === "") return void 0;
264
- try {
265
- statSync(interpreter);
266
- } catch {
267
- return `${command}: interpreter ${interpreter} not found`;
268
- }
269
- if (!isExecutableFile(interpreter)) return `${command}: interpreter ${interpreter} is not executable`;
270
- if (/(^|\/)env$/.test(interpreter) && first !== void 0 && !first.startsWith("-")) {
271
- if (!first.includes("=") && findCommand(first, path) === void 0) return `${command}: interpreter ${first} not found (${interpreter} ${first})`;
272
- }
273
- }
274
- /**
275
- * Why `command` can't run, or undefined if it looks runnable: not found, a
276
- * directory, not executable, or a `#!` interpreter that is missing. Asked before
277
- * any check, so the user sees the cause once instead of an error per probe.
278
- */
279
- function commandProblem(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
280
- if (command.includes("/")) {
281
- let isFile;
282
- try {
283
- const stat = statSync(command);
284
- if (stat.isDirectory()) return `${command} is a directory`;
285
- isFile = stat.isFile();
286
- } catch {
287
- return `command not found: ${command}`;
288
- }
289
- if (!isFile) return `${command} is not a regular file`;
290
- if (!isExecutableFile(command)) return `${command} is not executable (chmod +x?)`;
291
- return interpreterProblem(command, command, path);
292
- }
293
- const file = findCommand(command, path);
294
- if (file === void 0) return `command not found: ${command}`;
295
- return interpreterProblem(command, file, path);
296
- }
297
- /** The reason given for a file this system can't run as a program. */
298
- const notAProgram = (command, how) => `${command} is not a program this system can run (${how})`;
299
- /**
300
- * Whether `command` resolves to a file that no shell or kernel would run as a
301
- * program of this system: no `#!` line, and a NUL byte near its start, which no
302
- * script has. Alone this could be a binary run through binfmt_misc, so callers
303
- * also need the run to have exited 126 or 127.
304
- */
305
- function cannotExecute(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
306
- const file = findCommand(command, path);
307
- if (file === void 0) return false;
308
- const start = head(file);
309
- return start.subarray(0, 2).toString("latin1") !== "#!" && start.includes(0);
310
- }
311
- /**
312
- * Whether a run ended because the system could not run the file at all. On
313
- * Linux, spawn() hands a file the kernel can't execute (ENOEXEC) to /bin/sh,
314
- * as execvp() does, so a binary that isn't one for this system "runs" and exits
315
- * 126 or 127 with the shell's complaint, prefixed by the file's path. Only a
316
- * file with no `#!` line and a NUL byte near its start counts, as no script has
317
- * one: a binary run through binfmt_misc, or a script without `#!`, is left alone.
318
- * Returns the reason, or undefined.
319
- */
320
- function shellFallbackError(command, exitCode, stderr, path = process.env["PATH"] ?? "/usr/bin:/bin") {
321
- if (exitCode !== 126 && exitCode !== 127) return void 0;
322
- const file = findCommand(command, path);
323
- if (file === void 0 || !cannotExecute(command, path)) return void 0;
324
- if (!stderr.startsWith(`${command}: `) && !stderr.startsWith(`${file}: `)) return void 0;
325
- return notAProgram(command, `/bin/sh tried it as a script and exited ${exitCode}`);
326
- }
327
- // src/core/run.ts
328
- const STDERR_CAP = 65536;
329
- /** A device on Linux that accepts no data: every write to it fails with ENOSPC. */
330
- const DEV_FULL = "/dev/full";
331
- /** Whether this system has /dev/full (Linux does; macOS doesn't). */
332
- const hasDevFull = () => existsSync(DEV_FULL);
333
- const STDOUT_CAP = 1048576;
334
- /**
335
- * The longest delay setTimeout takes (2^31 - 1 ms, about 24.8 days). Node turns
336
- * anything longer into 1 ms, which would kill every probe at once.
337
- */
338
- const MAX_TIMEOUT_MS = 2 ** 31 - 1;
339
- /** How often the process table is read while the program runs, to learn its descendants. */
340
- const TREE_POLL_MS = 200;
341
- /** How long to wait for the output pipes to close once everything the run started is gone. */
342
- const CLOSE_WAIT_MS = 1e3;
343
- /** How often to look for leftovers while waiting for them to finish. */
344
- const LEFTOVER_POLL_MS = 50;
345
- const delay = (ms) => new Promise((resolve) => {
346
- setTimeout(resolve, ms);
347
- });
348
- /**
349
- * Runs one invocation. With `closedStdout`, stdout is the write end of a FIFO
350
- * whose read end is closed before the program starts, so its first write to
351
- * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
352
- * With `fullStdout`, stdout is /dev/full, so every write fails with ENOSPC.
353
- */
354
- function run$1(command, args, { closedStdout = false, fullStdout = false, timeout, env: overrides = {}, extraGroup, signal, stdin = "null", leftoversMs = 250 }) {
355
- const { dir, env: base } = sandbox();
356
- const env = { ...base };
357
- for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
358
- else env[key] = value;
359
- let stdoutFd = "pipe";
360
- if (closedStdout) {
361
- const fifo = join(dir, "stdout.fifo");
362
- execFileSync("mkfifo", [fifo]);
363
- const reader = openSync(fifo, constants.O_RDONLY | constants.O_NONBLOCK);
364
- stdoutFd = openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK);
365
- closeSync(reader);
366
- } else if (fullStdout) stdoutFd = openSync(DEV_FULL, "w");
367
- return new Promise((resolve) => {
368
- let stdoutBytes = 0;
369
- const stdoutChunks = [];
370
- let stderr = "";
371
- let timedOut = false;
372
- let finished = false;
373
- let exited = false;
374
- let signalSentMs;
375
- let stderrAtSignal;
376
- let leftRunning;
377
- let exitMs;
378
- let tree;
379
- let pollTimer;
380
- const start = performance.now();
381
- const groups = () => {
382
- const extra = extraGroup?.();
383
- return [...child?.pid === void 0 ? [] : [child.pid], ...extra === void 0 ? [] : [extra]];
384
- };
385
- /** Kills everything the run started, from a fresh look at the process table. */
386
- const killRun = () => {
387
- if (tree) killAll(tree.running(processTable()), groups());
388
- };
389
- const unregister = onInterrupt(() => {
390
- killRun();
391
- rmSync(dir, {
392
- recursive: true,
393
- force: true
394
- });
395
- });
396
- const finish = (outcome) => {
397
- if (finished) return;
398
- finished = true;
399
- clearInterval(pollTimer);
400
- unregister();
401
- if (typeof stdoutFd === "number") closeSync(stdoutFd);
402
- rmSync(dir, {
403
- recursive: true,
404
- force: true
405
- });
406
- const stdout = Buffer.concat(stdoutChunks).subarray(0, STDOUT_CAP);
407
- resolve({
408
- stdoutBytes,
409
- stdout,
410
- stderr,
411
- timedOut,
412
- durationMs: exitMs ?? Math.round(performance.now() - start),
413
- ...signalSentMs === void 0 ? {} : {
414
- signalSentMs,
415
- stderrAtSignal: stderrAtSignal ?? 0
416
- },
417
- ...leftRunning === void 0 ? {} : { leftRunning },
418
- ...outcome
419
- });
420
- };
421
- let child;
422
- try {
423
- child = spawn(command, [...args], {
424
- env,
425
- stdio: [
426
- stdin === "null" ? "ignore" : "pipe",
427
- stdoutFd,
428
- "pipe"
429
- ],
430
- detached: true
431
- });
432
- } catch (error) {
433
- finish({
434
- exitCode: null,
435
- signal: null,
436
- spawnError: spawnMessage(command, error)
437
- });
438
- return;
439
- }
440
- const proc = child;
441
- if (proc.pid !== void 0) {
442
- tree = new ProcessTree(proc.pid, groups);
443
- let polling = false;
444
- pollTimer = setInterval(() => {
445
- if (polling || exited) return;
446
- polling = true;
447
- (async () => {
448
- const table = await processTableAsync();
449
- polling = false;
450
- if (!exited) tree?.record(table);
451
- })();
452
- }, TREE_POLL_MS);
453
- }
454
- const recordTree = () => {
455
- tree?.record(processTable());
456
- };
457
- const timer = setTimeout(() => {
458
- timedOut = true;
459
- recordTree();
460
- killRun();
461
- }, Math.min(timeout, MAX_TIMEOUT_MS));
462
- const signalTimer = signal && setTimeout(() => {
463
- if (exited || proc.pid === void 0) return;
464
- recordTree();
465
- signalSentMs = Math.round(performance.now() - start);
466
- stderrAtSignal = stderr.length;
467
- try {
468
- process.kill(signal.to === "process" ? proc.pid : -proc.pid, signal.name);
469
- } catch {}
470
- }, signal.afterMs);
471
- const closeTimer = typeof stdin === "object" ? setTimeout(() => proc.stdin?.destroy(), stdin.closeAfterMs) : void 0;
472
- let closed = false;
473
- let onClosed;
474
- const outputClosed = new Promise((resolveClosed) => {
475
- onClosed = resolveClosed;
476
- });
477
- proc.on("exit", (exitCode, exitSignal) => {
478
- exited = true;
479
- exitMs = Math.round(performance.now() - start);
480
- clearTimeout(timer);
481
- clearTimeout(signalTimer);
482
- clearTimeout(closeTimer);
483
- clearInterval(pollTimer);
484
- tree?.programExited();
485
- proc.stdin?.destroy();
486
- (async () => {
487
- if (tree) {
488
- const left = await watchLeftovers(tree, timedOut ? 0 : leftoversMs);
489
- killAll(left, groups());
490
- leftRunning = left.map((p) => ({
491
- pid: p.pid,
492
- command: p.command
493
- }));
494
- }
495
- if (!closed) {
496
- let giveUp;
497
- const gaveUp = new Promise((resolveWait) => {
498
- giveUp = setTimeout(resolveWait, CLOSE_WAIT_MS);
499
- });
500
- await Promise.race([outputClosed, gaveUp]);
501
- clearTimeout(giveUp);
502
- }
503
- proc.stdout?.destroy();
504
- proc.stderr?.destroy();
505
- const notRun = timedOut ? void 0 : shellFallbackError(command, exitCode, stderr);
506
- finish({
507
- exitCode,
508
- signal: exitSignal,
509
- ...notRun === void 0 ? {} : { spawnError: notRun }
510
- });
511
- })();
512
- });
513
- proc.stdout?.on("data", (chunk) => {
514
- if (stdoutBytes < STDOUT_CAP) stdoutChunks.push(chunk);
515
- stdoutBytes += chunk.length;
516
- });
517
- proc.stderr?.on("data", (chunk) => {
518
- if (stderr.length < STDERR_CAP) stderr += chunk.toString("utf8");
519
- });
520
- proc.on("error", (error) => {
521
- clearTimeout(timer);
522
- clearTimeout(signalTimer);
523
- finish({
524
- exitCode: null,
525
- signal: null,
526
- spawnError: spawnMessage(command, error)
527
- });
528
- });
529
- proc.on("close", () => {
530
- closed = true;
531
- onClosed?.();
532
- });
533
- });
534
- }
535
- /** Why spawn() failed; "spawn ENOEXEC" names neither the file nor the problem. */
536
- function spawnMessage(command, error) {
537
- if (!(error instanceof Error)) return String(error);
538
- return "code" in error && error.code === "ENOEXEC" ? notAProgram(command, "exec format error") : error.message;
539
- }
540
- /**
541
- * Waits up to `ms` for what the program left running to finish on its own, as
542
- * children stopped by their parent take a moment to exit, and returns what is
543
- * still running then.
544
- */
545
- async function watchLeftovers(tree, ms) {
546
- const deadline = performance.now() + ms;
547
- let left = tree.running(processTable());
548
- while (left.length > 0 && performance.now() < deadline) {
549
- await delay(LEFTOVER_POLL_MS);
550
- left = tree.running(processTable());
551
- }
552
- return left;
553
- }
554
- // src/checks/baseline.ts
555
- /** A flag no real program defines. */
556
- const UNKNOWN_FLAG = "--cliprobe-unknown-flag";
557
- /** A program that ignores unknown flags may start its default action; don't wait long. */
558
- const UNKNOWN_FLAG_TIMEOUT_MS = 5e3;
559
- const lines = (text) => text.split("\n").filter((l) => l.trim() !== "");
560
- /** The first line printed, labelled with its stream, as evidence. */
561
- function firstLine(r) {
562
- const out = lines(r.stdout.toString("utf8"))[0];
563
- if (out !== void 0) return `stdout: ${out}`;
564
- const err = lines(r.stderr)[0];
565
- return err === void 0 ? "" : `stderr: ${err}`;
566
- }
567
- const exitText$1 = (r) => r.signal ? `was stopped by ${r.signal}` : `exited ${r.exitCode}`;
568
- /** Each describes one convention scripts and agents rely on; observations, never verdicts. */
569
- function describeVersion(r) {
570
- const out = lines(r.stdout.toString("utf8"));
571
- if (r.exitCode !== 0) return {
572
- reason: `${exitText$1(r)}; there may be no --version`,
573
- evidence: firstLine(r)
574
- };
575
- if (out.length === 1) return {
576
- reason: "printed one line to stdout",
577
- evidence: out[0] ?? ""
578
- };
579
- if (out.length > 1) return {
580
- reason: `printed ${out.length} lines to stdout; one line is easier for scripts to parse`,
581
- evidence: `first line: ${out[0] ?? ""}`
582
- };
583
- if (lines(r.stderr).length) return {
584
- reason: "printed the version to stderr, not stdout",
585
- evidence: firstLine(r)
586
- };
587
- return { reason: "printed nothing" };
588
- }
589
- function describeHelp(r) {
590
- const out = lines(r.stdout.toString("utf8"));
591
- const err = lines(r.stderr);
592
- if (out.length && r.exitCode === 0) {
593
- const noun = out.length === 1 ? "line" : "lines";
594
- return { reason: `printed ${out.length} ${noun} to stdout and exited 0` };
595
- }
596
- if (out.length) return { reason: `printed help to stdout but ${exitText$1(r)}` };
597
- if (err.length) return { reason: `printed help to stderr and ${exitText$1(r)}, so "--help | less" and agents reading stdout get nothing` };
598
- return { reason: `printed nothing and ${exitText$1(r)}` };
599
- }
600
- function describeUnknownFlag(r) {
601
- if (r.timedOut) return { reason: `still running after ${UNKNOWN_FLAG_TIMEOUT_MS / 1e3} s; it may have ignored the flag and started its default action` };
602
- const evidence = firstLine(r);
603
- const withEvidence = (reason) => evidence ? {
604
- reason,
605
- evidence
606
- } : { reason };
607
- if (r.exitCode === 0) return withEvidence("exited 0, so a script cannot tell the flag was wrong");
608
- if (lines(r.stdout.toString("utf8")).length) return withEvidence(`${exitText$1(r)}, but printed its message to stdout rather than stderr`);
609
- if (lines(r.stderr).length) return withEvidence(`${exitText$1(r)} with its message on stderr`);
610
- return { reason: `${exitText$1(r)} without saying why` };
611
- }
612
- async function probe(command, args, timeout, describe) {
613
- const r = await run$1(command, args, { timeout });
614
- const base = {
615
- check: "baseline",
616
- invocation: [command, ...args]
617
- };
618
- if (r.spawnError) return {
619
- ...base,
620
- verdict: "error",
621
- reason: `could not start: ${r.spawnError}`,
622
- exitCode: null,
623
- stdoutLines: 0,
624
- stderrLines: 0
625
- };
626
- const { reason, evidence } = r.timedOut && describe !== describeUnknownFlag ? {
627
- reason: "timed out",
628
- evidence: void 0
629
- } : describe(r);
630
- return {
631
- ...base,
632
- verdict: "info",
633
- reason,
634
- ...evidence ? { evidence } : {},
635
- exitCode: r.exitCode,
636
- stdoutLines: lines(r.stdout.toString("utf8")).length,
637
- stderrLines: lines(r.stderr).length
638
- };
639
- }
640
- const baselineCheck = {
641
- name: "baseline",
642
- kind: "info",
643
- summary: "--version prints one line, --help goes to stdout, an unknown flag exits non-zero",
644
- async run(target, ctx) {
645
- const [first] = target.probes;
646
- const prefix = first?.own ? first.args : target.programArgs ?? [];
647
- return [
648
- await probe(target.command, [...prefix, "--version"], ctx.timeout, describeVersion),
649
- await probe(target.command, [...prefix, "--help"], ctx.timeout, describeHelp),
650
- await probe(target.command, [...prefix, UNKNOWN_FLAG], Math.min(ctx.timeout, UNKNOWN_FLAG_TIMEOUT_MS), describeUnknownFlag)
651
- ];
652
- }
653
- };
654
- // src/core/evidence.ts
655
- /** Signs that a program reported a write failure or crashed with a stack trace. */
656
- const ERROR_RE = /EPIPE|broken ?pipe|BrokenPipeError|Unhandled 'error' event|^\s+at .+:\d+:\d+\)?$/im;
657
- /** Signs of a stack trace from Node, Python, Go or Rust. */
658
- const TRACE_RE = /Traceback \(most recent call last\)|^\s+at .+:\d+:\d+\)?$|^panic: |^goroutine \d+ \[|thread '.+' panicked/m;
659
- /** Lines worth quoting as the error message, best first. */
660
- const CRASH_MESSAGES = [/^(\w*Error\b|panic:)/, ERROR_RE];
661
- /**
662
- * Picks the most useful evidence from a crash: the error message plus the first
663
- * stack frame in the program's own code (not Node internals), which usually
664
- * points at the faulty line. `messages` ranks the patterns for the message line.
665
- */
666
- function crashEvidence(stderr, messages = CRASH_MESSAGES) {
667
- const lines = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
668
- let message = "";
669
- for (const pattern of messages) {
670
- message = lines.find((l) => pattern.test(l)) ?? "";
671
- if (message) break;
672
- }
673
- message ||= lines[0] ?? "";
674
- const frame = lines.find((l) => l.startsWith("at ") && !/\bnode:/.test(l))?.match(/(?:file:\/\/)?(\/[^\s()]+:\d+:\d+)/)?.[1];
675
- if (!frame) return message;
676
- const cwd = process.cwd() + "/";
677
- return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
678
- }
679
- /**
680
- * Adds to a SKIP that a probe exited with a failure code, so a probe that never ran
681
- * as intended (a typo, `--probe watch` running `node watch`) doesn't pass for a quiet
682
- * skip. The evidence is the error line from stderr, when there is one.
683
- */
684
- function noteFailedExit(judgement, r) {
685
- if (judgement.verdict !== "skip" || r.exitCode === null || r.exitCode === 0) return judgement;
686
- const message = crashEvidence(r.stderr);
687
- return {
688
- ...judgement,
689
- reason: `${judgement.reason}; it exited ${r.exitCode}, so the probe may not have run as intended`,
690
- ...message && judgement.evidence === void 0 ? { evidence: `stderr: ${message}` } : {}
691
- };
692
- }
693
- // src/core/long-running.ts
694
- /**
695
- * Once one check has seen a probe still running at the timeout (a server, a
696
- * watcher, a full-screen program), later checks watch it this long instead, so
697
- * the timeout is paid once rather than once per check.
698
- */
699
- const LONG_RUN_WINDOW_MS = 3e3;
700
- const key = (command, args) => JSON.stringify([command, ...args]);
701
- function isLongRunning(ctx, command, args) {
702
- return ctx.longRunning?.has(key(command, args)) === true;
703
- }
704
- /** How long to let a normal run of this probe go: the timeout, or the short window once it is known to keep running. */
705
- function probeTimeout(ctx, command, args) {
706
- return isLongRunning(ctx, command, args) ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout;
707
- }
708
- function markLongRunning(ctx, command, args) {
709
- ctx.longRunning?.add(key(command, args));
710
- }
711
- /** "still running after 15 s", from a run that was stopped at its timeout. */
712
- const stillRunning = (durationMs) => `still running after ${Math.round(durationMs / 1e3)} s`;
713
- // src/checks/closed-pipe.ts
714
- /** A program that writes an error to stderr only once its stdout is closed. */
715
- const newWriteError = (base, closed) => ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
716
- /**
717
- * For a program that keeps running (a server, a watcher): there is no normal exit
718
- * to compare with, but a crash once stdout is closed is still a crash.
719
- */
720
- function judgeLongRunning$1(base, closed) {
721
- if (!closed.timedOut && newWriteError(base, closed)) return {
722
- verdict: "fail",
723
- reason: `crashed when stdout was closed, while a normal run kept running (exit ${closed.exitCode})`,
724
- evidence: crashEvidence(closed.stderr)
725
- };
726
- if (closed.signal === "SIGPIPE") return {
727
- verdict: "pass",
728
- reason: "stopped by SIGPIPE, the conventional exit"
729
- };
730
- if (base.stdoutBytes === 0) return {
731
- verdict: "skip",
732
- reason: `${stillRunning(base.durationMs)} without writing to stdout, so a closed stdout was never touched`
733
- };
734
- if (!closed.timedOut) return {
735
- verdict: "pass",
736
- reason: "exited quietly when stdout was closed"
737
- };
738
- if (newWriteError(base, closed)) return {
739
- verdict: "warn",
740
- reason: "printed a write error when stdout was closed, and kept running",
741
- evidence: crashEvidence(closed.stderr)
742
- };
743
- return {
744
- verdict: "pass",
745
- reason: `${stillRunning(base.durationMs)}; with stdout closed it kept running without a write error`
746
- };
747
- }
748
- /** Compares a normal run with a closed-stdout run of the same invocation. */
749
- function judge$1(base, closed) {
750
- if (base.spawnError) return {
751
- verdict: "error",
752
- reason: `could not start: ${base.spawnError}`
753
- };
754
- if (base.timedOut) return judgeLongRunning$1(base, closed);
755
- if (base.stdoutBytes === 0) return noteFailedExit({
756
- verdict: "skip",
757
- reason: "wrote nothing to stdout, so a closed stdout is never touched"
758
- }, base);
759
- if (closed.timedOut) return {
760
- verdict: "fail",
761
- reason: "hung after stdout was closed"
762
- };
763
- if (closed.signal === "SIGPIPE") return {
764
- verdict: "pass",
765
- reason: "stopped by SIGPIPE, the conventional exit"
766
- };
767
- const newError = newWriteError(base, closed);
768
- if (newError && closed.exitCode !== base.exitCode) return {
769
- verdict: "fail",
770
- reason: `crashed when stdout was closed (exit ${base.exitCode} -> ${closed.exitCode})`,
771
- evidence: crashEvidence(closed.stderr)
772
- };
773
- if (newError) return {
774
- verdict: "warn",
775
- reason: "printed a write error but kept its exit code",
776
- evidence: crashEvidence(closed.stderr)
777
- };
778
- if (closed.exitCode !== base.exitCode) return {
779
- verdict: "pass",
780
- reason: `exited quietly with code ${closed.exitCode}`
781
- };
782
- return {
783
- verdict: "pass",
784
- reason: "exited quietly"
785
- };
786
- }
787
- async function closedPipe(command, args, ctx) {
788
- const base = await run$1(command, args, {
789
- closedStdout: false,
790
- timeout: probeTimeout(ctx, command, args)
791
- });
792
- if (base.timedOut) markLongRunning(ctx, command, args);
793
- const closed = await run$1(command, args, {
794
- closedStdout: true,
795
- timeout: base.timedOut ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout
796
- });
797
- return {
798
- check: "closed-pipe",
799
- invocation: [command, ...args],
800
- ...judge$1(base, closed),
801
- baseline: {
802
- exitCode: base.exitCode,
803
- signal: base.signal,
804
- stdoutBytes: base.stdoutBytes
805
- },
806
- closed: {
807
- exitCode: closed.exitCode,
808
- signal: closed.signal,
809
- timedOut: closed.timedOut,
810
- stderr: closed.stderr.slice(-2e3)
811
- }
812
- };
813
- }
814
- const closedPipeCheck = {
815
- name: "closed-pipe",
816
- kind: "check",
817
- summary: "crashes or hangs when stdout is closed early (| head, grep -q, an agent)",
818
- async run(target, ctx) {
819
- const results = [];
820
- for (const { args } of target.probes) results.push(await closedPipe(target.command, args, ctx));
821
- return results;
822
- }
823
- };
824
- // src/core/ansi.ts
825
- const SGR = /\x1b\[([0-9;:]*)m/g;
826
- /** SGR params that only turn something off. A sequence made only of these is not styling. */
827
- const RESETS = /* @__PURE__ */ new Set([
828
- "",
829
- "0",
830
- "22",
831
- "23",
832
- "24",
833
- "25",
834
- "27",
835
- "28",
836
- "29",
837
- "39",
838
- "49",
839
- "54",
840
- "55",
841
- "59"
842
- ]);
843
- /**
844
- * Finds the first SGR sequence that sets a color or style (red, bold, 256-color,
845
- * truecolor...). Pure resets are ignored: some programs always print them, and
846
- * they change nothing on screen.
847
- */
848
- function findStyle(text) {
849
- for (const match of text.matchAll(SGR)) {
850
- if ((match[1] ?? "").split(/[;:]/).every((p) => RESETS.has(p))) continue;
851
- const before = text.slice(0, match.index);
852
- const start = before.lastIndexOf("\n") + 1;
853
- const newline = text.indexOf("\n", match.index);
854
- const end = newline === -1 ? text.length : newline;
855
- return {
856
- sequence: match[0],
857
- line: before.split("\n").length,
858
- text: text.slice(start, end).slice(0, 120)
859
- };
860
- }
861
- }
862
- /**
863
- * Every control code findControls() knows, as alternatives tried in this order at each
864
- * position, so one sequence is never counted twice:
865
- * - csi: ESC [ parameter bytes, intermediate bytes, one final byte;
866
- * - osc: ESC ] number ; text, ended by BEL or ESC ;
867
- * - oscOther: any other OSC, such as ESC ] 104 BEL (no ";");
868
- * - string: DCS, SOS, PM or APC (ESC P, X, ^ or _), with its text when ST ends it;
869
- * - reset: ESC c, a full reset that clears the screen;
870
- * - escape: any other ESC sequence: intermediates (ESC ( B) or one final byte (ESC 7);
871
- * - c1: an 8-bit CSI, OSC, DCS, SOS, PM or APC introducer, with what it carries;
872
- * - redraw: a carriage return that does not end a CRLF line: a line being redrawn.
873
- * ESC \ (ST) alone ends a string and starts nothing.
874
- */
875
- const CONTROL = new RegExp([
876
- String.raw`(?<csi>\x1b\[(?<params>[0-?]*)[ -/]*(?<final>[@-~]))`,
877
- String.raw`(?<osc>\x1b\](?<code>\d*);[^\x07\x1b]*(?:\x07|\x1b\\))`,
878
- String.raw`(?<oscOther>\x1b\][^\x07\x1b]*(?:\x07|\x1b\\))`,
879
- String.raw`(?<string>\x1b[PX^_](?:[^\x1b]*\x1b\\)?)`,
880
- String.raw`(?<reset>\x1bc)`,
881
- String.raw`(?<escape>\x1b(?:[ -/]+[0-~]|[0-OQ-WYZ\x60-bd-~]))`,
882
- String.raw`(?<c1>\x9b[0-?]*[ -/]*[@-~]?|[\x90\x98\x9d\x9e\x9f][^\x07\x1b\x9c]*(?:\x07|\x9c|\x1b\\)?)`,
883
- String.raw`(?<redraw>\r(?!\n))`
884
- ].join("|"), "g");
885
- /** How each kind reads in a report. */
886
- const CONTROL_LABELS = {
887
- cursor: "cursor movement",
888
- erase: "line or screen erase",
889
- mode: "terminal mode switch (such as hiding the cursor)",
890
- hyperlink: "hyperlink (OSC 8)",
891
- title: "window title",
892
- osc: "operating system command (OSC)",
893
- redraw: "carriage-return redraw",
894
- escape: "other escape sequence (such as saving the cursor or switching the character set)",
895
- reset: "full terminal reset (ESC c)",
896
- string: "device control string (DCS, APC, PM or SOS)",
897
- c1: "8-bit control sequence (C1)"
898
- };
899
- function csiKind(params, final) {
900
- if (final === "m") return void 0;
901
- if (final === "K" || final === "J") return "erase";
902
- if ((final === "h" || final === "l") && params.startsWith("?")) return "mode";
903
- return "cursor";
904
- }
905
- function oscKind(code) {
906
- if (code === "8") return "hyperlink";
907
- if (code === "0" || code === "1" || code === "2") return "title";
908
- return "osc";
909
- }
910
- function hitAt(text, index, sequence, kind, warnOnly) {
911
- const before = text.slice(0, index);
912
- const start = before.lastIndexOf("\n") + 1;
913
- const newline = text.indexOf("\n", index);
914
- const end = newline === -1 ? text.length : newline;
915
- return {
916
- kind,
917
- sequence,
918
- line: before.split("\n").length,
919
- text: text.slice(start, end).slice(0, 120),
920
- warnOnly
921
- };
922
- }
923
- /** The kind of one CONTROL match, and whether it may only warn; undefined for SGR. */
924
- function classify(g) {
925
- if (g["csi"] !== void 0) {
926
- const kind = csiKind(g["params"] ?? "", g["final"] ?? "");
927
- return kind && [kind, false];
928
- }
929
- if (g["osc"] !== void 0) return [oscKind(g["code"] ?? ""), false];
930
- if (g["redraw"] !== void 0) return ["redraw", false];
931
- if (g["oscOther"] !== void 0) return ["osc", true];
932
- if (g["string"] !== void 0) return ["string", true];
933
- if (g["reset"] !== void 0) return ["reset", true];
934
- if (g["escape"] !== void 0) return ["escape", true];
935
- return ["c1", true];
936
- }
937
- /**
938
- * Every terminal control code in the text other than color and style (SGR):
939
- * cursor movement, erases, mode switches, OSC sequences such as hyperlinks and
940
- * window titles, carriage returns that redraw a line, and (warn-only) the other
941
- * ESC sequences, control strings and 8-bit controls. In reading order.
942
- */
943
- function findControls(text) {
944
- const hits = [];
945
- for (const m of text.matchAll(CONTROL)) {
946
- const found = classify(m.groups ?? {});
947
- if (found) hits.push(hitAt(text, m.index, m[0], ...found));
948
- }
949
- return hits;
950
- }
951
- const ANY_ESCAPE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
952
- /** The text with CSI and OSC escape sequences (color, cursor, links, titles) removed. */
953
- function stripEscapes(text) {
954
- return text.replace(ANY_ESCAPE, "");
955
- }
956
- /** The modes that leave a shell broken when a program forgets them. */
957
- const TERMINAL_MODES = [
958
- {
959
- label: "hidden cursor",
960
- codes: [25],
961
- inverted: true
962
- },
963
- {
964
- label: "alternate screen",
965
- codes: [
966
- 47,
967
- 1047,
968
- 1049
969
- ]
970
- },
971
- {
972
- label: "mouse reporting",
973
- codes: [
974
- 9,
975
- 1e3,
976
- 1001,
977
- 1002,
978
- 1003,
979
- 1005,
980
- 1006,
981
- 1015
982
- ]
983
- },
984
- {
985
- label: "focus reporting",
986
- codes: [1004]
987
- },
988
- {
989
- label: "bracketed paste",
990
- codes: [2004]
991
- },
992
- {
993
- label: "line wrapping off",
994
- codes: [7],
995
- inverted: true
996
- }
997
- ];
998
- /** DEC private mode set or reset (ESC [ ? numbers h|l), or a full reset (ESC c). */
999
- const DEC_MODE = /\x1b\[\?([\d;]+)([hl])|\x1bc/g;
1000
- /**
1001
- * The terminal modes the text leaves switched on, in the order they were
1002
- * switched on. A mode counts as on from its first switch-on until a later
1003
- * switch-off or a full reset, so a program that restores everything leaves none.
1004
- */
1005
- function findOpenModes(text) {
1006
- const open = /* @__PURE__ */ new Map();
1007
- for (const m of text.matchAll(DEC_MODE)) {
1008
- if (m[2] === void 0) {
1009
- open.clear();
1010
- continue;
1011
- }
1012
- const set = m[2] === "h";
1013
- for (const code of (m[1] ?? "").split(";").map(Number)) {
1014
- const mode = TERMINAL_MODES.find((t) => t.codes.includes(code));
1015
- if (!mode) continue;
1016
- if (!(mode.inverted ? !set : set)) open.delete(mode);
1017
- else if (!open.has(mode)) {
1018
- const line = text.slice(0, m.index).split("\n").length;
1019
- open.set(mode, {
1020
- label: mode.label,
1021
- sequence: m[0],
1022
- line,
1023
- index: m.index
1024
- });
1025
- }
1026
- }
1027
- }
1028
- return [...open.values()].sort((a, b) => a.index - b.index).map(({ label, sequence, line }) => ({
1029
- label,
1030
- sequence,
1031
- line
1032
- }));
1033
- }
1034
- let cached;
1035
- /** Whether this machine can run a program under a PTY, detected once. */
1036
- function ptySupport() {
1037
- cached ??= detect();
1038
- return cached;
1039
- }
1040
- function detect() {
1041
- if (process.platform === "darwin") try {
1042
- execFileSync("script", [
1043
- "-q",
1044
- "/dev/null",
1045
- "true"
1046
- ], {
1047
- stdio: "ignore",
1048
- timeout: 5e3
1049
- });
1050
- return {
1051
- ok: true,
1052
- flavor: "bsd"
1053
- };
1054
- } catch {
1055
- return {
1056
- ok: false,
1057
- reason: "script(1) did not run"
1058
- };
1059
- }
1060
- if (process.platform === "linux") {
1061
- try {
1062
- if (execFileSync("script", ["--version"], {
1063
- encoding: "utf8",
1064
- stdio: [
1065
- "ignore",
1066
- "pipe",
1067
- "pipe"
1068
- ],
1069
- timeout: 5e3
1070
- }).includes("util-linux")) return {
1071
- ok: true,
1072
- flavor: "util-linux"
1073
- };
1074
- } catch (error) {
1075
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
1076
- ok: false,
1077
- reason: "script(1) not found; install the package that has it (Debian and Ubuntu: bsdutils; Fedora: util-linux-script; Alpine: util-linux-misc)"
1078
- };
1079
- }
1080
- return {
1081
- ok: false,
1082
- reason: "script(1) is not the util-linux version"
1083
- };
1084
- }
1085
- return {
1086
- ok: false,
1087
- reason: `no PTY support on ${process.platform}`
1088
- };
1089
- }
1090
- /** Quotes one argument for a POSIX shell. */
1091
- function shellQuote(arg) {
1092
- return `'${arg.replaceAll("'", `'\\''`)}'`;
1093
- }
1094
- /**
1095
- * The script(1) arguments that run `command args...` under a PTY.
1096
- *
1097
- * A small /bin/sh wrapper writes its PID to `pidFile`, sets the window size and
1098
- * then execs the program, so the PID is the program's and the program leads its
1099
- * own session and process group. Everything after the script reaches the
1100
- * program as argv; only the util-linux form needs quoting, because its -c takes
1101
- * a single string.
1102
- */
1103
- function ptyArgs(flavor, pidFile, command, args, cols = 80, rows = 24, settingsFile) {
1104
- const size = `stty cols ${cols} rows ${rows} 2>/dev/null`;
1105
- const setup = settingsFile === void 0 ? `echo $$ > "$1"; shift; ${size}; exec "$@"` : `echo $$ > "$1"; s=$2; shift 2; ${size}; stty -a > "$s.before" 2>/dev/null; trap true INT; "$@"; c=$?; stty -a > "$s.after" 2>/dev/null; exit $c`;
1106
- const argv = settingsFile === void 0 ? [
1107
- pidFile,
1108
- command,
1109
- ...args
1110
- ] : [
1111
- pidFile,
1112
- settingsFile,
1113
- command,
1114
- ...args
1115
- ];
1116
- if (flavor === "bsd") return [
1117
- "-q",
1118
- "/dev/null",
1119
- "/bin/sh",
1120
- "-c",
1121
- setup,
1122
- "sh",
1123
- ...argv
1124
- ];
1125
- return [
1126
- "-qec",
1127
- `exec /bin/sh -c ${shellQuote(setup)} sh ${argv.map(shellQuote).join(" ")}`,
1128
- "/dev/null"
1129
- ];
1130
- }
1131
- /** The terminal settings that leave a shell unusable when a program exits with them off. */
1132
- const WATCHED_SETTINGS = [
1133
- "icanon",
1134
- "echo",
1135
- "isig",
1136
- "iexten",
1137
- "opost",
1138
- "onlcr",
1139
- "icrnl",
1140
- "ixon"
1141
- ];
1142
- /**
1143
- * The watched settings that were on in `before` and are off in `after`, both the
1144
- * output of `stty -a`, where BSD and GNU stty alike print a setting that is off as
1145
- * `-name`. Compared with the terminal as the program found it, not fixed values.
1146
- */
1147
- function settingsOff(before, after) {
1148
- const words = (text) => new Set(text.split(/[\s;]+/));
1149
- const was = words(before);
1150
- const now = words(after);
1151
- return WATCHED_SETTINGS.filter((name) => was.has(name) && now.has(`-${name}`));
1152
- }
1153
- /** BSD script echoes the EOF it forwards from /dev/null as "^D" and two backspaces. */
1154
- const BSD_EOF_ECHO = "^D\b\b";
1155
- /** Undoes the terminal's output processing: the EOF echo, and \n turned into \r\n. */
1156
- function cleanPtyOutput(raw, flavor) {
1157
- let text = raw.toString("utf8");
1158
- if (flavor === "bsd" && text.startsWith(BSD_EOF_ECHO)) text = text.slice(4);
1159
- return text.replaceAll("\r\n", "\n");
1160
- }
1161
- /**
1162
- * Runs a program with stdin, stdout and stderr on a PTY, an 80x24 window and
1163
- * TERM=xterm-256color. Without `input`, stdin is /dev/null behind the PTY: the
1164
- * program reads one EOF, and a second read blocks until the timeout. With it,
1165
- * the terminal's line discipline handles what is typed, so Ctrl-C (\x03) becomes
1166
- * SIGINT for the program, or a keypress if the program turned that off.
1167
- */
1168
- async function runPty(command, args, { timeout, env = {}, input, settings = false }) {
1169
- const support = ptySupport();
1170
- if (!support.ok) throw new Error(`no PTY: ${support.reason}`);
1171
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
1172
- const unregister = onInterrupt(() => rmSync(dir, {
1173
- recursive: true,
1174
- force: true
1175
- }));
1176
- const pidFile = join(dir, "pid");
1177
- let launcher = "script";
1178
- const settingsFile = settings ? join(dir, "stty") : void 0;
1179
- let argv = ptyArgs(support.flavor, pidFile, command, args, 80, 24, settingsFile);
1180
- let keyboard;
1181
- let inputSentMs;
1182
- let typeTimer;
1183
- let watchTimer;
1184
- const closeKeyboard = () => {
1185
- if (keyboard !== void 0) closeSync(keyboard);
1186
- keyboard = void 0;
1187
- };
1188
- const start = performance.now();
1189
- if (input) {
1190
- const fifo = join(dir, "keyboard");
1191
- execFileSync("mkfifo", [fifo]);
1192
- keyboard = openSync(fifo, constants.O_RDWR);
1193
- argv = [
1194
- "-c",
1195
- "cat -- \"$1\" 2>/dev/null | { shift; exec script \"$@\"; }",
1196
- "sh",
1197
- fifo,
1198
- ...argv
1199
- ];
1200
- launcher = "/bin/sh";
1201
- typeTimer = setTimeout(() => {
1202
- if (programState(pidFile) !== "running") return;
1203
- inputSentMs = Math.round(performance.now() - start);
1204
- if (keyboard !== void 0) writeSync(keyboard, input.data);
1205
- }, input.afterMs);
1206
- watchTimer = setInterval(() => {
1207
- if (programState(pidFile) !== "gone") return;
1208
- clearInterval(watchTimer);
1209
- closeKeyboard();
1210
- }, EXIT_POLL_MS);
1211
- }
1212
- try {
1213
- const result = await run$1(launcher, argv, {
1214
- timeout,
1215
- env: {
1216
- TERM: "xterm-256color",
1217
- SHELL: "/bin/sh",
1218
- ...env
1219
- },
1220
- extraGroup: () => programGroup(pidFile)
1221
- });
1222
- return {
1223
- output: cleanPtyOutput(result.stdout, support.flavor),
1224
- exitCode: result.exitCode,
1225
- timedOut: result.timedOut,
1226
- ...result.spawnError === void 0 ? {} : { spawnError: result.spawnError },
1227
- scriptStderr: result.stderr,
1228
- truncated: result.stdoutBytes > result.stdout.length,
1229
- ...inputSentMs === void 0 ? {} : { inputSentMs },
1230
- ...readSettings(settingsFile, result.timedOut)
1231
- };
1232
- } finally {
1233
- clearTimeout(typeTimer);
1234
- clearInterval(watchTimer);
1235
- closeKeyboard();
1236
- unregister();
1237
- rmSync(dir, {
1238
- recursive: true,
1239
- force: true
1240
- });
1241
- }
1242
- }
1243
- /** The settings the program left off, when the wrapper could read them after it. */
1244
- function readSettings(file, timedOut) {
1245
- if (file === void 0 || timedOut) return {};
1246
- try {
1247
- return { settingsOff: settingsOff(readFileSync(`${file}.before`, "utf8"), readFileSync(`${file}.after`, "utf8")) };
1248
- } catch {
1249
- return {};
1250
- }
1251
- }
1252
- /** How often to look for the end of a program that is being typed to. */
1253
- const EXIT_POLL_MS = 50;
1254
- function programGroup(pidFile) {
1255
- try {
1256
- const pid = Number(readFileSync(pidFile, "utf8").trim());
1257
- return Number.isInteger(pid) && pid > 1 ? pid : void 0;
1258
- } catch {
1259
- return;
1260
- }
1261
- }
1262
- /**
1263
- * Whether the program under the PTY has started, is running, or has exited.
1264
- * Asks about the program itself (or the wrapper that runs it and reads the
1265
- * settings it left, which ends right after it), which script(1) reaps, not its group: a child
1266
- * it left behind can stay a zombie for good where nothing reaps orphans, as in
1267
- * a container without an init process.
1268
- */
1269
- function programState(pidFile) {
1270
- const pid = programGroup(pidFile);
1271
- if (pid === void 0) return "starting";
1272
- try {
1273
- process.kill(pid, 0);
1274
- return "running";
1275
- } catch {
1276
- return "gone";
1277
- }
1278
- }
1279
- // src/checks/color.ts
1280
- /**
1281
- * Every color run gets a terminal type that supports color, so a program cannot
1282
- * pass by seeing TERM=dumb, and no CI variable, which some color libraries treat
1283
- * as a reason to force color on.
1284
- */
1285
- const COLOR_ENV = {
1286
- TERM: "xterm-256color",
1287
- CI: void 0
1288
- };
1289
- const describeHit = (stream, hit) => `${stream} line ${hit.line}: ${hit.text}`;
1290
- /** The first verdict the pipe run alone can settle, if any. */
1291
- function judgePipe(pipe) {
1292
- if (pipe.spawnError) return {
1293
- verdict: "error",
1294
- reason: `could not start: ${pipe.spawnError}`
1295
- };
1296
- const stdoutHit = findStyle(pipe.stdout.toString("utf8"));
1297
- if (stdoutHit) return {
1298
- verdict: "fail",
1299
- reason: "printed color codes into a pipe",
1300
- evidence: describeHit("stdout", stdoutHit)
1301
- };
1302
- const stderrHit = findStyle(pipe.stderr);
1303
- if (stderrHit) return {
1304
- verdict: "warn",
1305
- reason: "printed color codes to stderr when it was a pipe",
1306
- evidence: describeHit("stderr", stderrHit)
1307
- };
1308
- if (pipe.timedOut) return {
1309
- verdict: "skip",
1310
- reason: `${stillRunning(pipe.durationMs)} with no color in a pipe so far; a terminal is compared only for a command that finishes`
1311
- };
1312
- }
1313
- function judgeColor(runs) {
1314
- const fromPipe = judgePipe(runs.pipe);
1315
- if (fromPipe) return fromPipe;
1316
- const { tty, noColor } = runs;
1317
- if (!tty) return {
1318
- verdict: "skip",
1319
- reason: `no color in a pipe; no terminal to compare with (${runs.noPty ?? "no PTY"})`
1320
- };
1321
- if (tty.timedOut) return {
1322
- verdict: "skip",
1323
- reason: "no color in a pipe; in a terminal it waited for input, so it was not compared"
1324
- };
1325
- if (!findStyle(tty.output)) {
1326
- if (!(runs.pipe.stdoutBytes > 0 || runs.pipe.stderr.length > 0 || tty.output)) return noteFailedExit({
1327
- verdict: "skip",
1328
- reason: "printed nothing, so there is no color to check"
1329
- }, runs.pipe);
1330
- return {
1331
- verdict: "pass",
1332
- reason: "no color in a pipe or in a terminal"
1333
- };
1334
- }
1335
- if (!noColor || noColor.timedOut) return {
1336
- verdict: "skip",
1337
- reason: "colors only in a terminal; the NO_COLOR run did not finish"
1338
- };
1339
- const noColorHit = findStyle(noColor.output);
1340
- if (noColorHit) return {
1341
- verdict: "warn",
1342
- reason: "ignores NO_COLOR: still prints color in a terminal",
1343
- evidence: describeHit("terminal", noColorHit)
1344
- };
1345
- return {
1346
- verdict: "pass",
1347
- reason: "colors only in a terminal, and NO_COLOR turns it off"
1348
- };
1349
- }
1350
- /** Runs only as many probes as the verdict needs: a pipe, then a terminal, then NO_COLOR. */
1351
- async function colorRuns(command, args, ctx) {
1352
- const { timeout } = ctx;
1353
- const pipe = await run$1(command, args, {
1354
- timeout: probeTimeout(ctx, command, args),
1355
- env: COLOR_ENV
1356
- });
1357
- if (pipe.timedOut) markLongRunning(ctx, command, args);
1358
- if (judgePipe(pipe)) return { pipe };
1359
- const support = ptySupport();
1360
- if (!support.ok) return {
1361
- pipe,
1362
- noPty: support.reason
1363
- };
1364
- const tty = await runPty(command, args, {
1365
- timeout,
1366
- env: COLOR_ENV
1367
- });
1368
- if (tty.timedOut || !findStyle(tty.output)) return {
1369
- pipe,
1370
- tty
1371
- };
1372
- return {
1373
- pipe,
1374
- tty,
1375
- noColor: await runPty(command, args, {
1376
- timeout,
1377
- env: {
1378
- ...COLOR_ENV,
1379
- NO_COLOR: "1"
1380
- }
1381
- })
1382
- };
1383
- }
1384
- const summarize = (r) => r ? {
1385
- exitCode: r.exitCode,
1386
- timedOut: r.timedOut,
1387
- styled: findStyle(r.output) !== void 0
1388
- } : null;
1389
- async function color(command, args, ctx) {
1390
- const runs = await colorRuns(command, args, ctx);
1391
- return {
1392
- check: "color",
1393
- invocation: [command, ...args],
1394
- ...judgeColor(runs),
1395
- pipe: {
1396
- exitCode: runs.pipe.exitCode,
1397
- stdoutStyled: findStyle(runs.pipe.stdout.toString("utf8")) !== void 0,
1398
- stderrStyled: findStyle(runs.pipe.stderr) !== void 0
1399
- },
1400
- tty: summarize(runs.tty),
1401
- noColor: summarize(runs.noColor)
1402
- };
1403
- }
1404
- const colorCheck = {
1405
- name: "color",
1406
- kind: "check",
1407
- summary: "prints color codes into pipes, or ignores NO_COLOR in a terminal",
1408
- async run(target, ctx) {
1409
- const results = [];
1410
- for (const { args } of target.probes) results.push(await color(target.command, args, ctx));
1411
- return results;
1412
- }
1413
- };
1414
- // src/core/fixture.ts
1415
- /** Written in probe arguments; replaced with the path of a directory of hostile file names. */
1416
- const FIXTURE_PLACEHOLDER = "{fixture}";
1417
- const ESC = String.fromCharCode(27);
1418
- const BEL = String.fromCharCode(7);
1419
- const C1_CSI = String.fromCharCode(155);
1420
- const RIGHT_TO_LEFT_OVERRIDE = String.fromCharCode(8238);
1421
- /**
1422
- * File names a program may print. ESC sequences can drive the terminal (fail);
1423
- * C1 controls, carriage returns and newlines can hide or forge output (warn); a
1424
- * bidirectional override reorders text, but GNU ls and find print it raw too
1425
- * (note only).
1426
- */
1427
- const HOSTILE_NAMES = [
1428
- {
1429
- kind: "osc",
1430
- name: `title-${ESC}]0;cliprobe${BEL}.txt`,
1431
- marker: `${ESC}]0;cliprobe${BEL}`,
1432
- label: "an escape sequence that sets the window title",
1433
- severity: "fail"
1434
- },
1435
- {
1436
- kind: "csi",
1437
- name: `clear-${ESC}[2J.txt`,
1438
- marker: `${ESC}[2J`,
1439
- label: "an escape sequence that clears the screen",
1440
- severity: "fail"
1441
- },
1442
- {
1443
- kind: "c1",
1444
- name: `c1-${C1_CSI}2J.txt`,
1445
- marker: `${C1_CSI}2J`,
1446
- label: "a C1 control character",
1447
- severity: "warn"
1448
- },
1449
- {
1450
- kind: "cr",
1451
- name: "cr-\rspoof.txt",
1452
- marker: "cr-\rspoof",
1453
- label: "a carriage return",
1454
- severity: "warn"
1455
- },
1456
- {
1457
- kind: "newline",
1458
- name: "nl-\nspoof.txt",
1459
- marker: "nl-\nspoof",
1460
- label: "a newline",
1461
- severity: "warn"
1462
- },
1463
- {
1464
- kind: "bidi",
1465
- name: `bidi-${RIGHT_TO_LEFT_OVERRIDE}txt.exe`,
1466
- marker: `${RIGHT_TO_LEFT_OVERRIDE}txt`,
1467
- label: "a bidirectional override",
1468
- severity: "note"
1469
- }
1470
- ];
1471
- /** An ordinary name; seeing it in the output shows the program listed the directory. */
1472
- const PLAIN_NAME = "plain.txt";
1473
- /** Creates a temporary directory holding the hostile names and one plain file. */
1474
- function createFixture() {
1475
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-fixture-"));
1476
- for (const { name } of HOSTILE_NAMES) writeFileSync(join(dir, name), "");
1477
- writeFileSync(join(dir, PLAIN_NAME), "");
1478
- return {
1479
- dir,
1480
- realDir: realpathSync(dir),
1481
- cleanup: () => rmSync(dir, {
1482
- recursive: true,
1483
- force: true
1484
- })
1485
- };
1486
- }
1487
- function usesFixture(args) {
1488
- return args.some((a) => a.includes(FIXTURE_PLACEHOLDER));
1489
- }
1490
- /** Replaces the placeholder in every argument, including inside `--dir={fixture}`. */
1491
- function expandFixture(args, dir) {
1492
- return args.map((a) => a.replaceAll(FIXTURE_PLACEHOLDER, dir));
1493
- }
1494
- /**
1495
- * Puts the placeholder back wherever the fixture's path appears in report text,
1496
- * so reports show {fixture} rather than a path that no longer exists.
1497
- */
1498
- function collapseFixture(text, fixture) {
1499
- return text.replaceAll(fixture.realDir, FIXTURE_PLACEHOLDER).replaceAll(fixture.dir, FIXTURE_PLACEHOLDER);
1500
- }
1501
- /**
1502
- * Removes the hostile names' dangerous parts from output, for checks other than
1503
- * control-chars: a lister that prints them raw into a pipe is doing its job, and
1504
- * control-chars judges how they reach a terminal.
1505
- */
1506
- function withoutHostileNames(text) {
1507
- let out = text;
1508
- for (const { marker } of HOSTILE_NAMES) out = out.replaceAll(marker, "");
1509
- return out;
1510
- }
1511
- function collapseValue(value, fixture) {
1512
- if (typeof value === "string") return collapseFixture(value, fixture);
1513
- if (Array.isArray(value)) return value.map((v) => collapseValue(v, fixture));
1514
- if (value && typeof value === "object" && !Buffer.isBuffer(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, collapseValue(v, fixture)]));
1515
- return value;
1516
- }
1517
- /** collapseFixture applied to every string in the results: invocation, reason, evidence and data. */
1518
- function collapseResults(results, fixture) {
1519
- return results.map((r) => {
1520
- const data = Object.fromEntries(Object.entries(r).map(([k, v]) => [k, collapseValue(v, fixture)]));
1521
- const c = (text) => collapseFixture(text, fixture);
1522
- return {
1523
- ...data,
1524
- check: r.check,
1525
- invocation: r.invocation.map(c),
1526
- verdict: r.verdict,
1527
- reason: c(r.reason),
1528
- ...r.evidence === void 0 ? {} : { evidence: c(r.evidence) }
1529
- };
1530
- });
1531
- }
1532
- // src/checks/control-chars.ts
1533
- const ENV$1 = {
1534
- TERM: "xterm-256color",
1535
- CI: void 0
1536
- };
1537
- /** The hostile names whose dangerous part appears in the output unescaped. */
1538
- function rawNames(output) {
1539
- return HOSTILE_NAMES.filter((h) => output.includes(h.marker));
1540
- }
1541
- const listLabels$2 = (names) => {
1542
- const labels = names.map((h) => h.label);
1543
- return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1544
- };
1545
- const evidenceFor = (names) => `file names printed raw: ${names.map((h) => h.name).join(", ")}`;
1546
- function judgeControlChars(runs) {
1547
- if (!runs.usesFixture) return {
1548
- verdict: "skip",
1549
- reason: "no {fixture} in the arguments; add a probe that takes a path, e.g. --probe \"ls {fixture}\""
1550
- };
1551
- const { pipe, tty } = runs;
1552
- if (pipe?.spawnError) return {
1553
- verdict: "error",
1554
- reason: `could not start: ${pipe.spawnError}`
1555
- };
1556
- if (!tty) return {
1557
- verdict: "skip",
1558
- reason: `no terminal to check with (${runs.noPty ?? "no PTY"})`
1559
- };
1560
- if (tty.timedOut && !tty.output.includes("plain.txt")) return {
1561
- verdict: "skip",
1562
- reason: "still running in a terminal at the timeout, and had not printed the file names in {fixture}"
1563
- };
1564
- if (!tty.output.includes("plain.txt")) {
1565
- const skip = {
1566
- verdict: "skip",
1567
- reason: "did not print the file names in {fixture}, so there was nothing to escape"
1568
- };
1569
- return pipe ? noteFailedExit(skip, pipe) : skip;
1570
- }
1571
- const raw = rawNames(tty.output);
1572
- const failing = raw.filter((h) => h.severity === "fail");
1573
- if (failing.length) return {
1574
- verdict: "fail",
1575
- reason: `sent ${failing.length > 1 ? "escape sequences" : "an escape sequence"} from file names to the terminal unescaped`,
1576
- evidence: evidenceFor(failing)
1577
- };
1578
- const warning = raw.filter((h) => h.severity === "warn");
1579
- if (warning.length) return {
1580
- verdict: "warn",
1581
- reason: `printed ${listLabels$2(warning)} from file names unescaped, which can hide or forge output`,
1582
- evidence: evidenceFor(warning)
1583
- };
1584
- const noted = raw.filter((h) => h.severity === "note");
1585
- return {
1586
- verdict: "pass",
1587
- reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels$2(noted)} as is` : ""}`
1588
- };
1589
- }
1590
- async function controlCharsRuns(command, args, fixtureDir, ctx) {
1591
- const usesFixture = fixtureDir !== void 0 && args.some((a) => a.includes(fixtureDir));
1592
- if (!usesFixture) return { usesFixture };
1593
- const pipe = await run$1(command, args, {
1594
- timeout: probeTimeout(ctx, command, args),
1595
- env: ENV$1
1596
- });
1597
- if (pipe.spawnError) return {
1598
- usesFixture,
1599
- pipe
1600
- };
1601
- if (pipe.timedOut) markLongRunning(ctx, command, args);
1602
- const support = ptySupport();
1603
- if (!support.ok) return {
1604
- usesFixture,
1605
- pipe,
1606
- noPty: support.reason
1607
- };
1608
- return {
1609
- usesFixture,
1610
- pipe,
1611
- tty: await runPty(command, args, {
1612
- timeout: probeTimeout(ctx, command, args),
1613
- env: ENV$1
1614
- })
1615
- };
1616
- }
1617
- const kinds = (output) => output === void 0 ? [] : rawNames(output).map((h) => h.kind);
1618
- async function controlChars(command, args, fixtureDir, ctx) {
1619
- const runs = await controlCharsRuns(command, args, fixtureDir, ctx);
1620
- const pipeOutput = runs.pipe && runs.pipe.stdout.toString("utf8") + runs.pipe.stderr;
1621
- return {
1622
- check: "control-chars",
1623
- invocation: [command, ...args],
1624
- ...judgeControlChars(runs),
1625
- terminalRaw: kinds(runs.tty?.output),
1626
- pipeRaw: kinds(pipeOutput)
1627
- };
1628
- }
1629
- const controlCharsCheck = {
1630
- name: "control-chars",
1631
- kind: "check",
1632
- summary: "prints control characters from file names raw to the terminal",
1633
- async run(target, ctx) {
1634
- if (target.fixtureDir === void 0) {
1635
- const own = target.probes.filter((p) => p.own);
1636
- return (own.length ? own.map((p) => [target.command, ...p.args]) : [[target.command, ...target.programArgs ?? []]]).map((invocation) => ({
1637
- check: "control-chars",
1638
- invocation,
1639
- ...judgeControlChars({ usesFixture: false }),
1640
- terminalRaw: [],
1641
- pipeRaw: []
1642
- }));
1643
- }
1644
- const dir = target.fixtureDir;
1645
- const results = [];
1646
- for (const { args } of target.probes.filter((p) => p.args.some((a) => a.includes(dir)))) results.push(await controlChars(target.command, args, dir, ctx));
1647
- return results;
1648
- }
1649
- };
1650
- // src/checks/sigterm.ts
1651
- /** How long the program runs before SIGTERM. */
1652
- const SIGTERM_DELAY_MS = 1e3;
1653
- /** How long it gets to exit after SIGTERM. */
1654
- const SIGTERM_GRACE_MS = 3e3;
1655
- /** How long its children get to follow it once it has exited. */
1656
- const SIGTERM_LEFTOVERS_MS = 1e3;
1657
- /** Lines worth quoting from a trace printed on SIGTERM, best first. */
1658
- const TRACE_MESSAGES$1 = [/^(\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1659
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "es"}`;
1660
- /** "1 process" or "3 processes", and the evidence naming the first one, for a check that reports leftovers. */
1661
- function describeLeftovers(left) {
1662
- const [first] = left;
1663
- const more = left.length > 1 ? ` (and ${left.length - 1} more)` : "";
1664
- return {
1665
- count: plural(left.length, "process"),
1666
- evidence: `still running: ${first?.command ?? ""}${more}`
1667
- };
1668
- }
1669
- function judgeSigterm(r) {
1670
- if (r.spawnError) return {
1671
- verdict: "error",
1672
- reason: `could not start: ${r.spawnError}`
1673
- };
1674
- if (r.signalSentMs === void 0) return noteFailedExit({
1675
- verdict: "skip",
1676
- reason: `finished in ${r.durationMs} ms, before SIGTERM at ${SIGTERM_DELAY_MS} ms; probe a command that keeps running`
1677
- }, r);
1678
- if (r.timedOut) return {
1679
- verdict: "warn",
1680
- reason: `ignored SIGTERM: still running ${SIGTERM_GRACE_MS / 1e3} s later, so docker stop or a process manager has to kill it`
1681
- };
1682
- const left = r.leftRunning ?? [];
1683
- if (left.length > 0) {
1684
- const { count, evidence } = describeLeftovers(left);
1685
- return {
1686
- verdict: "warn",
1687
- reason: `exited on SIGTERM but left ${count} running, which keep ports and files busy`,
1688
- evidence
1689
- };
1690
- }
1691
- const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1692
- if (TRACE_RE.test(after)) return {
1693
- verdict: "warn",
1694
- reason: "printed a stack trace on SIGTERM",
1695
- evidence: crashEvidence(after, TRACE_MESSAGES$1)
1696
- };
1697
- const ms = `${r.durationMs - r.signalSentMs} ms`;
1698
- return {
1699
- verdict: "pass",
1700
- reason: `${r.signal ? `stopped by ${r.signal}` : `exited with code ${r.exitCode}`} in ${ms} and left nothing running`
1701
- };
1702
- }
1703
- async function sigterm(command, args) {
1704
- const r = await run$1(command, args, {
1705
- timeout: 4e3,
1706
- signal: {
1707
- name: "SIGTERM",
1708
- afterMs: SIGTERM_DELAY_MS,
1709
- to: "process"
1710
- },
1711
- stdin: "open",
1712
- leftoversMs: SIGTERM_LEFTOVERS_MS
1713
- });
1714
- const sent = r.signalSentMs;
1715
- return {
1716
- check: "sigterm",
1717
- invocation: [command, ...args],
1718
- ...judgeSigterm(r),
1719
- sentAfterMs: sent ?? null,
1720
- exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1721
- exitCode: r.exitCode,
1722
- signal: r.signal,
1723
- leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1724
- stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1725
- };
1726
- }
1727
- const sigtermCheck = {
1728
- name: "sigterm",
1729
- kind: "check",
1730
- summary: "ignores SIGTERM, or exits on it and leaves its child processes running",
1731
- async run(target) {
1732
- const own = target.probes.filter((p) => p.own);
1733
- if (own.length === 0) return [{
1734
- check: "sigterm",
1735
- invocation: [target.command, ...target.programArgs ?? []],
1736
- verdict: "skip",
1737
- reason: "needs a probe that keeps running, such as a watch or serve command (--probe), or --bare",
1738
- sentAfterMs: null,
1739
- exitedAfterMs: null,
1740
- exitCode: null,
1741
- signal: null,
1742
- leftRunning: [],
1743
- stderrAfter: ""
1744
- }];
1745
- const results = [];
1746
- for (const { args } of own) results.push(await sigterm(target.command, args));
1747
- return results;
1748
- }
1749
- };
1750
- // src/checks/ctrl-c.ts
1751
- /** How long the program runs before Ctrl-C. */
1752
- const CTRL_C_DELAY_MS = 1e3;
1753
- /** How long it gets to exit after Ctrl-C. */
1754
- const CTRL_C_GRACE_MS = 3e3;
1755
- /** How long the rest of its group gets to follow it once it has exited. */
1756
- const CTRL_C_LEFTOVERS_MS = 1e3;
1757
- /** Lines worth quoting from a trace printed on Ctrl-C, best first. */
1758
- const TRACE_MESSAGES = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1759
- /**
1760
- * `bare` is true for the --bare probe, the command with no arguments. A REPL run that
1761
- * way (python3) gets a pipe as stdin, reads it as a script and doesn't stop on SIGINT,
1762
- * which no one at a terminal sees; restore, under a terminal, skips REPLs too (#43).
1763
- */
1764
- function judgeCtrlC(r, bare = false) {
1765
- if (r.spawnError) return {
1766
- verdict: "error",
1767
- reason: `could not start: ${r.spawnError}`
1768
- };
1769
- if (r.signalSentMs === void 0) return noteFailedExit({
1770
- verdict: "skip",
1771
- reason: `finished in ${r.durationMs} ms, before Ctrl-C at ${CTRL_C_DELAY_MS} ms; probe a command that keeps running`
1772
- }, r);
1773
- if (r.timedOut) {
1774
- if (bare && r.stdoutBytes === 0 && r.stderr === "") return {
1775
- verdict: "skip",
1776
- reason: `still running ${CTRL_C_GRACE_MS / 1e3} s after Ctrl-C without printing anything, as a REPL does when stdin is a pipe (it waits for a script, not a keypress); run it in a terminal to check its Ctrl-C`
1777
- };
1778
- return {
1779
- verdict: "fail",
1780
- reason: `ignored Ctrl-C: still running ${CTRL_C_GRACE_MS / 1e3} s later`
1781
- };
1782
- }
1783
- const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1784
- const ms = `${r.durationMs - r.signalSentMs} ms`;
1785
- if (TRACE_RE.test(after)) return {
1786
- verdict: "fail",
1787
- reason: "printed a stack trace on Ctrl-C",
1788
- evidence: crashEvidence(after, TRACE_MESSAGES)
1789
- };
1790
- const left = r.leftRunning ?? [];
1791
- if (left.length > 0) {
1792
- const { count, evidence } = describeLeftovers(left);
1793
- return {
1794
- verdict: "warn",
1795
- reason: `exited on Ctrl-C in ${ms} but left ${count} running that ignored it`,
1796
- evidence
1797
- };
1798
- }
1799
- if (r.signal) return {
1800
- verdict: "pass",
1801
- reason: `stopped by ${r.signal} in ${ms}`
1802
- };
1803
- if (r.exitCode === 130) return {
1804
- verdict: "pass",
1805
- reason: `exited with 130, the Ctrl-C convention, in ${ms}`
1806
- };
1807
- if (r.exitCode === 0) return {
1808
- verdict: "warn",
1809
- reason: `exited 0 after Ctrl-C, so a script cannot tell it was interrupted (130 is the convention)`
1810
- };
1811
- return {
1812
- verdict: "pass",
1813
- reason: `exited with code ${r.exitCode} in ${ms} (130 is the convention)`
1814
- };
1815
- }
1816
- async function ctrlC(command, args, bare = args.length === 0) {
1817
- const r = await run$1(command, args, {
1818
- timeout: 4e3,
1819
- signal: {
1820
- name: "SIGINT",
1821
- afterMs: CTRL_C_DELAY_MS
1822
- },
1823
- stdin: "open",
1824
- leftoversMs: CTRL_C_LEFTOVERS_MS
1825
- });
1826
- const sent = r.signalSentMs;
1827
- return {
1828
- check: "ctrl-c",
1829
- invocation: [command, ...args],
1830
- ...judgeCtrlC(r, bare),
1831
- sentAfterMs: sent ?? null,
1832
- exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1833
- exitCode: r.exitCode,
1834
- signal: r.signal,
1835
- leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1836
- stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1837
- };
1838
- }
1839
- const ctrlCCheck = {
1840
- name: "ctrl-c",
1841
- kind: "check",
1842
- summary: "ignores Ctrl-C, or prints a stack trace when interrupted",
1843
- async run(target) {
1844
- const own = target.probes.filter((p) => p.own);
1845
- if (own.length === 0) return [{
1846
- check: "ctrl-c",
1847
- invocation: [target.command, ...target.programArgs ?? []],
1848
- verdict: "skip",
1849
- reason: "needs a probe that keeps running, such as a watch or serve command (--probe), or --bare",
1850
- sentAfterMs: null,
1851
- exitedAfterMs: null,
1852
- exitCode: null,
1853
- signal: null,
1854
- leftRunning: [],
1855
- stderrAfter: ""
1856
- }];
1857
- const results = [];
1858
- for (const { args, bare } of own) results.push(await ctrlC(target.command, args, bare));
1859
- return results;
1860
- }
1861
- };
1862
- // src/checks/pipe-escapes.ts
1863
- /** As in the color check: a capable TERM, so a program can't pass by seeing TERM=dumb, and no CI. */
1864
- const ENV = {
1865
- TERM: "xterm-256color",
1866
- CI: void 0
1867
- };
1868
- const kindsOf = (hits) => [...new Set(hits.map((h) => h.kind))];
1869
- function listLabels$1(kinds) {
1870
- const labels = kinds.map((k) => CONTROL_LABELS[k]);
1871
- return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1872
- }
1873
- /**
1874
- * Escape sequences (cursor, erase, mode, hyperlink, title, other OSC) in a pipe fail: no
1875
- * real tool in the censuses printed one there except by mistake. A carriage-return redraw
1876
- * alone only warns, because some tools draw a progress meter on stderr by design (curl).
1877
- * The sequences added in 1.5 (other ESC sequences, a full reset, control strings, OSC
1878
- * without ";", 8-bit controls) only warn until a census calibrates them (#42).
1879
- */
1880
- function judgePipeEscapes(r) {
1881
- if (r.spawnError) return {
1882
- verdict: "error",
1883
- reason: `could not start: ${r.spawnError}`
1884
- };
1885
- const stdout = r.stdout.toString("utf8");
1886
- const hits = [...findControls(stdout).map((hit) => ({
1887
- stream: "stdout",
1888
- hit
1889
- })), ...findControls(r.stderr).map((hit) => ({
1890
- stream: "stderr",
1891
- hit
1892
- }))];
1893
- const escape = hits.find((h) => h.hit.kind !== "redraw" && !h.hit.warnOnly);
1894
- const newEscape = hits.find((h) => h.hit.warnOnly);
1895
- const first = escape ?? newEscape ?? hits[0];
1896
- if (first) {
1897
- const kinds = [...new Set(hits.map((h) => h.hit.kind))];
1898
- const evidence = `${first.stream} line ${first.hit.line}: ${first.hit.text}`;
1899
- if (escape) return {
1900
- verdict: "fail",
1901
- reason: `printed terminal control codes into a pipe: ${listLabels$1(kinds)}`,
1902
- evidence
1903
- };
1904
- if (newEscape) return {
1905
- verdict: "warn",
1906
- reason: `printed terminal control codes into a pipe: ${listLabels$1(kinds)}; a new finding, so only a warning for now`,
1907
- evidence
1908
- };
1909
- return {
1910
- verdict: "warn",
1911
- reason: "redrew lines with carriage returns in a pipe, as a progress meter does",
1912
- evidence
1913
- };
1914
- }
1915
- if (!stdout && !r.stderr) return r.timedOut ? {
1916
- verdict: "skip",
1917
- reason: `${stillRunning(r.durationMs)} and printed nothing so far`
1918
- } : noteFailedExit({
1919
- verdict: "skip",
1920
- reason: "printed nothing, so there is nothing to check"
1921
- }, r);
1922
- if (r.timedOut) return {
1923
- verdict: "pass",
1924
- reason: `no cursor, erase, hyperlink, title or redraw codes in a pipe (${stillRunning(r.durationMs)})`
1925
- };
1926
- return {
1927
- verdict: "pass",
1928
- reason: "no cursor, erase, hyperlink, title or redraw codes in a pipe"
1929
- };
1930
- }
1931
- async function pipeEscapes(command, args, ctx, fixture = false) {
1932
- const raw = await run$1(command, args, {
1933
- timeout: probeTimeout(ctx, command, args),
1934
- env: ENV
1935
- });
1936
- if (raw.timedOut) markLongRunning(ctx, command, args);
1937
- const r = fixture ? {
1938
- ...raw,
1939
- stdout: Buffer.from(withoutHostileNames(raw.stdout.toString("utf8"))),
1940
- stderr: withoutHostileNames(raw.stderr)
1941
- } : raw;
1942
- return {
1943
- check: "pipe-escapes",
1944
- invocation: [command, ...args],
1945
- ...judgePipeEscapes(r),
1946
- stdoutKinds: kindsOf(findControls(r.stdout.toString("utf8"))),
1947
- stderrKinds: kindsOf(findControls(r.stderr))
1948
- };
1949
- }
1950
- const pipeEscapesCheck = {
1951
- name: "pipe-escapes",
1952
- kind: "check",
1953
- summary: "prints spinners, cursor codes, hyperlinks or titles into a pipe",
1954
- async run(target, ctx) {
1955
- const results = [];
1956
- for (const { args } of target.probes) results.push(await pipeEscapes(target.command, args, ctx, target.fixtureDir !== void 0));
1957
- return results;
1958
- }
1959
- };
1960
- // src/checks/restore.ts
1961
- function listLabels(modes) {
1962
- return listWords(modes.map((m) => m.label));
1963
- }
1964
- function listWords(labels) {
1965
- return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1966
- }
1967
- /** The PTY wrapper's own complaint when it can't exec the program. */
1968
- const WRAPPER_EXEC_FAILED = /^sh: [^\n]*(cannot execute|exec format error)/i;
1969
- /** What the Ctrl-C key sends to a terminal. */
1970
- const CTRL_C_KEY = "";
1971
- function judgeRestore(r) {
1972
- if (r.spawnError) return {
1973
- verdict: "error",
1974
- reason: `could not start: ${r.spawnError}`
1975
- };
1976
- const interrupted = r.inputSentMs !== void 0;
1977
- if (r.timedOut) return {
1978
- verdict: "skip",
1979
- reason: interrupted ? `still running ${CTRL_C_GRACE_MS / 1e3} s after Ctrl-C, so how it leaves the terminal wasn't seen (REPLs and some full-screen programs quit only on a second Ctrl-C)` : "waited for input in a terminal, so it never finished"
1980
- };
1981
- if (r.truncated) return {
1982
- verdict: "skip",
1983
- reason: "printed more than 1 MiB in a terminal, so the end of its output, where it would restore the terminal, was not kept"
1984
- };
1985
- const when = interrupted ? "after Ctrl-C" : "when it exited";
1986
- const open = findOpenModes(r.output);
1987
- const off = r.settingsOff ?? [];
1988
- if (open.length > 0 || off.length > 0) {
1989
- const parts = open.length > 0 ? [`with ${listLabels(open)}`] : [];
1990
- const evidence = open.map((m) => `${m.sequence} on line ${m.line}, never undone`);
1991
- if (off.length > 0) {
1992
- const raw = off.includes("icanon") && off.includes("echo");
1993
- const flags = off.map((name) => `-${name}`);
1994
- parts.push(raw ? `in raw mode (${listWords(off)} off)` : `with ${listWords(off)} off (${flags.join(" ")})`);
1995
- evidence.push(`stty settings never restored: ${flags.join(" ")}`);
1996
- }
1997
- const fix = off.length > 0 ? "; `stty sane` undoes it" : "";
1998
- return {
1999
- verdict: "warn",
2000
- reason: `left the terminal ${parts.join(" and ")} ${when}${fix}`,
2001
- evidence: evidence.join("; ")
2002
- };
2003
- }
2004
- return {
2005
- verdict: "pass",
2006
- reason: `left no terminal mode switched on${r.settingsOff === void 0 ? "" : " and the terminal's settings as it found them"} ${when}`
2007
- };
2008
- }
2009
- async function restore(command, args, { timeout, interrupt }) {
2010
- const r = await runPty(command, args, {
2011
- timeout: interrupt ? 4e3 : timeout,
2012
- ...interrupt ? { input: {
2013
- data: CTRL_C_KEY,
2014
- afterMs: CTRL_C_DELAY_MS
2015
- } } : {},
2016
- settings: true
2017
- });
2018
- const notRun = r.spawnError === void 0 && (r.exitCode === 126 || r.exitCode === 127 || WRAPPER_EXEC_FAILED.test(r.output)) && cannotExecute(command);
2019
- const judgement = judgeRestore(notRun ? {
2020
- ...r,
2021
- spawnError: notAProgram(command, "the terminal's shell could not exec it")
2022
- } : r);
2023
- return {
2024
- check: "restore",
2025
- invocation: [command, ...args],
2026
- ...judgement,
2027
- interrupted: r.inputSentMs !== void 0,
2028
- openModes: judgement.verdict === "warn" ? findOpenModes(r.output) : [],
2029
- settingsOff: notRun ? null : r.settingsOff ?? null
2030
- };
2031
- }
2032
- const restoreCheck = {
2033
- name: "restore",
2034
- kind: "check",
2035
- summary: "leaves the cursor hidden, the alternate screen or mouse mode on after Ctrl-C",
2036
- async run(target, ctx) {
2037
- const support = ptySupport();
2038
- const notRun = findCommand(target.command) === void 0 ? {
2039
- verdict: "error",
2040
- reason: "could not start: command not found"
2041
- } : support.ok ? void 0 : {
2042
- verdict: "skip",
2043
- reason: `needs a terminal (${support.reason})`
2044
- };
2045
- const results = [];
2046
- for (const { args, own } of target.probes) {
2047
- if (notRun) {
2048
- const result = {
2049
- check: "restore",
2050
- invocation: [target.command, ...args],
2051
- ...notRun,
2052
- interrupted: false,
2053
- openModes: [],
2054
- settingsOff: null
2055
- };
2056
- results.push(result);
2057
- continue;
2058
- }
2059
- results.push(await restore(target.command, args, {
2060
- timeout: ctx.timeout,
2061
- interrupt: own
2062
- }));
2063
- }
2064
- return results;
2065
- }
2066
- };
2067
- function median(values) {
2068
- const sorted = [...values].sort((a, b) => a - b);
2069
- const mid = Math.floor(sorted.length / 2);
2070
- return sorted.length % 2 ? sorted[mid] ?? 0 : Math.round(((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2);
2071
- }
2072
- /**
2073
- * Median wall time of one invocation: `<command> --version` by default, how long a
2074
- * user waits for the simplest answer; or the probe exactly as given, so that
2075
- * `node ./dist/cli.js --version` times the CLI rather than Node.
2076
- */
2077
- async function startup(command, args, timeout) {
2078
- const base = {
2079
- check: "startup",
2080
- invocation: [command, ...args]
2081
- };
2082
- const warmUp = await run$1(command, args, { timeout });
2083
- if (warmUp.spawnError) return {
2084
- ...base,
2085
- verdict: "error",
2086
- reason: `could not start: ${warmUp.spawnError}`,
2087
- runsMs: [],
2088
- medianMs: null
2089
- };
2090
- if (warmUp.timedOut) return {
2091
- ...base,
2092
- verdict: "error",
2093
- reason: "timed out",
2094
- runsMs: [],
2095
- medianMs: null
2096
- };
2097
- if (warmUp.exitCode !== 0) return {
2098
- ...base,
2099
- verdict: "skip",
2100
- reason: `exited ${warmUp.exitCode ?? warmUp.signal}, so its time is not a fair startup measure`,
2101
- runsMs: [],
2102
- medianMs: null
2103
- };
2104
- const runsMs = [];
2105
- for (let i = 0; i < 5; i++) {
2106
- const r = await run$1(command, args, { timeout });
2107
- if (r.timedOut || r.spawnError) return {
2108
- ...base,
2109
- verdict: "error",
2110
- reason: "a timed run did not finish",
2111
- runsMs,
2112
- medianMs: null
2113
- };
2114
- runsMs.push(r.durationMs);
2115
- }
2116
- const mid = median(runsMs);
2117
- return {
2118
- ...base,
2119
- verdict: "info",
2120
- reason: `median ${mid} ms over 5 runs (min ${Math.min(...runsMs)}, max ${Math.max(...runsMs)})`,
2121
- runsMs,
2122
- medianMs: mid
2123
- };
2124
- }
2125
- const startupCheck = {
2126
- name: "startup",
2127
- kind: "info",
2128
- summary: "median wall time of --version, or of the given probe, over 5 runs",
2129
- async run(target, ctx) {
2130
- const [first] = target.probes;
2131
- const args = first?.own ? first.args : [...target.programArgs ?? [], "--version"];
2132
- return [await startup(target.command, args, ctx.timeout)];
2133
- }
2134
- };
2135
- // src/checks/stdin.ts
2136
- /** The least time the program gets with stdin left open before it counts as waiting. */
2137
- const STDIN_WAIT_MS = 3e3;
2138
- /** The earliest the confirming run closes stdin, and the least time it then gets to finish. */
2139
- const STDIN_CLOSE_AFTER_MS = 1e3;
2140
- const STDIN_GRACE_MS = 3e3;
2141
- /**
2142
- * How long a run must go past the one with stdin closed before stdin can be
2143
- * blamed: twice that time and a second more, so a program that is merely slow
2144
- * (3 to 4 s to answer) finishes well within it.
2145
- */
2146
- const stdinMargin = (closedMs) => 2 * closedMs + 1e3;
2147
- /**
2148
- * Whether the runs prove the program waited for stdin: it hung with stdin open
2149
- * for well past the time it needed with stdin closed, and in the confirming run
2150
- * it finished after stdin was closed, not before.
2151
- */
2152
- function provenByClose(runs) {
2153
- const { closed, open, closing } = runs;
2154
- const openMs = runs.openMs ?? 3e3;
2155
- const closeAfterMs = runs.closeAfterMs ?? 1e3;
2156
- return open?.timedOut === true && openMs >= stdinMargin(closed.durationMs) && closing !== void 0 && !closing.timedOut && closing.durationMs >= closeAfterMs;
2157
- }
2158
- const seconds = (ms) => `${Math.round(ms / 100) / 10} s`;
2159
- /** The last line printed before waiting, when it reads like a question left on the line. */
2160
- function promptLine(r) {
2161
- const last = stripEscapes(r.stdout.toString("utf8") + r.stderr).split("\n").at(-1) ?? "";
2162
- if (last.includes("\r") || last.trim() === "") return void 0;
2163
- return last;
2164
- }
2165
- /**
2166
- * `defaultProbe` is true for cliprobe's own `--version` and `--help` probes, which
2167
- * must never wait for input. For probes the user wrote, waiting can be the point
2168
- * (a filter such as `grep pattern`), so only a prompt-like wait warns.
2169
- */
2170
- function judgeStdin(runs, defaultProbe) {
2171
- const { closed, open, closing } = runs;
2172
- if (closed.spawnError) return {
2173
- verdict: "error",
2174
- reason: `could not start: ${closed.spawnError}`
2175
- };
2176
- if (closed.timedOut) return {
2177
- verdict: "skip",
2178
- reason: "doesn't finish even with stdin closed, so stdin isn't what it waits for"
2179
- };
2180
- if (!open || !open.timedOut) return {
2181
- verdict: "pass",
2182
- reason: "finished without waiting for stdin"
2183
- };
2184
- const openMs = runs.openMs ?? 3e3;
2185
- const closeAfterMs = runs.closeAfterMs ?? 1e3;
2186
- if (openMs < stdinMargin(closed.durationMs)) return {
2187
- verdict: "skip",
2188
- reason: `takes ${closed.durationMs} ms even with stdin closed, too close to --timeout to tell whether an open stdin makes it wait; raise --timeout`
2189
- };
2190
- if (!closing || closing.timedOut) return {
2191
- verdict: "skip",
2192
- reason: "hung with stdin open, but closing stdin didn't end it, so the cause isn't proven"
2193
- };
2194
- if (!provenByClose(runs)) return {
2195
- verdict: "skip",
2196
- reason: "hung once with stdin open, but finished before stdin was closed the next time, so the cause isn't proven"
2197
- };
2198
- const evidence = `${closed.durationMs} ms with stdin closed; still running after ${seconds(openMs)} with stdin open; finished ${closing.durationMs - closeAfterMs} ms after stdin closed`;
2199
- if (defaultProbe) return {
2200
- verdict: "fail",
2201
- reason: "waited for stdin before answering, so an agent or CI step that leaves stdin open hangs forever",
2202
- evidence
2203
- };
2204
- const prompt = promptLine(open);
2205
- if (prompt !== void 0) return {
2206
- verdict: "warn",
2207
- reason: "seems to prompt for input even though stdin isn't a terminal",
2208
- evidence: `prompt: ${prompt.slice(0, 120)}; ${evidence}`
2209
- };
2210
- return {
2211
- verdict: "skip",
2212
- reason: "reads stdin like a filter and waits until it closes; give it input or </dev/null",
2213
- evidence
2214
- };
2215
- }
2216
- async function stdinRuns(command, args, timeout) {
2217
- const closed = await run$1(command, args, { timeout });
2218
- if (closed.timedOut) return { closed };
2219
- if (closed.spawnError) return { closed };
2220
- const margin = stdinMargin(closed.durationMs);
2221
- const openMs = Math.min(timeout, Math.max(STDIN_WAIT_MS, margin));
2222
- const open = await run$1(command, args, {
2223
- timeout: openMs,
2224
- stdin: "open"
2225
- });
2226
- if (!open.timedOut || openMs < margin) return {
2227
- closed,
2228
- open,
2229
- openMs
2230
- };
2231
- const closeAfterMs = Math.max(STDIN_CLOSE_AFTER_MS, margin);
2232
- return {
2233
- closed,
2234
- open,
2235
- openMs,
2236
- closing: await run$1(command, args, {
2237
- timeout: closeAfterMs + Math.max(STDIN_GRACE_MS, margin),
2238
- stdin: { closeAfterMs }
2239
- }),
2240
- closeAfterMs
2241
- };
2242
- }
2243
- async function stdinCheck(command, args, defaultProbe, ctx) {
2244
- if (isLongRunning(ctx, command, args)) return {
2245
- check: "stdin",
2246
- invocation: [command, ...args],
2247
- verdict: "skip",
2248
- reason: "keeps running even with stdin closed, so stdin isn't what it waits for",
2249
- closedMs: null,
2250
- waitedForStdin: false,
2251
- finishedAfterCloseMs: null
2252
- };
2253
- const runs = await stdinRuns(command, args, ctx.timeout);
2254
- if (runs.closed.timedOut) markLongRunning(ctx, command, args);
2255
- const proven = provenByClose(runs);
2256
- return {
2257
- check: "stdin",
2258
- invocation: [command, ...args],
2259
- ...judgeStdin(runs, defaultProbe),
2260
- closedMs: runs.closed.spawnError ? null : runs.closed.durationMs,
2261
- waitedForStdin: proven,
2262
- finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - (runs.closeAfterMs ?? 1e3) : null
2263
- };
2264
- }
2265
- const stdinCheckDefinition = {
2266
- name: "stdin",
2267
- kind: "check",
2268
- summary: "waits for stdin when it is an open pipe, as agents and CI runners leave it",
2269
- async run(target, ctx) {
2270
- const results = [];
2271
- for (const { args, own } of target.probes) results.push(await stdinCheck(target.command, args, !own, ctx));
2272
- return results;
2273
- }
2274
- };
2275
- // src/checks/write-error.ts
2276
- /** A stack trace that only the failed writes brought out. */
2277
- const newTrace = (base, full) => TRACE_RE.test(full.stderr) && !TRACE_RE.test(base.stderr);
2278
- /** The first line it printed to stderr, as evidence of how it reported the error. */
2279
- const stderrLine = (r) => {
2280
- const message = crashEvidence(r.stderr);
2281
- return message ? { evidence: message } : {};
2282
- };
2283
- const EXITED_ZERO = "exited 0 though every write to stdout failed (no space left on device), so `> file` on a full disk looks like success";
2284
- /** For a program that keeps running: only how it ends, if it ends, is judged. */
2285
- function judgeLongRunning(base, full) {
2286
- if (full.timedOut) return {
2287
- verdict: "pass",
2288
- reason: `${stillRunning(base.durationMs)}; with stdout on a full disk it kept running`
2289
- };
2290
- if (newTrace(base, full)) return {
2291
- verdict: "warn",
2292
- reason: "crashed with a stack trace when a write to stdout failed",
2293
- evidence: crashEvidence(full.stderr)
2294
- };
2295
- if (full.exitCode === 0) return {
2296
- verdict: "warn",
2297
- reason: EXITED_ZERO
2298
- };
2299
- return {
2300
- verdict: "pass",
2301
- reason: `stopped when a write to stdout failed (${exitText(full)})`,
2302
- ...stderrLine(full)
2303
- };
2304
- }
2305
- const exitText = (r) => r.signal ? `stopped by ${r.signal}` : `exit ${r.exitCode}`;
2306
- /**
2307
- * Compares a normal run with a run whose stdout is /dev/full, where every write
2308
- * fails with ENOSPC. A careful program says so and exits non-zero, as GNU
2309
- * coreutils, git and Python do. Warn-only until a census shows no false warns.
2310
- */
2311
- function judge(base, full) {
2312
- if (base.spawnError) return {
2313
- verdict: "error",
2314
- reason: `could not start: ${base.spawnError}`
2315
- };
2316
- if (base.stdoutBytes === 0) return noteFailedExit({
2317
- verdict: "skip",
2318
- reason: base.timedOut ? `${stillRunning(base.durationMs)} without writing to stdout, so a failed write never happened` : "wrote nothing to stdout, so a failed write never happens"
2319
- }, base);
2320
- if (!full) return {
2321
- verdict: "skip",
2322
- reason: "no /dev/full on this system (it needs Linux)"
2323
- };
2324
- if (base.timedOut) return judgeLongRunning(base, full);
2325
- if (full.timedOut) return {
2326
- verdict: "warn",
2327
- reason: "hung when a write to stdout failed",
2328
- ...stderrLine(full)
2329
- };
2330
- if (newTrace(base, full)) return {
2331
- verdict: "warn",
2332
- reason: `crashed with a stack trace when a write to stdout failed (${exitText(full)})`,
2333
- evidence: crashEvidence(full.stderr)
2334
- };
2335
- if (full.exitCode === 0) return {
2336
- verdict: "warn",
2337
- reason: EXITED_ZERO
2338
- };
2339
- return {
2340
- verdict: "pass",
2341
- reason: `reported the failed write (${exitText(full)})`,
2342
- ...stderrLine(full)
2343
- };
2344
- }
2345
- async function writeError(command, args, ctx) {
2346
- const base = await run$1(command, args, { timeout: probeTimeout(ctx, command, args) });
2347
- if (base.timedOut) markLongRunning(ctx, command, args);
2348
- const full = !base.spawnError && base.stdoutBytes > 0 && hasDevFull() ? await run$1(command, args, {
2349
- fullStdout: true,
2350
- timeout: base.timedOut ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout
2351
- }) : void 0;
2352
- return {
2353
- check: "write-error",
2354
- invocation: [command, ...args],
2355
- ...judge(base, full),
2356
- baseline: {
2357
- exitCode: base.exitCode,
2358
- signal: base.signal,
2359
- stdoutBytes: base.stdoutBytes
2360
- },
2361
- full: full ? {
2362
- exitCode: full.exitCode,
2363
- signal: full.signal,
2364
- timedOut: full.timedOut,
2365
- stderr: full.stderr.slice(-2e3)
2366
- } : null
2367
- };
2368
- }
2369
- // src/checks/index.ts
2370
- /** Every check, in the order they run and are reported. */
2371
- const CHECKS = [
2372
- closedPipeCheck,
2373
- {
2374
- name: "write-error",
2375
- kind: "check",
2376
- summary: "exits 0 or crashes when writing stdout fails (a full disk)",
2377
- async run(target, ctx) {
2378
- const results = [];
2379
- for (const { args } of target.probes) results.push(await writeError(target.command, args, ctx));
2380
- return results;
2381
- }
2382
- },
2383
- colorCheck,
2384
- pipeEscapesCheck,
2385
- stdinCheckDefinition,
2386
- ctrlCCheck,
2387
- sigtermCheck,
2388
- restoreCheck,
2389
- controlCharsCheck,
2390
- startupCheck,
2391
- baselineCheck
2392
- ];
2393
- /**
2394
- * Picks checks by name, keeping registry order, then leaves out those in `skip`.
2395
- * No names selects every check of kind "check": info checks only run when named,
2396
- * because they never fail and baseline sends a flag the user did not ask for.
2397
- */
2398
- function selectChecks(names, skip = []) {
2399
- const known = new Set(CHECKS.map((c) => c.name));
2400
- return {
2401
- checks: (names.length === 0 ? CHECKS.filter((c) => c.kind === "check") : CHECKS.filter((c) => names.includes(c.name))).filter((c) => !skip.includes(c.name)),
2402
- unknown: [...new Set([...names, ...skip].filter((n) => !known.has(n)))]
2403
- };
2404
- }
2405
- // src/core/safe.ts
2406
- /**
2407
- * C0 and C1 controls, DEL, Unicode line separators and bidirectional overrides:
2408
- * everything that can drive a terminal, forge a line, or reorder what is shown.
2409
- */
2410
- const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
2411
- /** The same, minus C0, which JSON.stringify already escapes. */
2412
- const JSON_UNSAFE = /[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
2413
- const hex = (c, width) => c.charCodeAt(0).toString(16).padStart(width, "0");
2414
- /**
2415
- * Escapes text from a target (its output, its arguments, file names) for one
2416
- * line of our own report: `\x1b`, `\x0a`, `\u202e`. It can no longer drive the
2417
- * terminal, break the line, or disguise itself.
2418
- */
2419
- function safe(text) {
2420
- return text.replace(UNSAFE, (c) => c.charCodeAt(0) <= 255 ? `\\x${hex(c, 2)}` : `\\u${hex(c, 4)}`);
2421
- }
2422
- /** JSON.stringify, plus \u escapes for the characters it leaves raw. Parses back identically. */
2423
- function safeJson(value) {
2424
- return JSON.stringify(value, null, 2).replace(JSON_UNSAFE, (c) => `\\u${hex(c, 4)}`);
2425
- }
2426
- // src/core/quote.ts
2427
- /** Characters a POSIX shell takes literally in a word; `{fixture}` stays readable. */
2428
- const PLAIN = /^[\w@%+=:,./{}-]+$/;
2429
- /**
2430
- * Joins a command and its arguments the way you would type them in a shell,
2431
- * single-quoting any argument with spaces, quotes or other special characters,
2432
- * so `python3 -c 'import time; time.sleep(30)'` doesn't read as five words.
2433
- * Only for display: cliprobe never runs a shell.
2434
- */
2435
- function shellJoin(args) {
2436
- return args.map((a) => PLAIN.test(a) ? a : `'${a.replaceAll("'", `'\\''`)}'`).join(" ");
2437
- }
2438
- /**
2439
- * Splits `text` into arguments the way a POSIX shell splits a command line:
2440
- * on unquoted whitespace, with '...' taken literally, "..." honoring \" \\ \$ \`,
2441
- * and a backslash escaping the next character. Nothing is expanded: no
2442
- * variables, wildcards or ~. Throws on an unclosed quote or a trailing backslash.
2443
- */
2444
- function shellSplit(text) {
2445
- const words = [];
2446
- let word = "";
2447
- let inWord = false;
2448
- for (let i = 0; i < text.length; i++) {
2449
- const c = text.charAt(i);
2450
- if (c === "'") {
2451
- const end = text.indexOf("'", i + 1);
2452
- if (end < 0) throw new Error("has an unclosed single quote");
2453
- word += text.slice(i + 1, end);
2454
- inWord = true;
2455
- i = end;
2456
- } else if (c === "\"") {
2457
- inWord = true;
2458
- for (i++;; i++) {
2459
- if (i >= text.length) throw new Error("has an unclosed double quote");
2460
- const d = text.charAt(i);
2461
- if (d === "\"") break;
2462
- const next = text.charAt(i + 1);
2463
- if (d === "\\" && next !== "" && "\"\\$`\n".includes(next)) {
2464
- i++;
2465
- if (next !== "\n") word += next;
2466
- } else word += d;
2467
- }
2468
- } else if (c === "\\") {
2469
- if (i + 1 >= text.length) throw new Error("ends with a backslash");
2470
- i++;
2471
- if (text.charAt(i) !== "\n") {
2472
- word += text.charAt(i);
2473
- inWord = true;
2474
- }
2475
- } else if (c === " " || c === " " || c === "\n") {
2476
- if (inWord) words.push(word);
2477
- word = "";
2478
- inWord = false;
2479
- } else {
2480
- word += c;
2481
- inWord = true;
2482
- }
2483
- }
2484
- if (inWord) words.push(word);
2485
- return words;
2486
- }
2487
- // src/report/summary.ts
2488
- function countVerdicts(results) {
2489
- const counts = {
2490
- pass: 0,
2491
- fail: 0,
2492
- warn: 0,
2493
- skip: 0,
2494
- error: 0,
2495
- info: 0
2496
- };
2497
- for (const r of results) counts[r.verdict]++;
2498
- return counts;
2499
- }
2500
- /** How many failures and warnings the config file accepts, so they don't fail the run. */
2501
- const countAccepted = (results) => results.filter((r) => r.accepted).length;
2502
- /**
2503
- * "2 failed, 0 warned, 2 passed, 2 skipped", plus info and could-not-run when
2504
- * present, a note when --strict makes warnings fail, and how many of the failures
2505
- * and warnings the config file accepts.
2506
- */
2507
- function summaryLine(c, strict = false, accepted = 0) {
2508
- const info = c.info ? `, ${c.info} info` : "";
2509
- const errors = c.error ? `, ${c.error} could not run` : "";
2510
- const mode = strict ? " (--strict: warnings fail)" : "";
2511
- const known = accepted ? ` (${accepted} accepted in the config)` : "";
2512
- return `${c.fail} failed, ${c.warn} warned, ${c.pass} passed, ${c.skip} skipped${info}${errors}${mode}${known}`;
2513
- }
2514
- // src/report/human.ts
2515
- const COLORS = {
2516
- pass: 32,
2517
- fail: 31,
2518
- warn: 33,
2519
- skip: 90,
2520
- error: 35,
2521
- info: 36
2522
- };
2523
- const CUT = " ... (--json has the rest)";
2524
- /**
2525
- * Evidence for one line of the report: escaped as safe() does, with a backslash from
2526
- * the program doubled, so the text `\x1b` can't pass for a real escape. Past the limit
2527
- * it ends at a word, or between two escapes, never inside one, and says it was cut.
2528
- */
2529
- function showEvidence(evidence, limit = 200) {
2530
- const pieces = Array.from(evidence, (c) => c === "\\" ? "\\\\" : safe(c));
2531
- let shown = "";
2532
- let wordEnd = 0;
2533
- for (const piece of pieces) {
2534
- if (shown.length + piece.length > limit) return (wordEnd > limit * .6 ? shown.slice(0, wordEnd) : shown) + CUT;
2535
- if (piece === " ") wordEnd = shown.length;
2536
- shown += piece;
2537
- }
2538
- return shown;
2539
- }
2540
- function formatHuman({ version, command, checks, strict, results }, { color }) {
2541
- const paint = (verdict) => {
2542
- const label = verdict.toUpperCase().padEnd(5);
2543
- return color ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
2544
- };
2545
- const shownInvocation = (invocation) => safe(shellJoin(invocation));
2546
- const width = Math.max(0, ...results.map((r) => shownInvocation(r.invocation).length).filter((length) => length <= 40));
2547
- const indent = ` ${" ".repeat(5)} ${" ".repeat(width)} `;
2548
- const noun = checks.length === 1 ? "check" : "checks";
2549
- const lines = [`cliprobe ${version}: ${checks.join(", ")} ${noun} for ${safe(command)}`];
2550
- for (const check of checks) {
2551
- lines.push("");
2552
- if (checks.length > 1) lines.push(check);
2553
- for (const r of results.filter((result) => result.check === check)) {
2554
- const invocation = shownInvocation(r.invocation);
2555
- if (invocation.length > width) lines.push(` ${paint(r.verdict)} ${invocation}`, `${indent}${safe(r.reason)}`);
2556
- else lines.push(` ${paint(r.verdict)} ${invocation.padEnd(width)} ${safe(r.reason)}`);
2557
- if (r.evidence) lines.push(`${indent}${showEvidence(r.evidence)}`);
2558
- if (r.accepted) lines.push(`${indent}accepted: ${safe(r.accepted.reason)}`);
2559
- }
2560
- }
2561
- lines.push("", summaryLine(countVerdicts(results), strict, countAccepted(results)));
2562
- return lines.join("\n") + "\n";
2563
- }
2564
- // src/report/github.ts
2565
- /** The text of a workflow command: GitHub reads `%0A` back as a line break. */
2566
- const commandData = (text) => text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
2567
- /** A workflow command's property value, where `:` and `,` also end something. */
2568
- const commandProperty = (text) => commandData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
2569
- /**
2570
- * The annotation level for a result, if it gets one: an error for what fails
2571
- * the step (a failure, could-not-run, a warning under --strict), a warning for
2572
- * other warnings, and a notice for a finding the config file accepts.
2573
- */
2574
- function annotationLevel(r, strict) {
2575
- if (r.verdict === "error") return "error";
2576
- if (r.verdict !== "fail" && r.verdict !== "warn") return null;
2577
- if (r.accepted) return "notice";
2578
- return r.verdict === "fail" || strict ? "error" : "warning";
2579
- }
2580
- function annotation(r, strict) {
2581
- const level = annotationLevel(r, strict);
2582
- if (level === null) return null;
2583
- const title = `cliprobe ${r.check}: ${safe(shellJoin(r.invocation))}`;
2584
- const lines = [
2585
- safe(r.reason),
2586
- ...r.evidence ? [showEvidence(r.evidence)] : [],
2587
- ...r.accepted ? [`accepted: ${safe(r.accepted.reason)}`] : []
2588
- ];
2589
- return `::${level} title=${commandProperty(title)}::${commandData(lines.join("\n"))}`;
2590
- }
2591
- /**
2592
- * For a GitHub Actions step: the human report for the log, then one workflow
2593
- * command per finding, which GitHub shows as an annotation on the run and on the
2594
- * pull request's checks.
2595
- *
2596
- * The report quotes the program under test, and GitHub reads a workflow command
2597
- * from any log line that starts with `::`, even an indented one. So the report
2598
- * is printed with command processing stopped, behind a token made after the
2599
- * program ran, which it therefore can't know and can't use to switch it back on.
2600
- */
2601
- function formatGithub(report) {
2602
- const token = randomUUID();
2603
- const annotations = report.results.map((r) => annotation(r, report.strict)).filter((line) => line !== null);
2604
- return [
2605
- `::stop-commands::${token}`,
2606
- formatHuman(report, { color: false }).trimEnd(),
2607
- `::${token}::`,
2608
- ...annotations,
2609
- ""
2610
- ].join("\n");
2611
- }
2612
- /**
2613
- * The report as JSON. Each result keeps the fields every check shares at the top
2614
- * and moves the check's own measurements into `details`.
2615
- */
2616
- function formatJson({ version, command, checks, strict, results }) {
2617
- return safeJson({
2618
- tool: "cliprobe",
2619
- schemaVersion: 1,
2620
- version,
2621
- command,
2622
- checks,
2623
- strict,
2624
- summary: countVerdicts(results),
2625
- results: results.map(({ check, invocation, verdict, reason, evidence, accepted, ...details }) => ({
2626
- check,
2627
- invocation,
2628
- verdict,
2629
- reason,
2630
- ...evidence === void 0 ? {} : { evidence },
2631
- ...accepted === void 0 ? {} : { accepted },
2632
- details
2633
- }))
2634
- }) + "\n";
2635
- }
2636
- // src/report/junit.ts
2637
- const XML_ESCAPES = {
2638
- "&": "&amp;",
2639
- "<": "&lt;",
2640
- ">": "&gt;",
2641
- "\"": "&quot;",
2642
- "'": "&apos;"
2643
- };
2644
- /**
2645
- * Text that is always well-formed XML 1.0: safe() first turns every control
2646
- * character (most of which XML forbids even when escaped) into a visible escape,
2647
- * then the five markup characters become entities.
2648
- */
2649
- function xml(text) {
2650
- return safe(text).replace(/[&<>"']/g, (c) => XML_ESCAPES[c] ?? c);
2651
- }
2652
- /** A failure, or with --strict a warning, that the config file doesn't accept. */
2653
- const fails = (r, strict) => !r.accepted && (r.verdict === "fail" || strict && r.verdict === "warn");
2654
- /** JUnit's count attributes for a suite or the whole run; with --strict, warnings are failures. */
2655
- function totals(results, strict) {
2656
- const c = countVerdicts(results);
2657
- const failures = results.filter((r) => fails(r, strict)).length;
2658
- return `tests="${results.length}" failures="${failures}" errors="${c.error}" skipped="${c.skip}"`;
2659
- }
2660
- function testcase(r, strict) {
2661
- const open = ` <testcase classname="cliprobe.${xml(r.check)}" name="${xml(shellJoin(r.invocation))}"`;
2662
- const message = `message="${xml(r.reason)}"`;
2663
- const body = r.evidence ? xml(r.evidence) : "";
2664
- const failure = (type) => `${open}>\n <failure ${message} type="${type}">${body}</failure>\n </testcase>`;
2665
- if (fails(r, strict)) return failure(r.verdict);
2666
- if (r.verdict === "error") return `${open}>\n <error ${message} type="error">${body}</error>\n </testcase>`;
2667
- if (r.verdict === "skip") return `${open}>\n <skipped ${message}/>\n </testcase>`;
2668
- const accepted = r.accepted ? `\nAccepted: ${xml(r.accepted.reason)}` : "";
2669
- return `${open}>\n <system-out>${`${r.verdict.toUpperCase()}: ${xml(r.reason)}${r.evidence ? `\n${body}` : ""}${accepted}`}</system-out>\n </testcase>`;
2670
- }
2671
- /** JUnit XML: one testsuite per check, one testcase per result. */
2672
- function formatJunit({ version, command, checks, strict, results }) {
2673
- const suites = checks.map((check) => {
2674
- const own = results.filter((r) => r.check === check);
2675
- return [
2676
- ` <testsuite name="${xml(check)}" ${totals(own, strict)}>`,
2677
- ...own.map((r) => testcase(r, strict)),
2678
- " </testsuite>"
2679
- ].join("\n");
2680
- });
2681
- return [
2682
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
2683
- `<testsuites name="cliprobe ${xml(version)}: ${xml(command)}" ${totals(results, strict)}>`,
2684
- ...suites,
2685
- "</testsuites>",
2686
- ""
2687
- ].join("\n");
2688
- }
2689
- // src/report/markdown.ts
2690
- /**
2691
- * A code span that shows any text literally: control characters escaped onto one
2692
- * line, `|` escaped so a table cell can't be split, and a fence longer than any
2693
- * run of backticks inside.
2694
- */
2695
- function code(text, { inTable }) {
2696
- const body = inTable ? safe(text).replaceAll("|", "\\|") : safe(text);
2697
- const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((run) => run.length));
2698
- const fence = "`".repeat(longest + 1);
2699
- const pad = body.startsWith("`") || body.endsWith("`") ? " " : "";
2700
- return `${fence}${pad}${body}${pad}${fence}`;
2701
- }
2702
- /**
2703
- * Prose for inside a table cell. Only characters that act mid-line are escaped:
2704
- * emphasis, code, links, HTML, entities and the cell separator. Line-start syntax
2705
- * (`#`, `-`, `1.`) can't trigger there, so it stays readable.
2706
- */
2707
- function prose(text) {
2708
- return safe(text).replace(/[\\`*_[\]<>|~&]/g, (c) => `\\${c}`);
2709
- }
2710
- function row(r, strict) {
2711
- const verdict = r.verdict === "error" || !r.accepted && (r.verdict === "fail" || strict && r.verdict === "warn") ? `**${r.verdict.toUpperCase()}**` : r.verdict.toUpperCase();
2712
- const evidence = (r.evidence ? `<br>${code(r.evidence.slice(0, 300), { inTable: true })}` : "") + (r.accepted ? `<br>Accepted: ${prose(r.accepted.reason)}` : "");
2713
- return `| ${[
2714
- prose(r.check),
2715
- verdict,
2716
- code(shellJoin(r.invocation), { inTable: true }),
2717
- prose(r.reason) + evidence
2718
- ].join(" | ")} |`;
2719
- }
2720
- /** GitHub-flavored Markdown, for a job summary ($GITHUB_STEP_SUMMARY) or a PR comment. */
2721
- function formatMarkdown({ version, command, strict, results }) {
2722
- return [
2723
- `## cliprobe ${version}: ${code(command, { inTable: false })}`,
2724
- "",
2725
- summaryLine(countVerdicts(results), strict, countAccepted(results)),
2726
- "",
2727
- "| Check | Verdict | Invocation | Result |",
2728
- "| --- | --- | --- | --- |",
2729
- ...results.map((r) => row(r, strict)),
2730
- ""
2731
- ].join("\n");
2732
- }
2733
- // src/report/index.ts
2734
- /** The format names, in the order --help lists them. */
2735
- const FORMAT_NAMES = [
2736
- "human",
2737
- "json",
2738
- "markdown",
2739
- "junit",
2740
- "github"
2741
- ];
2742
- function isFormat(name) {
2743
- return FORMAT_NAMES.includes(name);
2744
- }
2745
- /** Every output format; the Record type makes a missing formatter a type error. */
2746
- const FORMATS = {
2747
- human: formatHuman,
2748
- json: formatJson,
2749
- markdown: formatMarkdown,
2750
- junit: formatJunit,
2751
- github: formatGithub
2752
- };
2753
6
  // src/report/write.ts
2754
7
  /** Why a report can't be written to a path, in words for the person who gave it. */
2755
8
  var ReportPathError = class extends Error {};
@@ -2891,20 +144,6 @@ async function writeReportFile(path, text) {
2891
144
  unregister();
2892
145
  }
2893
146
  }
2894
- // src/version.ts
2895
- /**
2896
- * Read from the package manifest at runtime. Works from both `src/` (development)
2897
- * and `dist/` (published): each sits one level below the package root.
2898
- */
2899
- function readVersion() {
2900
- const manifest = createRequire(import.meta.url)("../package.json");
2901
- if (typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string") return manifest.version;
2902
- return "0.0.0";
2903
- }
2904
- const VERSION = readVersion();
2905
- // src/cli/usage.ts
2906
- /** A mistake in how cliprobe was called, or in its config file: reported with exit 2. */
2907
- var UsageError = class extends Error {};
2908
147
  // src/cli/args.ts
2909
148
  /** Every option cliprobe takes, to tell a forgotten value from a value that starts with -. */
2910
149
  const OPTIONS = /* @__PURE__ */ new Set([
@@ -2932,8 +171,6 @@ const PATH_OPTIONS = /* @__PURE__ */ new Set([
2932
171
  ]);
2933
172
  /** The option name in an argument such as --format=json. */
2934
173
  const flagOf = (arg) => arg.split("=")[0] ?? arg;
2935
- /** How long a probe may run when neither --timeout nor a config file says. */
2936
- const DEFAULT_TIMEOUT_MS = 15e3;
2937
174
  function parseArgs(argv) {
2938
175
  const opts = {
2939
176
  format: "human",
@@ -2963,7 +200,10 @@ function parseArgs(argv) {
2963
200
  const inline = a.includes("=");
2964
201
  const v = inline ? a.slice(a.indexOf("=") + 1) : argv[++i];
2965
202
  if (v === void 0 || v === "") throw new UsageError(`${flag} needs ${what}`);
2966
- if (!inline && v.startsWith("-")) throw new UsageError(`${flag} needs ${what}, got option "${v}"${PATH_OPTIONS.has(flag) && !OPTIONS.has(flagOf(v)) ? `; use ${flag}=${v} or ./${v} for a value that starts with -` : ""}`);
203
+ if (!inline && v.startsWith("-")) {
204
+ const hint = PATH_OPTIONS.has(flag) && !OPTIONS.has(flagOf(v)) ? `; use ${flag}=${v} or ./${v} for a value that starts with -` : "";
205
+ throw new UsageError(`${flag} needs ${what}, got option "${v}"${hint}`);
206
+ }
2967
207
  return v;
2968
208
  };
2969
209
  if (a === "--json") opts.format = "json";
@@ -3014,117 +254,6 @@ function parseArgs(argv) {
3014
254
  }
3015
255
  return opts;
3016
256
  }
3017
- /** The arguments given after the command, the empty --bare probe, or the default --version and --help. */
3018
- function mainProbe(opts) {
3019
- if (opts.bare) return [[]];
3020
- return opts.args.length ? [opts.args] : [["--version"], ["--help"]];
3021
- }
3022
- // src/cli/config.ts
3023
- /** The file `cliprobe` reads from the current directory when no command is given. */
3024
- const CONFIG_FILE = "cliprobe.config.json";
3025
- const KEYS = /* @__PURE__ */ new Set([
3026
- "$schema",
3027
- "command",
3028
- "probes",
3029
- "bare",
3030
- "checks",
3031
- "skip",
3032
- "strict",
3033
- "timeout",
3034
- "accept"
3035
- ]);
3036
- const ACCEPT_KEYS = /* @__PURE__ */ new Set([
3037
- "check",
3038
- "probe",
3039
- "reason"
3040
- ]);
3041
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3042
- const isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
3043
- /** Reads a config file's text. Every problem is a usage error that names the key. */
3044
- function parseConfig(text, path) {
3045
- const bad = (message) => new UsageError(`${path}: ${message}`);
3046
- let json;
3047
- try {
3048
- json = JSON.parse(text);
3049
- } catch (error) {
3050
- throw bad(`not valid JSON (${error instanceof Error ? error.message : String(error)})`);
3051
- }
3052
- if (!isObject(json)) throw bad("must hold a JSON object");
3053
- const unknownKey = Object.keys(json).find((key) => !KEYS.has(key));
3054
- if (unknownKey !== void 0) throw bad(`unknown key "${unknownKey}" (known: ${[...KEYS].slice(1).join(", ")})`);
3055
- /** Arguments as a string, split like --probe, or as an array of strings, taken as they are. */
3056
- const words = (value, key) => {
3057
- if (isStrings(value)) return value;
3058
- if (typeof value !== "string") throw bad(`"${key}" must be a string or an array of strings`);
3059
- try {
3060
- return shellSplit(value);
3061
- } catch (error) {
3062
- throw bad(`"${key}" ${error instanceof Error ? error.message : String(error)}`);
3063
- }
3064
- };
3065
- const flag = (key) => {
3066
- const value = json[key];
3067
- if (value === void 0) return false;
3068
- if (typeof value !== "boolean") throw bad(`"${key}" must be true or false`);
3069
- return value;
3070
- };
3071
- const names = (key) => {
3072
- const value = json[key];
3073
- if (value === void 0) return [];
3074
- if (!isStrings(value)) throw bad(`"${key}" must be an array of check names`);
3075
- return value;
3076
- };
3077
- const list = (key) => {
3078
- const value = json[key];
3079
- if (value === void 0) return [];
3080
- if (!Array.isArray(value)) throw bad(`"${key}" must be an array`);
3081
- return value;
3082
- };
3083
- if (json["command"] === void 0) throw bad("needs a \"command\", the program to probe");
3084
- const command = words(json["command"], "command");
3085
- if (command.length === 0 || command[0] === "") throw bad("\"command\" is empty");
3086
- const probes = list("probes").map((probe, i) => {
3087
- const args = words(probe, `probes[${i}]`);
3088
- if (args.length === 0) throw bad(`"probes[${i}]" is empty; use "bare": true for no arguments`);
3089
- return args;
3090
- });
3091
- const timeout = json["timeout"];
3092
- if (timeout !== void 0 && (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_MS)) throw bad(`"timeout" must be a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}`);
3093
- const accept = list("accept").map((entry, i) => {
3094
- const key = `accept[${i}]`;
3095
- if (!isObject(entry)) throw bad(`"${key}" must be an object with "check" and "reason"`);
3096
- const extra = Object.keys(entry).find((k) => !ACCEPT_KEYS.has(k));
3097
- if (extra !== void 0) throw bad(`"${key}" has an unknown key "${extra}"`);
3098
- const { check, reason, probe } = entry;
3099
- if (typeof check !== "string" || check === "") throw bad(`"${key}" needs a "check" name`);
3100
- if (typeof reason !== "string" || reason.trim() === "") throw bad(`"${key}" needs a "reason": say why the finding is accepted`);
3101
- return {
3102
- check,
3103
- reason,
3104
- ...probe === void 0 ? {} : { probe: words(probe, `${key}.probe`) }
3105
- };
3106
- });
3107
- return {
3108
- command,
3109
- probes,
3110
- bare: flag("bare"),
3111
- checks: names("checks"),
3112
- skip: names("skip"),
3113
- strict: flag("strict"),
3114
- timeout,
3115
- accept
3116
- };
3117
- }
3118
- /** Reads and parses a config file; a file that can't be read is a usage error too. */
3119
- function loadConfig(path) {
3120
- let text;
3121
- try {
3122
- text = readFileSync(path, "utf8");
3123
- } catch (error) {
3124
- throw new UsageError(`cannot read the config file ${path}: ${error instanceof Error && "code" in error && error.code === "ENOENT" ? "no such file" : error instanceof Error ? error.message : ""}`);
3125
- }
3126
- return parseConfig(text, path);
3127
- }
3128
257
  // src/cli/help.ts
3129
258
  const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
3130
259
 
@@ -3149,6 +278,11 @@ Checks:
3149
278
  if it exits 0 anyway, so the lost output looks like success,
3150
279
  crashes with a stack trace, or hangs. A careful program prints
3151
280
  the error and exits non-zero.
281
+ slow-pipe Runs the command with stdout in a file, then in a pipe nobody
282
+ reads until it exits. Warns if the end of its output is lost,
283
+ as when a Node.js program calls process.exit() while output
284
+ is still waiting for the pipe. Skips output under 64 KiB,
285
+ which a pipe holds whole.
3152
286
  color Runs the command into a pipe, then under a terminal, then under
3153
287
  a terminal with NO_COLOR=1. Fails if color codes reach a pipe;
3154
288
  warns if color goes to a piped stderr or NO_COLOR is ignored.
@@ -3237,12 +371,16 @@ current directory, so a project's run is just "npx cliprobe":
3237
371
  ]
3238
372
  }
3239
373
  "command" is the program, script included, so probes don't repeat it. Also
3240
- "bare", "checks", "skip" and "timeout", as the options. "accept" lists known
374
+ "bare", "checks", "skip" and "timeout", as the options, and "defaultProbes":
375
+ false to leave out --version and --help. "accept" lists known
3241
376
  failures and warnings: each stays in the report with its reason but no longer
3242
377
  changes the exit code; leave "probe" out to accept a check for every probe.
3243
378
  Options add to the file: --probe and --skip join its lists, --check and
3244
379
  --timeout replace its values.
3245
380
 
381
+ As a library: import { probe } from 'cliprobe' runs the same checks from a test
382
+ suite and returns the JSON report as an object; see the README.
383
+
3246
384
  Exit codes: 0 no failures, 1 a check failed (or warned, with --strict), 2 usage
3247
385
  error (or a bad config file), could not run, or could not write the report.
3248
386
  Runs the target in the current directory without a shell, with stdin closed
@@ -3250,119 +388,7 @@ Runs the target in the current directory without a shell, with stdin closed
3250
388
  temporary HOME and a minimal environment. Only run programs you trust. When a
3251
389
  probe exits, or when cliprobe is stopped, it kills whatever the probe left
3252
390
  running and removes its temporary files.`;
3253
- // src/cli/plan.ts
3254
- const same = (a, b) => a.length === b.length && a.every((word, i) => word === b[i]);
3255
- const shown = (args) => args.length ? `"${shellJoin(args)}"` : "the bare command";
3256
- /** The plan for a command given on the command line; null when there is none. */
3257
- function planFromArgs(opts) {
3258
- if (opts.command === void 0) return null;
3259
- const own = opts.bare || opts.args.length > 0;
3260
- return {
3261
- command: opts.command,
3262
- programArgs: [],
3263
- probes: [...mainProbe(opts).map((args) => ({
3264
- args,
3265
- own,
3266
- ...opts.bare ? { bare: true } : {}
3267
- })), ...opts.probes.map((args) => ({
3268
- args,
3269
- own: true
3270
- }))],
3271
- checks: opts.checks,
3272
- skip: opts.skip,
3273
- strict: opts.strict,
3274
- timeout: opts.timeout,
3275
- accept: []
3276
- };
3277
- }
3278
- /**
3279
- * The plan for a config file. The command line adds to it: its probes and skips
3280
- * join the file's, --bare and --strict switch on what the file left off, and
3281
- * --check and --timeout replace the file's.
3282
- */
3283
- function planFromConfig(config, path, opts) {
3284
- const bad = (message) => new UsageError(`${path}: ${message}`);
3285
- const [command = "", ...programArgs] = config.command;
3286
- const bare = opts.bare || config.bare;
3287
- const probes = mainProbe({
3288
- bare,
3289
- args: []
3290
- }).map((args) => ({
3291
- args,
3292
- own: bare,
3293
- ...bare ? { bare } : {}
3294
- }));
3295
- for (const args of [...config.probes, ...opts.probes]) {
3296
- if (probes.some((p) => same(p.args, args))) throw bad(`the probe ${shown(args)} is given twice, or already runs`);
3297
- probes.push({
3298
- args,
3299
- own: true
3300
- });
3301
- }
3302
- const known = new Set(CHECKS.map((c) => c.name));
3303
- for (const { check, probe } of config.accept) {
3304
- if (!known.has(check)) throw bad(`"accept" names an unknown check "${check}" (available: ${[...known].join(", ")})`);
3305
- if (probe !== void 0 && !probes.some((p) => same(p.args, probe))) {
3306
- const running = probes.map((p) => shown(p.args)).join(", ");
3307
- throw bad(`"accept" names ${shown(probe)}, which isn't a probe of this run (${running})`);
3308
- }
3309
- }
3310
- return {
3311
- command,
3312
- programArgs,
3313
- probes,
3314
- checks: opts.checks.length ? opts.checks : config.checks,
3315
- skip: [.../* @__PURE__ */ new Set([...config.skip, ...opts.skip])],
3316
- strict: opts.strict || config.strict,
3317
- timeout: opts.timeoutGiven ? opts.timeout : config.timeout ?? 15e3,
3318
- accept: config.accept,
3319
- configPath: path
3320
- };
3321
- }
3322
- /** Whether an accepted finding is this result: the same check and, when it names one, the same probe. */
3323
- const matches = (accept, r, plan) => accept.check === r.check && (accept.probe === void 0 || same(r.invocation, [
3324
- plan.command,
3325
- ...plan.programArgs,
3326
- ...accept.probe
3327
- ]));
3328
- /**
3329
- * Marks the failures and warnings the config accepts. A verdict never changes;
3330
- * an accepted result only stops counting toward the exit code.
3331
- */
3332
- function applyAccepts(results, plan) {
3333
- const used = /* @__PURE__ */ new Set();
3334
- return {
3335
- results: results.map((r) => {
3336
- if (r.verdict !== "fail" && r.verdict !== "warn") return r;
3337
- const accept = plan.accept.find((a) => matches(a, r, plan));
3338
- if (!accept) return r;
3339
- used.add(accept);
3340
- return {
3341
- ...r,
3342
- accepted: { reason: accept.reason }
3343
- };
3344
- }),
3345
- stale: plan.accept.filter((a) => {
3346
- if (used.has(a)) return false;
3347
- const own = results.filter((r) => matches(a, r, plan));
3348
- return own.length > 0 && own.every((r) => r.verdict === "pass");
3349
- })
3350
- };
3351
- }
3352
- /** How a stale accepted finding is named in the note about it. */
3353
- const describeAccept = ({ check, probe }) => probe === void 0 ? check : `${check} for ${shown(probe)}`;
3354
391
  // src/cli/program.ts
3355
- /**
3356
- * 0 no failures, 1 a check failed (or, with `strict`, warned), 2 nothing could be
3357
- * judged because something could not run. A failure or warning the config file
3358
- * accepts doesn't count.
3359
- */
3360
- function exitCodeFor(results, strict = false) {
3361
- const counts = (r) => !r.accepted && (r.verdict === "fail" || strict && r.verdict === "warn");
3362
- if (results.some(counts)) return 1;
3363
- if (!results.some((r) => r.verdict !== "error" && r.verdict !== "skip") && results.some((r) => r.verdict === "error")) return 2;
3364
- return 0;
3365
- }
3366
392
  /** The whole CLI: parses argv, runs the checks, reports, and returns the exit code. */
3367
393
  async function run(argv, io) {
3368
394
  const out = io.stdout;
@@ -3384,77 +410,27 @@ async function run(argv, io) {
3384
410
  return 0;
3385
411
  }
3386
412
  let plan;
413
+ let checks;
3387
414
  try {
3388
415
  plan = planFromArgs(opts);
3389
416
  const path = opts.config ?? (plan === null && existsSync("cliprobe.config.json") ? "cliprobe.config.json" : null);
3390
417
  if (path !== null) plan = planFromConfig(loadConfig(path), path, opts);
418
+ if (plan === null) {
419
+ err(`cliprobe: no command given, and no ${CONFIG_FILE} in this directory\nUsage: cliprobe [options] -- <command> [args...]\n`);
420
+ return 2;
421
+ }
422
+ checks = prepare(plan, io.platform);
3391
423
  } catch (error) {
3392
- if (!(error instanceof UsageError)) throw error;
424
+ if (!(error instanceof ProbeError)) throw error;
3393
425
  err(`cliprobe: ${safe(error.message)}\n`);
3394
426
  return 2;
3395
427
  }
3396
- if (plan === null) {
3397
- err(`cliprobe: no command given, and no ${CONFIG_FILE} in this directory\nUsage: cliprobe [options] -- <command> [args...]\n`);
3398
- return 2;
3399
- }
3400
- const { checks, unknown } = selectChecks(plan.checks, plan.skip);
3401
- if (unknown.length) {
3402
- const available = CHECKS.map((c) => c.name).join(", ");
3403
- err(`cliprobe: unknown check ${unknown.map((n) => `"${n}"`).join(", ")} (available: ${available})\n`);
3404
- return 2;
3405
- }
3406
- if (checks.length === 0) {
3407
- err("cliprobe: --skip leaves no check to run\n");
3408
- return 2;
3409
- }
3410
- if (io.platform === "win32") {
3411
- err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
3412
- return 2;
3413
- }
3414
- const problem = commandProblem(plan.command);
3415
- if (problem !== void 0) {
3416
- err(`cliprobe: ${safe(problem)}\n`);
3417
- return 2;
3418
- }
3419
428
  const pathProblem = opts.outputFile === void 0 ? void 0 : reportPathProblem(opts.outputFile);
3420
429
  if (pathProblem !== void 0) {
3421
430
  err(`cliprobe: cannot write the report to ${safe(opts.outputFile ?? "")}: ${safe(pathProblem)}\n`);
3422
431
  return 2;
3423
432
  }
3424
- const probes = plan.probes.map((p) => ({
3425
- ...p,
3426
- args: [...plan.programArgs, ...p.args]
3427
- }));
3428
- const fixture = probes.some((p) => usesFixture(p.args)) ? createFixture() : void 0;
3429
- const unregister = fixture && onInterrupt(() => fixture.cleanup());
3430
- const results = [];
3431
- try {
3432
- const target = {
3433
- command: plan.command,
3434
- ...plan.programArgs.length ? { programArgs: plan.programArgs } : {},
3435
- probes: fixture ? probes.map((p) => ({
3436
- ...p,
3437
- args: expandFixture(p.args, fixture.dir)
3438
- })) : probes,
3439
- ...fixture ? { fixtureDir: fixture.dir } : {}
3440
- };
3441
- const ctx = {
3442
- timeout: plan.timeout,
3443
- longRunning: /* @__PURE__ */ new Set()
3444
- };
3445
- for (const check of checks) results.push(...await check.run(target, ctx));
3446
- } finally {
3447
- unregister?.();
3448
- fixture?.cleanup();
3449
- }
3450
- const accepted = applyAccepts(fixture ? collapseResults(results, fixture) : results, plan);
3451
- const report = {
3452
- version: VERSION,
3453
- command: plan.command,
3454
- checks: checks.map((c) => c.name),
3455
- strict: plan.strict,
3456
- results: accepted.results
3457
- };
433
+ const { report, stale } = await execute(plan, checks);
3458
434
  const { color } = io;
3459
435
  if (opts.outputFile) {
3460
436
  let failure;
@@ -3469,7 +445,7 @@ async function run(argv, io) {
3469
445
  return 2;
3470
446
  }
3471
447
  } else out(FORMATS[opts.format](report, { color }));
3472
- for (const stale of accepted.stale) err(`cliprobe: ${safe(plan.configPath ?? "cliprobe.config.json")} accepts ${safe(describeAccept(stale))}, which passed: remove it from "accept"\n`);
448
+ for (const accept of stale) err(`cliprobe: ${safe(plan.configPath ?? "cliprobe.config.json")} accepts ${safe(describeAccept(accept))}, which passed: remove it from "accept"\n`);
3473
449
  return exitCodeFor(report.results, plan.strict);
3474
450
  }
3475
451
  // src/cli/main.ts