cliprobe 1.4.1 → 1.4.3

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.
Files changed (3) hide show
  1. package/README.md +54 -30
  2. package/dist/cli.js +244 -57
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -31,7 +31,7 @@ npx cliprobe -- tsx
31
31
  ```
32
32
 
33
33
  ```
34
- cliprobe 1.2.0: closed-pipe, color, pipe-escapes, stdin, ctrl-c, sigterm, restore, control-chars checks for tsx
34
+ cliprobe 1.4.3: closed-pipe, color, pipe-escapes, stdin, ctrl-c, sigterm, restore, control-chars checks for tsx
35
35
 
36
36
  closed-pipe
37
37
  FAIL tsx --version crashed when stdout was closed (exit 0 -> 1)
@@ -101,7 +101,9 @@ The other checks cover the rest of what goes wrong between a program and the thi
101
101
 
102
102
  ## Installation
103
103
 
104
- Requires Node.js 22.12 or later, on macOS or Linux (including Alpine). Windows isn't supported yet. Run it without installing:
104
+ Requires Node.js 22.12 or later, on macOS or Linux (including Alpine). Windows isn't supported yet. The terminal checks (color, restore and control-chars) also need the system's `script` command, which macOS has and most Linux distributions install by default. Without it they're skipped, and each skip says so. If it's missing, install the package that has it: `bsdutils` on Debian and Ubuntu, `util-linux-script` on Fedora, `util-linux-misc` on Alpine.
105
+
106
+ Run it without installing:
105
107
 
106
108
  ```sh
107
109
  npx cliprobe -- <command>
@@ -128,29 +130,33 @@ npx cliprobe --check startup,baseline -- node ./dist/cli.js # info checks, onl
128
130
  npx cliprobe --strict --skip restore -- node ./dist/cli.js server # warnings fail too, except restore's
129
131
  ```
130
132
 
131
- | Option | Meaning |
132
- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
133
- | `--bare` | Probe the command with no arguments instead of `--version` and `--help`, as a probe you wrote |
134
- | `--probe <args>` | Also probe `<command> <args>`; repeat it for several. Split like a shell command line (quotes and backslashes, no variables or wildcards) |
135
- | `--check <name>` | Run only this check; repeat it or use commas for several |
136
- | `--skip <name>` | Leave this check out; repeat it or use commas for several |
137
- | `--strict` | Exit 1 on a warning too, not only on a failure |
138
- | `--format <name>` | Output format: `human` (default), `json`, `markdown` (a GitHub job summary or PR comment) or `junit` (XML for CI test reports) |
139
- | `--json` | Same as `--format json` |
140
- | `-o`, `--output-file <path>` | Write the `--format` report to a file (atomically, creating parent folders); the human report still prints |
141
- | `--timeout <ms>` | Kill a probe after this long (default 15000); a command still running then is judged on what it did so far |
142
- | `-h`, `--help` | Show help |
143
- | `-v`, `--version` | Show the version |
133
+ | Option | Meaning |
134
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
135
+ | `--bare` | Probe the command with no arguments instead of `--version` and `--help`, as a probe you wrote |
136
+ | `--probe <args>` | Also probe `<command> <args>`; repeat it for several. Split like a shell command line (quotes and backslashes, no variables or wildcards). The args after `<command>` aren't kept: with `-- node ./cli.js`, write `--probe "./cli.js watch"` |
137
+ | `--check <name>` | Run only this check; repeat it or use commas for several |
138
+ | `--skip <name>` | Leave this check out; repeat it or use commas for several |
139
+ | `--strict` | Exit 1 on a warning too, not only on a failure |
140
+ | `--format <name>` | Output format: `human` (default), `json`, `markdown` (a GitHub job summary or PR comment) or `junit` (XML for CI test reports) |
141
+ | `--json` | Same as `--format json` |
142
+ | `-o`, `--output-file <path>` | Write the `--format` report to a file (replaced atomically, keeping its mode and following symlinks, with parent folders created; a FIFO, `/dev/stdout` or `/dev/fd/N` is written in place); the human report still prints. For a path that starts with `-`, write `-o=<path>` or `./<path>` |
143
+ | `--timeout <ms>` | Kill a probe after this long (default 15000, at most 2147483647, about 24 days); a command still running then is judged on what it did so far |
144
+ | `-h`, `--help` | Show help |
145
+ | `-v`, `--version` | Show the version |
146
+
147
+ An option's value follows it or comes after `=` (`--format=json`). A value that is another option, as in `-o --strict`, is a usage error rather than a file named `--strict`. `--probe` is the exception: its value may start with `-`, to probe a flag (`--probe --json`).
148
+
149
+ A probe runs `<command>` with its own args, in place of the args after the command, not after them. So when the command is an interpreter, name the script in every probe: `npx cliprobe --probe "./dist/cli.js watch" -- node ./dist/cli.js` probes `node ./dist/cli.js` and `node ./dist/cli.js watch`, while `--probe watch` would run `node watch`. A probe that exits with a failure code and is skipped says so in its reason, with the error line from stderr as evidence, so a probe that never ran as intended doesn't pass for a quiet skip.
144
150
 
