cliprobe 0.2.0 → 0.4.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.
Files changed (3) hide show
  1. package/README.md +47 -11
  2. package/dist/cli.js +290 -42
  3. package/package.json +8 -4
package/README.md CHANGED
@@ -7,7 +7,7 @@ npx cliprobe -- esbuild
7
7
  ```
8
8
 
9
9
  ```
10
- cliprobe 0.1.0: closed-pipe, color, ctrl-c, control-chars checks for esbuild
10
+ cliprobe 0.4.0: closed-pipe, color, pipe-escapes, stdin, ctrl-c, control-chars checks for esbuild
11
11
 
12
12
  closed-pipe
13
13
  FAIL esbuild --version crashed when stdout was closed (exit 0 -> 1)
@@ -19,20 +19,28 @@ color
19
19
  PASS esbuild --version no color in a pipe or in a terminal
20
20
  PASS esbuild --help colors only in a terminal, and NO_COLOR turns it off
21
21
 
22
+ pipe-escapes
23
+ PASS esbuild --version no cursor, erase, hyperlink, title or redraw codes in a pipe
24
+ PASS esbuild --help no cursor, erase, hyperlink, title or redraw codes in a pipe
25
+
26
+ stdin
27
+ PASS esbuild --version finished without waiting for stdin
28
+ PASS esbuild --help finished without waiting for stdin
29
+
22
30
  ctrl-c
23
31
  SKIP esbuild needs probe args that keep it running, such as a watch or serve command
24
32
 
25
33
  control-chars
26
34
  SKIP esbuild no {fixture} in the arguments; put it where the command takes a path, e.g. ls {fixture}
27
35
 
28
- 2 failed, 0 warned, 2 passed, 2 skipped
36
+ 2 failed, 0 warned, 6 passed, 2 skipped
29
37
  ```
30
38
 
31
39
  ## Why
32
40
 
33
41
  When a program's output goes into a reader that stops early (`| head`, `grep -q`, a closed agent pipe), its next write to stdout fails. A well-behaved program exits quietly. Many Node.js CLIs instead crash with `Error: write EPIPE`, a stack trace, and exit code 1. That breaks scripts running under `set -o pipefail` and confuses agents that read stderr.
34
42
 
35
- In a census of the 100 most-downloaded npm packages that ship a command (119 commands, run offline in a throwaway container), **9 crashed this way every time**: esbuild, browserslist, update-browserslist-db, autoprefixer, husky, tsconfck, ts-jest, rolldown, and tsx on `--version`. The best-known existing CLI auditor rated the first 8 as passing its SIGPIPE check. The same census found two commands that print color codes into a pipe (`giget --help`, `tsx --help`), and no false failures: every `FAIL` reproduced by hand. (A census of `--help` and `--version` can't exercise ctrl-c or control-chars, which need a command that keeps running or takes a path; their fixtures and real-tool tests are in `test/`.)
43
+ In a census of the 100 most-downloaded npm packages that ship a command (119 commands, run offline in a throwaway container), **9 crashed this way every time**: esbuild, browserslist, update-browserslist-db, autoprefixer, husky, tsconfck, ts-jest, rolldown, and tsx on `--version`. The best-known existing CLI auditor rated the first 8 as passing its SIGPIPE check. The same census found two commands that print color codes into a pipe (`giget --help`, `tsx --help`), five whose `--help` or `--version` waits for stdin (he, cssesc, ansi-html, webpack and webpack-dev-server), and no false failures: every `FAIL` reproduced by hand. (A census of `--help` and `--version` can't exercise ctrl-c or control-chars, which need a command that keeps running or takes a path; their fixtures and real-tool tests are in `test/`.)
36
44
 
37
45
  The other checks cover the rest of what goes wrong between a program and the thing reading it: color codes leaking into logs and agent transcripts, Ctrl-C that is ignored or ends in a stack trace, and file names that can send escape sequences to your terminal.
38
46
 
@@ -84,7 +92,7 @@ In JUnit, each check is a test suite and each probe a test case: `FAIL` is a fai
84
92
 
85
93
  ## Checks
86
94
 
87
- A default run does the four checks below: closed-pipe, color, ctrl-c and control-chars. Each one reports evidence, never a score. Two info checks, startup and baseline, run only when you name them with `--check`.
95
+ A default run does the six checks below: closed-pipe, color, pipe-escapes, stdin, ctrl-c and control-chars. Each one reports evidence, never a score. Two info checks, startup and baseline, run only when you name them with `--check`.
88
96
 
89
97
  **closed-pipe**. cliprobe runs the command twice: once normally, then with stdout set to a pipe whose reading end is already closed, so the first write fails every time, even for fast native programs. Results:
90
98
 
@@ -97,15 +105,36 @@ A default run does the four checks below: closed-pipe, color, ctrl-c and control
97
105
 
98
106
  **color**. 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:
99
107
 
100
- | Verdict | Meaning |
101
- | ------- | -------------------------------------------------------------------------------------------- |
102
- | `PASS` | No color in a pipe; in a terminal, either no color at all or color that `NO_COLOR` turns off |
103
- | `FAIL` | Printed color or style codes (bold counts, a bare reset doesn't) to stdout in a pipe |
104
- | `WARN` | Printed color to stderr in a pipe, or kept printing color under `NO_COLOR` |
105
- | `SKIP` | Printed nothing, waited for input in a terminal, or no usable `script` (BusyBox) |
108
+ | Verdict | Meaning |
109
+ | ------- | -------------------------------------------------------------------------------------------------------------- |
110
+ | `PASS` | No color in a pipe; in a terminal, either no color at all or color that `NO_COLOR` turns off |
111
+ | `FAIL` | Printed color or style codes (bold counts, a bare reset doesn't) to stdout in a pipe |
112
+ | `WARN` | Printed color to stderr in a pipe, or kept printing color under `NO_COLOR` |
113
+ | `SKIP` | Printed nothing, waited for input in a terminal, or no `script` command (on Alpine, install `util-linux-misc`) |
106
114
 
107
115
  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`.
