@testsprite/testsprite-cli 0.1.2 → 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.
@@ -35,10 +35,15 @@
35
35
  import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
36
36
  import { pipeline } from 'node:stream/promises';
37
37
  import { createWriteStream } from 'node:fs';
38
- import { dirname, isAbsolute, join, resolve } from 'node:path';
39
- import { ApiError, TransportError } from './errors.js';
38
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
39
+ import { ApiError, TransportError, localValidationError } from './errors.js';
40
+ import { requireEnum } from './validate.js';
40
41
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
41
42
  export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
43
+ /** Max fetch attempts for each presigned URL (initial + retries). */
44
+ export const STREAM_URL_MAX_RETRIES = 3;
45
+ /** Delay between retries for transient transport failures (ms). */
46
+ export const STREAM_URL_RETRY_DELAY_MS = 1000;
42
47
  /** Default radius around the failed step when `--failed-only` is set. */
43
48
  export const FAILED_ONLY_RADIUS = 1;
44
49
  /**
@@ -198,10 +203,13 @@ export function pickCodeExtension(language, framework) {
198
203
  return 'js';
199
204
  if (language === 'typescript')
200
205
  return 'ts';
201
- // Fallback: framework-keyed default. pytest is python, playwright TS.
206
+ // Fallback when the server didn't stamp a language: both TestSprite
207
+ // frameworks are Python — backend `pytest` and frontend Playwright
208
+ // (`playwright.async_api`) — so default to `.py`. (Legacy TS/JS rows
209
+ // carry an explicit `language` above and are honored as `.ts`/`.js`.)
202
210
  if (framework === 'pytest')
203
211
  return 'py';
204
- return 'ts';
212
+ return 'py';
205
213
  }
206
214
  /**
207
215
  * Step filename per §7.2 — 1-based index, zero-padded to two digits
@@ -213,6 +221,19 @@ export function pickCodeExtension(language, framework) {
213
221
  export function stepFilenamePrefix(stepIndex) {
214
222
  return stepIndex >= 100 ? String(stepIndex).padStart(3, '0') : String(stepIndex).padStart(2, '0');
215
223
  }
224
+ /**
225
+ * Refuse a composed artifact path that escapes `baseDir`. Step filenames are
226
+ * built from response-controlled fields, so this is the final containment
227
+ * check before any write. Returns the validated absolute path.
228
+ */
229
+ export function assertNoEscape(baseDir, segment) {
230
+ const composed = resolve(baseDir, segment);
231
+ const rel = relative(baseDir, composed);
232
+ if (rel.startsWith('..') || isAbsolute(rel)) {
233
+ throw localValidationError('out', 'resolved artifact path escapes the bundle directory', undefined, 'field');
234
+ }
235
+ return composed;
236
+ }
216
237
  /**
217
238
  * Build the §7.1 meta.json given a context. Pure function, no I/O —
218
239
  * lets specs assert the meta shape without touching disk.
@@ -417,15 +438,20 @@ async function dirExists(path) {
417
438
  * there's nothing to put in it; it's NOT a placeholder.
418
439
  */
419
440
  async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten) {
441
+ // stepIndex comes straight from the response and is used to build the
442
+ // filename — reject anything that isn't a real index before composing a path.
443
+ if (!Number.isInteger(step.stepIndex) || step.stepIndex < 0) {
444
+ throw localValidationError('stepIndex', 'must be a non-negative integer', undefined, 'field');
445
+ }
420
446
  const prefix = stepFilenamePrefix(step.stepIndex);
421
447
  if (step.screenshotUrl) {
422
448
  const file = `${prefix}-screenshot.png`;
423
- await streamUrlToFile(step.screenshotUrl, join(stepsTmpDir, file), fetchImpl);
449
+ await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
424
450
  filesWritten.push(`steps/${file}`);
425
451
  }
426
452
  if (step.htmlSnapshotUrl) {
427
453
  const file = `${prefix}-snapshot.html`;
428
- await streamUrlToFile(step.htmlSnapshotUrl, join(stepsTmpDir, file), fetchImpl);
454
+ await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
429
455
  filesWritten.push(`steps/${file}`);
430
456
  }
431
457
  // Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
@@ -448,6 +474,8 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
448
474
  const sidecar = allEvidence.filter(e => e.stepIndex === step.stepIndex);
449
475
  if (sidecar.length > 0) {
450
476
  const dereferenced = await Promise.all(sidecar.map(async (entry, i) => {
477
+ // kind comes from the response and is used in the filename — validate it.
478
+ requireEnum('kind', entry.kind, ['screenshot', 'snapshot', 'log', 'network', 'console']);
451
479
  // Reuse the already-downloaded step file when the evidence URL
452
480
  // matches the step's primary screenshot/snapshot URL. Cheap
453
481
  // dedupe — no extra HTTP round-trip, no duplicate bytes on disk.
@@ -471,7 +499,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
471
499
  }
472
500
  const ext = sidecarExtension(entry.kind);
473
501
  const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
474
- await streamUrlToFile(entry.url, join(stepsTmpDir, filename), fetchImpl);
502
+ await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl);
475
503
  filesWritten.push(`steps/${filename}`);
476
504
  return {
477
505
  kind: entry.kind,
@@ -484,7 +512,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
484
512
  };
485
513
  }));
