cliprobe 0.1.0 → 0.3.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 +50 -15
  2. package/dist/cli.js +366 -52
  3. package/package.json +7 -2
package/README.md CHANGED
@@ -43,23 +43,48 @@ npx cliprobe -- <command> # probes "<command> --version" and "<c
43
43
  npx cliprobe -- <command> [args...] # probes exactly this invocation
44
44
  npx cliprobe -- node ./dist/cli.js list # test your own CLI before publishing
45
45
  npx cliprobe --json -- <command> # machine-readable results
46
+ npx cliprobe --format junit -o report.xml -- <command> # JUnit file for CI; human report on stdout
46
47
  npx cliprobe -- ls {fixture} # {fixture}: a directory of hostile file names
47
48
  npx cliprobe --check startup,baseline -- node ./dist/cli.js # info checks, only when named
48
49
  ```
49
50
 
50
- | Option | Meaning |
51
- | ----------------- | -------------------------------------------------------- |
52
- | `--check <name>` | Run only this check; repeat it or use commas for several |
53
- | `--json` | Print results as JSON, including the checks that ran |
54
- | `--timeout <ms>` | Kill a probe after this long (default 15000) |
55
- | `-h`, `--help` | Show help |
56
- | `-v`, `--version` | Show the version |
51
+ | Option | Meaning |
52
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
53
+ | `--check <name>` | Run only this check; repeat it or use commas for several |
54
+ | `--format <name>` | Output format: `human` (default), `json`, `markdown` (a GitHub job summary or PR comment) or `junit` (XML for CI test reports) |
55
+ | `--json` | Same as `--format json` |
56
+ | `-o`, `--output-file <path>` | Write the `--format` report to a file (atomically, creating parent folders); the human report still prints |
57
+ | `--timeout <ms>` | Kill a probe after this long (default 15000) |
58
+ | `-h`, `--help` | Show help |
59
+ | `-v`, `--version` | Show the version |
57
60
 
58
61
  Exit codes: `0` no failures, `1` a check failed, `2` usage error or the command could not run. That makes it usable as a CI gate.
59
62
 
63
+ ### In CI
64
+
65
+ A failed check exits 1, so the step fails. In GitHub Actions, write a Markdown report to the job summary while the log keeps the human report:
66
+
67
+ ```yaml
68
+ - name: Check the CLI for terminal-edge bugs
69
+ run: npx --yes cliprobe@0 --format markdown --output-file "$GITHUB_STEP_SUMMARY" -- node ./dist/cli.js
70
+ ```
71
+
72
+ For CI systems that read test results, write JUnit XML instead and keep it even when the step fails:
73
+
74
+ ```yaml
75
+ - run: npx --yes cliprobe@0 --format junit --output-file reports/cliprobe.xml -- node ./dist/cli.js
76
+ - uses: actions/upload-artifact@v7
77
+ if: always()
78
+ with:
79
+ name: cliprobe-report
80
+ path: reports/cliprobe.xml
81
+ ```
82
+
83
+ In JUnit, each check is a test suite and each probe a test case: `FAIL` is a failure, could-not-run an error, `SKIP` skipped; `WARN`, `INFO` and `PASS` pass, with the verdict and reason in the case's output.
84
+
60
85
  ## Checks
61
86
 
62
- 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`.
87
+ A default run does the five checks below: closed-pipe, color, pipe-escapes, 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`.
63
88
 
64
89
  **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:
65
90
 
@@ -72,15 +97,25 @@ A default run does the four checks below: closed-pipe, color, ctrl-c and control
72
97
 
73
98
  **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:
74
99
 
75
- | Verdict | Meaning |
76
- | ------- | -------------------------------------------------------------------------------------------- |
77
- | `PASS` | No color in a pipe; in a terminal, either no color at all or color that `NO_COLOR` turns off |
78
- | `FAIL` | Printed color or style codes (bold counts, a bare reset doesn't) to stdout in a pipe |
79
- | `WARN` | Printed color to stderr in a pipe, or kept printing color under `NO_COLOR` |
80
- | `SKIP` | Printed nothing, waited for input in a terminal, or no usable `script` (BusyBox) |
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 `script` command (on Alpine, install `util-linux-misc`) |
81
106
 
82
107
  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`.
83
108
 
