@testsprite/testsprite-cli 0.1.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.
- package/README.md +16 -13
- package/dist/commands/agent.d.ts +9 -0
- package/dist/commands/agent.js +145 -79
- package/dist/commands/auth.d.ts +10 -0
- package/dist/commands/auth.js +30 -16
- package/dist/commands/init.d.ts +21 -1
- package/dist/commands/init.js +134 -61
- package/dist/commands/project.js +6 -1
- package/dist/commands/test.d.ts +26 -11
- package/dist/commands/test.js +226 -97
- package/dist/index.js +87 -19
- package/dist/lib/agent-targets.d.ts +102 -19
- package/dist/lib/agent-targets.js +156 -35
- package/dist/lib/bundle.d.ts +17 -1
- package/dist/lib/bundle.js +110 -53
- package/dist/lib/client-factory.d.ts +18 -0
- package/dist/lib/client-factory.js +42 -2
- package/dist/lib/credentials.d.ts +7 -0
- package/dist/lib/credentials.js +30 -0
- package/dist/lib/deprecate.d.ts +10 -0
- package/dist/lib/deprecate.js +13 -0
- package/dist/lib/dry-run/samples.js +26 -9
- package/dist/lib/errors.js +3 -3
- package/dist/lib/http.js +2 -1
- package/dist/lib/render-error.d.ts +13 -0
- package/dist/lib/render-error.js +27 -6
- package/dist/lib/skill-nudge.d.ts +73 -0
- package/dist/lib/skill-nudge.js +115 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +3 -1
- package/package.json +4 -1
- package/skills/testsprite-onboard.skill.md +162 -0
- package/{dist/assets/agent-skill → skills}/testsprite-verify.codex.md +4 -2
- package/{dist/assets/agent-skill → skills}/testsprite-verify.skill.md +19 -1
package/dist/lib/bundle.js
CHANGED
|
@@ -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
|
|
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 '
|
|
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,
|
|
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,
|
|
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,
|
|
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(
|
|
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
|
-
|
|
516
|
-
|
|
517
|
-
response
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
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(
|
|
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;
|
package/dist/lib/credentials.js
CHANGED
|
@@ -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))
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helper for the hidden, deprecated command aliases introduced by the
|
|
3
|
+
* setup consolidation (`init`/`auth configure`/`auth whoami`/`auth logout`).
|
|
4
|
+
*
|
|
5
|
+
* The aliases are hidden from `--help` (so a coding agent never sees the old
|
|
6
|
+
* names) but still work (so existing scripts and any agent trained on the old
|
|
7
|
+
* commands keep running). When invoked, they print this one-line notice to
|
|
8
|
+
* stderr — stdout stays clean so JSON pipelines are unaffected.
|
|
9
|
+
*/
|
|
10
|
+
export declare function emitDeprecationNotice(oldCmd: string, newCmd: string, stderr?: (line: string) => void): void;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helper for the hidden, deprecated command aliases introduced by the
|
|
3
|
+
* setup consolidation (`init`/`auth configure`/`auth whoami`/`auth logout`).
|
|
4
|
+
*
|
|
5
|
+
* The aliases are hidden from `--help` (so a coding agent never sees the old
|
|
6
|
+
* names) but still work (so existing scripts and any agent trained on the old
|
|
7
|
+
* commands keep running). When invoked, they print this one-line notice to
|
|
8
|
+
* stderr — stdout stays clean so JSON pipelines are unaffected.
|
|
9
|
+
*/
|
|
10
|
+
export function emitDeprecationNotice(oldCmd, newCmd, stderr = (line) => process.stderr.write(`${line}\n`)) {
|
|
11
|
+
stderr(`[deprecated] \`testsprite ${oldCmd}\` is deprecated — use \`testsprite ${newCmd}\`.`);
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=deprecate.js.map
|
|
@@ -106,16 +106,31 @@ const tests = [
|
|
|
106
106
|
];
|
|
107
107
|
const testCode = {
|
|
108
108
|
testId: SAMPLE_TEST_ID_FAILED,
|
|
109
|
-
language: '
|
|
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
|
-
|
|
113
|
-
|
|
114
|
-
'
|
|
115
|
-
'
|
|
116
|
-
'
|
|
117
|
-
|
|
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
|
-
|
|
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,
|
package/dist/lib/errors.js
CHANGED
|
@@ -174,8 +174,8 @@ export class ApiError extends CLIError {
|
|
|
174
174
|
return new ApiError({
|
|
175
175
|
code: 'AUTH_REQUIRED',
|
|
176
176
|
message: 'Authentication is required.',
|
|
177
|
-
nextAction: 'Run `testsprite
|
|
178
|
-
' or set TESTSPRITE_API_KEY and run `testsprite
|
|
177
|
+
nextAction: 'Run `testsprite setup` (interactive — prompts for your API key and installs the verification skill),' +
|
|
178
|
+
' or set TESTSPRITE_API_KEY and run `testsprite setup --from-env` for non-interactive flows.',
|
|
179
179
|
requestId,
|
|
180
180
|
details: {},
|
|
181
181
|
});
|
|
@@ -335,7 +335,7 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
|
|
|
335
335
|
? `${message} — endpoint not available on the current backend deployment.`
|
|
336
336
|
: message,
|
|
337
337
|
nextAction: isRouteMissing404
|
|
338
|
-
? 'Verify the CLI is targeting the right environment (check `testsprite auth
|
|
338
|
+
? 'Verify the CLI is targeting the right environment (check `testsprite auth status` for `env`), and confirm the backend has the corresponding M3.3 piece deployed.'
|
|
339
339
|
: '',
|
|
340
340
|
requestId: 'unknown',
|
|
341
341
|
details: { statusCode: obj.statusCode },
|
package/dist/lib/http.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { ApiError, RequestTimeoutError, TransportError } from './errors.js';
|
|
3
|
+
import { VERSION } from '../version.js';
|
|
3
4
|
/**
|
|
4
5
|
* Default per-request timeout (120s). Comfortably covers every metadata/read
|
|
5
6
|
* request and every <=25s long-poll request (`?waitSeconds` is capped at 25
|
|
@@ -423,7 +424,7 @@ export class HttpClient {
|
|
|
423
424
|
const headers = {
|
|
424
425
|
'x-request-id': requestId,
|
|
425
426
|
accept: 'application/json',
|
|
426
|
-
'user-agent':
|
|
427
|
+
'user-agent': `testsprite-cli/${VERSION}`,
|
|
427
428
|
};
|
|
428
429
|
// The CLI v1 facade authenticates via `x-api-key`.
|
|
429
430
|
// (securitySchemes.ApiKeyAuth). Sending only Authorization Bearer would be
|
|
@@ -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;
|
package/dist/lib/render-error.js
CHANGED
|
@@ -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);
|