108
116
 
117
+ **pipe-escapes**. cliprobe runs the command into a pipe, with the same environment as the color check, and looks at stdout and stderr for terminal control codes that only make sense on a screen: cursor movement, line and screen erases, mode switches such as hiding the cursor, hyperlinks (OSC 8), window titles, and carriage returns that redraw a line. Spinners and progress bars are the usual source. In a pipe they turn logs and agent transcripts into `\r\x1b[2K` noise. Results:
118
+
119
+ | Verdict | Meaning |
120
+ | ------- | -------------------------------------------------------------------------- |
121
+ | `PASS` | None of those codes reached the pipe (color is the color check's business) |
122
+ | `WARN` | One or more reached stdout or stderr; the reason lists which kinds |
123
+ | `SKIP` | Printed nothing |
124
+
125
+ It only warns for now, never fails. In the census of the top 100 npm CLIs, no `--help` or `--version` printed any of these codes, which says nothing about their spinners: probe a command that does real work, such as an install or a build.
126
+
127
+ **stdin**. Agents and CI runners often start a command with stdin as a pipe that stays open and never receives anything. A program that reads stdin, or asks a question, then waits forever. cliprobe runs the command three ways: with stdin closed (`/dev/null`), with an open pipe, and, if that hangs for 3 seconds, with a pipe it closes after 1 second. Finishing right after the close proves stdin was the cause. Results:
128
+
129
+ | Verdict | Meaning |
130
+ | ------- | ------------------------------------------------------------------------------------------------------------------------- |
131
+ | `PASS` | Finished without waiting for stdin |
132
+ | `FAIL` | `--version` or `--help` waited for stdin before answering: they must never need input |
133
+ | `WARN` | A probe you wrote printed an unfinished line, like a question, then waited: it prompts even though stdin isn't a terminal |
134
+ | `SKIP` | A probe you wrote waited silently, like a filter (`grep pattern`), or the hang wasn't caused by stdin |
135
+
136
+ In the census of the top 100 npm CLIs, 9 of 238 `--help` and `--version` runs failed, each confirmed by hand. he, cssesc and ansi-html read stdin before looking at their arguments. webpack and webpack-dev-server, when webpack-cli is missing, ask whether to install it and wait for an answer without checking for a terminal. With no arguments, 17 tools waited on stdin as filters by design, which is why probes you write never fail this check.
137
+
109
138
  **ctrl-c**. cliprobe lets the command run for 1 second, then sends SIGINT to its process group, which is what a terminal does when you press Ctrl-C, and gives it 3 seconds to exit. Results:
110
139
 
111
140
  | Verdict | Meaning |
@@ -155,6 +184,13 @@ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
155
184
 
156
185
  `util.styleText` makes that decision for you on Node 22.13 and later (its `validateStream` option, on by default), and most color libraries check `isTTY` already, but some turn color on whenever `TERM` allows it or `CI` is set.
157
186
 
187
+ **stdin:** look at your arguments before reading stdin, so `--help` and `--version` answer at once, and only prompt when stdin is a terminal:
188
+
189
+ ```js
190
+ if (process.stdin.isTTY) askTheQuestion();
191
+ else useTheDefault(); // or fail with a message saying which flag to pass
192
+ ```
193
+
158
194
  **ctrl-c:** Node's default already does the right thing, dying by SIGINT. If you add a handler to clean up, finish by exiting 130 rather than 0, and don't throw from it:
159
195
 
160
196
  ```js
@@ -177,7 +213,7 @@ Also escape U+2028, U+2029 and the bidi controls (U+202A to U+202E, U+2066 to U+
177
213
 
178
214
  ## Safety
179
215
 
180
- cliprobe runs the target in your current directory without a shell, with stdin closed, 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, or `--version` and `--help`; only the baseline check, when you name it, adds an unknown flag. It kills each run's whole process group on timeout, including under a pseudo-terminal. macOS and Linux only for now.
216
+ cliprobe runs the target in your current directory without a shell, with stdin closed, 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, or `--version` and `--help`; only the baseline check, when you name it, adds an unknown flag. It kills each run's whole process group on timeout, including under a pseudo-terminal. 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.
181
217
 
182
218
  ## License
183
219
 
package/dist/cli.js CHANGED
@@ -29,7 +29,7 @@ const STDOUT_CAP = 1048576;
29
29
  * whose read end is closed before the program starts, so its first write to
30
30
  * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
31
31
  */
32
- function run(command, args, { closedStdout = false, timeout, env: overrides = {}, beforeKill, signal }) {
32
+ function run$1(command, args, { closedStdout = false, timeout, env: overrides = {}, beforeKill, signal, stdin = "null" }) {
33
33
  const { dir, env: base } = sandbox();
34
34
  const env = { ...base };
35
35
  for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
@@ -79,7 +79,7 @@ function run(command, args, { closedStdout = false, timeout, env: overrides = {}
79
79
  child = spawn(command, [...args], {
80
80
  env,
81
81
  stdio: [
82
- "ignore",
82
+ stdin === "null" ? "ignore" : "pipe",
83
83
  stdoutFd,
84
84
  "pipe"
85
85
  ],
@@ -108,9 +108,12 @@ function run(command, args, { closedStdout = false, timeout, env: overrides = {}
108
108
  process.kill(-child.pid, signal.name);
109
109
  } catch {}
110
110
  }, signal.afterMs);
111
+ const closeTimer = typeof stdin === "object" ? setTimeout(() => child.stdin?.destroy(), stdin.closeAfterMs) : void 0;
111
112
  child.on("exit", () => {
112
113
  exited = true;
113
114
  clearTimeout(signalTimer);
115
+ clearTimeout(closeTimer);
116
+ child.stdin?.destroy();
114
117
  });
115
118
  child.stdout?.on("data", (chunk) => {
116
119
  if (stdoutBytes < STDOUT_CAP) stdoutChunks.push(chunk);
@@ -188,7 +191,7 @@ function describeUnknownFlag(r) {
188
191
  return { reason: `${exitText(r)} without saying why` };
189
192
  }
190
193
  async function probe(command, args, timeout, describe) {
191
- const r = await run(command, args, { timeout });
194
+ const r = await run$1(command, args, { timeout });
192
195
  const base = {
193
196
  check: "baseline",
194
197
  invocation: [command, ...args]
@@ -297,11 +300,11 @@ function judge(base, closed) {
297
300
  };
298
301
  }
299
302
  async function closedPipe(command, args, timeout) {
300
- const base = await run(command, args, {
303
+ const base = await run$1(command, args, {
301
304
  closedStdout: false,
302
305
  timeout
303
306
  });
304
- const closed = await run(command, args, {
307
+ const closed = await run$1(command, args, {
305
308
  closedStdout: true,
306
309
  timeout
307
310
  });
@@ -370,6 +373,74 @@ function findStyle(text) {
370
373
  };
371
374
  }
372
375
  }
376
+ /** CSI: ESC [ parameter bytes, intermediate bytes, one final byte. */
377
+ const CSI = /\x1b\[([0-?]*)[ -/]*([@-~])/g;
378
+ /** OSC: ESC ] number ; text, ended by BEL or ESC \. */
379
+ const OSC = /\x1b\](\d*);[^\x07\x1b]*(?:\x07|\x1b\\)/g;
380
+ /** A carriage return that does not end a CRLF line: a line being redrawn. */
381
+ const BARE_CR = /\r(?!\n)/g;
382
+ /** How each kind reads in a report. */
383
+ const CONTROL_LABELS = {
384
+ cursor: "cursor movement",
385
+ erase: "line or screen erase",
386
+ mode: "terminal mode switch (such as hiding the cursor)",
387
+ hyperlink: "hyperlink (OSC 8)",
388
+ title: "window title",
389
+ osc: "operating system command (OSC)",
390
+ redraw: "carriage-return redraw"
391
+ };
392
+ function csiKind(params, final) {
393
+ if (final === "m") return void 0;
394
+ if (final === "K" || final === "J") return "erase";
395
+ if ((final === "h" || final === "l") && params.startsWith("?")) return "mode";
396
+ return "cursor";
397
+ }
398
+ function oscKind(code) {
399
+ if (code === "8") return "hyperlink";
400
+ if (code === "0" || code === "1" || code === "2") return "title";
401
+ return "osc";
402
+ }
403
+ function hitAt(text, index, sequence, kind) {
404
+ const before = text.slice(0, index);
405
+ const start = before.lastIndexOf("\n") + 1;
406
+ const newline = text.indexOf("\n", index);
407
+ const end = newline === -1 ? text.length : newline;
408
+ return {
409
+ kind,
410
+ sequence,
411
+ line: before.split("\n").length,
412
+ text: text.slice(start, end).slice(0, 120)
413
+ };
414
+ }
415
+ /**
416
+ * Every terminal control code in the text other than color and style (SGR):
417
+ * cursor movement, erases, mode switches, OSC sequences such as hyperlinks and
418
+ * window titles, and carriage returns that redraw a line. In reading order.
419
+ */
420
+ function findControls(text) {
421
+ const hits = [];
422
+ for (const m of text.matchAll(CSI)) {
423
+ const kind = csiKind(m[1] ?? "", m[2] ?? "");
424
+ if (kind) hits.push({
425
+ index: m.index,
426
+ hit: hitAt(text, m.index, m[0], kind)
427
+ });
428
+ }
429
+ for (const m of text.matchAll(OSC)) hits.push({
430
+ index: m.index,
431
+ hit: hitAt(text, m.index, m[0], oscKind(m[1] ?? ""))
432
+ });
433
+ for (const m of text.matchAll(BARE_CR)) hits.push({
434
+ index: m.index,
435
+ hit: hitAt(text, m.index, m[0], "redraw")
436
+ });
437
+ return hits.sort((a, b) => a.index - b.index).map((h) => h.hit);
438
+ }
439
+ const ANY_ESCAPE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
440
+ /** The text with CSI and OSC escape sequences (color, cursor, links, titles) removed. */
441
+ function stripEscapes(text) {
442
+ return text.replace(ANY_ESCAPE, "");
443
+ }
373
444
  let cached;
374
445
  /** Whether this machine can run a program under a PTY, detected once. */
375
446
  function ptySupport() {
@@ -413,7 +484,7 @@ function detect() {
413
484
  } catch (error) {
414
485
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
415
486
  ok: false,
416
- reason: "script(1) not found; install util-linux (bsdutils on Debian and Ubuntu)"
487
+ reason: "script(1) not found; install util-linux (Debian and Ubuntu: bsdutils; Alpine: util-linux-misc)"
417
488
  };
418
489
  }
419
490
  return {
@@ -480,7 +551,7 @@ async function runPty(command, args, { timeout, env = {} }) {
480
551
  const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
481
552
  const pidFile = join(dir, "pid");
482
553
  try {
483
- const result = await run("script", ptyArgs(support.flavor, pidFile, command, args), {
554
+ const result = await run$1("script", ptyArgs(support.flavor, pidFile, command, args), {
484
555
  timeout,
485
556
  env: {
486
557
  TERM: "xterm-256color",
@@ -582,7 +653,7 @@ function judgeColor(runs) {
582
653
  }
583
654
  /** Runs only as many probes as the verdict needs: a pipe, then a terminal, then NO_COLOR. */
584
655
  async function colorRuns(command, args, timeout) {
585
- const pipe = await run(command, args, {
656
+ const pipe = await run$1(command, args, {
586
657
  timeout,
587
658
  env: COLOR_ENV
588
659
  });
@@ -730,7 +801,7 @@ function collapseFixture(text, fixture) {
730
801
  return text.replaceAll(fixture.realDir, FIXTURE_PLACEHOLDER).replaceAll(fixture.dir, FIXTURE_PLACEHOLDER);
731
802
  }
732
803
  // src/checks/control-chars.ts
733
- const ENV = {
804
+ const ENV$1 = {
734
805
  TERM: "xterm-256color",
735
806
  CI: void 0
736
807
  };
@@ -738,7 +809,7 @@ const ENV = {
738
809
  function rawNames(output) {
739
810
  return HOSTILE_NAMES.filter((h) => output.includes(h.marker));
740
811
  }
741
- const listLabels = (names) => {
812
+ const listLabels$1 = (names) => {
742
813
  const labels = names.map((h) => h.label);
743
814
  return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
744
815
  };
@@ -779,21 +850,21 @@ function judgeControlChars(runs) {
779
850
  const warning = raw.filter((h) => h.severity === "warn");
780
851
  if (warning.length) return {
781
852
  verdict: "warn",
782
- reason: `printed ${listLabels(warning)} from file names unescaped, which can hide or forge output`,
853
+ reason: `printed ${listLabels$1(warning)} from file names unescaped, which can hide or forge output`,
783
854
  evidence: evidenceFor(warning)
784
855
  };
785
856
  const noted = raw.filter((h) => h.severity === "note");
786
857
  return {
787
858
  verdict: "pass",
788
- reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels(noted)} as is` : ""}`
859
+ reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels$1(noted)} as is` : ""}`
789
860
  };
790
861
  }
791
862
  async function controlCharsRuns(command, args, fixtureDir, timeout) {
792
863
  const usesFixture = fixtureDir !== void 0 && args.some((a) => a.includes(fixtureDir));
793
864
  if (!usesFixture) return { usesFixture };
794
- const pipe = await run(command, args, {
865
+ const pipe = await run$1(command, args, {
795
866
  timeout,
796
- env: ENV
867
+ env: ENV$1
797
868
  });
798
869
  if (pipe.spawnError || pipe.timedOut) return {
799
870
  usesFixture,
@@ -810,7 +881,7 @@ async function controlCharsRuns(command, args, fixtureDir, timeout) {
810
881
  pipe,
811
882
  tty: await runPty(command, args, {
812
883
  timeout,
813
- env: ENV
884
+ env: ENV$1
814
885
  })
815
886
  };
816
887
  }
@@ -888,7 +959,7 @@ function judgeCtrlC(r) {
888
959
  };
889
960
  }
890
961
  async function ctrlC(command, args) {
891
- const r = await run(command, args, {
962
+ const r = await run$1(command, args, {
892
963
  timeout: 4e3,
893
964
  signal: {
894
965
  name: "SIGINT",
@@ -928,6 +999,73 @@ const ctrlCCheck = {
928
999
  return results;
929
1000
  }
930
1001
  };
1002
+ // src/checks/pipe-escapes.ts
1003
+ /** As in the color check: a capable TERM, so a program can't pass by seeing TERM=dumb, and no CI. */
1004
+ const ENV = {
1005
+ TERM: "xterm-256color",
1006
+ CI: void 0
1007
+ };
1008
+ const kindsOf = (hits) => [...new Set(hits.map((h) => h.kind))];
1009
+ function listLabels(kinds) {
1010
+ const labels = kinds.map((k) => CONTROL_LABELS[k]);
1011
+ return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1012
+ }
1013
+ function judgePipeEscapes(r) {
1014
+ if (r.spawnError) return {
1015
+ verdict: "error",
1016
+ reason: `could not start: ${r.spawnError}`
1017
+ };
1018
+ if (r.timedOut) return {
1019
+ verdict: "error",
1020
+ reason: "timed out on a normal run"
1021
+ };
1022
+ const stdout = r.stdout.toString("utf8");
1023
+ const outHits = findControls(stdout);
1024
+ const errHits = findControls(r.stderr);
1025
+ const first = outHits[0] ? {
1026
+ stream: "stdout",
1027
+ hit: outHits[0]
1028
+ } : errHits[0] && {
1029
+ stream: "stderr",
1030
+ hit: errHits[0]
1031
+ };
1032
+ if (first) return {
1033
+ verdict: "warn",
1034
+ reason: `printed terminal control codes into a pipe: ${listLabels([.../* @__PURE__ */ new Set([...kindsOf(outHits), ...kindsOf(errHits)])])}`,
1035
+ evidence: `${first.stream} line ${first.hit.line}: ${first.hit.text}`
1036
+ };
1037
+ if (!stdout && !r.stderr) return {
1038
+ verdict: "skip",
1039
+ reason: "printed nothing, so there is nothing to check"
1040
+ };
1041
+ return {
1042
+ verdict: "pass",
1043
+ reason: "no cursor, erase, hyperlink, title or redraw codes in a pipe"
1044
+ };
1045
+ }
1046
+ async function pipeEscapes(command, args, timeout) {
1047
+ const r = await run$1(command, args, {
1048
+ timeout,
1049
+ env: ENV
1050
+ });
1051
+ return {
1052
+ check: "pipe-escapes",
1053
+ invocation: [command, ...args],
1054
+ ...judgePipeEscapes(r),
1055
+ stdoutKinds: kindsOf(findControls(r.stdout.toString("utf8"))),
1056
+ stderrKinds: kindsOf(findControls(r.stderr))
1057
+ };
1058
+ }
1059
+ const pipeEscapesCheck = {
1060
+ name: "pipe-escapes",
1061
+ kind: "check",
1062
+ summary: "prints spinners, cursor codes, hyperlinks or titles into a pipe",
1063
+ async run(target, ctx) {
1064
+ const results = [];
1065
+ for (const args of target.invocations) results.push(await pipeEscapes(target.command, args, ctx.timeout));
1066
+ return results;
1067
+ }
1068
+ };
931
1069
  function median(values) {
932
1070
  const sorted = [...values].sort((a, b) => a - b);
933
1071
  const mid = Math.floor(sorted.length / 2);
@@ -943,7 +1081,7 @@ async function startup(command, args, timeout) {
943
1081
  check: "startup",
944
1082
  invocation: [command, ...args]
945
1083
  };
946
- const warmUp = await run(command, args, { timeout });
1084
+ const warmUp = await run$1(command, args, { timeout });
947
1085
  if (warmUp.spawnError) return {
948
1086
  ...base,
949
1087
  verdict: "error",
@@ -967,7 +1105,7 @@ async function startup(command, args, timeout) {
967
1105
  };
968
1106
  const runsMs = [];
969
1107
  for (let i = 0; i < 5; i++) {
970
- const r = await run(command, args, { timeout });
1108
+ const r = await run$1(command, args, { timeout });
971
1109
  if (r.timedOut || r.spawnError) return {
972
1110
  ...base,
973
1111
  verdict: "error",
@@ -986,22 +1124,118 @@ async function startup(command, args, timeout) {
986
1124
  medianMs: mid
987
1125
  };
988
1126
  }
1127
+ const startupCheck = {
1128
+ name: "startup",
1129
+ kind: "info",
1130
+ summary: "median wall time of --version, or of the given probe, over 5 runs",
1131
+ async run(target, ctx) {
1132
+ const args = target.explicit ? target.invocations[0] ?? [] : ["--version"];
1133
+ return [await startup(target.command, args, ctx.timeout)];
1134
+ }
1135
+ };
1136
+ // src/checks/stdin.ts
1137
+ /** How long the program gets with stdin left open before it counts as waiting. */
1138
+ const STDIN_WAIT_MS = 3e3;
1139
+ /** When the confirming run closes stdin, and how long it then gets to finish. */
1140
+ const STDIN_CLOSE_AFTER_MS = 1e3;
1141
+ /** The last line printed before waiting, when it reads like a question left on the line. */
1142
+ function promptLine(r) {
1143
+ const last = stripEscapes(r.stdout.toString("utf8") + r.stderr).split("\n").at(-1) ?? "";
1144
+ if (last.includes("\r") || last.trim() === "") return void 0;
1145
+ return last;
1146
+ }
1147
+ /**
1148
+ * `defaultProbe` is true for cliprobe's own `--version` and `--help` probes, which
1149
+ * must never wait for input. For probes the user wrote, waiting can be the point
1150
+ * (a filter such as `grep pattern`), so only a prompt-like wait warns.
1151
+ */
1152
+ function judgeStdin(runs, defaultProbe) {
1153
+ const { closed, open, closing } = runs;
1154
+ if (closed.spawnError) return {
1155
+ verdict: "error",
1156
+ reason: `could not start: ${closed.spawnError}`
1157
+ };
1158
+ if (closed.timedOut) return {
1159
+ verdict: "skip",
1160
+ reason: "doesn't finish even with stdin closed, so stdin isn't what it waits for"
1161
+ };
1162
+ if (!open || !open.timedOut) return {
1163
+ verdict: "pass",
1164
+ reason: "finished without waiting for stdin"
1165
+ };
1166
+ if (!closing || closing.timedOut) return {
1167
+ verdict: "skip",
1168
+ reason: "hung with stdin open, but closing stdin didn't end it, so the cause isn't proven"
1169
+ };
1170
+ const evidence = `${closed.durationMs} ms with stdin closed; still running after ${STDIN_WAIT_MS / 1e3} s with stdin open; finished ${closing.durationMs - STDIN_CLOSE_AFTER_MS} ms after stdin closed`;
1171
+ if (defaultProbe) return {
1172
+ verdict: "fail",
1173
+ reason: "waited for stdin before answering, so an agent or CI step that leaves stdin open hangs forever",
1174
+ evidence
1175
+ };
1176
+ const prompt = promptLine(open);
1177
+ if (prompt !== void 0) return {
1178
+ verdict: "warn",
1179
+ reason: "seems to prompt for input even though stdin isn't a terminal",
1180
+ evidence: `prompt: ${prompt.slice(0, 120)}; ${evidence}`
1181
+ };
1182
+ return {
1183
+ verdict: "skip",
1184
+ reason: "reads stdin like a filter and waits until it closes; give it input or </dev/null",
1185
+ evidence
1186
+ };
1187
+ }
1188
+ async function stdinRuns(command, args, timeout) {
1189
+ const closed = await run$1(command, args, { timeout });
1190
+ if (closed.spawnError || closed.timedOut) return { closed };
1191
+ const open = await run$1(command, args, {
1192
+ timeout: STDIN_WAIT_MS,
1193
+ stdin: "open"
1194
+ });
1195
+ if (!open.timedOut) return {
1196
+ closed,
1197
+ open
1198
+ };
1199
+ return {
1200
+ closed,
1201
+ open,
1202
+ closing: await run$1(command, args, {
1203
+ timeout: 4e3,
1204
+ stdin: { closeAfterMs: STDIN_CLOSE_AFTER_MS }
1205
+ })
1206
+ };
1207
+ }
1208
+ async function stdinCheck(command, args, defaultProbe, timeout) {
1209
+ const runs = await stdinRuns(command, args, timeout);
1210
+ const proven = runs.open?.timedOut === true && runs.closing !== void 0 && !runs.closing.timedOut;
1211
+ return {
1212
+ check: "stdin",
1213
+ invocation: [command, ...args],
1214
+ ...judgeStdin(runs, defaultProbe),
1215
+ closedMs: runs.closed.spawnError ? null : runs.closed.durationMs,
1216
+ waitedForStdin: proven,
1217
+ finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - STDIN_CLOSE_AFTER_MS : null
1218
+ };
1219
+ }
989
1220
  // src/checks/index.ts
990
1221
  /** Every check, in the order they run and are reported. */
991
1222
  const CHECKS = [
992
1223
  closedPipeCheck,
993
1224
  colorCheck,
994
- ctrlCCheck,
995
- controlCharsCheck,
1225
+ pipeEscapesCheck,
996
1226
  {
997
- name: "startup",
998
- kind: "info",
999
- summary: "median wall time of --version, or of the given probe, over 5 runs",
1227
+ name: "stdin",
1228
+ kind: "check",
1229
+ summary: "waits for stdin when it is an open pipe, as agents and CI runners leave it",
1000
1230
  async run(target, ctx) {
1001
- const args = target.explicit ? target.invocations[0] ?? [] : ["--version"];
1002
- return [await startup(target.command, args, ctx.timeout)];
1231
+ const results = [];
1232
+ for (const args of target.invocations) results.push(await stdinCheck(target.command, args, !target.explicit, ctx.timeout));
1233
+ return results;
1003
1234
  }
1004
1235
  },
1236
+ ctrlCCheck,
1237
+ controlCharsCheck,
1238
+ startupCheck,
1005
1239
  baselineCheck
1006
1240
  ];
1007
1241
  /**
@@ -1286,7 +1520,7 @@ function parseArgs(argv) {
1286
1520
  }
1287
1521
  return opts;
1288
1522
  }
1289
- // src/cli/main.ts
1523
+ // src/cli/help.ts
1290
1524
  const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
1291
1525
 
1292
1526
  Usage:
@@ -1305,6 +1539,13 @@ Checks:
1305
1539
  color Runs the command into a pipe, then under a terminal, then under
1306
1540
  a terminal with NO_COLOR=1. Fails if color codes reach a pipe;
1307
1541
  warns if color goes to a piped stderr or NO_COLOR is ignored.
1542
+ pipe-escapes Runs the command into a pipe and warns if cursor movement,
1543
+ erase, hyperlink, window title or carriage-return redraw
1544
+ codes (spinners, progress bars) reach stdout or stderr.
1545
+ stdin Runs the command with stdin as an open pipe nobody writes to,
1546
+ as agents and CI runners often leave it. Fails if --version or
1547
+ --help waits for input; for your own probes, warns if it
1548
+ prompts and skips if it reads stdin like a filter.
1308
1549
  ctrl-c Sends Ctrl-C (SIGINT) after 1 s. Fails if the command is still
1309
1550
  running 3 s later or prints a stack trace; warns if it exits 0.
1310
1551
  Skipped when the command finishes first, so probe a command
@@ -1338,16 +1579,20 @@ Options:
1338
1579
  Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
1339
1580
  Runs the target in the current directory without a shell, with stdin closed,
1340
1581
  a temporary HOME and a minimal environment. Only run programs you trust.`;
