cliprobe 0.0.1 → 0.2.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 (4) hide show
  1. package/README.md +131 -21
  2. package/dist/cli.js +1420 -0
  3. package/package.json +90 -44
  4. package/bin/cliprobe.js +0 -225
package/dist/cli.js ADDED
@@ -0,0 +1,1420 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { execFileSync, spawn } from "node:child_process";
4
+ import { closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+ // src/core/sandbox.ts
8
+ /** A minimal environment: no tokens or config from the caller's shell. */
9
+ function sandbox() {
10
+ const dir = mkdtempSync(join(tmpdir(), "cliprobe-"));
11
+ return {
12
+ dir,
13
+ env: {
14
+ PATH: process.env["PATH"] ?? "/usr/bin:/bin",
15
+ LANG: process.env["LANG"] ?? "C.UTF-8",
16
+ HOME: dir,
17
+ TMPDIR: dir,
18
+ TERM: "dumb",
19
+ CI: "1",
20
+ NO_UPDATE_NOTIFIER: "1"
21
+ }
22
+ };
23
+ }
24
+ // src/core/run.ts
25
+ const STDERR_CAP = 65536;
26
+ const STDOUT_CAP = 1048576;
27
+ /**
28
+ * Runs one invocation. With `closedStdout`, stdout is the write end of a FIFO
29
+ * whose read end is closed before the program starts, so its first write to
30
+ * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
31
+ */
32
+ function run(command, args, { closedStdout = false, timeout, env: overrides = {}, beforeKill, signal }) {
33
+ const { dir, env: base } = sandbox();
34
+ const env = { ...base };
35
+ for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
36
+ else env[key] = value;
37
+ let stdoutFd = "pipe";
38
+ if (closedStdout) {
39
+ const fifo = join(dir, "stdout.fifo");
40
+ execFileSync("mkfifo", [fifo]);
41
+ const reader = openSync(fifo, constants.O_RDONLY | constants.O_NONBLOCK);
42
+ stdoutFd = openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK);
43
+ closeSync(reader);
44
+ }
45
+ return new Promise((resolve) => {
46
+ let stdoutBytes = 0;
47
+ const stdoutChunks = [];
48
+ let stderr = "";
49
+ let timedOut = false;
50
+ let finished = false;
51
+ let exited = false;
52
+ let signalSentMs;
53
+ let stderrAtSignal;
54
+ const start = performance.now();
55
+ const finish = (outcome) => {
56
+ if (finished) return;
57
+ finished = true;
58
+ if (typeof stdoutFd === "number") closeSync(stdoutFd);
59
+ rmSync(dir, {
60
+ recursive: true,
61
+ force: true
62
+ });
63
+ const stdout = Buffer.concat(stdoutChunks).subarray(0, STDOUT_CAP);
64
+ resolve({
65
+ stdoutBytes,
66
+ stdout,
67
+ stderr,
68
+ timedOut,
69
+ durationMs: Math.round(performance.now() - start),
70
+ ...signalSentMs === void 0 ? {} : {
71
+ signalSentMs,
72
+ stderrAtSignal: stderrAtSignal ?? 0
73
+ },
74
+ ...outcome
75
+ });
76
+ };
77
+ let child;
78
+ try {
79
+ child = spawn(command, [...args], {
80
+ env,
81
+ stdio: [
82
+ "ignore",
83
+ stdoutFd,
84
+ "pipe"
85
+ ],
86
+ detached: true
87
+ });
88
+ } catch (error) {
89
+ finish({
90
+ exitCode: null,
91
+ signal: null,
92
+ spawnError: error instanceof Error ? error.message : String(error)
93
+ });
94
+ return;
95
+ }
96
+ const timer = setTimeout(() => {
97
+ timedOut = true;
98
+ beforeKill?.();
99
+ try {
100
+ if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
101
+ } catch {}
102
+ }, timeout);
103
+ const signalTimer = signal && setTimeout(() => {
104
+ if (exited || child.pid === void 0) return;
105
+ signalSentMs = Math.round(performance.now() - start);
106
+ stderrAtSignal = stderr.length;
107
+ try {
108
+ process.kill(-child.pid, signal.name);
109
+ } catch {}
110
+ }, signal.afterMs);
111
+ child.on("exit", () => {
112
+ exited = true;
113
+ clearTimeout(signalTimer);
114
+ });
115
+ child.stdout?.on("data", (chunk) => {
116
+ if (stdoutBytes < STDOUT_CAP) stdoutChunks.push(chunk);
117
+ stdoutBytes += chunk.length;
118
+ });
119
+ child.stderr?.on("data", (chunk) => {
120
+ if (stderr.length < STDERR_CAP) stderr += chunk.toString("utf8");
121
+ });
122
+ child.on("error", (error) => {
123
+ clearTimeout(timer);
124
+ clearTimeout(signalTimer);
125
+ finish({
126
+ exitCode: null,
127
+ signal: null,
128
+ spawnError: error.message
129
+ });
130
+ });
131
+ child.on("close", (exitCode, exitSignal) => {
132
+ clearTimeout(timer);
133
+ clearTimeout(signalTimer);
134
+ finish({
135
+ exitCode,
136
+ signal: exitSignal
137
+ });
138
+ });
139
+ });
140
+ }
141
+ // src/checks/baseline.ts
142
+ /** A flag no real program defines. */
143
+ const UNKNOWN_FLAG = "--cliprobe-unknown-flag";
144
+ /** A program that ignores unknown flags may start its default action; don't wait long. */
145
+ const UNKNOWN_FLAG_TIMEOUT_MS = 5e3;
146
+ const lines = (text) => text.split("\n").filter((l) => l.trim() !== "");
147
+ const firstLine = (r) => lines(r.stdout.toString("utf8"))[0] ?? lines(r.stderr)[0] ?? "";
148
+ const exitText = (r) => r.signal ? `was stopped by ${r.signal}` : `exited ${r.exitCode}`;
149
+ /** Each describes one convention scripts and agents rely on; observations, never verdicts. */
150
+ function describeVersion(r) {
151
+ const out = lines(r.stdout.toString("utf8"));
152
+ if (r.exitCode !== 0) return {
153
+ reason: `${exitText(r)}; there may be no --version`,
154
+ evidence: firstLine(r)
155
+ };
156
+ if (out.length === 1) return {
157
+ reason: "printed one line to stdout",
158
+ evidence: out[0] ?? ""
159
+ };
160
+ if (out.length > 1) return {
161
+ reason: `printed ${out.length} lines to stdout; one line is easier for scripts to parse`,
162
+ evidence: out[0] ?? ""
163
+ };
164
+ if (lines(r.stderr).length) return {
165
+ reason: "printed the version to stderr, not stdout",
166
+ evidence: firstLine(r)
167
+ };
168
+ return { reason: "printed nothing" };
169
+ }
170
+ function describeHelp(r) {
171
+ const out = lines(r.stdout.toString("utf8"));
172
+ const err = lines(r.stderr);
173
+ if (out.length && r.exitCode === 0) return { reason: `printed ${out.length} lines to stdout and exited 0` };
174
+ if (out.length) return { reason: `printed help to stdout but ${exitText(r)}` };
175
+ if (err.length) return { reason: `printed help to stderr and ${exitText(r)}, so "--help | less" and agents reading stdout get nothing` };
176
+ return { reason: `printed nothing and ${exitText(r)}` };
177
+ }
178
+ function describeUnknownFlag(r) {
179
+ if (r.timedOut) return { reason: `still running after ${UNKNOWN_FLAG_TIMEOUT_MS / 1e3} s; it may have ignored the flag and started its default action` };
180
+ const evidence = firstLine(r);
181
+ const withEvidence = (reason) => evidence ? {
182
+ reason,
183
+ evidence
184
+ } : { reason };
185
+ if (r.exitCode === 0) return withEvidence("exited 0, so a script cannot tell the flag was wrong");
186
+ if (lines(r.stdout.toString("utf8")).length) return withEvidence(`${exitText(r)}, but printed its message to stdout rather than stderr`);
187
+ if (lines(r.stderr).length) return withEvidence(`${exitText(r)} with its message on stderr`);
188
+ return { reason: `${exitText(r)} without saying why` };
189
+ }
190
+ async function probe(command, args, timeout, describe) {
191
+ const r = await run(command, args, { timeout });
192
+ const base = {
193
+ check: "baseline",
194
+ invocation: [command, ...args]
195
+ };
196
+ if (r.spawnError) return {
197
+ ...base,
198
+ verdict: "error",
199
+ reason: `could not start: ${r.spawnError}`,
200
+ exitCode: null,
201
+ stdoutLines: 0,
202
+ stderrLines: 0
203
+ };
204
+ const { reason, evidence } = r.timedOut && describe !== describeUnknownFlag ? {
205
+ reason: "timed out",
206
+ evidence: void 0
207
+ } : describe(r);
208
+ return {
209
+ ...base,
210
+ verdict: "info",
211
+ reason,
212
+ ...evidence ? { evidence } : {},
213
+ exitCode: r.exitCode,
214
+ stdoutLines: lines(r.stdout.toString("utf8")).length,
215
+ stderrLines: lines(r.stderr).length
216
+ };
217
+ }
218
+ const baselineCheck = {
219
+ name: "baseline",
220
+ kind: "info",
221
+ summary: "--version prints one line, --help goes to stdout, an unknown flag exits non-zero",
222
+ async run(target, ctx) {
223
+ const prefix = target.explicit ? target.invocations[0] ?? [] : [];
224
+ return [
225
+ await probe(target.command, [...prefix, "--version"], ctx.timeout, describeVersion),
226
+ await probe(target.command, [...prefix, "--help"], ctx.timeout, describeHelp),
227
+ await probe(target.command, [...prefix, UNKNOWN_FLAG], Math.min(ctx.timeout, UNKNOWN_FLAG_TIMEOUT_MS), describeUnknownFlag)
228
+ ];
229
+ }
230
+ };
231
+ // src/core/evidence.ts
232
+ /** Signs that a program reported a write failure or crashed with a stack trace. */
233
+ const ERROR_RE = /EPIPE|broken ?pipe|BrokenPipeError|Unhandled 'error' event|^\s+at .+:\d+:\d+\)?$/im;
234
+ /** Signs of a stack trace from Node, Python, Go or Rust. */
235
+ const TRACE_RE = /Traceback \(most recent call last\)|^\s+at .+:\d+:\d+\)?$|^panic: |^goroutine \d+ \[|thread '.+' panicked/m;
236
+ /** Lines worth quoting as the error message, best first. */
237
+ const CRASH_MESSAGES = [/^(\w*Error\b|panic:)/, ERROR_RE];
238
+ /**
239
+ * Picks the most useful evidence from a crash: the error message plus the first
240
+ * stack frame in the program's own code (not Node internals), which usually
241
+ * points at the faulty line. `messages` ranks the patterns for the message line.
242
+ */
243
+ function crashEvidence(stderr, messages = CRASH_MESSAGES) {
244
+ const lines = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
245
+ let message = "";
246
+ for (const pattern of messages) {
247
+ message = lines.find((l) => pattern.test(l)) ?? "";
248
+ if (message) break;
249
+ }
250
+ message ||= lines[0] ?? "";
251
+ const frame = lines.find((l) => l.startsWith("at ") && !/\bnode:/.test(l))?.match(/(?:file:\/\/)?(\/[^\s()]+:\d+:\d+)/)?.[1];
252
+ if (!frame) return message;
253
+ const cwd = process.cwd() + "/";
254
+ return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
255
+ }
256
+ // src/checks/closed-pipe.ts
257
+ /** Compares a normal run with a closed-stdout run of the same invocation. */
258
+ function judge(base, closed) {
259
+ if (base.spawnError) return {
260
+ verdict: "error",
261
+ reason: `could not start: ${base.spawnError}`
262
+ };
263
+ if (base.timedOut) return {
264
+ verdict: "error",
265
+ reason: "timed out on a normal run"
266
+ };
267
+ if (base.stdoutBytes === 0) return {
268
+ verdict: "skip",
269
+ reason: "wrote nothing to stdout, so a closed stdout is never touched"
270
+ };
271
+ if (closed.timedOut) return {
272
+ verdict: "fail",
273
+ reason: "hung after stdout was closed"
274
+ };
275
+ if (closed.signal === "SIGPIPE") return {
276
+ verdict: "pass",
277
+ reason: "stopped by SIGPIPE, the conventional exit"
278
+ };
279
+ const newError = ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
280
+ if (newError && closed.exitCode !== base.exitCode) return {
281
+ verdict: "fail",
282
+ reason: `crashed when stdout was closed (exit ${base.exitCode} -> ${closed.exitCode})`,
283
+ evidence: crashEvidence(closed.stderr)
284
+ };
285
+ if (newError) return {
286
+ verdict: "warn",
287
+ reason: "printed a write error but kept its exit code",
288
+ evidence: crashEvidence(closed.stderr)
289
+ };
290
+ if (closed.exitCode !== base.exitCode) return {
291
+ verdict: "pass",
292
+ reason: `exited quietly with code ${closed.exitCode}`
293
+ };
294
+ return {
295
+ verdict: "pass",
296
+ reason: "exited quietly"
297
+ };
298
+ }
299
+ async function closedPipe(command, args, timeout) {
300
+ const base = await run(command, args, {
301
+ closedStdout: false,
302
+ timeout
303
+ });
304
+ const closed = await run(command, args, {
305
+ closedStdout: true,
306
+ timeout
307
+ });
308
+ return {
309
+ check: "closed-pipe",
310
+ invocation: [command, ...args],
311
+ ...judge(base, closed),
312
+ baseline: {
313
+ exitCode: base.exitCode,
314
+ signal: base.signal,
315
+ stdoutBytes: base.stdoutBytes
316
+ },
317
+ closed: {
318
+ exitCode: closed.exitCode,
319
+ signal: closed.signal,
320
+ timedOut: closed.timedOut,
321
+ stderr: closed.stderr.slice(-2e3)
322
+ }
323
+ };
324
+ }
325
+ const closedPipeCheck = {
326
+ name: "closed-pipe",
327
+ kind: "check",
328
+ summary: "crashes or hangs when stdout is closed early (| head, grep -q, an agent)",
329
+ async run(target, ctx) {
330
+ const results = [];
331
+ for (const args of target.invocations) results.push(await closedPipe(target.command, args, ctx.timeout));
332
+ return results;
333
+ }
334
+ };
335
+ // src/core/ansi.ts
336
+ const SGR = /\x1b\[([0-9;:]*)m/g;
337
+ /** SGR params that only turn something off. A sequence made only of these is not styling. */
338
+ const RESETS = /* @__PURE__ */ new Set([
339
+ "",
340
+ "0",
341
+ "22",
342
+ "23",
343
+ "24",
344
+ "25",
345
+ "27",
346
+ "28",
347
+ "29",
348
+ "39",
349
+ "49",
350
+ "54",
351
+ "55",
352
+ "59"
353
+ ]);
354
+ /**
355
+ * Finds the first SGR sequence that sets a color or style (red, bold, 256-color,
356
+ * truecolor...). Pure resets are ignored: some programs always print them, and
357
+ * they change nothing on screen.
358
+ */
359
+ function findStyle(text) {
360
+ for (const match of text.matchAll(SGR)) {
361
+ if ((match[1] ?? "").split(/[;:]/).every((p) => RESETS.has(p))) continue;
362
+ const before = text.slice(0, match.index);
363
+ const start = before.lastIndexOf("\n") + 1;
364
+ const newline = text.indexOf("\n", match.index);
365
+ const end = newline === -1 ? text.length : newline;
366
+ return {
367
+ sequence: match[0],
368
+ line: before.split("\n").length,
369
+ text: text.slice(start, end).slice(0, 120)
370
+ };
371
+ }
372
+ }
373
+ let cached;
374
+ /** Whether this machine can run a program under a PTY, detected once. */
375
+ function ptySupport() {
376
+ cached ??= detect();
377
+ return cached;
378
+ }
379
+ function detect() {
380
+ if (process.platform === "darwin") try {
381
+ execFileSync("script", [
382
+ "-q",
383
+ "/dev/null",
384
+ "true"
385
+ ], {
386
+ stdio: "ignore",
387
+ timeout: 5e3
388
+ });
389
+ return {
390
+ ok: true,
391
+ flavor: "bsd"
392
+ };
393
+ } catch {
394
+ return {
395
+ ok: false,
396
+ reason: "script(1) did not run"
397
+ };
398
+ }
399
+ if (process.platform === "linux") {
400
+ try {
401
+ if (execFileSync("script", ["--version"], {
402
+ encoding: "utf8",
403
+ stdio: [
404
+ "ignore",
405
+ "pipe",
406
+ "pipe"
407
+ ],
408
+ timeout: 5e3
409
+ }).includes("util-linux")) return {
410
+ ok: true,
411
+ flavor: "util-linux"
412
+ };
413
+ } catch (error) {
414
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
415
+ ok: false,
416
+ reason: "script(1) not found; install util-linux (bsdutils on Debian and Ubuntu)"
417
+ };
418
+ }
419
+ return {
420
+ ok: false,
421
+ reason: "script(1) is not the util-linux version"
422
+ };
423
+ }
424
+ return {
425
+ ok: false,
426
+ reason: `no PTY support on ${process.platform}`
427
+ };
428
+ }
429
+ /** Quotes one argument for a POSIX shell. */
430
+ function shellQuote(arg) {
431
+ return `'${arg.replaceAll("'", `'\\''`)}'`;
432
+ }
433
+ /**
434
+ * The script(1) arguments that run `command args...` under a PTY.
435
+ *
436
+ * A small /bin/sh wrapper writes its PID to `pidFile`, sets the window size and
437
+ * then execs the program, so the PID is the program's and the program leads its
438
+ * own session and process group. Everything after the script reaches the
439
+ * program as argv; only the util-linux form needs quoting, because its -c takes
440
+ * a single string.
441
+ */
442
+ function ptyArgs(flavor, pidFile, command, args, cols = 80, rows = 24) {
443
+ const setup = `echo $$ > "$1"; shift; stty cols ${cols} rows ${rows} 2>/dev/null; exec "$@"`;
444
+ const argv = [
445
+ pidFile,
446
+ command,
447
+ ...args
448
+ ];
449
+ if (flavor === "bsd") return [
450
+ "-q",
451
+ "/dev/null",
452
+ "/bin/sh",
453
+ "-c",
454
+ setup,
455
+ "sh",
456
+ ...argv
457
+ ];
458
+ return [
459
+ "-qec",
460
+ `exec /bin/sh -c ${shellQuote(setup)} sh ${argv.map(shellQuote).join(" ")}`,
461
+ "/dev/null"
462
+ ];
463
+ }
464
+ /** BSD script echoes the EOF it forwards from /dev/null as "^D" and two backspaces. */
465
+ const BSD_EOF_ECHO = "^D\b\b";
466
+ /** Undoes the terminal's output processing: the EOF echo, and \n turned into \r\n. */
467
+ function cleanPtyOutput(raw, flavor) {
468
+ let text = raw.toString("utf8");
469
+ if (flavor === "bsd" && text.startsWith(BSD_EOF_ECHO)) text = text.slice(4);
470
+ return text.replaceAll("\r\n", "\n");
471
+ }
472
+ /**
473
+ * Runs a program with stdin, stdout and stderr on a PTY, an 80x24 window and
474
+ * TERM=xterm-256color. stdin is /dev/null behind the PTY: the program reads one
475
+ * EOF, and a second read blocks until the timeout.
476
+ */
477
+ async function runPty(command, args, { timeout, env = {} }) {
478
+ const support = ptySupport();
479
+ if (!support.ok) throw new Error(`no PTY: ${support.reason}`);
480
+ const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
481
+ const pidFile = join(dir, "pid");
482
+ try {
483
+ const result = await run("script", ptyArgs(support.flavor, pidFile, command, args), {
484
+ timeout,
485
+ env: {
486
+ TERM: "xterm-256color",
487
+ SHELL: "/bin/sh",
488
+ ...env
489
+ },
490
+ beforeKill: () => killGroupFromPidFile(pidFile)
491
+ });
492
+ return {
493
+ output: cleanPtyOutput(result.stdout, support.flavor),
494
+ exitCode: result.exitCode,
495
+ timedOut: result.timedOut,
496
+ ...result.spawnError === void 0 ? {} : { spawnError: result.spawnError },
497
+ scriptStderr: result.stderr
498
+ };
499
+ } finally {
500
+ rmSync(dir, {
501
+ recursive: true,
502
+ force: true
503
+ });
504
+ }
505
+ }
506
+ function killGroupFromPidFile(pidFile) {
507
+ try {
508
+ const pid = Number(readFileSync(pidFile, "utf8").trim());
509
+ if (Number.isInteger(pid) && pid > 1) process.kill(-pid, "SIGKILL");
510
+ } catch {}
511
+ }
512
+ // src/checks/color.ts
513
+ /**
514
+ * Every color run gets a terminal type that supports color, so a program cannot
515
+ * pass by seeing TERM=dumb, and no CI variable, which some color libraries treat
516
+ * as a reason to force color on.
517
+ */
518
+ const COLOR_ENV = {
519
+ TERM: "xterm-256color",
520
+ CI: void 0
521
+ };
522
+ const describeHit = (stream, hit) => `${stream} line ${hit.line}: ${hit.text}`;
523
+ /** The first verdict the pipe run alone can settle, if any. */
524
+ function judgePipe(pipe) {
525
+ if (pipe.spawnError) return {
526
+ verdict: "error",
527
+ reason: `could not start: ${pipe.spawnError}`
528
+ };
529
+ if (pipe.timedOut) return {
530
+ verdict: "error",
531
+ reason: "timed out on a normal run"
532
+ };
533
+ const stdoutHit = findStyle(pipe.stdout.toString("utf8"));
534
+ if (stdoutHit) return {
535
+ verdict: "fail",
536
+ reason: "printed color codes into a pipe",
537
+ evidence: describeHit("stdout", stdoutHit)
538
+ };
539
+ const stderrHit = findStyle(pipe.stderr);
540
+ if (stderrHit) return {
541
+ verdict: "warn",
542
+ reason: "printed color codes to stderr when it was a pipe",
543
+ evidence: describeHit("stderr", stderrHit)
544
+ };
545
+ }
546
+ function judgeColor(runs) {
547
+ const fromPipe = judgePipe(runs.pipe);
548
+ if (fromPipe) return fromPipe;
549
+ const { tty, noColor } = runs;
550
+ if (!tty) return {
551
+ verdict: "skip",
552
+ reason: `no color in a pipe; no terminal to compare with (${runs.noPty ?? "no PTY"})`
553
+ };
554
+ if (tty.timedOut) return {
555
+ verdict: "skip",
556
+ reason: "no color in a pipe; in a terminal it waited for input, so it was not compared"
557
+ };
558
+ if (!findStyle(tty.output)) {
559
+ if (!(runs.pipe.stdoutBytes > 0 || runs.pipe.stderr.length > 0 || tty.output)) return {
560
+ verdict: "skip",
561
+ reason: "printed nothing, so there is no color to check"
562
+ };
563
+ return {
564
+ verdict: "pass",
565
+ reason: "no color in a pipe or in a terminal"
566
+ };
567
+ }
568
+ if (!noColor || noColor.timedOut) return {
569
+ verdict: "skip",
570
+ reason: "colors only in a terminal; the NO_COLOR run did not finish"
571
+ };
572
+ const noColorHit = findStyle(noColor.output);
573
+ if (noColorHit) return {
574
+ verdict: "warn",
575
+ reason: "ignores NO_COLOR: still prints color in a terminal",
576
+ evidence: describeHit("terminal", noColorHit)
577
+ };
578
+ return {
579
+ verdict: "pass",
580
+ reason: "colors only in a terminal, and NO_COLOR turns it off"
581
+ };
582
+ }
583
+ /** Runs only as many probes as the verdict needs: a pipe, then a terminal, then NO_COLOR. */
584
+ async function colorRuns(command, args, timeout) {
585
+ const pipe = await run(command, args, {
586
+ timeout,
587
+ env: COLOR_ENV
588
+ });
589
+ if (judgePipe(pipe)) return { pipe };
590
+ const support = ptySupport();
591
+ if (!support.ok) return {
592
+ pipe,
593
+ noPty: support.reason
594
+ };
595
+ const tty = await runPty(command, args, {
596
+ timeout,
597
+ env: COLOR_ENV
598
+ });
599
+ if (tty.timedOut || !findStyle(tty.output)) return {
600
+ pipe,
601
+ tty
602
+ };
603
+ return {
604
+ pipe,
605
+ tty,
606
+ noColor: await runPty(command, args, {
607
+ timeout,
608
+ env: {
609
+ ...COLOR_ENV,
610
+ NO_COLOR: "1"
611
+ }
612
+ })
613
+ };
614
+ }
615
+ const summarize = (r) => r ? {
616
+ exitCode: r.exitCode,
617
+ timedOut: r.timedOut,
618
+ styled: findStyle(r.output) !== void 0
619
+ } : null;
620
+ async function color(command, args, timeout) {
621
+ const runs = await colorRuns(command, args, timeout);
622
+ return {
623
+ check: "color",
624
+ invocation: [command, ...args],
625
+ ...judgeColor(runs),
626
+ pipe: {
627
+ exitCode: runs.pipe.exitCode,
628
+ stdoutStyled: findStyle(runs.pipe.stdout.toString("utf8")) !== void 0,
629
+ stderrStyled: findStyle(runs.pipe.stderr) !== void 0
630
+ },
631
+ tty: summarize(runs.tty),
632
+ noColor: summarize(runs.noColor)
633
+ };
634
+ }
635
+ const colorCheck = {
636
+ name: "color",
637
+ kind: "check",
638
+ summary: "prints color codes into pipes, or ignores NO_COLOR in a terminal",
639
+ async run(target, ctx) {
640
+ const results = [];
641
+ for (const args of target.invocations) results.push(await color(target.command, args, ctx.timeout));
642
+ return results;
643
+ }
644
+ };
645
+ // src/core/fixture.ts
646
+ /** Written in probe arguments; replaced with the path of a directory of hostile file names. */
647
+ const FIXTURE_PLACEHOLDER = "{fixture}";
648
+ const ESC = String.fromCharCode(27);
649
+ const BEL = String.fromCharCode(7);
650
+ const C1_CSI = String.fromCharCode(155);
651
+ const RIGHT_TO_LEFT_OVERRIDE = String.fromCharCode(8238);
652
+ /**
653
+ * File names a program may print. ESC sequences can drive the terminal (fail);
654
+ * C1 controls, carriage returns and newlines can hide or forge output (warn); a
655
+ * bidirectional override reorders text, but GNU ls and find print it raw too
656
+ * (note only).
657
+ */
658
+ const HOSTILE_NAMES = [
659
+ {
660
+ kind: "osc",
661
+ name: `title-${ESC}]0;cliprobe${BEL}.txt`,
662
+ marker: `${ESC}]0;cliprobe${BEL}`,
663
+ label: "an escape sequence that sets the window title",
664
+ severity: "fail"
665
+ },
666
+ {
667
+ kind: "csi",
668
+ name: `clear-${ESC}[2J.txt`,
669
+ marker: `${ESC}[2J`,
670
+ label: "an escape sequence that clears the screen",
671
+ severity: "fail"
672
+ },
673
+ {
674
+ kind: "c1",
675
+ name: `c1-${C1_CSI}2J.txt`,
676
+ marker: `${C1_CSI}2J`,
677
+ label: "a C1 control character",
678
+ severity: "warn"
679
+ },
680
+ {
681
+ kind: "cr",
682
+ name: "cr-\rspoof.txt",
683
+ marker: "cr-\rspoof",
684
+ label: "a carriage return",
685
+ severity: "warn"
686
+ },
687
+ {
688
+ kind: "newline",
689
+ name: "nl-\nspoof.txt",
690
+ marker: "nl-\nspoof",
691
+ label: "a newline",
692
+ severity: "warn"
693
+ },
694
+ {
695
+ kind: "bidi",
696
+ name: `bidi-${RIGHT_TO_LEFT_OVERRIDE}txt.exe`,
697
+ marker: `${RIGHT_TO_LEFT_OVERRIDE}txt`,
698
+ label: "a bidirectional override",
699
+ severity: "note"
700
+ }
701
+ ];
702
+ /** An ordinary name; seeing it in the output shows the program listed the directory. */
703
+ const PLAIN_NAME = "plain.txt";
704
+ /** Creates a temporary directory holding the hostile names and one plain file. */
705
+ function createFixture() {
706
+ const dir = mkdtempSync(join(tmpdir(), "cliprobe-fixture-"));
707
+ for (const { name } of HOSTILE_NAMES) writeFileSync(join(dir, name), "");
708
+ writeFileSync(join(dir, PLAIN_NAME), "");
709
+ return {
710
+ dir,
711
+ realDir: realpathSync(dir),
712
+ cleanup: () => rmSync(dir, {
713
+ recursive: true,
714
+ force: true
715
+ })
716
+ };
717
+ }
718
+ function usesFixture(args) {
719
+ return args.some((a) => a.includes(FIXTURE_PLACEHOLDER));
720
+ }
721
+ /** Replaces the placeholder in every argument, including inside `--dir={fixture}`. */
722
+ function expandFixture(args, dir) {
723
+ return args.map((a) => a.replaceAll(FIXTURE_PLACEHOLDER, dir));
724
+ }
725
+ /**
726
+ * Puts the placeholder back wherever the fixture's path appears in report text,
727
+ * so reports show {fixture} rather than a path that no longer exists.
728
+ */
729
+ function collapseFixture(text, fixture) {
730
+ return text.replaceAll(fixture.realDir, FIXTURE_PLACEHOLDER).replaceAll(fixture.dir, FIXTURE_PLACEHOLDER);
731
+ }
732
+ // src/checks/control-chars.ts
733
+ const ENV = {
734
+ TERM: "xterm-256color",
735
+ CI: void 0
736
+ };
737
+ /** The hostile names whose dangerous part appears in the output unescaped. */
738
+ function rawNames(output) {
739
+ return HOSTILE_NAMES.filter((h) => output.includes(h.marker));
740
+ }
741
+ const listLabels = (names) => {
742
+ const labels = names.map((h) => h.label);
743
+ return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
744
+ };
745
+ const evidenceFor = (names) => `file names printed raw: ${names.map((h) => h.name).join(", ")}`;
746
+ function judgeControlChars(runs) {
747
+ if (!runs.usesFixture) return {
748
+ verdict: "skip",
749
+ reason: "no {fixture} in the arguments; put it where the command takes a path, e.g. ls {fixture}"
750
+ };
751
+ const { pipe, tty } = runs;
752
+ if (pipe?.spawnError) return {
753
+ verdict: "error",
754
+ reason: `could not start: ${pipe.spawnError}`
755
+ };
756
+ if (pipe?.timedOut) return {
757
+ verdict: "error",
758
+ reason: "timed out on a normal run"
759
+ };
760
+ if (!tty) return {
761
+ verdict: "skip",
762
+ reason: `no terminal to check with (${runs.noPty ?? "no PTY"})`
763
+ };
764
+ if (tty.timedOut) return {
765
+ verdict: "skip",
766
+ reason: "waited for input in a terminal"
767
+ };
768
+ if (!tty.output.includes("plain.txt")) return {
769
+ verdict: "skip",
770
+ reason: "did not print the file names in {fixture}, so there was nothing to escape"
771
+ };
772
+ const raw = rawNames(tty.output);
773
+ const failing = raw.filter((h) => h.severity === "fail");
774
+ if (failing.length) return {
775
+ verdict: "fail",
776
+ reason: `sent ${failing.length > 1 ? "escape sequences" : "an escape sequence"} from file names to the terminal unescaped`,
777
+ evidence: evidenceFor(failing)
778
+ };
779
+ const warning = raw.filter((h) => h.severity === "warn");
780
+ if (warning.length) return {
781
+ verdict: "warn",
782
+ reason: `printed ${listLabels(warning)} from file names unescaped, which can hide or forge output`,
783
+ evidence: evidenceFor(warning)
784
+ };
785
+ const noted = raw.filter((h) => h.severity === "note");
786
+ return {
787
+ verdict: "pass",
788
+ reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels(noted)} as is` : ""}`
789
+ };
790
+ }
791
+ async function controlCharsRuns(command, args, fixtureDir, timeout) {
792
+ const usesFixture = fixtureDir !== void 0 && args.some((a) => a.includes(fixtureDir));
793
+ if (!usesFixture) return { usesFixture };
794
+ const pipe = await run(command, args, {
795
+ timeout,
796
+ env: ENV
797
+ });
798
+ if (pipe.spawnError || pipe.timedOut) return {
799
+ usesFixture,
800
+ pipe
801
+ };
802
+ const support = ptySupport();
803
+ if (!support.ok) return {
804
+ usesFixture,
805
+ pipe,
806
+ noPty: support.reason
807
+ };
808
+ return {
809
+ usesFixture,
810
+ pipe,
811
+ tty: await runPty(command, args, {
812
+ timeout,
813
+ env: ENV
814
+ })
815
+ };
816
+ }
817
+ const kinds = (output) => output === void 0 ? [] : rawNames(output).map((h) => h.kind);
818
+ async function controlChars(command, args, fixtureDir, timeout) {
819
+ const runs = await controlCharsRuns(command, args, fixtureDir, timeout);
820
+ const pipeOutput = runs.pipe && runs.pipe.stdout.toString("utf8") + runs.pipe.stderr;
821
+ return {
822
+ check: "control-chars",
823
+ invocation: [command, ...args],
824
+ ...judgeControlChars(runs),
825
+ terminalRaw: kinds(runs.tty?.output),
826
+ pipeRaw: kinds(pipeOutput)
827
+ };
828
+ }
829
+ const controlCharsCheck = {
830
+ name: "control-chars",
831
+ kind: "check",
832
+ summary: "prints control characters from file names raw to the terminal",
833
+ async run(target, ctx) {
834
+ if (target.fixtureDir === void 0) return [{
835
+ check: "control-chars",
836
+ invocation: [target.command],
837
+ ...judgeControlChars({ usesFixture: false }),
838
+ terminalRaw: [],
839
+ pipeRaw: []
840
+ }];
841
+ const results = [];
842
+ for (const args of target.invocations) results.push(await controlChars(target.command, args, target.fixtureDir, ctx.timeout));
843
+ return results;
844
+ }
845
+ };
846
+ // src/checks/ctrl-c.ts
847
+ /** How long the program runs before Ctrl-C. */
848
+ const CTRL_C_DELAY_MS = 1e3;
849
+ /** How long it gets to exit after Ctrl-C. */
850
+ const CTRL_C_GRACE_MS = 3e3;
851
+ /** Lines worth quoting from a trace printed on Ctrl-C, best first. */
852
+ const TRACE_MESSAGES = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
853
+ function judgeCtrlC(r) {
854
+ if (r.spawnError) return {
855
+ verdict: "error",
856
+ reason: `could not start: ${r.spawnError}`
857
+ };
858
+ if (r.signalSentMs === void 0) return {
859
+ verdict: "skip",
860
+ reason: `finished in ${r.durationMs} ms, before Ctrl-C at ${CTRL_C_DELAY_MS} ms; probe a command that keeps running`
861
+ };
862
+ if (r.timedOut) return {
863
+ verdict: "fail",
864
+ reason: `ignored Ctrl-C: still running ${CTRL_C_GRACE_MS / 1e3} s later`
865
+ };
866
+ const after = r.stderr.slice(r.stderrAtSignal ?? 0);
867
+ const ms = `${r.durationMs - r.signalSentMs} ms`;
868
+ if (TRACE_RE.test(after)) return {
869
+ verdict: "fail",
870
+ reason: "printed a stack trace on Ctrl-C",
871
+ evidence: crashEvidence(after, TRACE_MESSAGES)
872
+ };
873
+ if (r.signal) return {
874
+ verdict: "pass",
875
+ reason: `stopped by ${r.signal} in ${ms}`
876
+ };
877
+ if (r.exitCode === 130) return {
878
+ verdict: "pass",
879
+ reason: `exited with 130, the Ctrl-C convention, in ${ms}`
880
+ };
881
+ if (r.exitCode === 0) return {
882
+ verdict: "warn",
883
+ reason: `exited 0 after Ctrl-C, so a script cannot tell it was interrupted (130 is the convention)`
884
+ };
885
+ return {
886
+ verdict: "pass",
887
+ reason: `exited with code ${r.exitCode} in ${ms} (130 is the convention)`
888
+ };
889
+ }
890
+ async function ctrlC(command, args) {
891
+ const r = await run(command, args, {
892
+ timeout: 4e3,
893
+ signal: {
894
+ name: "SIGINT",
895
+ afterMs: CTRL_C_DELAY_MS
896
+ }
897
+ });
898
+ const sent = r.signalSentMs;
899
+ return {
900
+ check: "ctrl-c",
901
+ invocation: [command, ...args],
902
+ ...judgeCtrlC(r),
903
+ sentAfterMs: sent ?? null,
904
+ exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
905
+ exitCode: r.exitCode,
906
+ signal: r.signal,
907
+ stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
908
+ };
909
+ }
910
+ const ctrlCCheck = {
911
+ name: "ctrl-c",
912
+ kind: "check",
913
+ summary: "ignores Ctrl-C, or prints a stack trace when interrupted",
914
+ async run(target) {
915
+ if (!target.explicit) return [{
916
+ check: "ctrl-c",
917
+ invocation: [target.command],
918
+ verdict: "skip",
919
+ reason: "needs probe args that keep it running, such as a watch or serve command",
920
+ sentAfterMs: null,
921
+ exitedAfterMs: null,
922
+ exitCode: null,
923
+ signal: null,
924
+ stderrAfter: ""
925
+ }];
926
+ const results = [];
927
+ for (const args of target.invocations) results.push(await ctrlC(target.command, args));
928
+ return results;
929
+ }
930
+ };
931
+ function median(values) {
932
+ const sorted = [...values].sort((a, b) => a - b);
933
+ const mid = Math.floor(sorted.length / 2);
934
+ return sorted.length % 2 ? sorted[mid] ?? 0 : Math.round(((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2);
935
+ }
936
+ /**
937
+ * Median wall time of one invocation: `<command> --version` by default, how long a
938
+ * user waits for the simplest answer; or the probe exactly as given, so that
939
+ * `node ./dist/cli.js --version` times the CLI rather than Node.
940
+ */
941
+ async function startup(command, args, timeout) {
942
+ const base = {
943
+ check: "startup",
944
+ invocation: [command, ...args]
945
+ };
946
+ const warmUp = await run(command, args, { timeout });
947
+ if (warmUp.spawnError) return {
948
+ ...base,
949
+ verdict: "error",
950
+ reason: `could not start: ${warmUp.spawnError}`,
951
+ runsMs: [],
952
+ medianMs: null
953
+ };
954
+ if (warmUp.timedOut) return {
955
+ ...base,
956
+ verdict: "error",
957
+ reason: "timed out",
958
+ runsMs: [],
959
+ medianMs: null
960
+ };
961
+ if (warmUp.exitCode !== 0) return {
962
+ ...base,
963
+ verdict: "skip",
964
+ reason: `exited ${warmUp.exitCode ?? warmUp.signal}, so its time is not a fair startup measure`,
965
+ runsMs: [],
966
+ medianMs: null
967
+ };
968
+ const runsMs = [];
969
+ for (let i = 0; i < 5; i++) {
970
+ const r = await run(command, args, { timeout });
971
+ if (r.timedOut || r.spawnError) return {
972
+ ...base,
973
+ verdict: "error",
974
+ reason: "a timed run did not finish",
975
+ runsMs,
976
+ medianMs: null
977
+ };
978
+ runsMs.push(r.durationMs);
979
+ }
980
+ const mid = median(runsMs);
981
+ return {
982
+ ...base,
983
+ verdict: "info",
984
+ reason: `median ${mid} ms over 5 runs (min ${Math.min(...runsMs)}, max ${Math.max(...runsMs)})`,
985
+ runsMs,
986
+ medianMs: mid
987
+ };
988
+ }
989
+ // src/checks/index.ts
990
+ /** Every check, in the order they run and are reported. */
991
+ const CHECKS = [
992
+ closedPipeCheck,
993
+ colorCheck,
994
+ ctrlCCheck,
995
+ controlCharsCheck,
996
+ {
997
+ name: "startup",
998
+ kind: "info",
999
+ summary: "median wall time of --version, or of the given probe, over 5 runs",
1000
+ async run(target, ctx) {
1001
+ const args = target.explicit ? target.invocations[0] ?? [] : ["--version"];
1002
+ return [await startup(target.command, args, ctx.timeout)];
1003
+ }
1004
+ },
1005
+ baselineCheck
1006
+ ];
1007
+ /**
1008
+ * Picks checks by name, keeping registry order. No names selects every check of
1009
+ * kind "check": info checks only run when named, because they never fail and
1010
+ * baseline sends a flag the user did not ask for.
1011
+ */
1012
+ function selectChecks(names) {
1013
+ if (names.length === 0) return {
1014
+ checks: CHECKS.filter((c) => c.kind === "check"),
1015
+ unknown: []
1016
+ };
1017
+ const known = new Set(CHECKS.map((c) => c.name));
1018
+ return {
1019
+ checks: CHECKS.filter((c) => names.includes(c.name)),
1020
+ unknown: [...new Set(names.filter((n) => !known.has(n)))]
1021
+ };
1022
+ }
1023
+ // src/core/safe.ts
1024
+ /**
1025
+ * C0 and C1 controls, DEL, Unicode line separators and bidirectional overrides:
1026
+ * everything that can drive a terminal, forge a line, or reorder what is shown.
1027
+ */
1028
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
1029
+ /** The same, minus C0, which JSON.stringify already escapes. */
1030
+ const JSON_UNSAFE = /[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
1031
+ const hex = (c, width) => c.charCodeAt(0).toString(16).padStart(width, "0");
1032
+ /**
1033
+ * Escapes text from a target (its output, its arguments, file names) for one
1034
+ * line of our own report: `\x1b`, `\x0a`, `\u202e`. It can no longer drive the
1035
+ * terminal, break the line, or disguise itself.
1036
+ */
1037
+ function safe(text) {
1038
+ return text.replace(UNSAFE, (c) => c.charCodeAt(0) <= 255 ? `\\x${hex(c, 2)}` : `\\u${hex(c, 4)}`);
1039
+ }
1040
+ /** JSON.stringify, plus \u escapes for the characters it leaves raw. Parses back identically. */
1041
+ function safeJson(value) {
1042
+ return JSON.stringify(value, null, 2).replace(JSON_UNSAFE, (c) => `\\u${hex(c, 4)}`);
1043
+ }
1044
+ // src/report/summary.ts
1045
+ function countVerdicts(results) {
1046
+ const counts = {
1047
+ pass: 0,
1048
+ fail: 0,
1049
+ warn: 0,
1050
+ skip: 0,
1051
+ error: 0,
1052
+ info: 0
1053
+ };
1054
+ for (const r of results) counts[r.verdict]++;
1055
+ return counts;
1056
+ }
1057
+ /** "2 failed, 0 warned, 2 passed, 2 skipped", plus info and could-not-run when present. */
1058
+ function summaryLine(c) {
1059
+ const info = c.info ? `, ${c.info} info` : "";
1060
+ const errors = c.error ? `, ${c.error} could not run` : "";
1061
+ return `${c.fail} failed, ${c.warn} warned, ${c.pass} passed, ${c.skip} skipped${info}${errors}`;
1062
+ }
1063
+ // src/report/human.ts
1064
+ const COLORS = {
1065
+ pass: 32,
1066
+ fail: 31,
1067
+ warn: 33,
1068
+ skip: 90,
1069
+ error: 35,
1070
+ info: 36
1071
+ };
1072
+ function formatHuman({ version, command, checks, results }, { color }) {
1073
+ const paint = (verdict) => {
1074
+ const label = verdict.toUpperCase().padEnd(5);
1075
+ return color ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
1076
+ };
1077
+ const width = Math.max(0, ...results.map((r) => safe(r.invocation.join(" ")).length));
1078
+ const noun = checks.length === 1 ? "check" : "checks";
1079
+ const lines = [`cliprobe ${version}: ${checks.join(", ")} ${noun} for ${safe(command)}`];
1080
+ for (const check of checks) {
1081
+ lines.push("");
1082
+ if (checks.length > 1) lines.push(check);
1083
+ for (const r of results.filter((result) => result.check === check)) {
1084
+ lines.push(` ${paint(r.verdict)} ${safe(r.invocation.join(" ")).padEnd(width)} ${r.reason}`);
1085
+ if (r.evidence) lines.push(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
1086
+ }
1087
+ }
1088
+ lines.push("", summaryLine(countVerdicts(results)));
1089
+ return lines.join("\n") + "\n";
1090
+ }
1091
+ // src/report/json.ts
1092
+ function formatJson({ version, command, checks, results }) {
1093
+ return safeJson({
1094
+ tool: "cliprobe",
1095
+ version,
1096
+ command,
1097
+ checks,
1098
+ results
1099
+ }) + "\n";
1100
+ }
1101
+ // src/report/junit.ts
1102
+ const XML_ESCAPES = {
1103
+ "&": "&amp;",
1104
+ "<": "&lt;",
1105
+ ">": "&gt;",
1106
+ "\"": "&quot;",
1107
+ "'": "&apos;"
1108
+ };
1109
+ /**
1110
+ * Text that is always well-formed XML 1.0: safe() first turns every control
1111
+ * character (most of which XML forbids even when escaped) into a visible escape,
1112
+ * then the five markup characters become entities.
1113
+ */
1114
+ function xml(text) {
1115
+ return safe(text).replace(/[&<>"']/g, (c) => XML_ESCAPES[c] ?? c);
1116
+ }
1117
+ /** JUnit's count attributes for a suite or the whole run. */
1118
+ function totals(results) {
1119
+ const c = countVerdicts(results);
1120
+ return `tests="${results.length}" failures="${c.fail}" errors="${c.error}" skipped="${c.skip}"`;
1121
+ }
1122
+ function testcase(r) {
1123
+ const open = ` <testcase classname="cliprobe.${xml(r.check)}" name="${xml(r.invocation.join(" "))}"`;
1124
+ const message = `message="${xml(r.reason)}"`;
1125
+ const body = r.evidence ? xml(r.evidence) : "";
1126
+ switch (r.verdict) {
1127
+ case "fail": return `${open}>\n <failure ${message} type="fail">${body}</failure>\n </testcase>`;
1128
+ case "error": return `${open}>\n <error ${message} type="error">${body}</error>\n </testcase>`;
1129
+ case "skip": return `${open}>\n <skipped ${message}/>\n </testcase>`;
1130
+ case "pass":
1131
+ case "warn":
1132
+ case "info": return `${open}>\n <system-out>${`${r.verdict.toUpperCase()}: ${xml(r.reason)}${r.evidence ? `\n${body}` : ""}`}</system-out>\n </testcase>`;
1133
+ }
1134
+ }
1135
+ /** JUnit XML: one testsuite per check, one testcase per result. */
1136
+ function formatJunit({ version, command, checks, results }) {
1137
+ const suites = checks.map((check) => {
1138
+ const own = results.filter((r) => r.check === check);
1139
+ return [
1140
+ ` <testsuite name="${xml(check)}" ${totals(own)}>`,
1141
+ ...own.map(testcase),
1142
+ " </testsuite>"
1143
+ ].join("\n");
1144
+ });
1145
+ return [
1146
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
1147
+ `<testsuites name="cliprobe ${xml(version)}: ${xml(command)}" ${totals(results)}>`,
1148
+ ...suites,
1149
+ "</testsuites>",
1150
+ ""
1151
+ ].join("\n");
1152
+ }
1153
+ // src/report/markdown.ts
1154
+ /**
1155
+ * A code span that shows any text literally: control characters escaped onto one
1156
+ * line, `|` escaped so a table cell can't be split, and a fence longer than any
1157
+ * run of backticks inside.
1158
+ */
1159
+ function code(text, { inTable }) {
1160
+ const body = inTable ? safe(text).replaceAll("|", "\\|") : safe(text);
1161
+ const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((run) => run.length));
1162
+ const fence = "`".repeat(longest + 1);
1163
+ const pad = body.startsWith("`") || body.endsWith("`") ? " " : "";
1164
+ return `${fence}${pad}${body}${pad}${fence}`;
1165
+ }
1166
+ /**
1167
+ * Prose for inside a table cell. Only characters that act mid-line are escaped:
1168
+ * emphasis, code, links, HTML, entities and the cell separator. Line-start syntax
1169
+ * (`#`, `-`, `1.`) can't trigger there, so it stays readable.
1170
+ */
1171
+ function prose(text) {
1172
+ return safe(text).replace(/[\\`*_[\]<>|~&]/g, (c) => `\\${c}`);
1173
+ }
1174
+ function row(r) {
1175
+ const verdict = r.verdict === "fail" || r.verdict === "error" ? `**${r.verdict.toUpperCase()}**` : r.verdict.toUpperCase();
1176
+ const evidence = r.evidence ? `<br>${code(r.evidence.slice(0, 300), { inTable: true })}` : "";
1177
+ return `| ${[
1178
+ prose(r.check),
1179
+ verdict,
1180
+ code(r.invocation.join(" "), { inTable: true }),
1181
+ prose(r.reason) + evidence
1182
+ ].join(" | ")} |`;
1183
+ }
1184
+ /** GitHub-flavored Markdown, for a job summary ($GITHUB_STEP_SUMMARY) or a PR comment. */
1185
+ function formatMarkdown({ version, command, results }) {
1186
+ return [
1187
+ `## cliprobe ${version}: ${code(command, { inTable: false })}`,
1188
+ "",
1189
+ summaryLine(countVerdicts(results)),
1190
+ "",
1191
+ "| Check | Verdict | Invocation | Result |",
1192
+ "| --- | --- | --- | --- |",
1193
+ ...results.map(row),
1194
+ ""
1195
+ ].join("\n");
1196
+ }
1197
+ // src/report/index.ts
1198
+ /** The format names, in the order --help lists them. */
1199
+ const FORMAT_NAMES = [
1200
+ "human",
1201
+ "json",
1202
+ "markdown",
1203
+ "junit"
1204
+ ];
1205
+ function isFormat(name) {
1206
+ return FORMAT_NAMES.includes(name);
1207
+ }
1208
+ /** Every output format; the Record type makes a missing formatter a type error. */
1209
+ const FORMATS = {
1210
+ human: formatHuman,
1211
+ json: formatJson,
1212
+ markdown: formatMarkdown,
1213
+ junit: formatJunit
1214
+ };
1215
+ // src/report/write.ts
1216
+ /**
1217
+ * Writes a report so that nothing ever sees half of it: a temporary file in the
1218
+ * same directory, then a rename, which is atomic on one file system. Missing
1219
+ * parent directories are created. Throws on failure, leaving no temporary file.
1220
+ */
1221
+ function writeReportFile(path, text) {
1222
+ mkdirSync(dirname(path), { recursive: true });
1223
+ const temp = `${path}.cliprobe-${process.pid}.tmp`;
1224
+ try {
1225
+ writeFileSync(temp, text);
1226
+ renameSync(temp, path);
1227
+ } catch (error) {
1228
+ rmSync(temp, { force: true });
1229
+ throw error;
1230
+ }
1231
+ }
1232
+ // src/version.ts
1233
+ /**
1234
+ * Read from the package manifest at runtime. Works from both `src/` (development)
1235
+ * and `dist/` (published): each sits one level below the package root.
1236
+ */
1237
+ function readVersion() {
1238
+ const manifest = createRequire(import.meta.url)("../package.json");
1239
+ if (typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string") return manifest.version;
1240
+ return "0.0.0";
1241
+ }
1242
+ const VERSION = readVersion();
1243
+ // src/cli/args.ts
1244
+ var UsageError = class extends Error {};
1245
+ function parseArgs(argv) {
1246
+ const opts = {
1247
+ format: "human",
1248
+ outputFile: void 0,
1249
+ timeout: 15e3,
1250
+ help: false,
1251
+ version: false,
1252
+ checks: [],
1253
+ command: void 0,
1254
+ args: []
1255
+ };
1256
+ for (let i = 0; i < argv.length; i++) {
1257
+ const a = argv[i] ?? "";
1258
+ if (a === "--") {
1259
+ [opts.command, ...opts.args] = argv.slice(i + 1);
1260
+ break;
1261
+ }
1262
+ if (a === "--json") opts.format = "json";
1263
+ else if (a === "-o" || a === "--output-file" || a.startsWith("--output-file=")) {
1264
+ const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
1265
+ if (!value) throw new UsageError(`${a.split("=")[0] ?? a} needs a file path`);
1266
+ opts.outputFile = value;
1267
+ } else if (a === "--format" || a.startsWith("--format=")) {
1268
+ const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
1269
+ if (value === void 0 || !isFormat(value)) throw new UsageError(`--format needs one of ${FORMAT_NAMES.join(", ")}, got "${String(value)}"`);
1270
+ opts.format = value;
1271
+ } else if (a === "-h" || a === "--help") opts.help = true;
1272
+ else if (a === "-v" || a === "--version") opts.version = true;
1273
+ else if (a === "--timeout" || a.startsWith("--timeout=")) {
1274
+ const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
1275
+ opts.timeout = Number(value);
1276
+ if (!Number.isInteger(opts.timeout) || opts.timeout <= 0) throw new UsageError(`--timeout needs a positive whole number of milliseconds, got "${String(value)}"`);
1277
+ } else if (a === "--check" || a.startsWith("--check=")) {
1278
+ const names = ((a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i]) ?? "").split(",").map((n) => n.trim()).filter(Boolean);
1279
+ if (names.length === 0) throw new UsageError("--check needs a check name");
1280
+ opts.checks.push(...names);
1281
+ } else if (a.startsWith("-")) throw new UsageError(`unknown option "${a}"`);
1282
+ else {
1283
+ [opts.command, ...opts.args] = argv.slice(i);
1284
+ break;
1285
+ }
1286
+ }
1287
+ return opts;
1288
+ }
1289
+ // src/cli/main.ts
1290
+ const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
1291
+
1292
+ Usage:
1293
+ cliprobe [options] -- <command> [args...]
1294
+
1295
+ With no args after <command>, cliprobe probes "<command> --version" and
1296
+ "<command> --help". With args, it probes exactly that invocation. An argument
1297
+ containing {fixture} gets the path of a temporary directory of file names with
1298
+ control characters in them, for the control-chars check.
1299
+
1300
+ Checks:
1301
+ closed-pipe Runs the command with stdout already closed, as when output is
1302
+ piped into a reader that quits early (head, grep -q, an agent).
1303
+ A well-behaved program exits quietly; a buggy one crashes with
1304
+ an EPIPE error and a stack trace.
1305
+ color Runs the command into a pipe, then under a terminal, then under
1306
+ a terminal with NO_COLOR=1. Fails if color codes reach a pipe;
1307
+ warns if color goes to a piped stderr or NO_COLOR is ignored.
1308
+ ctrl-c Sends Ctrl-C (SIGINT) after 1 s. Fails if the command is still
1309
+ running 3 s later or prints a stack trace; warns if it exits 0.
1310
+ Skipped when the command finishes first, so probe a command
1311
+ that keeps running (a watcher, a server, a long task).
1312
+ control-chars Runs the command under a terminal with {fixture} replaced by a
1313
+ directory of file names holding escape sequences, a carriage
1314
+ return, a newline and more. Fails if an escape sequence reaches
1315
+ the terminal unescaped; warns for the others. Skipped without
1316
+ {fixture}, e.g. cliprobe -- ls {fixture}
1317
+
1318
+ Info checks (never fail; run only when named with --check):
1319
+ startup Median wall time over 5 runs of "<command> --version", or of the
1320
+ probe as given, e.g. cliprobe --check startup -- node cli.js -v
1321
+ baseline Appends --version, --help and an unknown flag to the probe and
1322
+ reports what scripts rely on: one version line, help on stdout,
1323
+ non-zero exit for a bad flag. A program that ignores unknown
1324
+ flags runs its default action, cut off after 5 s.
1325
+
1326
+ Options:
1327
+ --check <name> Run only this check; repeat it or use commas for several
1328
+ --format <name> Output format: human (default), json, markdown (a CI job
1329
+ summary or PR comment) or junit (XML for CI test reports)
1330
+ --json Same as --format json
1331
+ -o, --output-file <path>
1332
+ Write the --format report to a file (created atomically,
1333
+ with parent folders); the human report still prints
1334
+ --timeout <ms> Kill a probe after this long (default 15000)
1335
+ -h, --help Show this help
1336
+ -v, --version Show the version
1337
+
1338
+ Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
1339
+ Runs the target in the current directory without a shell, with stdin closed,
1340
+ 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() {
1348
+ let opts;
1349
+ try {
1350
+ opts = parseArgs(process.argv.slice(2));
1351
+ } catch (error) {
1352
+ if (!(error instanceof UsageError)) throw error;
1353
+ err(`cliprobe: ${error.message}\nRun "cliprobe --help" for usage.\n`);
1354
+ return 2;
1355
+ }
1356
+ if (opts.help) {
1357
+ out(HELP + "\n");
1358
+ return 0;
1359
+ }
1360
+ if (opts.version) {
1361
+ out(VERSION + "\n");
1362
+ return 0;
1363
+ }
1364
+ const { checks, unknown } = selectChecks(opts.checks);
1365
+ if (unknown.length) {
1366
+ 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`);
1369
+ return 2;
1370
+ }
1371
+ if (!opts.command) {
1372
+ err("cliprobe: no command given\nUsage: cliprobe [options] -- <command> [args...]\n");
1373
+ return 2;
1374
+ }
1375
+ if (process.platform === "win32") {
1376
+ err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
1377
+ return 2;
1378
+ }
1379
+ const invocations = opts.args.length ? [opts.args] : [["--version"], ["--help"]];
1380
+ const fixture = usesFixture(opts.args) ? createFixture() : void 0;
1381
+ const results = [];
1382
+ try {
1383
+ const target = {
1384
+ command: opts.command,
1385
+ explicit: opts.args.length > 0,
1386
+ invocations: fixture ? invocations.map((a) => expandFixture(a, fixture.dir)) : invocations,
1387
+ ...fixture ? { fixtureDir: fixture.dir } : {}
1388
+ };
1389
+ for (const check of checks) results.push(...await check.run(target, { timeout: opts.timeout }));
1390
+ } finally {
1391
+ fixture?.cleanup();
1392
+ }
1393
+ const collapse = (text) => fixture ? collapseFixture(text, fixture) : text;
1394
+ const report = {
1395
+ version: VERSION,
1396
+ command: opts.command,
1397
+ checks: checks.map((c) => c.name),
1398
+ results
1399
+ };
1400
+ const color = process.stdout.isTTY && !process.env["NO_COLOR"];
1401
+ if (opts.outputFile) {
1402
+ try {
1403
+ writeReportFile(opts.outputFile, collapse(FORMATS[opts.format](report, { color: false })));
1404
+ } catch (error) {
1405
+ const reason = error instanceof Error ? error.message : String(error);
1406
+ err(`cliprobe: could not write ${safe(opts.outputFile)}: ${safe(reason)}\n`);
1407
+ return 2;
1408
+ }
1409
+ out(collapse(FORMATS.human(report, { color })));
1410
+ } 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;
1414
+ }
1415
+ process.stdout.on("error", (error) => {
1416
+ if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1417
+ throw error;
1418
+ });
1419
+ process.exitCode = await main();
1420
+ export {};