@testsprite/testsprite-cli 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 (68) hide show
  1. package/README.md +35 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.d.ts +5 -0
  5. package/dist/commands/auth.js +38 -27
  6. package/dist/commands/doctor.d.ts +49 -0
  7. package/dist/commands/doctor.js +233 -0
  8. package/dist/commands/init.d.ts +1 -1
  9. package/dist/commands/init.js +24 -14
  10. package/dist/commands/project.d.ts +75 -2
  11. package/dist/commands/project.js +326 -47
  12. package/dist/commands/test.d.ts +281 -2
  13. package/dist/commands/test.js +1658 -177
  14. package/dist/commands/usage.js +13 -12
  15. package/dist/index.js +71 -3
  16. package/dist/lib/agent-targets.d.ts +72 -6
  17. package/dist/lib/agent-targets.js +188 -6
  18. package/dist/lib/bundle.d.ts +34 -0
  19. package/dist/lib/bundle.js +63 -11
  20. package/dist/lib/client-factory.d.ts +31 -0
  21. package/dist/lib/client-factory.js +63 -0
  22. package/dist/lib/config.d.ts +2 -0
  23. package/dist/lib/config.js +11 -2
  24. package/dist/lib/credentials.js +10 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +64 -0
  27. package/dist/lib/errors.d.ts +28 -1
  28. package/dist/lib/errors.js +40 -0
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +80 -0
  32. package/dist/lib/flaky.js +76 -0
  33. package/dist/lib/http.d.ts +73 -1
  34. package/dist/lib/http.js +327 -135
  35. package/dist/lib/interrupt.d.ts +116 -0
  36. package/dist/lib/interrupt.js +182 -0
  37. package/dist/lib/junit-report.d.ts +58 -0
  38. package/dist/lib/junit-report.js +210 -0
  39. package/dist/lib/output.d.ts +16 -1
  40. package/dist/lib/output.js +24 -2
  41. package/dist/lib/pagination.d.ts +4 -3
  42. package/dist/lib/pagination.js +34 -6
  43. package/dist/lib/poll.d.ts +11 -0
  44. package/dist/lib/poll.js +70 -5
  45. package/dist/lib/prompt.js +52 -8
  46. package/dist/lib/proxy.d.ts +29 -0
  47. package/dist/lib/proxy.js +30 -0
  48. package/dist/lib/render-error.js +3 -1
  49. package/dist/lib/runs.types.d.ts +9 -0
  50. package/dist/lib/skill-nudge.d.ts +2 -2
  51. package/dist/lib/skill-nudge.js +13 -4
  52. package/dist/lib/target-url.js +8 -1
  53. package/dist/lib/ticker.d.ts +11 -1
  54. package/dist/lib/ticker.js +33 -1
  55. package/dist/lib/update-check.d.ts +67 -0
  56. package/dist/lib/update-check.js +246 -0
  57. package/dist/lib/v3-advisory.d.ts +13 -0
  58. package/dist/lib/v3-advisory.js +24 -0
  59. package/dist/lib/version-notice.d.ts +37 -0
  60. package/dist/lib/version-notice.js +87 -0
  61. package/dist/version-guard.d.ts +33 -0
  62. package/dist/version-guard.js +39 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +3 -2
  66. package/skills/testsprite-onboard.skill.md +21 -0
  67. package/skills/testsprite-verify.codex.md +6 -0
  68. package/skills/testsprite-verify.skill.md +48 -4
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Process lifecycle hardening: graceful termination signals and broken-pipe.
3
+ *
4
+ * Termination signals: without a handler, Node terminates the process abruptly
5
+ * with no output, so a user (Ctrl+C), a CI runner or `docker stop` (SIGTERM), or
6
+ * a closed terminal/SSH session (SIGHUP) that interrupts a long
7
+ * `test run --wait` is left unsure whether the run was cancelled or is still
8
+ * executing server-side (it is: the CLI only polls; the run lives on the
9
+ * backend). The handler prints a one-line explanation plus how to resume, then
10
+ * exits with the conventional `128 + signal` code.
11
+ *
12
+ * Broken pipe: when output is piped to a reader that closes early
13
+ * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
+ * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
+ * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
+ * conventional SIGPIPE-equivalent result for "the reader went away".
17
+ *
18
+ * `process` and the streams are injectable so the wiring is unit-testable
19
+ * without spawning a subprocess or sending a real signal.
20
+ */
21
+ import { type TerminationSignal } from './errors.js';
22
+ export { TERMINATION_EXIT_CODES, type TerminationSignal } from './errors.js';
23
+ /** Back-compat alias: SIGINT's conventional exit code. */
24
+ export declare const SIGINT_EXIT_CODE: 130;
25
+ /**
26
+ * Structural view of {@link ShutdownController} threaded through the DI
27
+ * surfaces (`TestDeps`, `PollOptions`) — commands and the polling loop need
28
+ * only these members, and tests can supply a lightweight fake.
29
+ */
30
+ export interface ShutdownHandle {
31
+ /** Aborts (reason: `InterruptError`) when a termination signal arrives while armed. */
32
+ readonly signal: AbortSignal;
33
+ /** Enter a graceful-detach scope. Returns the disposer that leaves it. */
34
+ arm(): () => void;
35
+ }
36
+ /**
37
+ * Process-lifetime coordinator between the signal handler and the `--wait`
38
+ * polling paths (DEV-331 piece 1).
39
+ *
40
+ * Two modes, chosen by whether a graceful-detach scope is armed when the
41
+ * signal arrives:
42
+ *
43
+ * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
44
+ * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
45
+ * and every backoff sleep bail immediately; the `--wait` catch blocks own
46
+ * the cleanup (finalize the ticker, print the honest partial envelope +
47
+ * re-attach hint, rethrow to `index.ts` → exit 130/143/129).
48
+ * - **Disarmed** (no wait in progress — prompts, one-shot commands, local
49
+ * FS work): the handler prints the generic explanation and exits
50
+ * immediately, preserving the pre-DEV-331 behavior. An abort nobody
51
+ * observes must never leave the process hanging at e.g. a readline prompt.
52
+ *
53
+ * A second signal while the armed cleanup is in flight is the documented
54
+ * escape hatch: immediate hard exit.
55
+ */
56
+ export declare class ShutdownController {
57
+ private readonly controller;
58
+ private armedCount;
59
+ private receivedSignal;
60
+ constructor();
61
+ get signal(): AbortSignal;
62
+ /** The first termination signal received, or null if none yet. */
63
+ get received(): TerminationSignal | null;
64
+ get isArmed(): boolean;
65
+ /**
66
+ * Enter a graceful-detach scope (re-entrant: fan-out members overlap).
67
+ * Returns an idempotent disposer.
68
+ */
69
+ arm(): () => void;
70
+ /** Record the signal and abort with an `InterruptError` carrying it. */
71
+ interrupt(signal: TerminationSignal): void;
72
+ }
73
+ /**
74
+ * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
75
+ * and it is the default `shutdown` for `TestDeps` / `PollOptions` /
76
+ * `ClientFactoryDeps`, so production wiring is automatic. Tests inject their
77
+ * own `ShutdownController` (or a `ShutdownHandle` fake) instead.
78
+ */
79
+ export declare const globalShutdown: ShutdownController;
80
+ export declare function formatInterruptMessage(signal?: TerminationSignal): string;
81
+ export interface InterruptDeps {
82
+ /** Signal registrar. Defaults to `process.on`. */
83
+ on?: (signal: TerminationSignal, handler: () => void) => void;
84
+ /** Line-oriented stderr writer (appends a newline). */
85
+ stderr?: (line: string) => void;
86
+ /** Process exit. Defaults to `process.exit`. */
87
+ exit?: (code: number) => void;
88
+ /** Shutdown coordinator. Defaults to {@link globalShutdown}. */
89
+ shutdown?: ShutdownController;
90
+ }
91
+ /**
92
+ * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
93
+ * single top-level call in `index.ts`; not designed to be installed twice.
94
+ *
95
+ * First signal, armed scope: abort-only — the `--wait` catch paths own the
96
+ * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
97
+ * First signal, disarmed: print the generic explanation + exit `128+signum`.
98
+ * Second signal (any mode): immediate hard exit — the escape hatch when the
99
+ * graceful cleanup itself wedges.
100
+ */
101
+ export declare function installSignalHandlers(deps?: InterruptDeps): void;
102
+ export interface BrokenPipeDeps {
103
+ /** stdout stream. Defaults to `process.stdout`. */
104
+ stdout?: NodeJS.EventEmitter;
105
+ /** stderr stream. Defaults to `process.stderr`. */
106
+ stderr?: NodeJS.EventEmitter;
107
+ /** Process exit. Defaults to `process.exit`. */
108
+ exit?: (code: number) => void;
109
+ }
110
+ /**
111
+ * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
112
+ * early (`testsprite ... | head`) exits cleanly instead of crashing with an
113
+ * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
114
+ * error is left to surface normally.
115
+ */
116
+ export declare function installBrokenPipeGuard(deps?: BrokenPipeDeps): void;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Process lifecycle hardening: graceful termination signals and broken-pipe.
3
+ *
4
+ * Termination signals: without a handler, Node terminates the process abruptly
5
+ * with no output, so a user (Ctrl+C), a CI runner or `docker stop` (SIGTERM), or
6
+ * a closed terminal/SSH session (SIGHUP) that interrupts a long
7
+ * `test run --wait` is left unsure whether the run was cancelled or is still
8
+ * executing server-side (it is: the CLI only polls; the run lives on the
9
+ * backend). The handler prints a one-line explanation plus how to resume, then
10
+ * exits with the conventional `128 + signal` code.
11
+ *
12
+ * Broken pipe: when output is piped to a reader that closes early
13
+ * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
+ * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
+ * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
+ * conventional SIGPIPE-equivalent result for "the reader went away".
17
+ *
18
+ * `process` and the streams are injectable so the wiring is unit-testable
19
+ * without spawning a subprocess or sending a real signal.
20
+ */
21
+ import { setMaxListeners } from 'node:events';
22
+ import { writeSync } from 'node:fs';
23
+ import { InterruptError, TERMINATION_EXIT_CODES } from './errors.js';
24
+ export { TERMINATION_EXIT_CODES } from './errors.js';
25
+ /** Back-compat alias: SIGINT's conventional exit code. */
26
+ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
27
+ /**
28
+ * Process-lifetime coordinator between the signal handler and the `--wait`
29
+ * polling paths (DEV-331 piece 1).
30
+ *
31
+ * Two modes, chosen by whether a graceful-detach scope is armed when the
32
+ * signal arrives:
33
+ *
34
+ * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
35
+ * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
36
+ * and every backoff sleep bail immediately; the `--wait` catch blocks own
37
+ * the cleanup (finalize the ticker, print the honest partial envelope +
38
+ * re-attach hint, rethrow to `index.ts` → exit 130/143/129).
39
+ * - **Disarmed** (no wait in progress — prompts, one-shot commands, local
40
+ * FS work): the handler prints the generic explanation and exits
41
+ * immediately, preserving the pre-DEV-331 behavior. An abort nobody
42
+ * observes must never leave the process hanging at e.g. a readline prompt.
43
+ *
44
+ * A second signal while the armed cleanup is in flight is the documented
45
+ * escape hatch: immediate hard exit.
46
+ */
47
+ export class ShutdownController {
48
+ controller = new AbortController();
49
+ armedCount = 0;
50
+ receivedSignal = null;
51
+ constructor() {
52
+ // Every fetch and every poll iteration composes this signal via
53
+ // AbortSignal.any — a 50-run batch fan-out legitimately holds >10
54
+ // concurrent listeners, so silence Node's MaxListeners warning.
55
+ setMaxListeners(0, this.controller.signal);
56
+ }
57
+ get signal() {
58
+ return this.controller.signal;
59
+ }
60
+ /** The first termination signal received, or null if none yet. */
61
+ get received() {
62
+ return this.receivedSignal;
63
+ }
64
+ get isArmed() {
65
+ return this.armedCount > 0;
66
+ }
67
+ /**
68
+ * Enter a graceful-detach scope (re-entrant: fan-out members overlap).
69
+ * Returns an idempotent disposer.
70
+ */
71
+ arm() {
72
+ this.armedCount += 1;
73
+ let disposed = false;
74
+ return () => {
75
+ if (disposed)
76
+ return;
77
+ disposed = true;
78
+ this.armedCount -= 1;
79
+ };
80
+ }
81
+ /** Record the signal and abort with an `InterruptError` carrying it. */
82
+ interrupt(signal) {
83
+ this.receivedSignal = signal;
84
+ this.controller.abort(new InterruptError(signal));
85
+ }
86
+ }
87
+ /**
88
+ * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
89
+ * and it is the default `shutdown` for `TestDeps` / `PollOptions` /
90
+ * `ClientFactoryDeps`, so production wiring is automatic. Tests inject their
91
+ * own `ShutdownController` (or a `ShutdownHandle` fake) instead.
92
+ */
93
+ export const globalShutdown = new ShutdownController();
94
+ export function formatInterruptMessage(signal = 'SIGINT') {
95
+ return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
96
+ 'check it with `testsprite test list` or `testsprite test wait <runId>`.');
97
+ }
98
+ /**
99
+ * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
100
+ * single top-level call in `index.ts`; not designed to be installed twice.
101
+ *
102
+ * First signal, armed scope: abort-only — the `--wait` catch paths own the
103
+ * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
104
+ * First signal, disarmed: print the generic explanation + exit `128+signum`.
105
+ * Second signal (any mode): immediate hard exit — the escape hatch when the
106
+ * graceful cleanup itself wedges.
107
+ */
108
+ export function installSignalHandlers(deps = {}) {
109
+ const on = deps.on ??
110
+ ((signal, handler) => {
111
+ process.on(signal, handler);
112
+ });
113
+ const stderr = deps.stderr ??
114
+ ((line) => {
115
+ // A signal handler calls process.exit() right after writing, which can
116
+ // truncate an async process.stderr.write() when stderr is a pipe. Write
117
+ // synchronously so the interrupt hint is flushed before the process exits.
118
+ try {
119
+ writeSync(process.stderr.fd, `${line}\n`);
120
+ }
121
+ catch {
122
+ // Best-effort: if stderr is already gone (EPIPE), still exit cleanly.
123
+ }
124
+ });
125
+ const exit = deps.exit ?? ((code) => process.exit(code));
126
+ const shutdown = deps.shutdown ?? globalShutdown;
127
+ for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
128
+ on(signal, () => {
129
+ if (shutdown.received !== null) {
130
+ // Second signal while graceful cleanup is in flight: hard exit now.
131
+ exit(TERMINATION_EXIT_CODES[signal]);
132
+ return;
133
+ }
134
+ if (shutdown.isArmed) {
135
+ // Graceful detach: abort only (sync, signal-safe — no I/O here so a
136
+ // pending stdout `drain` wait can settle); the armed catch paths
137
+ // finalize the ticker, print the partial + re-attach hint, and exit
138
+ // via index.ts with this signal's code.
139
+ shutdown.interrupt(signal);
140
+ return;
141
+ }
142
+ // Disarmed (no --wait in progress): legacy immediate exit. Record the
143
+ // signal first so a second one takes the hard-exit branch even when
144
+ // `exit` is injected and does not terminate (unit tests).
145
+ shutdown.interrupt(signal);
146
+ // Blank line first so the message starts on its own row rather than
147
+ // trailing the progress ticker's in-place line.
148
+ stderr('');
149
+ stderr(formatInterruptMessage(signal));
150
+ exit(TERMINATION_EXIT_CODES[signal]);
151
+ });
152
+ }
153
+ }
154
+ /**
155
+ * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
156
+ * early (`testsprite ... | head`) exits cleanly instead of crashing with an
157
+ * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
158
+ * error is left to surface normally.
159
+ */
160
+ export function installBrokenPipeGuard(deps = {}) {
161
+ const stdout = deps.stdout ?? process.stdout;
162
+ const stderr = deps.stderr ?? process.stderr;
163
+ const exit = deps.exit ?? ((code) => process.exit(code));
164
+ stdout.on('error', (error) => {
165
+ // Reader went away (`| head`, `| less` then q): exit cleanly like SIGPIPE
166
+ // rather than dumping an unhandled `write EPIPE` stack. Any other stdout
167
+ // error is a genuine, actionable failure, so re-throw it (Node's default).
168
+ if (error.code === 'EPIPE') {
169
+ exit(0);
170
+ return;
171
+ }
172
+ throw error;
173
+ });
174
+ stderr.on('error', (error) => {
175
+ // stderr closed: nothing can be reported over it, so swallow EPIPE. Any
176
+ // other error re-throws so a genuine failure is not silently hidden.
177
+ if (error.code === 'EPIPE')
178
+ return;
179
+ throw error;
180
+ });
181
+ }
182
+ //# sourceMappingURL=interrupt.js.map
@@ -0,0 +1,58 @@
1
+ export type JUnitReportFormat = 'junit';
2
+ /** Minimal testcase input shared by batch run and batch rerun poll results. */
3
+ export interface JUnitTestResult {
4
+ testId: string;
5
+ runId?: string;
6
+ status: string;
7
+ /** Observed on polled runs; used for classname when --project is omitted. */
8
+ projectId?: string;
9
+ error?: {
10
+ code: string;
11
+ message: string;
12
+ exitCode?: number;
13
+ };
14
+ }
15
+ export interface JUnitReportBuildOptions {
16
+ suiteName: string;
17
+ classname: string;
18
+ results: readonly JUnitTestResult[];
19
+ }
20
+ export interface JUnitReportFlagOptions {
21
+ report?: JUnitReportFormat;
22
+ reportFile?: string;
23
+ reportSuiteName?: string;
24
+ wait: boolean;
25
+ /** True when the invocation is a batch path (run --all or rerun batch). */
26
+ batchPath: boolean;
27
+ }
28
+ /**
29
+ * Parse `--report <format>`. Only `junit` is accepted in v1.
30
+ */
31
+ export declare function parseJUnitReportFormat(raw: string | undefined): JUnitReportFormat | undefined;
32
+ /**
33
+ * Validate `--report` / `--report-file` / `--report-suite-name` combinations.
34
+ * Report export is a sidecar artifact for batch `--wait` runs only.
35
+ */
36
+ export declare function assertJUnitReportOptions(opts: JUnitReportFlagOptions): void;
37
+ /**
38
+ * Resolve the project id used for JUnit classname / default suite naming.
39
+ * Prefer explicit `--project`, then ids observed on polled run rows.
40
+ */
41
+ export declare function resolveBatchReportProjectId(opts: {
42
+ projectId?: string;
43
+ }, results: ReadonlyArray<{
44
+ projectId?: string;
45
+ }>): string;
46
+ /**
47
+ * Escape text for inclusion in XML element bodies and double-quoted attributes.
48
+ */
49
+ export declare function escapeXml(text: string): string;
50
+ /**
51
+ * Build a JUnit XML document from batch poll results. Duration is `0` in v1
52
+ * because batch poll envelopes do not carry per-run timing.
53
+ */
54
+ export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
55
+ /**
56
+ * Atomically write JUnit XML to `--report-file` (temp sibling + rename).
57
+ */
58
+ export declare function writeJUnitReportFile(rawPath: string, xml: string): Promise<void>;
@@ -0,0 +1,210 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { rename, stat, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { localValidationError, TransportError } from './errors.js';
6
+ const XML_DECL = '<?xml version="1.0" encoding="UTF-8"?>';
7
+ /**
8
+ * Parse `--report <format>`. Only `junit` is accepted in v1.
9
+ */
10
+ export function parseJUnitReportFormat(raw) {
11
+ if (raw === undefined || raw === '')
12
+ return undefined;
13
+ if (raw === 'junit')
14
+ return 'junit';
15
+ throw localValidationError('report', `unsupported report format "${raw}" — accepted: junit`);
16
+ }
17
+ /**
18
+ * Validate `--report` / `--report-file` / `--report-suite-name` combinations.
19
+ * Report export is a sidecar artifact for batch `--wait` runs only.
20
+ */
21
+ export function assertJUnitReportOptions(opts) {
22
+ if (opts.report === undefined) {
23
+ if (opts.reportFile !== undefined && opts.reportFile !== '') {
24
+ throw localValidationError('report-file', '--report-file requires --report junit');
25
+ }
26
+ if (opts.reportSuiteName !== undefined && opts.reportSuiteName !== '') {
27
+ throw localValidationError('report-suite-name', '--report-suite-name requires --report junit');
28
+ }
29
+ return;
30
+ }
31
+ if (!opts.batchPath) {
32
+ throw localValidationError('report', '--report junit only applies to batch --wait runs (test run --all, or test rerun --all / multiple test ids)');
33
+ }
34
+ if (!opts.wait) {
35
+ throw localValidationError('report', '--report junit requires --wait (the report is written after batch polling completes)');
36
+ }
37
+ if (opts.reportFile === undefined || opts.reportFile === '') {
38
+ throw localValidationError('report-file', '--report junit requires --report-file <path>');
39
+ }
40
+ }
41
+ /**
42
+ * Resolve the project id used for JUnit classname / default suite naming.
43
+ * Prefer explicit `--project`, then ids observed on polled run rows.
44
+ */
45
+ export function resolveBatchReportProjectId(opts, results) {
46
+ if (opts.projectId)
47
+ return opts.projectId;
48
+ const fromPoll = results.map(r => r.projectId).find((id) => !!id);
49
+ if (fromPoll)
50
+ return fromPoll;
51
+ throw localValidationError('project', '--report junit requires --project <id> when the project cannot be inferred from run results');
52
+ }
53
+ /**
54
+ * Escape text for inclusion in XML element bodies and double-quoted attributes.
55
+ */
56
+ export function escapeXml(text) {
57
+ return text
58
+ .replace(/&/g, '&amp;')
59
+ .replace(/</g, '&lt;')
60
+ .replace(/>/g, '&gt;')
61
+ .replace(/"/g, '&quot;')
62
+ .replace(/'/g, '&apos;');
63
+ }
64
+ function classifyJUnitOutcome(status, error) {
65
+ if (status === 'passed')
66
+ return 'passed';
67
+ if (status === 'skipped')
68
+ return 'skipped';
69
+ if (status === 'error' || error?.exitCode === 3)
70
+ return 'error';
71
+ return 'failure';
72
+ }
73
+ function failureMessage(result) {
74
+ if (result.error?.message)
75
+ return result.error.message;
76
+ if (result.error?.code)
77
+ return result.error.code;
78
+ return result.status;
79
+ }
80
+ function renderTestcase(result, classname) {
81
+ const outcome = classifyJUnitOutcome(result.status, result.error);
82
+ const name = escapeXml(result.testId);
83
+ const cls = escapeXml(classname);
84
+ const lines = [` <testcase classname="${cls}" name="${name}" time="0">`];
85
+ if (outcome === 'failure') {
86
+ const message = escapeXml(failureMessage(result));
87
+ const type = escapeXml(result.status);
88
+ const body = escapeXml([
89
+ `status: ${result.status}`,
90
+ result.runId ? `runId: ${result.runId}` : undefined,
91
+ result.error?.code ? `code: ${result.error.code}` : undefined,
92
+ result.error?.message ? `message: ${result.error.message}` : undefined,
93
+ ]
94
+ .filter(Boolean)
95
+ .join('\n'));
96
+ lines.push(` <failure message="${message}" type="${type}">${body}</failure>`);
97
+ }
98
+ else if (outcome === 'error') {
99
+ const message = escapeXml(failureMessage(result));
100
+ const type = escapeXml(result.error?.code ?? result.status);
101
+ const body = escapeXml([
102
+ result.error?.code ? `code: ${result.error.code}` : undefined,
103
+ result.error?.message ? `message: ${result.error.message}` : undefined,
104
+ result.runId ? `runId: ${result.runId}` : undefined,
105
+ ]
106
+ .filter(Boolean)
107
+ .join('\n'));
108
+ lines.push(` <error message="${message}" type="${type}">${body}</error>`);
109
+ }
110
+ else if (outcome === 'skipped') {
111
+ lines.push(` <skipped/>`);
112
+ }
113
+ lines.push(' </testcase>');
114
+ return lines.join('\n');
115
+ }
116
+ /**
117
+ * Build a JUnit XML document from batch poll results. Duration is `0` in v1
118
+ * because batch poll envelopes do not carry per-run timing.
119
+ */
120
+ export function buildJUnitReport(opts) {
121
+ const results = opts.results;
122
+ let failures = 0;
123
+ let errors = 0;
124
+ let skipped = 0;
125
+ for (const result of results) {
126
+ const outcome = classifyJUnitOutcome(result.status, result.error);
127
+ if (outcome === 'failure')
128
+ failures++;
129
+ else if (outcome === 'error')
130
+ errors++;
131
+ else if (outcome === 'skipped')
132
+ skipped++;
133
+ }
134
+ const suiteName = escapeXml(opts.suiteName);
135
+ const testcases = results.map(r => renderTestcase(r, opts.classname)).join('\n');
136
+ return [
137
+ XML_DECL,
138
+ '<testsuites>',
139
+ ` <testsuite name="${suiteName}" tests="${results.length}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="0">`,
140
+ testcases,
141
+ ' </testsuite>',
142
+ '</testsuites>',
143
+ '',
144
+ ].join('\n');
145
+ }
146
+ async function assertReportFileParent(rawPath) {
147
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
148
+ throw localValidationError('report-file', 'must be a non-empty file path');
149
+ }
150
+ const resolved = isAbsolute(rawPath) ? rawPath : resolve(process.cwd(), rawPath);
151
+ if (resolved.endsWith('/') || resolved.endsWith('\\')) {
152
+ throw localValidationError('report-file', 'must point to a file, not a directory');
153
+ }
154
+ const parent = dirname(resolved);
155
+ let parentStat;
156
+ try {
157
+ parentStat = await stat(parent);
158
+ }
159
+ catch {
160
+ throw localValidationError('report-file', `parent directory does not exist: ${parent}`);
161
+ }
162
+ if (!parentStat.isDirectory()) {
163
+ throw localValidationError('report-file', `parent path is not a directory: ${parent}`);
164
+ }
165
+ let targetStat;
166
+ try {
167
+ targetStat = await stat(resolved);
168
+ }
169
+ catch {
170
+ return resolved;
171
+ }
172
+ if (targetStat.isDirectory()) {
173
+ throw localValidationError('report-file', `must point to a file, not a directory: ${resolved}`);
174
+ }
175
+ return resolved;
176
+ }
177
+ /**
178
+ * Atomically write JUnit XML to `--report-file` (temp sibling + rename).
179
+ */
180
+ export async function writeJUnitReportFile(rawPath, xml) {
181
+ const resolved = await assertReportFileParent(rawPath);
182
+ const parent = dirname(resolved);
183
+ const tmpPath = join(parent, `.${basename(resolved)}.tmp-${randomUUID()}`);
184
+ await new Promise((resolvePromise, reject) => {
185
+ const stream = createWriteStream(tmpPath, { encoding: 'utf8' });
186
+ let streamError = null;
187
+ stream.on('error', err => {
188
+ streamError = err instanceof Error ? err : new Error(String(err));
189
+ });
190
+ stream.write(xml, err => {
191
+ if (err) {
192
+ streamError = err instanceof Error ? err : new Error(String(err));
193
+ }
194
+ stream.end(() => {
195
+ if (streamError) {
196
+ unlink(tmpPath).catch(() => undefined);
197
+ reject(new TransportError(`Failed to write --report-file ${resolved}: ${streamError.message}`));
198
+ return;
199
+ }
200
+ rename(tmpPath, resolved)
201
+ .then(() => resolvePromise())
202
+ .catch(renameErr => {
203
+ unlink(tmpPath).catch(() => undefined);
204
+ reject(new TransportError(`Failed to write --report-file ${resolved}: ${renameErr instanceof Error ? renameErr.message : String(renameErr)}`));
205
+ });
206
+ });
207
+ });
208
+ });
209
+ }
210
+ //# sourceMappingURL=junit-report.js.map
@@ -2,10 +2,25 @@ export type OutputMode = 'json' | 'text';
2
2
  /**
3
3
  * Help-text footer pointing at the global options surface so users
4
4
  * looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
5
- * `--profile`, `--endpoint-url`, `--debug`.
5
+ * `--profile`, `--endpoint-url`, `--request-timeout`, `--debug`.
6
6
  */
7
7
  export declare const GLOBAL_OPTS_HINT: string;
8
8
  export declare function isOutputMode(value: unknown): value is OutputMode;
9
+ /**
10
+ * Resolve a raw `--output` flag value to a concrete {@link OutputMode}.
11
+ *
12
+ * `undefined` (flag omitted) resolves to the default `'text'`. Any other
13
+ * value that is not `'json'` or `'text'` throws a typed VALIDATION_ERROR
14
+ * (exit 5) with an actionable message.
15
+ *
16
+ * The alternative — silently falling back to `'text'` — is a footgun for the
17
+ * CLI's primary consumer (coding agents): a caller that asks for
18
+ * `--output json` but mistypes it (`--output josn`) would otherwise receive a
19
+ * human-readable text payload and fail to parse it as JSON, with no signal as
20
+ * to why. Every command group routes its global-option resolution through this
21
+ * helper so the validation is uniform.
22
+ */
23
+ export declare function resolveOutputMode(raw: unknown): OutputMode;
9
24
  export interface OutputStreams {
10
25
  /**
11
26
  * Line-oriented stdout writer. Each call is one logical line; the
@@ -1,13 +1,35 @@
1
+ import { localValidationError } from './errors.js';
1
2
  /**
2
3
  * Help-text footer pointing at the global options surface so users
3
4
  * looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
4
- * `--profile`, `--endpoint-url`, `--debug`.
5
+ * `--profile`, `--endpoint-url`, `--request-timeout`, `--debug`.
5
6
  */
6
- export const GLOBAL_OPTS_HINT = '\nGlobal options (--dry-run, --output, --profile, --endpoint-url, --verbose, --debug):' +
7
+ export const GLOBAL_OPTS_HINT = '\nGlobal options (--dry-run, --output, --profile, --endpoint-url, --request-timeout, --verbose, --debug):' +
7
8
  '\n testsprite --help';
8
9
  export function isOutputMode(value) {
9
10
  return value === 'json' || value === 'text';
10
11
  }
12
+ /**
13
+ * Resolve a raw `--output` flag value to a concrete {@link OutputMode}.
14
+ *
15
+ * `undefined` (flag omitted) resolves to the default `'text'`. Any other
16
+ * value that is not `'json'` or `'text'` throws a typed VALIDATION_ERROR
17
+ * (exit 5) with an actionable message.
18
+ *
19
+ * The alternative — silently falling back to `'text'` — is a footgun for the
20
+ * CLI's primary consumer (coding agents): a caller that asks for
21
+ * `--output json` but mistypes it (`--output josn`) would otherwise receive a
22
+ * human-readable text payload and fail to parse it as JSON, with no signal as
23
+ * to why. Every command group routes its global-option resolution through this
24
+ * helper so the validation is uniform.
25
+ */
26
+ export function resolveOutputMode(raw) {
27
+ if (raw === undefined)
28
+ return 'text';
29
+ if (isOutputMode(raw))
30
+ return raw;
31
+ throw localValidationError('output', 'must be one of: json, text', ['json', 'text']);
32
+ }
11
33
  export class Output {
12
34
  mode;
13
35
  stdoutWrite;
@@ -16,13 +16,14 @@ export interface PaginationFlags {
16
16
  /** Client-side cap on total items returned across pages. */
17
17
  maxItems?: number;
18
18
  }
19
+ export declare const MAX_AUTO_PAGES = 1000;
19
20
  /**
20
21
  * Validates and normalizes pagination flags. Per the CLI OpenAPI spec
21
22
  * §components.parameters.PageSize the hard cap is 100. Values above the
22
23
  * cap are now rejected with exit 5 rather than silently clamped, giving
23
- * callers fast feedback that their flag value is out of range. Sub-1 /
24
- * NaN values also throw. `maxItems` is validated but not capped (it is a
25
- * client-side cursor, not a server parameter).
24
+ * callers fast feedback that their flag value is out of range. Fractional,
25
+ * sub-1, and NaN values also throw. `maxItems` is validated but not capped
26
+ * (it is a client-side cursor, not a server parameter).
26
27
  *
27
28
  * NOTE: `runResultHistory` previously did its own silent clamp via
28
29
  * `Math.min(Math.max(1, n), 100)` — that was unified to this path by the