1341
- const out = (text) => {
1342
- process.stdout.write(text);
1343
- };
1344
- const err = (text) => {
1345
- process.stderr.write(text);
1346
- };
1347
- async function main() {
1582
+ // src/cli/program.ts
1583
+ /** 0 no failures, 1 a check failed, 2 nothing could be judged because something could not run. */
1584
+ function exitCodeFor(results) {
1585
+ if (results.some((r) => r.verdict === "fail")) return 1;
1586
+ if (!results.some((r) => r.verdict !== "error" && r.verdict !== "skip") && results.some((r) => r.verdict === "error")) return 2;
1587
+ return 0;
1588
+ }
1589
+ /** The whole CLI: parses argv, runs the checks, reports, and returns the exit code. */
1590
+ async function run(argv, io) {
1591
+ const out = io.stdout;
1592
+ const err = io.stderr;
1348
1593
  let opts;
1349
1594
  try {
1350
- opts = parseArgs(process.argv.slice(2));
1595
+ opts = parseArgs(argv);
1351
1596
  } catch (error) {
1352
1597
  if (!(error instanceof UsageError)) throw error;
1353
1598
  err(`cliprobe: ${error.message}\nRun "cliprobe --help" for usage.\n`);
@@ -1364,15 +1609,14 @@ async function main() {
1364
1609
  const { checks, unknown } = selectChecks(opts.checks);
1365
1610
  if (unknown.length) {
1366
1611
  const available = CHECKS.map((c) => c.name).join(", ");
1367
- const quoted = unknown.map((n) => `"${n}"`).join(", ");
1368
- err(`cliprobe: unknown check ${quoted} (available: ${available})\n`);
1612
+ err(`cliprobe: unknown check ${unknown.map((n) => `"${n}"`).join(", ")} (available: ${available})\n`);
1369
1613
  return 2;
1370
1614
  }
1371
1615
  if (!opts.command) {
1372
1616
  err("cliprobe: no command given\nUsage: cliprobe [options] -- <command> [args...]\n");
1373
1617
  return 2;
1374
1618
  }
1375
- if (process.platform === "win32") {
1619
+ if (io.platform === "win32") {
1376
1620
  err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
1377
1621
  return 2;
1378
1622
  }
@@ -1397,7 +1641,7 @@ async function main() {
1397
1641
  checks: checks.map((c) => c.name),
1398
1642
  results
1399
1643
  };
1400
- const color = process.stdout.isTTY && !process.env["NO_COLOR"];
1644
+ const { color } = io;
1401
1645
  if (opts.outputFile) {
1402
1646
  try {
1403
1647
  writeReportFile(opts.outputFile, collapse(FORMATS[opts.format](report, { color: false })));
@@ -1408,13 +1652,17 @@ async function main() {
1408
1652
  }
1409
1653
  out(collapse(FORMATS.human(report, { color })));
1410
1654
  } else out(collapse(FORMATS[opts.format](report, { color })));
1411
- if (results.some((r) => r.verdict === "fail")) return 1;
1412
- if (!results.some((r) => r.verdict !== "error" && r.verdict !== "skip") && results.some((r) => r.verdict === "error")) return 2;
1413
- return 0;
1655
+ return exitCodeFor(results);
1414
1656
  }
1657
+ // src/cli/main.ts
1415
1658
  process.stdout.on("error", (error) => {
1416
1659
  if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1417
1660
  throw error;
1418
1661
  });
1419
- process.exitCode = await main();
1662
+ process.exitCode = await run(process.argv.slice(2), {
1663
+ stdout: (text) => process.stdout.write(text),
1664
+ stderr: (text) => process.stderr.write(text),
1665
+ color: process.stdout.isTTY && !process.env["NO_COLOR"],
1666
+ platform: process.platform
1667
+ });
1420
1668
  export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "0.2.0",
4
- "description": "Black-box test any command-line program for terminal-edge bugs: crashes on a closed pipe (| head), color codes leaking into pipes, broken Ctrl-C handling, and control characters from file names reaching your terminal.",
3
+ "version": "0.4.0",
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, and control characters from file names reaching your terminal.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "cliprobe": "dist/cli.js"
@@ -18,10 +18,11 @@
18
18
  "format": "prettier --write .",
19
19
  "format:check": "prettier --check .",
20
20
  "test": "vitest run",
21
- "check": "pnpm typecheck && pnpm lint && pnpm format:check && pnpm build && pnpm test && pnpm check:package",
21
+ "check": "pnpm typecheck && pnpm lint && pnpm format:check && pnpm build && pnpm test:coverage && pnpm check:package",
22
22
  "check:package": "publint --strict",
23
23
  "prepublishOnly": "pnpm build",
24
24
  "test:watch": "vitest",
25
+ "test:coverage": "vitest run --coverage",
25
26
  "prepare": "husky"
26
27
  },
27
28
  "keywords": [
@@ -38,7 +39,9 @@
38
39
  "sigint",
39
40
  "ctrl-c",
40
41
  "terminal-injection",
41
- "pty"
42
+ "pty",
43
+ "stdin",
44
+ "hang"
42
45
  ],
43
46
  "author": {
44
47
  "name": "Khaled Saeed",
@@ -75,6 +78,7 @@
75
78
  "@semantic-release/release-notes-generator": "^14.1.1",
76
79
  "@types/markdown-it": "^14.2.0",
77
80
  "@types/node": "^22.20.5",
81
+ "@vitest/coverage-v8": "^5.1.0",
78
82
  "conventional-changelog-conventionalcommits": "^9.3.1",
79
83
  "fast-xml-parser": "^5.12.0",
80
84
  "husky": "^9.1.7",