109
+ **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:
110
+
111
+ | Verdict | Meaning |
112
+ | ------- | -------------------------------------------------------------------------- |
113
+ | `PASS` | None of those codes reached the pipe (color is the color check's business) |
114
+ | `WARN` | One or more reached stdout or stderr; the reason lists which kinds |
115
+ | `SKIP` | Printed nothing |
116
+
117
+ 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.
118
+
84
119
  **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:
85
120
 
86
121
  | Verdict | Meaning |
@@ -152,7 +187,7 @@ Also escape U+2028, U+2029 and the bidi controls (U+202A to U+202E, U+2066 to U+
152
187
 
153
188
  ## Safety
154
189
 
155
- 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.
190
+ 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.
156
191
 
157
192
  ## License
158
193
 
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { execFileSync, spawn } from "node:child_process";
4
- import { closeSync, constants, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
5
- import { join } from "node:path";
4
+ import { closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
6
  import { tmpdir } from "node:os";
7
7
  // src/core/sandbox.ts
8
8
  /** A minimal environment: no tokens or config from the caller's shell. */
@@ -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 }) {
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];
@@ -188,7 +188,7 @@ function describeUnknownFlag(r) {
188
188
  return { reason: `${exitText(r)} without saying why` };
189
189
  }
190
190
  async function probe(command, args, timeout, describe) {
191
- const r = await run(command, args, { timeout });
191
+ const r = await run$1(command, args, { timeout });
192
192
  const base = {
193
193
  check: "baseline",
194
194
  invocation: [command, ...args]
@@ -297,11 +297,11 @@ function judge(base, closed) {
297
297
  };
298
298
  }
299
299
  async function closedPipe(command, args, timeout) {
300
- const base = await run(command, args, {
300
+ const base = await run$1(command, args, {
301
301
  closedStdout: false,
302
302
  timeout
303
303
  });
304
- const closed = await run(command, args, {
304
+ const closed = await run$1(command, args, {
305
305
  closedStdout: true,
306
306
  timeout
307
307
  });
@@ -370,6 +370,69 @@ function findStyle(text) {
370
370
  };
371
371
  }
372
372
  }
373
+ /** CSI: ESC [ parameter bytes, intermediate bytes, one final byte. */
374
+ const CSI = /\x1b\[([0-?]*)[ -/]*([@-~])/g;
375
+ /** OSC: ESC ] number ; text, ended by BEL or ESC \. */
376
+ const OSC = /\x1b\](\d*);[^\x07\x1b]*(?:\x07|\x1b\\)/g;
377
+ /** A carriage return that does not end a CRLF line: a line being redrawn. */
378
+ const BARE_CR = /\r(?!\n)/g;
379
+ /** How each kind reads in a report. */
380
+ const CONTROL_LABELS = {
381
+ cursor: "cursor movement",
382
+ erase: "line or screen erase",
383
+ mode: "terminal mode switch (such as hiding the cursor)",
384
+ hyperlink: "hyperlink (OSC 8)",
385
+ title: "window title",
386
+ osc: "operating system command (OSC)",
387
+ redraw: "carriage-return redraw"
388
+ };
389
+ function csiKind(params, final) {
390
+ if (final === "m") return void 0;
391
+ if (final === "K" || final === "J") return "erase";
392
+ if ((final === "h" || final === "l") && params.startsWith("?")) return "mode";
393
+ return "cursor";
394
+ }
395
+ function oscKind(code) {
396
+ if (code === "8") return "hyperlink";
397
+ if (code === "0" || code === "1" || code === "2") return "title";
398
+ return "osc";
399
+ }
400
+ function hitAt(text, index, sequence, kind) {
401
+ const before = text.slice(0, index);
402
+ const start = before.lastIndexOf("\n") + 1;
403
+ const newline = text.indexOf("\n", index);
404
+ const end = newline === -1 ? text.length : newline;
405
+ return {
406
+ kind,
407
+ sequence,
408
+ line: before.split("\n").length,
409
+ text: text.slice(start, end).slice(0, 120)
410
+ };
411
+ }
412
+ /**
413
+ * Every terminal control code in the text other than color and style (SGR):
414
+ * cursor movement, erases, mode switches, OSC sequences such as hyperlinks and
415
+ * window titles, and carriage returns that redraw a line. In reading order.
416
+ */
417
+ function findControls(text) {
418
+ const hits = [];
419
+ for (const m of text.matchAll(CSI)) {
420
+ const kind = csiKind(m[1] ?? "", m[2] ?? "");
421
+ if (kind) hits.push({
422
+ index: m.index,
423
+ hit: hitAt(text, m.index, m[0], kind)
424
+ });
425
+ }
426
+ for (const m of text.matchAll(OSC)) hits.push({
427
+ index: m.index,
428
+ hit: hitAt(text, m.index, m[0], oscKind(m[1] ?? ""))
429
+ });
430
+ for (const m of text.matchAll(BARE_CR)) hits.push({
431
+ index: m.index,
432
+ hit: hitAt(text, m.index, m[0], "redraw")
433
+ });
434
+ return hits.sort((a, b) => a.index - b.index).map((h) => h.hit);
435
+ }
373
436
  let cached;
374
437
  /** Whether this machine can run a program under a PTY, detected once. */
375
438
  function ptySupport() {
@@ -413,7 +476,7 @@ function detect() {
413
476
  } catch (error) {
414
477
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
415
478
  ok: false,
416
- reason: "script(1) not found; install util-linux (bsdutils on Debian and Ubuntu)"
479
+ reason: "script(1) not found; install util-linux (Debian and Ubuntu: bsdutils; Alpine: util-linux-misc)"
417
480
  };
418
481
  }
419
482
  return {
@@ -480,7 +543,7 @@ async function runPty(command, args, { timeout, env = {} }) {
480
543
  const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
481
544
  const pidFile = join(dir, "pid");
482
545
  try {
483
- const result = await run("script", ptyArgs(support.flavor, pidFile, command, args), {
546
+ const result = await run$1("script", ptyArgs(support.flavor, pidFile, command, args), {
484
547
  timeout,
485
548
  env: {
486
549
  TERM: "xterm-256color",
@@ -582,7 +645,7 @@ function judgeColor(runs) {
582
645
  }
583
646
  /** Runs only as many probes as the verdict needs: a pipe, then a terminal, then NO_COLOR. */
584
647
  async function colorRuns(command, args, timeout) {
585
- const pipe = await run(command, args, {
648
+ const pipe = await run$1(command, args, {
586
649
  timeout,
587
650
  env: COLOR_ENV
588
651
  });
@@ -730,7 +793,7 @@ function collapseFixture(text, fixture) {
730
793
  return text.replaceAll(fixture.realDir, FIXTURE_PLACEHOLDER).replaceAll(fixture.dir, FIXTURE_PLACEHOLDER);
731
794
  }
732
795
  // src/checks/control-chars.ts
733
- const ENV = {
796
+ const ENV$1 = {
734
797
  TERM: "xterm-256color",
735
798
  CI: void 0
736
799
  };
@@ -738,7 +801,7 @@ const ENV = {
738
801
  function rawNames(output) {
739
802
  return HOSTILE_NAMES.filter((h) => output.includes(h.marker));
740
803
  }
741
- const listLabels = (names) => {
804
+ const listLabels$1 = (names) => {
742
805
  const labels = names.map((h) => h.label);
743
806
  return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
744
807
  };
@@ -779,21 +842,21 @@ function judgeControlChars(runs) {
779
842
  const warning = raw.filter((h) => h.severity === "warn");
780
843
  if (warning.length) return {
781
844
  verdict: "warn",
782
- reason: `printed ${listLabels(warning)} from file names unescaped, which can hide or forge output`,
845
+ reason: `printed ${listLabels$1(warning)} from file names unescaped, which can hide or forge output`,
783
846
  evidence: evidenceFor(warning)
784
847
  };
785
848
  const noted = raw.filter((h) => h.severity === "note");
786
849
  return {
787
850
  verdict: "pass",
788
- reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels(noted)} as is` : ""}`
851
+ reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels$1(noted)} as is` : ""}`
789
852
  };
790
853
  }
791
854
  async function controlCharsRuns(command, args, fixtureDir, timeout) {
792
855
  const usesFixture = fixtureDir !== void 0 && args.some((a) => a.includes(fixtureDir));
793
856
  if (!usesFixture) return { usesFixture };
794
- const pipe = await run(command, args, {
857
+ const pipe = await run$1(command, args, {
795
858
  timeout,
796
- env: ENV
859
+ env: ENV$1
797
860
  });
798
861
  if (pipe.spawnError || pipe.timedOut) return {
799
862
  usesFixture,
@@ -810,7 +873,7 @@ async function controlCharsRuns(command, args, fixtureDir, timeout) {
810
873
  pipe,
811
874
  tty: await runPty(command, args, {
812
875
  timeout,
813
- env: ENV
876
+ env: ENV$1
814
877
  })
815
878
  };
816
879
  }
@@ -888,7 +951,7 @@ function judgeCtrlC(r) {
888
951
  };
889
952
  }
890
953
  async function ctrlC(command, args) {
891
- const r = await run(command, args, {
954
+ const r = await run$1(command, args, {
892
955
  timeout: 4e3,
893
956
  signal: {
894
957
  name: "SIGINT",
@@ -928,6 +991,73 @@ const ctrlCCheck = {
928
991
  return results;
929
992
  }
930
993
  };
994
+ // src/checks/pipe-escapes.ts
995
+ /** As in the color check: a capable TERM, so a program can't pass by seeing TERM=dumb, and no CI. */
996
+ const ENV = {
997
+ TERM: "xterm-256color",
998
+ CI: void 0
999
+ };
1000
+ const kindsOf = (hits) => [...new Set(hits.map((h) => h.kind))];
1001
+ function listLabels(kinds) {
1002
+ const labels = kinds.map((k) => CONTROL_LABELS[k]);
1003
+ return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1004
+ }
1005
+ function judgePipeEscapes(r) {
1006
+ if (r.spawnError) return {
1007
+ verdict: "error",
1008
+ reason: `could not start: ${r.spawnError}`
1009
+ };
1010
+ if (r.timedOut) return {
1011
+ verdict: "error",
1012
+ reason: "timed out on a normal run"
1013
+ };
1014
+ const stdout = r.stdout.toString("utf8");
1015
+ const outHits = findControls(stdout);
1016
+ const errHits = findControls(r.stderr);
1017
+ const first = outHits[0] ? {
1018
+ stream: "stdout",
1019
+ hit: outHits[0]
1020
+ } : errHits[0] && {
1021
+ stream: "stderr",
1022
+ hit: errHits[0]
1023
+ };
1024
+ if (first) return {
1025
+ verdict: "warn",
1026
+ reason: `printed terminal control codes into a pipe: ${listLabels([.../* @__PURE__ */ new Set([...kindsOf(outHits), ...kindsOf(errHits)])])}`,
1027
+ evidence: `${first.stream} line ${first.hit.line}: ${first.hit.text}`
1028
+ };
1029
+ if (!stdout && !r.stderr) return {
1030
+ verdict: "skip",
1031
+ reason: "printed nothing, so there is nothing to check"
1032
+ };
1033
+ return {
1034
+ verdict: "pass",
1035
+ reason: "no cursor, erase, hyperlink, title or redraw codes in a pipe"
1036
+ };
1037
+ }
1038
+ async function pipeEscapes(command, args, timeout) {
1039
+ const r = await run$1(command, args, {
1040
+ timeout,
1041
+ env: ENV
1042
+ });
1043
+ return {
1044
+ check: "pipe-escapes",
1045
+ invocation: [command, ...args],
1046
+ ...judgePipeEscapes(r),
1047
+ stdoutKinds: kindsOf(findControls(r.stdout.toString("utf8"))),
1048
+ stderrKinds: kindsOf(findControls(r.stderr))
1049
+ };
1050
+ }
1051
+ const pipeEscapesCheck = {
1052
+ name: "pipe-escapes",
1053
+ kind: "check",
1054
+ summary: "prints spinners, cursor codes, hyperlinks or titles into a pipe",
1055
+ async run(target, ctx) {
1056
+ const results = [];
1057
+ for (const args of target.invocations) results.push(await pipeEscapes(target.command, args, ctx.timeout));
1058
+ return results;
1059
+ }
1060
+ };
931
1061
  function median(values) {
932
1062
  const sorted = [...values].sort((a, b) => a - b);
933
1063
  const mid = Math.floor(sorted.length / 2);
@@ -943,7 +1073,7 @@ async function startup(command, args, timeout) {
943
1073
  check: "startup",
944
1074
  invocation: [command, ...args]
945
1075
  };
946
- const warmUp = await run(command, args, { timeout });
1076
+ const warmUp = await run$1(command, args, { timeout });
947
1077
  if (warmUp.spawnError) return {
948
1078
  ...base,
949
1079
  verdict: "error",
@@ -967,7 +1097,7 @@ async function startup(command, args, timeout) {
967
1097
  };
968
1098
  const runsMs = [];
969
1099
  for (let i = 0; i < 5; i++) {
970
- const r = await run(command, args, { timeout });
1100
+ const r = await run$1(command, args, { timeout });
971
1101
  if (r.timedOut || r.spawnError) return {
972
1102
  ...base,
973
1103
  verdict: "error",
@@ -991,6 +1121,7 @@ async function startup(command, args, timeout) {
991
1121
  const CHECKS = [
992
1122
  closedPipeCheck,
993
1123
  colorCheck,
1124
+ pipeEscapesCheck,
994
1125
  ctrlCCheck,
995
1126
  controlCharsCheck,
996
1127
  {
@@ -1041,6 +1172,25 @@ function safe(text) {
1041
1172
  function safeJson(value) {
1042
1173
  return JSON.stringify(value, null, 2).replace(JSON_UNSAFE, (c) => `\\u${hex(c, 4)}`);
1043
1174
  }
1175
+ // src/report/summary.ts
1176
+ function countVerdicts(results) {
1177
+ const counts = {
1178
+ pass: 0,
1179
+ fail: 0,
1180
+ warn: 0,
1181
+ skip: 0,
1182
+ error: 0,
1183
+ info: 0
1184
+ };
1185
+ for (const r of results) counts[r.verdict]++;
1186
+ return counts;
1187
+ }
1188
+ /** "2 failed, 0 warned, 2 passed, 2 skipped", plus info and could-not-run when present. */
1189
+ function summaryLine(c) {
1190
+ const info = c.info ? `, ${c.info} info` : "";
1191
+ const errors = c.error ? `, ${c.error} could not run` : "";
1192
+ return `${c.fail} failed, ${c.warn} warned, ${c.pass} passed, ${c.skip} skipped${info}${errors}`;
1193
+ }
1044
1194
  // src/report/human.ts
1045
1195
  const COLORS = {
1046
1196
  pass: 32,
@@ -1050,10 +1200,10 @@ const COLORS = {
1050
1200
  error: 35,
1051
1201
  info: 36
1052
1202
  };
1053
- function formatHuman(version, command, checks, results, useColor) {
1203
+ function formatHuman({ version, command, checks, results }, { color }) {
1054
1204
  const paint = (verdict) => {
1055
1205
  const label = verdict.toUpperCase().padEnd(5);
1056
- return useColor ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
1206
+ return color ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
1057
1207
  };
1058
1208
  const width = Math.max(0, ...results.map((r) => safe(r.invocation.join(" ")).length));
1059
1209
  const noun = checks.length === 1 ? "check" : "checks";
@@ -1066,14 +1216,11 @@ function formatHuman(version, command, checks, results, useColor) {
1066
1216
  if (r.evidence) lines.push(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
1067
1217
  }
1068
1218
  }
1069
- const count = (v) => results.filter((r) => r.verdict === v).length;
1070
- const info = count("info") ? `, ${count("info")} info` : "";
1071
- const errors = count("error") ? `, ${count("error")} could not run` : "";
1072
- lines.push("", `${count("fail")} failed, ${count("warn")} warned, ${count("pass")} passed, ${count("skip")} skipped${info}${errors}`);
1219
+ lines.push("", summaryLine(countVerdicts(results)));
1073
1220
  return lines.join("\n") + "\n";
1074
1221
  }
1075
1222
  // src/report/json.ts
1076
- function formatJson(version, command, checks, results) {
1223
+ function formatJson({ version, command, checks, results }) {
1077
1224
  return safeJson({
1078
1225
  tool: "cliprobe",
1079
1226
  version,
@@ -1082,6 +1229,137 @@ function formatJson(version, command, checks, results) {
1082
1229
  results
1083
1230
  }) + "\n";
1084
1231
  }
1232
+ // src/report/junit.ts
1233
+ const XML_ESCAPES = {
1234
+ "&": "&amp;",
1235
+ "<": "&lt;",
1236
+ ">": "&gt;",
1237
+ "\"": "&quot;",
1238
+ "'": "&apos;"
1239
+ };
1240
+ /**
1241
+ * Text that is always well-formed XML 1.0: safe() first turns every control
1242
+ * character (most of which XML forbids even when escaped) into a visible escape,
1243
+ * then the five markup characters become entities.
1244
+ */
1245
+ function xml(text) {
1246
+ return safe(text).replace(/[&<>"']/g, (c) => XML_ESCAPES[c] ?? c);
1247
+ }
1248
+ /** JUnit's count attributes for a suite or the whole run. */
1249
+ function totals(results) {
1250
+ const c = countVerdicts(results);
1251
+ return `tests="${results.length}" failures="${c.fail}" errors="${c.error}" skipped="${c.skip}"`;
1252
+ }
1253
+ function testcase(r) {
1254
+ const open = ` <testcase classname="cliprobe.${xml(r.check)}" name="${xml(r.invocation.join(" "))}"`;
1255
+ const message = `message="${xml(r.reason)}"`;
1256
+ const body = r.evidence ? xml(r.evidence) : "";
1257
+ switch (r.verdict) {
1258
+ case "fail": return `${open}>\n <failure ${message} type="fail">${body}</failure>\n </testcase>`;
1259
+ case "error": return `${open}>\n <error ${message} type="error">${body}</error>\n </testcase>`;
1260
+ case "skip": return `${open}>\n <skipped ${message}/>\n </testcase>`;
1261
+ case "pass":
1262
+ case "warn":
1263
+ case "info": return `${open}>\n <system-out>${`${r.verdict.toUpperCase()}: ${xml(r.reason)}${r.evidence ? `\n${body}` : ""}`}</system-out>\n </testcase>`;
1264
+ }
1265
+ }
1266
+ /** JUnit XML: one testsuite per check, one testcase per result. */
1267
+ function formatJunit({ version, command, checks, results }) {
1268
+ const suites = checks.map((check) => {
1269
+ const own = results.filter((r) => r.check === check);
1270
+ return [
1271
+ ` <testsuite name="${xml(check)}" ${totals(own)}>`,
1272
+ ...own.map(testcase),
1273
+ " </testsuite>"
1274
+ ].join("\n");
1275
+ });
1276
+ return [
1277
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
1278
+ `<testsuites name="cliprobe ${xml(version)}: ${xml(command)}" ${totals(results)}>`,
1279
+ ...suites,
1280
+ "</testsuites>",
1281
+ ""
1282
+ ].join("\n");
1283
+ }
1284
+ // src/report/markdown.ts
1285
+ /**
1286
+ * A code span that shows any text literally: control characters escaped onto one
1287
+ * line, `|` escaped so a table cell can't be split, and a fence longer than any
1288
+ * run of backticks inside.
1289
+ */
1290
+ function code(text, { inTable }) {
1291
+ const body = inTable ? safe(text).replaceAll("|", "\\|") : safe(text);
1292
+ const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((run) => run.length));
1293
+ const fence = "`".repeat(longest + 1);
1294
+ const pad = body.startsWith("`") || body.endsWith("`") ? " " : "";
1295
+ return `${fence}${pad}${body}${pad}${fence}`;
1296
+ }
1297
+ /**
1298
+ * Prose for inside a table cell. Only characters that act mid-line are escaped:
1299
+ * emphasis, code, links, HTML, entities and the cell separator. Line-start syntax
1300
+ * (`#`, `-`, `1.`) can't trigger there, so it stays readable.
1301
+ */
1302
+ function prose(text) {
1303
+ return safe(text).replace(/[\\`*_[\]<>|~&]/g, (c) => `\\${c}`);
1304
+ }
1305
+ function row(r) {
1306
+ const verdict = r.verdict === "fail" || r.verdict === "error" ? `**${r.verdict.toUpperCase()}**` : r.verdict.toUpperCase();
1307
+ const evidence = r.evidence ? `<br>${code(r.evidence.slice(0, 300), { inTable: true })}` : "";
1308
+ return `| ${[
1309
+ prose(r.check),
1310
+ verdict,
1311
+ code(r.invocation.join(" "), { inTable: true }),
1312
+ prose(r.reason) + evidence
1313
+ ].join(" | ")} |`;
1314
+ }
1315
+ /** GitHub-flavored Markdown, for a job summary ($GITHUB_STEP_SUMMARY) or a PR comment. */
1316
+ function formatMarkdown({ version, command, results }) {
1317
+ return [
1318
+ `## cliprobe ${version}: ${code(command, { inTable: false })}`,
1319
+ "",
1320
+ summaryLine(countVerdicts(results)),
1321
+ "",
1322
+ "| Check | Verdict | Invocation | Result |",
1323
+ "| --- | --- | --- | --- |",
1324
+ ...results.map(row),
1325
+ ""
1326
+ ].join("\n");
1327
+ }
1328
+ // src/report/index.ts
1329
+ /** The format names, in the order --help lists them. */
1330
+ const FORMAT_NAMES = [
1331
+ "human",
1332
+ "json",
1333
+ "markdown",
1334
+ "junit"
1335
+ ];
1336
+ function isFormat(name) {
1337
+ return FORMAT_NAMES.includes(name);
1338
+ }
1339
+ /** Every output format; the Record type makes a missing formatter a type error. */
1340
+ const FORMATS = {
1341
+ human: formatHuman,
1342
+ json: formatJson,
1343
+ markdown: formatMarkdown,
1344
+ junit: formatJunit
1345
+ };
1346
+ // src/report/write.ts
1347
+ /**
1348
+ * Writes a report so that nothing ever sees half of it: a temporary file in the
1349
+ * same directory, then a rename, which is atomic on one file system. Missing
1350
+ * parent directories are created. Throws on failure, leaving no temporary file.
1351
+ */
1352
+ function writeReportFile(path, text) {
1353
+ mkdirSync(dirname(path), { recursive: true });
1354
+ const temp = `${path}.cliprobe-${process.pid}.tmp`;
1355
+ try {
1356
+ writeFileSync(temp, text);
1357
+ renameSync(temp, path);
1358
+ } catch (error) {
1359
+ rmSync(temp, { force: true });
1360
+ throw error;
1361
+ }
1362
+ }
1085
1363
  // src/version.ts
1086
1364
  /**
1087
1365
  * Read from the package manifest at runtime. Works from both `src/` (development)
@@ -1097,7 +1375,8 @@ const VERSION = readVersion();
1097
1375
  var UsageError = class extends Error {};
1098
1376
  function parseArgs(argv) {
1099
1377
  const opts = {
1100
- json: false,
1378
+ format: "human",
1379
+ outputFile: void 0,
1101
1380
  timeout: 15e3,
1102
1381
  help: false,
1103
1382
  version: false,
@@ -1111,8 +1390,16 @@ function parseArgs(argv) {
1111
1390
  [opts.command, ...opts.args] = argv.slice(i + 1);
1112
1391
  break;
1113
1392
  }
1114
- if (a === "--json") opts.json = true;
1115
- else if (a === "-h" || a === "--help") opts.help = true;
1393
+ if (a === "--json") opts.format = "json";
1394
+ else if (a === "-o" || a === "--output-file" || a.startsWith("--output-file=")) {
1395
+ const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
1396
+ if (!value) throw new UsageError(`${a.split("=")[0] ?? a} needs a file path`);
1397
+ opts.outputFile = value;
1398
+ } else if (a === "--format" || a.startsWith("--format=")) {
1399
+ const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
1400
+ if (value === void 0 || !isFormat(value)) throw new UsageError(`--format needs one of ${FORMAT_NAMES.join(", ")}, got "${String(value)}"`);
1401
+ opts.format = value;
1402
+ } else if (a === "-h" || a === "--help") opts.help = true;
1116
1403
  else if (a === "-v" || a === "--version") opts.version = true;
1117
1404
  else if (a === "--timeout" || a.startsWith("--timeout=")) {
1118
1405
  const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
@@ -1130,7 +1417,7 @@ function parseArgs(argv) {
1130
1417
  }
1131
1418
  return opts;
1132
1419
  }
1133
- // src/cli/main.ts
1420
+ // src/cli/help.ts
1134
1421
  const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
1135
1422
 
1136
1423
  Usage:
@@ -1149,6 +1436,9 @@ Checks:
1149
1436
  color Runs the command into a pipe, then under a terminal, then under
1150
1437
  a terminal with NO_COLOR=1. Fails if color codes reach a pipe;
1151
1438
  warns if color goes to a piped stderr or NO_COLOR is ignored.
1439
+ pipe-escapes Runs the command into a pipe and warns if cursor movement,
1440
+ erase, hyperlink, window title or carriage-return redraw
1441
+ codes (spinners, progress bars) reach stdout or stderr.
1152
1442
  ctrl-c Sends Ctrl-C (SIGINT) after 1 s. Fails if the command is still
1153
1443
  running 3 s later or prints a stack trace; warns if it exits 0.
1154
1444
  Skipped when the command finishes first, so probe a command
@@ -1169,7 +1459,12 @@ Info checks (never fail; run only when named with --check):
1169
1459
 
1170
1460
  Options:
1171
1461
  --check <name> Run only this check; repeat it or use commas for several
1172
- --json Print results as JSON
1462
+ --format <name> Output format: human (default), json, markdown (a CI job
1463
+ summary or PR comment) or junit (XML for CI test reports)
1464
+ --json Same as --format json
1465
+ -o, --output-file <path>
1466
+ Write the --format report to a file (created atomically,
1467
+ with parent folders); the human report still prints
1173
1468
  --timeout <ms> Kill a probe after this long (default 15000)
1174
1469
  -h, --help Show this help
1175
1470
  -v, --version Show the version
@@ -1177,16 +1472,20 @@ Options:
1177
1472
  Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
1178
1473
  Runs the target in the current directory without a shell, with stdin closed,
1179
1474
  a temporary HOME and a minimal environment. Only run programs you trust.`;
1180
- const out = (text) => {
1181
- process.stdout.write(text);
1182
- };
1183
- const err = (text) => {
1184
- process.stderr.write(text);
1185
- };
1186
- async function main() {
1475
+ // src/cli/program.ts
1476
+ /** 0 no failures, 1 a check failed, 2 nothing could be judged because something could not run. */
1477
+ function exitCodeFor(results) {
1478
+ if (results.some((r) => r.verdict === "fail")) return 1;
1479
+ if (!results.some((r) => r.verdict !== "error" && r.verdict !== "skip") && results.some((r) => r.verdict === "error")) return 2;
1480
+ return 0;
1481
+ }
1482
+ /** The whole CLI: parses argv, runs the checks, reports, and returns the exit code. */
1483
+ async function run(argv, io) {
1484
+ const out = io.stdout;
1485
+ const err = io.stderr;
1187
1486
  let opts;
1188
1487
  try {
1189
- opts = parseArgs(process.argv.slice(2));
1488
+ opts = parseArgs(argv);
1190
1489
  } catch (error) {
1191
1490
  if (!(error instanceof UsageError)) throw error;
1192
1491
  err(`cliprobe: ${error.message}\nRun "cliprobe --help" for usage.\n`);
@@ -1203,15 +1502,14 @@ async function main() {
1203
1502
  const { checks, unknown } = selectChecks(opts.checks);
1204
1503
  if (unknown.length) {
1205
1504
  const available = CHECKS.map((c) => c.name).join(", ");
1206
- const quoted = unknown.map((n) => `"${n}"`).join(", ");
1207
- err(`cliprobe: unknown check ${quoted} (available: ${available})\n`);
1505
+ err(`cliprobe: unknown check ${unknown.map((n) => `"${n}"`).join(", ")} (available: ${available})\n`);
1208
1506
  return 2;
1209
1507
  }
1210
1508
  if (!opts.command) {
1211
1509
  err("cliprobe: no command given\nUsage: cliprobe [options] -- <command> [args...]\n");
1212
1510
  return 2;
1213
1511
  }
1214
- if (process.platform === "win32") {
1512
+ if (io.platform === "win32") {
1215
1513
  err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
1216
1514
  return 2;
1217
1515
  }
@@ -1229,19 +1527,35 @@ async function main() {
1229
1527
  } finally {
1230
1528
  fixture?.cleanup();
1231
1529
  }
1232
- const report = (text) => out(fixture ? collapseFixture(text, fixture) : text);
1233
- if (opts.json) report(formatJson(VERSION, opts.command, checks.map((c) => c.name), results));
1234
- else {
1235
- const useColor = process.stdout.isTTY && !process.env["NO_COLOR"];
1236
- report(formatHuman(VERSION, opts.command, checks.map((c) => c.name), results, useColor));
1237
- }
1238
- if (results.some((r) => r.verdict === "fail")) return 1;
1239
- if (!results.some((r) => r.verdict !== "error" && r.verdict !== "skip") && results.some((r) => r.verdict === "error")) return 2;
1240
- return 0;
1530
+ const collapse = (text) => fixture ? collapseFixture(text, fixture) : text;
1531
+ const report = {
1532
+ version: VERSION,
1533
+ command: opts.command,
1534
+ checks: checks.map((c) => c.name),
1535
+ results
1536
+ };
1537
+ const { color } = io;
1538
+ if (opts.outputFile) {
1539
+ try {
1540
+ writeReportFile(opts.outputFile, collapse(FORMATS[opts.format](report, { color: false })));
1541
+ } catch (error) {
1542
+ const reason = error instanceof Error ? error.message : String(error);
1543
+ err(`cliprobe: could not write ${safe(opts.outputFile)}: ${safe(reason)}\n`);
1544
+ return 2;
1545
+ }
1546
+ out(collapse(FORMATS.human(report, { color })));
1547
+ } else out(collapse(FORMATS[opts.format](report, { color })));
1548
+ return exitCodeFor(results);
1241
1549
  }
1550
+ // src/cli/main.ts
1242
1551
  process.stdout.on("error", (error) => {
1243
1552
  if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1244
1553
  throw error;
1245
1554
  });
1246
- process.exitCode = await main();
1555
+ process.exitCode = await run(process.argv.slice(2), {
1556
+ stdout: (text) => process.stdout.write(text),
1557
+ stderr: (text) => process.stderr.write(text),
1558
+ color: process.stdout.isTTY && !process.env["NO_COLOR"],
1559
+ platform: process.platform
1560
+ });
1247
1561
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
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.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -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": [
@@ -73,9 +74,13 @@
73
74
  "@semantic-release/github": "^12.0.10",
74
75
  "@semantic-release/npm": "^13.2.0",
75
76
  "@semantic-release/release-notes-generator": "^14.1.1",
77
+ "@types/markdown-it": "^14.2.0",
76
78
  "@types/node": "^22.20.5",
79
+ "@vitest/coverage-v8": "^5.1.0",
77
80
  "conventional-changelog-conventionalcommits": "^9.3.1",
81
+ "fast-xml-parser": "^5.12.0",
78
82
  "husky": "^9.1.7",
83
+ "markdown-it": "^15.0.3",
79
84
  "oxlint": "^1.88.0",
80
85
  "oxlint-tsgolint": "^7.0.2004",
81
86
  "prettier": "^3.9.10",