486
514
  const file = `${prefix}-evidence.json`;
487
- await writeFile(join(stepsTmpDir, file), JSON.stringify(dereferenced, null, 2) + '\n', 'utf8');
515
+ await writeFile(assertNoEscape(stepsTmpDir, file), JSON.stringify(dereferenced, null, 2) + '\n', 'utf8');
488
516
  filesWritten.push(`steps/${file}`);
489
517
  }
490
518
  }
@@ -510,52 +538,81 @@ function sidecarExtension(kind) {
510
538
  * the upstream reader rather than buffering chunks in V8 heap. This
511
539
  * matters for video files (multi-MB) and for very large HTML
512
540
  * snapshots.
541
+ *
542
+ * Transport failures (network reset, DNS blip, mid-stream EOF) are
543
+ * retried up to STREAM_URL_MAX_RETRIES times with a fixed delay.
544
+ * Presigned URLs are valid for 15 minutes, so retries are safe.
513
545
  */
514
- export async function streamUrlToFile(url, filePath, fetchImpl) {
515
- let response;
516
- try {
517
- response = await fetchImpl(url);
518
- }
519
- catch (err) {
520
- const message = err instanceof Error ? err.message : String(err);
521
- throw new TransportError(`Failed to download presigned URL ${url}: ${message}`);
522
- }
523
- if (!response.ok) {
524
- throw ApiError.fromEnvelope({
525
- error: {
526
- code: 'UNAVAILABLE',
527
- message: `Failed to download presigned URL (HTTP ${response.status}).`,
528
- nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
529
- requestId: 'local',
530
- details: { status: response.status, url },
531
- },
532
- });
533
- }
534
- if (!response.body) {
535
- // Some test runtimes / fetch polyfills don't expose `body` as a
536
- // ReadableStream. Fall back to a buffered write — same correctness,
537
- // just no streaming benefit. The bundle is bounded by the
538
- // backend's 15-min TTL, so even a multi-MB video buffers fully in
539
- // a tolerable amount of memory.
540
- const buffer = Buffer.from(await response.arrayBuffer());
541
- await writeFile(filePath, buffer);
542
- return;
543
- }
544
- await mkdir(dirname(filePath), { recursive: true });
545
- // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
546
- // it via `Readable.fromWeb` (Node ≥ 18). Wrap in a try so any error
547
- // from the stream propagates as a TransportError, preserving the
548
- // exit-code contract.
549
- const fileSink = createWriteStream(filePath);
550
- try {
551
- const webBody = response.body;
552
- const { Readable } = await import('node:stream');
553
- const nodeStream = Readable.fromWeb(webBody);
554
- await pipeline(nodeStream, fileSink);
555
- }
556
- catch (err) {
557
- const message = err instanceof Error ? err.message : String(err);
558
- throw new TransportError(`Failed mid-download of ${url}: ${message}`);
546
+ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
547
+ const sleepFn = deps?.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
548
+ for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
549
+ let response;
550
+ try {
551
+ response = await fetchImpl(url);
552
+ }
553
+ catch (err) {
554
+ const message = err instanceof Error ? err.message : String(err);
555
+ if (attempt < STREAM_URL_MAX_RETRIES) {
556
+ await sleepFn(STREAM_URL_RETRY_DELAY_MS);
557
+ continue;
558
+ }
559
+ throw new TransportError(`Failed to download presigned URL ${url}: ${message}`);
560
+ }
561
+ if (!response.ok) {
562
+ // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
563
+ // Retrying the same URL won't help — surface immediately.
564
+ throw ApiError.fromEnvelope({
565
+ error: {
566
+ code: 'UNAVAILABLE',
567
+ message: `Failed to download presigned URL (HTTP ${response.status}).`,
568
+ nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
569
+ requestId: 'local',
570
+ details: { status: response.status, url },
571
+ },
572
+ });
573
+ }
574
+ if (!response.body) {
575
+ // Some test runtimes / fetch polyfills don't expose `body` as a
576
+ // ReadableStream. Fall back to a buffered write — same correctness,
577
+ // just no streaming benefit. The bundle is bounded by the
578
+ // backend's 15-min TTL, so even a multi-MB video buffers fully in
579
+ // a tolerable amount of memory.
580
+ try {
581
+ const buffer = Buffer.from(await response.arrayBuffer());
582
+ await writeFile(filePath, buffer);
583
+ return;
584
+ }
585
+ catch (err) {
586
+ const message = err instanceof Error ? err.message : String(err);
587
+ if (attempt < STREAM_URL_MAX_RETRIES) {
588
+ await sleepFn(STREAM_URL_RETRY_DELAY_MS);
589
+ continue;
590
+ }
591
+ throw new TransportError(`Failed to download presigned URL ${url}: ${message}`);
592
+ }
593
+ }
594
+ await mkdir(dirname(filePath), { recursive: true });
595
+ // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
596
+ // it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
597
+ // from the stream propagates as a TransportError, preserving the
598
+ // exit-code contract. `pipeline` destroys both streams on error, so
599
+ // a new WriteStream on retry starts clean.
600
+ const fileSink = createWriteStream(filePath);
601
+ try {
602
+ const webBody = response.body;
603
+ const { Readable } = await import('node:stream');
604
+ const nodeStream = Readable.fromWeb(webBody);
605
+ await pipeline(nodeStream, fileSink);
606
+ return;
607
+ }
608
+ catch (err) {
609
+ const message = err instanceof Error ? err.message : String(err);
610
+ if (attempt < STREAM_URL_MAX_RETRIES) {
611
+ await sleepFn(STREAM_URL_RETRY_DELAY_MS);
612
+ continue;
613
+ }
614
+ throw new TransportError(`Failed mid-download of ${url}: ${message}`);
615
+ }
559
616
  }
560
617
  }
561
618
  function isPresignedUrl(value) {
@@ -69,4 +69,22 @@ export declare function resetDryRunBannerForTesting(): void;
69
69
  * not a safety-critical gate.
70
70
  */
71
71
  export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'requestTimeoutMs'>, env: NodeJS.ProcessEnv): number;
72
+ /**
73
+ * Validate that the resolved API endpoint is a syntactically valid http(s)
74
+ * URL before it is used to build requests.
75
+ *
76
+ * Unlike the `--target-url` guard in `target-url.ts`, this deliberately does
77
+ * NOT reject localhost or private addresses: the API endpoint legitimately
78
+ * points at a self-hosted, local-dev, or mock backend on a private host. It
79
+ * only catches a malformed value (unparseable, or a non-http(s) scheme) so the
80
+ * operator gets a fast, actionable VALIDATION_ERROR (exit 5) instead of an
81
+ * opaque `Invalid URL` (exit 1, a raw `new URL()` throw) or a misleading
82
+ * `fetch failed / Service temporarily unavailable` emitted only after a full
83
+ * retry-and-backoff cycle.
84
+ *
85
+ * The value can originate from `--endpoint-url`, `TESTSPRITE_API_URL`, or the
86
+ * credentials file `api_url`, so the message names all three rather than
87
+ * assuming the flag.
88
+ */
89
+ export declare function assertValidEndpointUrl(rawUrl: string): void;
72
90
  export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClient;
@@ -15,7 +15,7 @@
15
15
  */
16
16
  import { loadConfig } from './config.js';
17
17
  import { defaultCredentialsPath } from './credentials.js';
18
- import { ApiError } from './errors.js';
18
+ import { ApiError, localValidationError } from './errors.js';
19
19
  import { facadeBaseUrl } from './facade.js';
20
20
  import { HttpClient, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, REQUEST_TIMEOUT_MIN_MS, } from './http.js';
21
21
  import { createDryRunFetch } from './dry-run/fetch.js';
@@ -78,14 +78,50 @@ export function resolveRequestTimeoutMs(opts, env) {
78
78
  function clampRequestTimeout(ms) {
79
79
  return Math.min(Math.max(Math.round(ms), REQUEST_TIMEOUT_MIN_MS), REQUEST_TIMEOUT_MAX_MS);
80
80
  }
81
+ /**
82
+ * Validate that the resolved API endpoint is a syntactically valid http(s)
83
+ * URL before it is used to build requests.
84
+ *
85
+ * Unlike the `--target-url` guard in `target-url.ts`, this deliberately does
86
+ * NOT reject localhost or private addresses: the API endpoint legitimately
87
+ * points at a self-hosted, local-dev, or mock backend on a private host. It
88
+ * only catches a malformed value (unparseable, or a non-http(s) scheme) so the
89
+ * operator gets a fast, actionable VALIDATION_ERROR (exit 5) instead of an
90
+ * opaque `Invalid URL` (exit 1, a raw `new URL()` throw) or a misleading
91
+ * `fetch failed / Service temporarily unavailable` emitted only after a full
92
+ * retry-and-backoff cycle.
93
+ *
94
+ * The value can originate from `--endpoint-url`, `TESTSPRITE_API_URL`, or the
95
+ * credentials file `api_url`, so the message names all three rather than
96
+ * assuming the flag.
97
+ */
98
+ export function assertValidEndpointUrl(rawUrl) {
99
+ let parsed;
100
+ try {
101
+ parsed = new URL(rawUrl);
102
+ }
103
+ catch {
104
+ throw localValidationError('endpoint-url', `"${rawUrl}" is not a valid URL — provide an http(s) URL (e.g. https://api.testsprite.com) ` +
105
+ `via --endpoint-url, TESTSPRITE_API_URL, or the credentials file`, undefined, 'field');
106
+ }
107
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
108
+ throw localValidationError('endpoint-url', `scheme "${parsed.protocol.replace(/:$/, '')}" is not supported — use http or https ` +
109
+ `(e.g. https://api.testsprite.com)`, undefined, 'field');
110
+ }
111
+ }
81
112
  export function makeHttpClient(opts, deps = {}) {
82
113
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
83
114
  const env = deps.env ?? process.env;
84
115
  const requestTimeoutMs = resolveRequestTimeoutMs(opts, env);
85
116
  if (opts.dryRun) {
117
+ const dryRunEndpoint = opts.endpointUrl ?? DRY_RUN_DEFAULT_ENDPOINT;
118
+ // Validate even under --dry-run so a typo in --endpoint-url is caught
119
+ // offline (no creds, no network). Validate BEFORE the banner so a rejected
120
+ // endpoint doesn't first announce a "sample response".
121
+ assertValidEndpointUrl(dryRunEndpoint);
86
122
  emitDryRunBanner(stderr);
87
123
  return new HttpClient({
88
- baseUrl: facadeBaseUrl(opts.endpointUrl ?? DRY_RUN_DEFAULT_ENDPOINT),
124
+ baseUrl: facadeBaseUrl(dryRunEndpoint),
89
125
  apiKey: DRY_RUN_API_KEY,
90
126
  fetchImpl: deps.fetchImpl ?? createDryRunFetch(),
91
127
  onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
@@ -100,6 +136,10 @@ export function makeHttpClient(opts, deps = {}) {
100
136
  env,
101
137
  credentialsPath,
102
138
  });
139
+ // Catch a malformed endpoint (from --endpoint-url / TESTSPRITE_API_URL /
140
+ // credentials) before the auth check so a config typo surfaces as a clear
141
+ // VALIDATION_ERROR rather than an opaque URL throw or a retried "fetch failed".
142
+ assertValidEndpointUrl(config.apiUrl);
103
143
  if (!config.apiKey)
104
144
  throw ApiError.authRequired();
105
145
  return new HttpClient({
@@ -1,4 +1,11 @@
1
1
  export declare const DEFAULT_PROFILE = "default";
2
+ /**
3
+ * Throw a typed VALIDATION_ERROR (exit 5) when `profile` is not a safe INI
4
+ * section name. Guards every credential read/write so a malformed `--profile`
5
+ * (or `TESTSPRITE_PROFILE`) value fails loudly instead of silently corrupting
6
+ * `~/.testsprite/credentials` or failing to persist a key written by `setup`.
7
+ */
8
+ export declare function assertValidProfileName(profile: string): void;
2
9
  export declare function defaultCredentialsPath(): string;
3
10
  export interface ProfileEntry {
4
11
  apiKey?: string;
@@ -1,7 +1,34 @@
1
1
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
+ import { localValidationError } from './errors.js';
4
5
  export const DEFAULT_PROFILE = 'default';
6
+ /**
7
+ * Allowed profile-name characters. A profile name is written verbatim as an
8
+ * INI section header (`[name]`) in the credentials file, so any character that
9
+ * breaks that grammar must be rejected:
10
+ * - `]` closes the header early — `prod]` serialises to `[prod]]`, which the
11
+ * section regex cannot match, so the api_key/api_url lines that follow are
12
+ * silently dropped on read (the credential never persists).
13
+ * - CR/LF splits the header across lines, corrupting the file.
14
+ * - leading/trailing whitespace does not round-trip — the parser trims
15
+ * section names, so `[ prod ]` reads back as `prod`.
16
+ * A conservative allowlist (letters, digits, dot, underscore, hyphen) matches
17
+ * conventional profile names (`default`, `prod`, `ci-staging`, `team.qa`) and
18
+ * cannot corrupt the file.
19
+ */
20
+ const PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
21
+ /**
22
+ * Throw a typed VALIDATION_ERROR (exit 5) when `profile` is not a safe INI
23
+ * section name. Guards every credential read/write so a malformed `--profile`
24
+ * (or `TESTSPRITE_PROFILE`) value fails loudly instead of silently corrupting
25
+ * `~/.testsprite/credentials` or failing to persist a key written by `setup`.
26
+ */
27
+ export function assertValidProfileName(profile) {
28
+ if (!PROFILE_NAME_RE.test(profile)) {
29
+ throw localValidationError('profile', 'must contain only letters, digits, dot, underscore, or hyphen (no spaces, brackets, or newlines)', undefined, 'flag');
30
+ }
31
+ }
5
32
  export function defaultCredentialsPath() {
6
33
  return join(homedir(), '.testsprite', 'credentials');
7
34
  }
@@ -79,16 +106,19 @@ export function readCredentialsFile(options = {}) {
79
106
  return parseCredentials(readFileSync(path, 'utf-8'));
80
107
  }
81
108
  export function readProfile(profile, options = {}) {
109
+ assertValidProfileName(profile);
82
110
  const file = readCredentialsFile(options);
83
111
  return file[profile];
84
112
  }
85
113
  export function writeProfile(profile, entry, options = {}) {
114
+ assertValidProfileName(profile);
86
115
  const path = resolvePath(options);
87
116
  const file = readCredentialsFile(options);
88
117
  file[profile] = { ...file[profile], ...entry };
89
118
  writeCredentialsAtomic(path, file);
90
119
  }
91
120
  export function deleteProfile(profile, options = {}) {
121
+ assertValidProfileName(profile);
92
122
  const path = resolvePath(options);
93
123
  const file = readCredentialsFile(options);
94
124
  if (!(profile in file))
@@ -106,16 +106,31 @@ const tests = [
106
106
  ];
107
107
  const testCode = {
108
108
  testId: SAMPLE_TEST_ID_FAILED,
109
- language: 'typescript',
109
+ language: 'python',
110
110
  framework: 'playwright',
111
+ // TestSprite test code is Python: frontend tests are Playwright
112
+ // (`playwright.async_api`); backend tests use `requests` + assertions.
111
113
  code: [
112
- "import { test, expect } from '@playwright/test';",
113
- "test('checkout happy path', async ({ page }) => {",
114
- ' await page.goto(process.env.TARGET_URL!);',
115
- ' await page.click(\'[data-testid="cart"]\');',
116
- ' await page.click(\'[data-testid="submit"]\');',
117
- " await expect(page.getByRole('heading', { name: 'Order placed' })).toBeVisible();",
118
- '});',
114
+ 'import asyncio',
115
+ 'from playwright.async_api import async_playwright, expect',
116
+ '',
117
+ '',
118
+ 'async def run_test():',
119
+ ' async with async_playwright() as pw:',
120
+ ' browser = await pw.chromium.launch(headless=True)',
121
+ ' context = await browser.new_context()',
122
+ ' page = await context.new_page()',
123
+ ' try:',
124
+ ' await page.goto("https://example.com") # target URL injected by the runner',
125
+ ' await page.click(\'[data-testid="cart"]\')',
126
+ ' await page.click(\'[data-testid="submit"]\')',
127
+ ' await expect(page.get_by_role("heading", name="Order placed")).to_be_visible()',
128
+ ' finally:',
129
+ ' await context.close()',
130
+ ' await browser.close()',
131
+ '',
132
+ '',
133
+ 'asyncio.run(run_test())',
119
134
  '',
120
135
  ].join('\n'),
121
136
  codeVersion: 'v3',
@@ -186,7 +201,9 @@ const latestResult = {
186
201
  targetUrlSource: 'run',
187
202
  failedStepIndex: 5,
188
203
  failureKind: 'assertion',
189
- summary: { passed: 4, failed: 1, skipped: 0 },
204
+ verdict: 'failed',
205
+ executionStatus: 'completed',
206
+ summary: 'Failed (assertion) on step 5: expected cart badge to show 1 item, but it was empty.',
190
207
  };
191
208
  const failureContext = {
192
209
  snapshotId: SAMPLE_SNAPSHOT_ID,
@@ -4,6 +4,7 @@
4
4
  * Extracted so the output-interceptor rephrasing logic (P10) is
5
5
  * unit-testable without spawning a full CLI process.
6
6
  */
7
+ import type { OutputMode } from './output.js';
7
8
  /**
8
9
  * Rephrase Commander's "unknown option '--foo'" error when `--foo` is
9
10
  * a known global flag that was placed after the subcommand.
@@ -12,4 +13,16 @@
12
13
  * it is an ordinary unknown flag that should fall through to the original
13
14
  * Commander output.
14
15
  */
16
+ /**
17
+ * Format a Commander parse-error message for the requested output mode.
18
+ * Returns the string to write to stderr; the caller writes it.
19
+ *
20
+ * pendingMsg: message captured by configureOutput.outputError before the
21
+ * CommanderError was thrown (may already be rephrased by
22
+ * rephraseUnknownOption). Null only when Commander threw without
23
+ * first calling outputError (should not happen for parse errors).
24
+ * fallbackMsg: err.message from CommanderError, used when pendingMsg is null.
25
+ * mode: the output mode resolved from --output (or argv fallback).
26
+ */
27
+ export declare function renderCommanderError(pendingMsg: string | null, fallbackMsg: string, mode: OutputMode): string;
15
28
  export declare function rephraseUnknownOption(raw: string): string | null;
@@ -1,9 +1,3 @@
1
- /**
2
- * Shared error rendering helpers for `src/index.ts`.
3
- *
4
- * Extracted so the output-interceptor rephrasing logic (P10) is
5
- * unit-testable without spawning a full CLI process.
6
- */
7
1
  /**
8
2
  * Global flags that belong before the subcommand, not after it.
9
3
  *
@@ -27,6 +21,33 @@ const GLOBAL_FLAG_ARITY = {
27
21
  * it is an ordinary unknown flag that should fall through to the original
28
22
  * Commander output.
29
23
  */
24
+ /**
25
+ * Format a Commander parse-error message for the requested output mode.
26
+ * Returns the string to write to stderr; the caller writes it.
27
+ *
28
+ * pendingMsg: message captured by configureOutput.outputError before the
29
+ * CommanderError was thrown (may already be rephrased by
30
+ * rephraseUnknownOption). Null only when Commander threw without
31
+ * first calling outputError (should not happen for parse errors).
32
+ * fallbackMsg: err.message from CommanderError, used when pendingMsg is null.
33
+ * mode: the output mode resolved from --output (or argv fallback).
34
+ */
35
+ export function renderCommanderError(pendingMsg, fallbackMsg, mode) {
36
+ const rawMsg = (pendingMsg ?? fallbackMsg).trim();
37
+ if (mode === 'json') {
38
+ return (JSON.stringify({
39
+ error: {
40
+ code: 'VALIDATION_ERROR',
41
+ message: rawMsg,
42
+ nextAction: 'Run testsprite --help or testsprite <command> --help for usage.',
43
+ requestId: 'local',
44
+ },
45
+ }, null, 2) + '\n');
46
+ }
47
+ // Text mode: emit the buffered message as-is (already formatted by Commander
48
+ // or rephrased by rephraseUnknownOption). Synthesize when null.
49
+ return pendingMsg ?? `${rawMsg}\n`;
50
+ }
30
51
  export function rephraseUnknownOption(raw) {
31
52
  // Commander emits: "error: unknown option '--foo'"
32
53
  const match = /unknown option\s+'--([^']+)'/.exec(raw);
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.2";
1
+ export declare const VERSION = "0.2.0";
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // AUTO-GENERATED by scripts/generate-version.mjs — do not edit by hand.
2
2
  // Run `npm run build` (or `npm run generate:version`) to regenerate.
3
- export const VERSION = '0.1.2';
3
+ export const VERSION = '0.2.0';
4
4
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testsprite/testsprite-cli",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Official TestSprite command-line interface",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",