145
151
  ## Exit codes
146
152
 
147
- | Code | Meaning |
148
- | ---- | ----------------------------------------- |
149
- | `0` | No check failed |
150
- | `1` | A check failed, or warned with `--strict` |
151
- | `2` | Usage error, or the command could not run |
153
+ | Code | Meaning |
154
+ | ---- | ------------------------------------------------------------------------------------------ |
155
+ | `0` | No check failed |
156
+ | `1` | A check failed, or warned with `--strict` |
157
+ | `2` | Usage error, the command could not run, or the `--output-file` report could not be written |
152
158
 
153
- A command that can't run is reported once, before any check runs, with exit `2` and no report: one that isn't on `PATH`, a directory, a file without the execute bit (`chmod +x`), or a script whose `#!` interpreter is missing. A file this system can't execute at all, such as a binary built for another platform, makes every check say could-not-run (`ERROR`), so cliprobe exits `2` there too; on Linux, where `/bin/sh` tries such a file as a script, cliprobe recognizes the shell's complaint. That makes cliprobe usable as a CI gate.
159
+ A command that can't run is reported once, before any check runs, with exit `2` and no report: one that isn't on `PATH`, a directory, a file without the execute bit (`chmod +x`), or a script whose `#!` interpreter is missing. A file this system can't execute at all, such as a binary built for another platform, makes every check say could-not-run (`ERROR`), so cliprobe exits `2` there too; on Linux, where `/bin/sh` tries such a file as a script, cliprobe recognizes the shell's complaint. An `--output-file` path that can't be written, such as a directory or a folder without write permission, is also reported before any check runs, with exit `2`. If the file still can't be written at the end, cliprobe prints the human report first, so no result is lost, then the error, and exits `2` even when a check failed: CI fails the step either way. That makes cliprobe usable as a CI gate.
154
160
 
155
161
  ## In CI
156
162
 
@@ -246,12 +252,12 @@ Servers and watchers crash the same way. Among 38 watch and serve modes of popul
246
252
 
247
253
  cliprobe runs the command up to three times: into a pipe, under a real terminal (a pseudo-terminal through the system's `script` command, 80×24), and under a terminal with `NO_COLOR=1`. Every run gets `TERM=xterm-256color` and no `CI` variable, so a program can't pass just because the terminal type looks colorless, and color libraries that force color in CI don't fail it. Color codes in piped output end up in log files and agent transcripts as `\x1b[31m` noise. Results:
248
254
 
249
- | Verdict | Meaning |
250
- | ------- | -------------------------------------------------------------------------------------------------------------- |
251
- | `PASS` | No color in a pipe; in a terminal, either no color at all or color that `NO_COLOR` turns off |
252
- | `FAIL` | Printed color or style codes (bold counts, a bare reset doesn't) to stdout in a pipe |
253
- | `WARN` | Printed color to stderr in a pipe, or kept printing color under `NO_COLOR` |
254
- | `SKIP` | Printed nothing, waited for input in a terminal, or no `script` command (on Alpine, install `util-linux-misc`) |
255
+ | Verdict | Meaning |
256
+ | ------- | ----------------------------------------------------------------------------------------------------------- |
257
+ | `PASS` | No color in a pipe; in a terminal, either no color at all or color that `NO_COLOR` turns off |
258
+ | `FAIL` | Printed color or style codes (bold counts, a bare reset doesn't) to stdout in a pipe |
259
+ | `WARN` | Printed color to stderr in a pipe, or kept printing color under `NO_COLOR` |
260
+ | `SKIP` | Printed nothing, waited for input in a terminal, or no `script` command (see [Installation](#installation)) |
255
261
 
256
262
  Many classic tools (git, BSD `ls` and `grep`) color correctly but don't implement [`NO_COLOR`](https://no-color.org), so they get a `WARN`, never a `FAIL`. Probe a command that prints color in normal use: almost no CLI colors its `--help`.
257
263
 
@@ -433,15 +439,33 @@ Then ask in your own words, for example "check my CLI for pipe and Ctrl-C bugs b
433
439
 
434
440
  ## Safety
435
441
 
436
- cliprobe runs the target in your current directory without a shell, with stdin closed (`/dev/null`; the stdin, ctrl-c and sigterm checks use a pipe that they never write to), a temporary `HOME`, and a minimal environment (no tokens from your shell). It still executes the program, so only probe programs you trust. By default cliprobe passes only the arguments you give, after the command or with `--probe`, or `--version` and `--help`, or none with `--bare`; only the baseline check, when you name it, adds an unknown flag. The only input it ever sends is Ctrl-C, from the ctrl-c and restore checks, and SIGTERM, from the sigterm check, to probes you write. It kills each run's whole process group on timeout, including under a pseudo-terminal, and when a program exits it kills whatever it left running, in its group or started in another one, in every check. If cliprobe itself is stopped by Ctrl-C, SIGTERM or SIGHUP, it first kills the probe it is running and removes its temporary directories, then exits by the same signal (130, 143 or 129). It runs on macOS and Linux, including Alpine; the terminal checks need the `script` command, which Alpine ships in `util-linux-misc`. Windows isn't supported yet.
442
+ cliprobe runs the target in your current directory without a shell, with stdin closed (`/dev/null`; the stdin, ctrl-c and sigterm checks use a pipe that they never write to), a temporary `HOME`, and a minimal environment (no tokens from your shell; see [the probe's environment](#the-probes-environment)). It still executes the program, so only probe programs you trust. By default cliprobe passes only the arguments you give, after the command or with `--probe`, or `--version` and `--help`, or none with `--bare`; only the baseline check, when you name it, adds an unknown flag. The only input it ever sends is Ctrl-C, from the ctrl-c and restore checks, and SIGTERM, from the sigterm check, to probes you write. It kills each run's whole process group on timeout, including under a pseudo-terminal, and when a program exits it kills whatever it left running, in its group or started in another one, in every check. If cliprobe itself is stopped by Ctrl-C, SIGTERM or SIGHUP, it first kills the probe it is running and removes its temporary directories and any half-written report file, then exits by the same signal (130, 143 or 129). It runs on macOS and Linux, including Alpine; the terminal checks need the `script` command (see [Installation](#installation)). Windows isn't supported yet.
443
+
444
+ ### The probe's environment
445
+
446
+ A probe gets only these variables. Nothing else from your shell reaches it, not even `LC_ALL` or the other `LC_*` variables, so only `LANG` sets the locale:
447
+
448
+ | Variable | Value |
449
+ | -------------------- | --------------------------------------------------------------------------------------------------------- |
450
+ | `PATH` | Yours |
451
+ | `LANG` | Yours, or `C.UTF-8` if you have none |
452
+ | `HOME`, `TMPDIR` | A new temporary directory for each run, removed afterwards |
453
+ | `TERM` | `dumb`; `xterm-256color` in color, pipe-escapes and control-chars, and in every run under a terminal |
454
+ | `CI` | `1`; unset in color, pipe-escapes and control-chars, so color libraries that force color in CI don't fail |
455
+ | `NO_UPDATE_NOTIFIER` | `1`, so update checks stay quiet |
456
+ | `NO_COLOR` | `1` in the color check's last run only |
457
+ | `SHELL` | `/bin/sh` in runs under a terminal, which `script` needs |
458
+ | `SCRIPT` | `/dev/null` in runs under a terminal on macOS, set by `script` itself |
459
+
460
+ The runs under a terminal are color's second and third, restore's, and control-chars'.
437
461
 
438
462
  ## FAQ
439
463
 
440
- **Why were ctrl-c, sigterm and control-chars skipped?** They need probes that a plain `--version` and `--help` run doesn't have: ctrl-c and sigterm need a command that keeps running, such as a server or a watcher, and control-chars needs one that prints file names from `{fixture}`. Add them with `--probe`, so one run covers every check: `npx cliprobe --probe "serve --port 0" --probe "list {fixture}" -- my-cli`.
464
+ **Why were ctrl-c, sigterm and control-chars skipped?** They need probes that a plain `--version` and `--help` run doesn't have: ctrl-c and sigterm need a command that keeps running, such as a server or a watcher, and control-chars needs one that prints file names from `{fixture}`. Add them with `--probe`, so one run covers every check: `npx cliprobe --probe "serve --port 0" --probe "list {fixture}" -- my-cli`. If the reason adds that the probe exited with a failure code, it never ran as intended: check its arguments, and with `-- node ./cli.js`, name the script in the probe (`--probe "./cli.js serve"`).
441
465
 
442
466
  **My program works when I run it, so why does a check fail?** cliprobe sets up conditions that are rare by hand: stdout closed before the program starts, output into a pipe, stdin that nobody writes to, a minimal environment. Reproduce the failure the way the check's section shows, for example `my-cli --help | head -n 1` for closed-pipe or `my-cli --help | cat -v` for color, and read the evidence in `--json`. If you still believe the verdict is wrong, [open a wrong verdict issue](https://github.com/KhaledSaeed18/cliprobe/issues/new?template=wrong_verdict.yml).
443
467
 
444
- **Why does my program behave differently under cliprobe?** It runs without your shell's variables or your home directory: the environment has only `PATH`, `LANG`, `TERM`, `CI` and a temporary `HOME` and `TMPDIR`. A program that needs a token or a config file from your home directory sees neither, as on a fresh CI runner.
468
+ **Why does my program behave differently under cliprobe?** It runs without your shell's variables or your home directory, with `TERM=dumb` and `CI=1` in most checks: [the probe's environment](#the-probes-environment) lists every variable. A program that needs a token or a config file from your home directory sees neither, as on a fresh CI runner.
445
469
 
446
470
  **Does a pass mean my CLI has no terminal bugs?** No. Each check tests one behavior, on the probes that ran; a subcommand that wasn't probed wasn't checked. cliprobe reports evidence, not a score, so add a `--probe` for each command your users pipe or interrupt.
447
471
 
package/dist/cli.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { execFile, execFileSync, spawn } from "node:child_process";
4
- import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
- import { delimiter, dirname, join } from "node:path";
4
+ import { accessSync, closeSync, constants, 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
6
  import { tmpdir } from "node:os";
7
+ import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises";
7
8
  // src/core/interrupt.ts
8
9
  const cleanups = /* @__PURE__ */ new Set();
9
10
  /** Registers `cleanup` until the returned function is called. */
@@ -325,6 +326,11 @@ function shellFallbackError(command, exitCode, stderr, path = process.env["PATH"
325
326
  // src/core/run.ts
326
327
  const STDERR_CAP = 65536;
327
328
  const STDOUT_CAP = 1048576;
329
+ /**
330
+ * The longest delay setTimeout takes (2^31 - 1 ms, about 24.8 days). Node turns
331
+ * anything longer into 1 ms, which would kill every probe at once.
332
+ */
333
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
328
334
  /** How often the process table is read while the program runs, to learn its descendants. */
329
335
  const TREE_POLL_MS = 200;
330
336
  /** How long to wait for the output pipes to close once everything the run started is gone. */
@@ -446,7 +452,7 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
446
452
  timedOut = true;
447
453
  recordTree();
448
454
  killRun();
449
- }, timeout);
455
+ }, Math.min(timeout, MAX_TIMEOUT_MS));
450
456
  const signalTimer = signal && setTimeout(() => {
451
457
  if (exited || proc.pid === void 0) return;
452
458
  recordTree();
@@ -661,6 +667,20 @@ function crashEvidence(stderr, messages = CRASH_MESSAGES) {
661
667
  const cwd = process.cwd() + "/";
662
668
  return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
663
669
  }
670
+ /**
671
+ * Adds to a SKIP that a probe exited with a failure code, so a probe that never ran
672
+ * as intended (a typo, `--probe watch` running `node watch`) doesn't pass for a quiet
673
+ * skip. The evidence is the error line from stderr, when there is one.
674
+ */
675
+ function noteFailedExit(judgement, r) {
676
+ if (judgement.verdict !== "skip" || r.exitCode === null || r.exitCode === 0) return judgement;
677
+ const message = crashEvidence(r.stderr);
678
+ return {
679
+ ...judgement,
680
+ reason: `${judgement.reason}; it exited ${r.exitCode}, so the probe may not have run as intended`,
681
+ ...message && judgement.evidence === void 0 ? { evidence: `stderr: ${message}` } : {}
682
+ };
683
+ }
664
684
  // src/core/long-running.ts
665
685
  /**
666
686
  * Once one check has seen a probe still running at the timeout (a server, a
@@ -723,10 +743,10 @@ function judge(base, closed) {
723
743
  reason: `could not start: ${base.spawnError}`
724
744
  };
725
745
  if (base.timedOut) return judgeLongRunning(base, closed);
726
- if (base.stdoutBytes === 0) return {
746
+ if (base.stdoutBytes === 0) return noteFailedExit({
727
747
  verdict: "skip",
728
748
  reason: "wrote nothing to stdout, so a closed stdout is never touched"
729
- };
749
+ }, base);
730
750
  if (closed.timedOut) return {
731
751
  verdict: "fail",
732
752
  reason: "hung after stdout was closed"
@@ -1019,7 +1039,7 @@ function detect() {
1019
1039
  } catch (error) {
1020
1040
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
1021
1041
  ok: false,
1022
- reason: "script(1) not found; install util-linux (Debian and Ubuntu: bsdutils; Alpine: util-linux-misc)"
1042
+ reason: "script(1) not found; install the package that has it (Debian and Ubuntu: bsdutils; Fedora: util-linux-script; Alpine: util-linux-misc)"
1023
1043
  };
1024
1044
  }
1025
1045
  return {
@@ -1228,10 +1248,10 @@ function judgeColor(runs) {
1228
1248
  reason: "no color in a pipe; in a terminal it waited for input, so it was not compared"
1229
1249
  };
1230
1250
  if (!findStyle(tty.output)) {
1231
- if (!(runs.pipe.stdoutBytes > 0 || runs.pipe.stderr.length > 0 || tty.output)) return {
1251
+ if (!(runs.pipe.stdoutBytes > 0 || runs.pipe.stderr.length > 0 || tty.output)) return noteFailedExit({
1232
1252
  verdict: "skip",
1233
1253
  reason: "printed nothing, so there is no color to check"
1234
- };
1254
+ }, runs.pipe);
1235
1255
  return {
1236
1256
  verdict: "pass",
1237
1257
  reason: "no color in a pipe or in a terminal"
@@ -1466,10 +1486,13 @@ function judgeControlChars(runs) {
1466
1486
  verdict: "skip",
1467
1487
  reason: "still running in a terminal at the timeout, and had not printed the file names in {fixture}"
1468
1488
  };
1469
- if (!tty.output.includes("plain.txt")) return {
1470
- verdict: "skip",
1471
- reason: "did not print the file names in {fixture}, so there was nothing to escape"
1472
- };
1489
+ if (!tty.output.includes("plain.txt")) {
1490
+ const skip = {
1491
+ verdict: "skip",
1492
+ reason: "did not print the file names in {fixture}, so there was nothing to escape"
1493
+ };
1494
+ return pipe ? noteFailedExit(skip, pipe) : skip;
1495
+ }
1473
1496
  const raw = rawNames(tty.output);
1474
1497
  const failing = raw.filter((h) => h.severity === "fail");
1475
1498
  if (failing.length) return {
@@ -1570,10 +1593,10 @@ function judgeSigterm(r) {
1570
1593
  verdict: "error",
1571
1594
  reason: `could not start: ${r.spawnError}`
1572
1595
  };
1573
- if (r.signalSentMs === void 0) return {
1596
+ if (r.signalSentMs === void 0) return noteFailedExit({
1574
1597
  verdict: "skip",
1575
1598
  reason: `finished in ${r.durationMs} ms, before SIGTERM at ${SIGTERM_DELAY_MS} ms; probe a command that keeps running`
1576
- };
1599
+ }, r);
1577
1600
  if (r.timedOut) return {
1578
1601
  verdict: "warn",
1579
1602
  reason: `ignored SIGTERM: still running ${SIGTERM_GRACE_MS / 1e3} s later, so docker stop or a process manager has to kill it`
@@ -1660,10 +1683,10 @@ function judgeCtrlC(r) {
1660
1683
  verdict: "error",
1661
1684
  reason: `could not start: ${r.spawnError}`
1662
1685
  };
1663
- if (r.signalSentMs === void 0) return {
1686
+ if (r.signalSentMs === void 0) return noteFailedExit({
1664
1687
  verdict: "skip",
1665
1688
  reason: `finished in ${r.durationMs} ms, before Ctrl-C at ${CTRL_C_DELAY_MS} ms; probe a command that keeps running`
1666
- };
1689
+ }, r);
1667
1690
  if (r.timedOut) return {
1668
1691
  verdict: "fail",
1669
1692
  reason: `ignored Ctrl-C: still running ${CTRL_C_GRACE_MS / 1e3} s later`
@@ -1789,10 +1812,10 @@ function judgePipeEscapes(r) {
1789
1812
  if (!stdout && !r.stderr) return r.timedOut ? {
1790
1813
  verdict: "skip",
1791
1814
  reason: `${stillRunning(r.durationMs)} and printed nothing so far`
1792
- } : {
1815
+ } : noteFailedExit({
1793
1816
  verdict: "skip",
1794
1817
  reason: "printed nothing, so there is nothing to check"
1795
- };
1818
+ }, r);
1796
1819
  if (r.timedOut) return {
1797
1820
  verdict: "pass",
1798
1821
  reason: `no cursor, erase, hyperlink, title or redraw codes in a pipe (${stillRunning(r.durationMs)})`
@@ -2423,20 +2446,144 @@ const FORMATS = {
2423
2446
  junit: formatJunit
2424
2447
  };
2425
2448
  // src/report/write.ts
2449
+ /** Why a report can't be written to a path, in words for the person who gave it. */
2450
+ var ReportPathError = class extends Error {};
2451
+ const allowed = (path, mode) => {
2452
+ try {
2453
+ accessSync(path, mode);
2454
+ return true;
2455
+ } catch {
2456
+ return false;
2457
+ }
2458
+ };
2459
+ /** The errno code of a failed file system call, such as ENOENT. */
2460
+ const errorCode = (error) => error instanceof Error && "code" in error ? error.code : void 0;
2461
+ /** A folder in which cliprobe may create and rename files. */
2462
+ const writableFolder = (path) => allowed(path, constants.W_OK | constants.X_OK);
2463
+ /** stat() that follows symlinks, undefined for a path that doesn't exist (or runs through a file). */
2464
+ function statPath(path) {
2465
+ try {
2466
+ return statSync(path);
2467
+ } catch (error) {
2468
+ const code = errorCode(error);
2469
+ if (code === "ENOENT" || code === "ENOTDIR") return void 0;
2470
+ throw new ReportPathError(describeWriteError(error));
2471
+ }
2472
+ }
2473
+ /** A symlink's final target, followed even when that target doesn't exist yet. */
2474
+ function followLinks(path) {
2475
+ let current = resolve(path);
2476
+ for (let hops = 0; hops < 40; hops++) {
2477
+ let st;
2478
+ try {
2479
+ st = lstatSync(current);
2480
+ } catch {
2481
+ return current;
2482
+ }
2483
+ if (!st.isSymbolicLink()) return current;
2484
+ current = resolve(dirname(current), readlinkSync(current));
2485
+ }
2486
+ throw new ReportPathError("too many levels of symbolic links");
2487
+ }
2488
+ /**
2489
+ * Decides how to write a report to `path`, or throws a ReportPathError that says
2490
+ * why it can't be written. It changes nothing on disk, so the same rule serves
2491
+ * the check before any probe runs and the write at the end.
2492
+ */
2493
+ function reportTarget(path) {
2494
+ const st = statPath(path);
2495
+ if (st?.isDirectory()) throw new ReportPathError("is a directory");
2496
+ if (st && (!st.isFile() || /^\/(dev|proc)\//.test(resolve(path)))) return {
2497
+ how: "direct",
2498
+ path
2499
+ };
2500
+ if (st) {
2501
+ const real = realpathSync(path);
2502
+ const mode = st.mode & 4095;
2503
+ if (writableFolder(dirname(real))) return {
2504
+ how: "replace",
2505
+ path: real,
2506
+ mode
2507
+ };
2508
+ if (allowed(real, constants.W_OK)) return {
2509
+ how: "direct",
2510
+ path: real
2511
+ };
2512
+ throw new ReportPathError("permission denied");
2513
+ }
2514
+ if (path.endsWith(sep) || path.endsWith(`${sep}.`)) throw new ReportPathError("names a folder, not a file");
2515
+ const target = followLinks(path);
2516
+ let ancestor = dirname(target);
2517
+ let ancestorStat = statPath(ancestor);
2518
+ while (!ancestorStat && dirname(ancestor) !== ancestor) {
2519
+ ancestor = dirname(ancestor);
2520
+ ancestorStat = statPath(ancestor);
2521
+ }
2522
+ if (!ancestorStat?.isDirectory()) throw new ReportPathError(`${ancestor} is not a folder`);
2523
+ if (!writableFolder(ancestor)) throw new ReportPathError("permission denied");
2524
+ return {
2525
+ how: "replace",
2526
+ path: target,
2527
+ mode: void 0
2528
+ };
2529
+ }
2530
+ /**
2531
+ * A failed write in words, without the file name that a raw error ends with, which
2532
+ * may be the temporary file's: "ENOSPC: no space left on device".
2533
+ */
2534
+ function describeWriteError(error) {
2535
+ if (error instanceof ReportPathError) return error.message;
2536
+ const code = errorCode(error);
2537
+ if (code === "ELOOP") return "too many levels of symbolic links";
2538
+ if (code === "EACCES" || code === "EPERM") return "permission denied";
2539
+ return (error instanceof Error ? error.message : String(error)).replace(/, \w+ '.*$/s, "");
2540
+ }
2426
2541
  /**
2427
- * Writes a report so that nothing ever sees half of it: a temporary file in the
2428
- * same directory, then a rename, which is atomic on one file system. Missing
2429
- * parent directories are created. Throws on failure, leaving no temporary file.
2542
+ * Checks `path` the way writeReportFile will write it, and returns why it can't
2543
+ * be written, or undefined when it can.
2430
2544
  */
2431
- function writeReportFile(path, text) {
2432
- mkdirSync(dirname(path), { recursive: true });
2433
- const temp = `${path}.cliprobe-${process.pid}.tmp`;
2545
+ function reportPathProblem(path) {
2434
2546
  try {
2435
- writeFileSync(temp, text);
2436
- renameSync(temp, path);
2547
+ reportTarget(path);
2548
+ return;
2437
2549
  } catch (error) {
2438
- rmSync(temp, { force: true });
2439
- throw error;
2550
+ return describeWriteError(error);
2551
+ }
2552
+ }
2553
+ /**
2554
+ * Writes a report to `path` as reportTarget decides: a regular file is replaced
2555
+ * whole (missing parent folders are created), anything else is written in
2556
+ * place. Asynchronous, so that waiting for a FIFO's reader leaves the event
2557
+ * loop, and the signal handlers, running. Throws an Error that says why on failure, leaving no
2558
+ * temporary file, even if cliprobe is interrupted meanwhile.
2559
+ */
2560
+ async function writeReportFile(path, text) {
2561
+ let target;
2562
+ try {
2563
+ target = reportTarget(path);
2564
+ } catch (error) {
2565
+ throw new Error(describeWriteError(error), { cause: error });
2566
+ }
2567
+ if (target.how === "direct") {
2568
+ try {
2569
+ await writeFile(target.path, text);
2570
+ } catch (error) {
2571
+ throw new Error(describeWriteError(error), { cause: error });
2572
+ }
2573
+ return;
2574
+ }
2575
+ const temp = `${target.path}.cliprobe-${process.pid}.tmp`;
2576
+ const unregister = onInterrupt(() => rmSync(temp, { force: true }));
2577
+ try {
2578
+ await mkdir(dirname(target.path), { recursive: true });
2579
+ await writeFile(temp, text);
2580
+ if (target.mode !== void 0) await chmod(temp, target.mode);
2581
+ await rename(temp, target.path);
2582
+ } catch (error) {
2583
+ await rm(temp, { force: true }).catch(() => void 0);
2584
+ throw new Error(describeWriteError(error), { cause: error });
2585
+ } finally {
2586
+ unregister();
2440
2587
  }
2441
2588
  }
2442
2589
  // src/version.ts
@@ -2452,6 +2599,27 @@ function readVersion() {
2452
2599
  const VERSION = readVersion();
2453
2600
  // src/cli/args.ts
2454
2601
  var UsageError = class extends Error {};
2602
+ /** Every option cliprobe takes, to tell a forgotten value from a value that starts with -. */
2603
+ const OPTIONS = /* @__PURE__ */ new Set([
2604
+ "--json",
2605
+ "--bare",
2606
+ "--strict",
2607
+ "-o",
2608
+ "--output-file",
2609
+ "--format",
2610
+ "-h",
2611
+ "--help",
2612
+ "-v",
2613
+ "--version",
2614
+ "--timeout",
2615
+ "--probe",
2616
+ "--check",
2617
+ "--skip"
2618
+ ]);
2619
+ /** Options whose value is a path, which ./ can make start with something other than -. */
2620
+ const PATH_OPTIONS = /* @__PURE__ */ new Set(["-o", "--output-file"]);
2621
+ /** The option name in an argument such as --format=json. */
2622
+ const flagOf = (arg) => arg.split("=")[0] ?? arg;
2455
2623
  function parseArgs(argv) {
2456
2624
  const opts = {
2457
2625
  format: "human",
@@ -2473,37 +2641,43 @@ function parseArgs(argv) {
2473
2641
  [opts.command, ...opts.args] = argv.slice(i + 1);
2474
2642
  break;
2475
2643
  }
2644
+ /** The value of the option `a`: after its `=`, or the next argument, which must not be another option. */
2645
+ const value = (what) => {
2646
+ const flag = flagOf(a);
2647
+ const inline = a.includes("=");
2648
+ const v = inline ? a.slice(a.indexOf("=") + 1) : argv[++i];
2649
+ if (v === void 0 || v === "") throw new UsageError(`${flag} needs ${what}`);
2650
+ 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 -` : ""}`);
2651
+ return v;
2652
+ };
2476
2653
  if (a === "--json") opts.format = "json";
2477
2654
  else if (a === "--bare") opts.bare = true;
2478
2655
  else if (a === "--strict") opts.strict = true;
2479
- else if (a === "-o" || a === "--output-file" || a.startsWith("--output-file=")) {
2480
- const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
2481
- if (!value) throw new UsageError(`${a.split("=")[0] ?? a} needs a file path`);
2482
- opts.outputFile = value;
2483
- } else if (a === "--format" || a.startsWith("--format=")) {
2484
- const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
2485
- if (value === void 0 || !isFormat(value)) throw new UsageError(`--format needs one of ${FORMAT_NAMES.join(", ")}, got "${String(value)}"`);
2486
- opts.format = value;
2656
+ else if (/^(-o|--output-file)(=|$)/.test(a)) opts.outputFile = value("a file path");
2657
+ else if (/^--format(=|$)/.test(a)) {
2658
+ const format = value(`a value (one of ${FORMAT_NAMES.join(", ")})`);
2659
+ if (!isFormat(format)) throw new UsageError(`--format needs one of ${FORMAT_NAMES.join(", ")}, got "${format}"`);
2660
+ opts.format = format;
2487
2661
  } else if (a === "-h" || a === "--help") opts.help = true;
2488
2662
  else if (a === "-v" || a === "--version") opts.version = true;
2489
- else if (a === "--timeout" || a.startsWith("--timeout=")) {
2490
- const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
2491
- opts.timeout = Number(value);
2492
- if (!Number.isInteger(opts.timeout) || opts.timeout <= 0) throw new UsageError(`--timeout needs a positive whole number of milliseconds, got "${String(value)}"`);
2663
+ else if (/^--timeout(=|$)/.test(a)) {
2664
+ const ms = value("a value");
2665
+ opts.timeout = Number(ms);
2666
+ if (!Number.isInteger(opts.timeout) || opts.timeout <= 0 || opts.timeout > MAX_TIMEOUT_MS) throw new UsageError(`--timeout needs a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS} (about 24 days), got "${ms}"`);
2493
2667
  } else if (a === "--probe" || a.startsWith("--probe=")) {
2494
- const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
2495
- if (value === void 0) throw new UsageError("--probe needs the arguments to probe");
2668
+ const probe = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
2669
+ if (probe === void 0) throw new UsageError("--probe needs the arguments to probe");
2496
2670
  let words;
2497
2671
  try {
2498
- words = shellSplit(value);
2672
+ words = shellSplit(probe);
2499
2673
  } catch (error) {
2500
- throw new UsageError(`--probe ${shellJoin([value])} ${error instanceof Error ? error.message : String(error)}`);
2674
+ throw new UsageError(`--probe ${shellJoin([probe])} ${error instanceof Error ? error.message : String(error)}`);
2501
2675
  }
2502
2676
  if (words.length === 0) throw new UsageError("--probe needs the arguments to probe; use --bare for none");
2503
2677
  opts.probes.push(words);
2504
2678
  } else if (/^--(check|skip)(=|$)/.test(a)) {
2505
- const flag = a.split("=")[0] ?? a;
2506
- const names = ((a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i]) ?? "").split(",").map((n) => n.trim()).filter(Boolean);
2679
+ const flag = flagOf(a);
2680
+ const names = value("a check name").split(",").map((n) => n.trim()).filter(Boolean);
2507
2681
  if (names.length === 0) throw new UsageError(`${flag} needs a check name`);
2508
2682
  (flag === "--skip" ? opts.skip : opts.checks).push(...names);
2509
2683
  } else if (a.startsWith("-")) throw new UsageError(`unknown option "${a}"`);
@@ -2591,7 +2765,9 @@ Options:
2591
2765
  program, a server) instead of --version and --help
2592
2766
  --probe <args> Also probe "<command> <args>"; repeat it for several. Split
2593
2767
  like a shell command line: quotes and backslashes work,
2594
- variables and wildcards are not expanded
2768
+ variables and wildcards are not expanded. The args after
2769
+ <command> are not kept, so name the script in each probe:
2770
+ cliprobe --probe "./cli.js watch" -- node ./cli.js
2595
2771
  --check <name> Run only this check; repeat it or use commas for several
2596
2772
  --skip <name> Leave this check out; repeat it or use commas for several
2597
2773
  --strict Exit 1 on a warning too, not only on a failure
@@ -2599,16 +2775,19 @@ Options:
2599
2775
  summary or PR comment) or junit (XML for CI test reports)
2600
2776
  --json Same as --format json
2601
2777
  -o, --output-file <path>
2602
- Write the --format report to a file (created atomically,
2603
- with parent folders); the human report still prints
2604
- --timeout <ms> Kill a probe after this long (default 15000). A command
2605
- still running then (a server, a watcher) is judged on
2606
- what it did so far, and later checks watch it for 3 s
2778
+ Write the --format report to a file (replaced atomically,
2779
+ keeping its mode, with parent folders created; a FIFO or
2780
+ /dev/stdout is written in place); the human report still
2781
+ prints. For a path that starts with -, use -o=<path>
2782
+ --timeout <ms> Kill a probe after this long (default 15000, at most
2783
+ 2147483647, about 24 days). A command still running then
2784
+ (a server, a watcher) is judged on what it did so far,
2785
+ and later checks watch it for 3 s
2607
2786
  -h, --help Show this help
2608
2787
  -v, --version Show the version
2609
2788
 
2610
2789
  Exit codes: 0 no failures, 1 a check failed (or warned, with --strict), 2 usage
2611
- error or could not run.
2790
+ error, could not run, or could not write the --output-file report.
2612
2791
  Runs the target in the current directory without a shell, with stdin closed
2613
2792
  (the stdin, ctrl-c and sigterm checks use a pipe they never write to), a
2614
2793
  temporary HOME and a minimal environment. Only run programs you trust. When a
@@ -2667,6 +2846,11 @@ async function run(argv, io) {
2667
2846
  err(`cliprobe: ${safe(problem)}\n`);
2668
2847
  return 2;
2669
2848
  }
2849
+ const pathProblem = opts.outputFile === void 0 ? void 0 : reportPathProblem(opts.outputFile);
2850
+ if (pathProblem !== void 0) {
2851
+ err(`cliprobe: cannot write the report to ${safe(opts.outputFile ?? "")}: ${safe(pathProblem)}\n`);
2852
+ return 2;
2853
+ }
2670
2854
  const own = opts.bare || opts.args.length > 0;
2671
2855
  const probes = [...mainProbe(opts).map((args) => ({
2672
2856
  args,
@@ -2705,14 +2889,17 @@ async function run(argv, io) {
2705
2889
  };
2706
2890
  const { color } = io;
2707
2891
  if (opts.outputFile) {
2892
+ let failure;
2708
2893
  try {
2709
- writeReportFile(opts.outputFile, FORMATS[opts.format](report, { color: false }));
2894
+ await writeReportFile(opts.outputFile, FORMATS[opts.format](report, { color: false }));
2710
2895
  } catch (error) {
2711
- const reason = error instanceof Error ? error.message : String(error);
2712
- err(`cliprobe: could not write ${safe(opts.outputFile)}: ${safe(reason)}\n`);
2713
- return 2;
2896
+ failure = error instanceof Error ? error.message : String(error);
2714
2897
  }
2715
2898
  out(FORMATS.human(report, { color }));
2899
+ if (failure !== void 0) {
2900
+ err(`cliprobe: could not write ${safe(opts.outputFile)}: ${safe(failure)}\n`);
2901
+ return 2;
2902
+ }
2716
2903
  } else out(FORMATS[opts.format](report, { color }));
2717
2904
  return exitCodeFor(results, opts.strict);
2718
2905
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "1.4.1",
3
+ "version": "1.4.3",
4
4
  "description": "Black-box test any command-line program for terminal-edge bugs: crashes on a closed pipe (| head), color and control codes leaking into pipes, hangs waiting on stdin, broken Ctrl-C handling, child processes left running after SIGTERM, a terminal left broken after Ctrl-C, and control characters from file names reaching your terminal.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -97,7 +97,7 @@
97
97
  "oxlint-tsgolint": "^7.0.2007",
98
98
  "prettier": "^3.10.1",
99
99
  "publint": "^0.3.25",
100
- "semantic-release": "^25.0.9",
100
+ "semantic-release": "^26.0.1",
101
101
  "tsdown": "^0.23.1",
102
102
  "typescript": "^7.0.2",
103
103
  "vitest": "^5.1.0"