@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.
- package/README.md +35 -26
- package/dist/commands/agent.d.ts +43 -0
- package/dist/commands/agent.js +200 -18
- package/dist/commands/auth.d.ts +5 -0
- package/dist/commands/auth.js +38 -27
- package/dist/commands/doctor.d.ts +49 -0
- package/dist/commands/doctor.js +233 -0
- package/dist/commands/init.d.ts +1 -1
- package/dist/commands/init.js +24 -14
- package/dist/commands/project.d.ts +75 -2
- package/dist/commands/project.js +326 -47
- package/dist/commands/test.d.ts +281 -2
- package/dist/commands/test.js +1658 -177
- package/dist/commands/usage.js +13 -12
- package/dist/index.js +71 -3
- package/dist/lib/agent-targets.d.ts +72 -6
- package/dist/lib/agent-targets.js +188 -6
- package/dist/lib/bundle.d.ts +34 -0
- package/dist/lib/bundle.js +63 -11
- package/dist/lib/client-factory.d.ts +31 -0
- package/dist/lib/client-factory.js +63 -0
- package/dist/lib/config.d.ts +2 -0
- package/dist/lib/config.js +11 -2
- package/dist/lib/credentials.js +10 -1
- package/dist/lib/dry-run/samples.d.ts +5 -0
- package/dist/lib/dry-run/samples.js +64 -0
- package/dist/lib/errors.d.ts +28 -1
- package/dist/lib/errors.js +40 -0
- package/dist/lib/failing-fe-resolver.d.ts +15 -0
- package/dist/lib/failing-fe-resolver.js +49 -1
- package/dist/lib/flaky.d.ts +80 -0
- package/dist/lib/flaky.js +76 -0
- package/dist/lib/http.d.ts +73 -1
- package/dist/lib/http.js +327 -135
- package/dist/lib/interrupt.d.ts +116 -0
- package/dist/lib/interrupt.js +182 -0
- package/dist/lib/junit-report.d.ts +58 -0
- package/dist/lib/junit-report.js +210 -0
- package/dist/lib/output.d.ts +16 -1
- package/dist/lib/output.js +24 -2
- package/dist/lib/pagination.d.ts +4 -3
- package/dist/lib/pagination.js +34 -6
- package/dist/lib/poll.d.ts +11 -0
- package/dist/lib/poll.js +70 -5
- package/dist/lib/prompt.js +52 -8
- package/dist/lib/proxy.d.ts +29 -0
- package/dist/lib/proxy.js +30 -0
- package/dist/lib/render-error.js +3 -1
- package/dist/lib/runs.types.d.ts +9 -0
- package/dist/lib/skill-nudge.d.ts +2 -2
- package/dist/lib/skill-nudge.js +13 -4
- package/dist/lib/target-url.js +8 -1
- package/dist/lib/ticker.d.ts +11 -1
- package/dist/lib/ticker.js +33 -1
- package/dist/lib/update-check.d.ts +67 -0
- package/dist/lib/update-check.js +246 -0
- package/dist/lib/v3-advisory.d.ts +13 -0
- package/dist/lib/v3-advisory.js +24 -0
- package/dist/lib/version-notice.d.ts +37 -0
- package/dist/lib/version-notice.js +87 -0
- package/dist/version-guard.d.ts +33 -0
- package/dist/version-guard.js +39 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -2
- package/skills/testsprite-onboard.skill.md +21 -0
- package/skills/testsprite-verify.codex.md +6 -0
- package/skills/testsprite-verify.skill.md +48 -4
package/dist/lib/bundle.js
CHANGED
|
@@ -169,6 +169,24 @@ export function applyFailedOnly(ctx) {
|
|
|
169
169
|
failure: { ...ctx.failure, evidence: filteredEvidence },
|
|
170
170
|
};
|
|
171
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Strip trailing path separators, tolerating both `/` and `\` since a
|
|
174
|
+
* native Windows `--out` value (typed or pasted from Explorer) commonly
|
|
175
|
+
* ends in a backslash. Preserves a bare drive root (`C:\`) — stripping
|
|
176
|
+
* its separator would turn it into `C:`, which Windows resolves as
|
|
177
|
+
* "current directory on drive C", not the drive root.
|
|
178
|
+
*/
|
|
179
|
+
function stripTrailingSeparators(rawPath) {
|
|
180
|
+
if (rawPath.length <= 1)
|
|
181
|
+
return rawPath;
|
|
182
|
+
let end = rawPath.length;
|
|
183
|
+
while (end > 1 && (rawPath[end - 1] === '/' || rawPath[end - 1] === '\\')) {
|
|
184
|
+
if (end === 3 && rawPath[1] === ':' && /[A-Za-z]/.test(rawPath[0]))
|
|
185
|
+
break;
|
|
186
|
+
end--;
|
|
187
|
+
}
|
|
188
|
+
return rawPath.slice(0, end);
|
|
189
|
+
}
|
|
172
190
|
/**
|
|
173
191
|
* Resolve the user-supplied `--out` path into an absolute directory.
|
|
174
192
|
* Empty strings are rejected with `VALIDATION_ERROR` for consistency
|
|
@@ -188,7 +206,7 @@ export function resolveBundleDir(rawPath) {
|
|
|
188
206
|
},
|
|
189
207
|
});
|
|
190
208
|
}
|
|
191
|
-
const trimmed =
|
|
209
|
+
const trimmed = stripTrailingSeparators(rawPath);
|
|
192
210
|
return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
|
|
193
211
|
}
|
|
194
212
|
/**
|
|
@@ -371,28 +389,52 @@ async function freshTmpDir(dir) {
|
|
|
371
389
|
* caught reading the dir during it sees no meta and refuses to consume
|
|
372
390
|
* (per §7.3). That's what we want.
|
|
373
391
|
*/
|
|
392
|
+
/**
|
|
393
|
+
* Whether a top-level directory entry belongs to the bundle format —
|
|
394
|
+
* i.e. something a prior `writeBundle` could have produced and this
|
|
395
|
+
* commit is therefore allowed to clean up. `code.<ext>` is matched by
|
|
396
|
+
* pattern (not the current run's extension) so a stale `code.py` is
|
|
397
|
+
* still swept when the new bundle writes `code.ts`. Everything else in
|
|
398
|
+
* the directory is the user's and must never be deleted (`--out` can
|
|
399
|
+
* point at a pre-existing, populated directory).
|
|
400
|
+
*/
|
|
401
|
+
export function isBundleOwnedEntry(entry) {
|
|
402
|
+
if (entry === 'result.json' ||
|
|
403
|
+
entry === 'failure.json' ||
|
|
404
|
+
entry === 'video.mp4' ||
|
|
405
|
+
entry === 'meta.json' ||
|
|
406
|
+
entry === 'steps' ||
|
|
407
|
+
entry === '.tmp' ||
|
|
408
|
+
entry === '.partial') {
|
|
409
|
+
return true;
|
|
410
|
+
}
|
|
411
|
+
return /^code\.[A-Za-z0-9]+$/.test(entry);
|
|
412
|
+
}
|
|
374
413
|
async function commitBundle(tmpDir, dir, files) {
|
|
375
414
|
// (1) Remove the prior bundle's completion signal FIRST.
|
|
376
415
|
await unlink(join(dir, 'meta.json')).catch(() => undefined);
|
|
377
416
|
// (2) Sweep stale top-level files that the new bundle won't write.
|
|
378
417
|
// If the prior run wrote `video.mp4` and the new run has no video,
|
|
379
|
-
// an in-place rename leaves the old video lingering.
|
|
380
|
-
//
|
|
381
|
-
//
|
|
418
|
+
// an in-place rename leaves the old video lingering. Only entries the
|
|
419
|
+
// bundle format OWNS are candidates: `--out` may point at a directory
|
|
420
|
+
// that also holds the user's unrelated files, and those must survive
|
|
421
|
+
// the commit (deleting them would be silent data loss).
|
|
382
422
|
const topLevel = files.filter(f => !f.startsWith('steps/'));
|
|
383
423
|
const newTopLevelSet = new Set(topLevel);
|
|
384
424
|
newTopLevelSet.add('meta.json'); // about to land last, do not delete
|
|
385
425
|
const existing = await readdir(dir).catch(() => []);
|
|
386
426
|
for (const entry of existing) {
|
|
387
427
|
// Preserve the writer's own scratch dir + the .partial marker
|
|
388
|
-
// (we'll re-evaluate .partial at the end of commit).
|
|
389
|
-
// not-listed in the new bundle is stale.
|
|
428
|
+
// (we'll re-evaluate .partial at the end of commit). Any other
|
|
429
|
+
// bundle-owned entry not-listed in the new bundle is stale.
|
|
390
430
|
if (entry === '.tmp' || entry === '.partial')
|
|
391
431
|
continue;
|
|
392
432
|
if (newTopLevelSet.has(entry))
|
|
393
433
|
continue;
|
|
394
434
|
if (entry === 'steps')
|
|
395
435
|
continue; // handled below
|
|
436
|
+
if (!isBundleOwnedEntry(entry))
|
|
437
|
+
continue; // foreign file — never touch
|
|
396
438
|
await rm(join(dir, entry), { recursive: true, force: true });
|
|
397
439
|
}
|
|
398
440
|
// (3) Replace `<dir>/steps/` with `<tmp>/steps/`.
|
|
@@ -545,10 +587,11 @@ function sidecarExtension(kind) {
|
|
|
545
587
|
*/
|
|
546
588
|
export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
547
589
|
const sleepFn = deps?.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
|
|
590
|
+
const artifactUrl = redactArtifactUrlForDetails(url);
|
|
548
591
|
for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
|
|
549
592
|
let response;
|
|
550
593
|
try {
|
|
551
|
-
response = await fetchImpl(url);
|
|
594
|
+
response = await fetchImpl(url, { redirect: 'error' });
|
|
552
595
|
}
|
|
553
596
|
catch (err) {
|
|
554
597
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -556,7 +599,7 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
|
556
599
|
await sleepFn(STREAM_URL_RETRY_DELAY_MS);
|
|
557
600
|
continue;
|
|
558
601
|
}
|
|
559
|
-
throw new TransportError(`Failed to download presigned URL ${
|
|
602
|
+
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
560
603
|
}
|
|
561
604
|
if (!response.ok) {
|
|
562
605
|
// Non-2xx: the URL itself is bad (expired, unauthorized, not found).
|
|
@@ -567,7 +610,7 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
|
567
610
|
message: `Failed to download presigned URL (HTTP ${response.status}).`,
|
|
568
611
|
nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
|
|
569
612
|
requestId: 'local',
|
|
570
|
-
details: { status: response.status,
|
|
613
|
+
details: { status: response.status, artifactUrl },
|
|
571
614
|
},
|
|
572
615
|
});
|
|
573
616
|
}
|
|
@@ -588,7 +631,7 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
|
588
631
|
await sleepFn(STREAM_URL_RETRY_DELAY_MS);
|
|
589
632
|
continue;
|
|
590
633
|
}
|
|
591
|
-
throw new TransportError(`Failed to download presigned URL ${
|
|
634
|
+
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
592
635
|
}
|
|
593
636
|
}
|
|
594
637
|
await mkdir(dirname(filePath), { recursive: true });
|
|
@@ -611,10 +654,19 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
|
611
654
|
await sleepFn(STREAM_URL_RETRY_DELAY_MS);
|
|
612
655
|
continue;
|
|
613
656
|
}
|
|
614
|
-
throw new TransportError(`Failed mid-download of ${
|
|
657
|
+
throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
|
|
615
658
|
}
|
|
616
659
|
}
|
|
617
660
|
}
|
|
661
|
+
function redactArtifactUrlForDetails(url) {
|
|
662
|
+
try {
|
|
663
|
+
const parsed = new URL(url);
|
|
664
|
+
return `${parsed.origin}${parsed.pathname}`;
|
|
665
|
+
}
|
|
666
|
+
catch {
|
|
667
|
+
return '<invalid-url>';
|
|
668
|
+
}
|
|
669
|
+
}
|
|
618
670
|
function isPresignedUrl(value) {
|
|
619
671
|
return value.startsWith('https://');
|
|
620
672
|
}
|
|
@@ -41,6 +41,12 @@ export interface ClientFactoryDeps {
|
|
|
41
41
|
credentialsPath?: string;
|
|
42
42
|
fetchImpl?: FetchImpl;
|
|
43
43
|
stderr?: (line: string) => void;
|
|
44
|
+
/**
|
|
45
|
+
* Shutdown signal composed into every outgoing fetch (DEV-331 piece 1).
|
|
46
|
+
* Defaults to `globalShutdown.signal` so an armed SIGINT/SIGTERM aborts an
|
|
47
|
+
* in-flight request; tests inject their own controller's signal.
|
|
48
|
+
*/
|
|
49
|
+
shutdownSignal?: AbortSignal;
|
|
44
50
|
}
|
|
45
51
|
/**
|
|
46
52
|
* The fake API key used in dry-run. Never sent — the dry-run fetch
|
|
@@ -87,4 +93,29 @@ export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'reque
|
|
|
87
93
|
* assuming the flag.
|
|
88
94
|
*/
|
|
89
95
|
export declare function assertValidEndpointUrl(rawUrl: string): void;
|
|
96
|
+
export declare function assertValidApiKeyHeaderValue(apiKey: string): void;
|
|
97
|
+
/**
|
|
98
|
+
* Parse the `--request-timeout <seconds>` flag value into milliseconds.
|
|
99
|
+
*
|
|
100
|
+
* Returns `undefined` when the flag was omitted (the factory then falls back to
|
|
101
|
+
* the `TESTSPRITE_REQUEST_TIMEOUT_MS` env var, else the 120s default).
|
|
102
|
+
*
|
|
103
|
+
* A supplied-but-invalid value (non-numeric, zero, or negative) throws a typed
|
|
104
|
+
* VALIDATION_ERROR (exit 5) rather than being silently dropped. An explicit
|
|
105
|
+
* `--request-timeout 30s` typo previously resolved to `undefined` and the
|
|
106
|
+
* command ran with the default 120s deadline — the operator believed they had
|
|
107
|
+
* set a timeout but had not, with no signal. Failing loudly here is consistent
|
|
108
|
+
* with every other validated flag (`--page-size`, `--output`, `--type`).
|
|
109
|
+
*
|
|
110
|
+
* Out-of-range but positive values are intentionally NOT rejected — they flow
|
|
111
|
+
* through to {@link resolveRequestTimeoutMs}, which clamps to
|
|
112
|
+
* `[REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS]`. The env-var path stays
|
|
113
|
+
* lenient by design (a stray global env var should not hard-fail every
|
|
114
|
+
* command); only the explicit per-invocation flag is strict.
|
|
115
|
+
*
|
|
116
|
+
* This single definition replaces five byte-identical copies that previously
|
|
117
|
+
* lived in `auth`, `project`, `usage`, `init`, and `test` — drift between them
|
|
118
|
+
* would have silently changed timeout behaviour depending on the command.
|
|
119
|
+
*/
|
|
120
|
+
export declare function parseRequestTimeoutFlag(raw: string | undefined): number | undefined;
|
|
90
121
|
export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClient;
|
|
@@ -18,7 +18,10 @@ import { defaultCredentialsPath } from './credentials.js';
|
|
|
18
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
|
+
import { globalShutdown } from './interrupt.js';
|
|
21
22
|
import { createDryRunFetch } from './dry-run/fetch.js';
|
|
23
|
+
import { noteServerVersion } from './version-notice.js';
|
|
24
|
+
import { VERSION } from '../version.js';
|
|
22
25
|
/**
|
|
23
26
|
* The fake API key used in dry-run. Never sent — the dry-run fetch
|
|
24
27
|
* impl ignores headers and returns a canned sample. Documented in the
|
|
@@ -109,6 +112,52 @@ export function assertValidEndpointUrl(rawUrl) {
|
|
|
109
112
|
`(e.g. https://api.testsprite.com)`, undefined, 'field');
|
|
110
113
|
}
|
|
111
114
|
}
|
|
115
|
+
export function assertValidApiKeyHeaderValue(apiKey) {
|
|
116
|
+
const reason = 'must be a non-empty HTTP header value; paste the raw key without smart punctuation, emoji, or line breaks';
|
|
117
|
+
if (apiKey.trim().length === 0) {
|
|
118
|
+
throw localValidationError('api-key', reason, undefined, 'field');
|
|
119
|
+
}
|
|
120
|
+
for (let i = 0; i < apiKey.length; i += 1) {
|
|
121
|
+
const code = apiKey.charCodeAt(i);
|
|
122
|
+
if (code < 0x20 || code === 0x7f || code > 0xff) {
|
|
123
|
+
throw localValidationError('api-key', reason, undefined, 'field');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Parse the `--request-timeout <seconds>` flag value into milliseconds.
|
|
129
|
+
*
|
|
130
|
+
* Returns `undefined` when the flag was omitted (the factory then falls back to
|
|
131
|
+
* the `TESTSPRITE_REQUEST_TIMEOUT_MS` env var, else the 120s default).
|
|
132
|
+
*
|
|
133
|
+
* A supplied-but-invalid value (non-numeric, zero, or negative) throws a typed
|
|
134
|
+
* VALIDATION_ERROR (exit 5) rather than being silently dropped. An explicit
|
|
135
|
+
* `--request-timeout 30s` typo previously resolved to `undefined` and the
|
|
136
|
+
* command ran with the default 120s deadline — the operator believed they had
|
|
137
|
+
* set a timeout but had not, with no signal. Failing loudly here is consistent
|
|
138
|
+
* with every other validated flag (`--page-size`, `--output`, `--type`).
|
|
139
|
+
*
|
|
140
|
+
* Out-of-range but positive values are intentionally NOT rejected — they flow
|
|
141
|
+
* through to {@link resolveRequestTimeoutMs}, which clamps to
|
|
142
|
+
* `[REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS]`. The env-var path stays
|
|
143
|
+
* lenient by design (a stray global env var should not hard-fail every
|
|
144
|
+
* command); only the explicit per-invocation flag is strict.
|
|
145
|
+
*
|
|
146
|
+
* This single definition replaces five byte-identical copies that previously
|
|
147
|
+
* lived in `auth`, `project`, `usage`, `init`, and `test` — drift between them
|
|
148
|
+
* would have silently changed timeout behaviour depending on the command.
|
|
149
|
+
*/
|
|
150
|
+
export function parseRequestTimeoutFlag(raw) {
|
|
151
|
+
if (raw === undefined)
|
|
152
|
+
return undefined;
|
|
153
|
+
const n = Number(raw);
|
|
154
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
155
|
+
// Surface the offending value in the message (same as assertValidEndpointUrl)
|
|
156
|
+
// so the operator sees exactly what they typed.
|
|
157
|
+
throw localValidationError('request-timeout', `"${raw}" is not valid — must be a positive number of seconds`);
|
|
158
|
+
}
|
|
159
|
+
return Math.round(n * 1000); // seconds → milliseconds
|
|
160
|
+
}
|
|
112
161
|
export function makeHttpClient(opts, deps = {}) {
|
|
113
162
|
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
114
163
|
const env = deps.env ?? process.env;
|
|
@@ -127,6 +176,7 @@ export function makeHttpClient(opts, deps = {}) {
|
|
|
127
176
|
onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
|
|
128
177
|
onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
|
|
129
178
|
requestTimeoutMs,
|
|
179
|
+
shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
|
|
130
180
|
});
|
|
131
181
|
}
|
|
132
182
|
const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
|
|
@@ -142,13 +192,26 @@ export function makeHttpClient(opts, deps = {}) {
|
|
|
142
192
|
assertValidEndpointUrl(config.apiUrl);
|
|
143
193
|
if (!config.apiKey)
|
|
144
194
|
throw ApiError.authRequired();
|
|
195
|
+
assertValidApiKeyHeaderValue(config.apiKey);
|
|
145
196
|
return new HttpClient({
|
|
146
197
|
baseUrl: facadeBaseUrl(config.apiUrl),
|
|
147
198
|
apiKey: config.apiKey,
|
|
148
199
|
fetchImpl: deps.fetchImpl,
|
|
149
200
|
onDebug: opts.debug ? (event) => stderr(formatDebug(event)) : undefined,
|
|
150
201
|
onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
|
|
202
|
+
// Warn once if the backend advertises a minimum supported version above
|
|
203
|
+
// this binary's. Gating (opt-out env, TTY, output mode, dry-run) lives in
|
|
204
|
+
// noteServerVersion; the client just forwards the observed headers.
|
|
205
|
+
onServerVersion: info => noteServerVersion(info, {
|
|
206
|
+
currentVersion: VERSION,
|
|
207
|
+
env,
|
|
208
|
+
isTTY: process.stderr.isTTY === true,
|
|
209
|
+
outputMode: opts.output,
|
|
210
|
+
dryRun: opts.dryRun,
|
|
211
|
+
stderr,
|
|
212
|
+
}),
|
|
151
213
|
requestTimeoutMs,
|
|
214
|
+
shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
|
|
152
215
|
});
|
|
153
216
|
}
|
|
154
217
|
function formatDebug(event) {
|
package/dist/lib/config.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export interface LoadConfigOptions {
|
|
|
9
9
|
env?: NodeJS.ProcessEnv;
|
|
10
10
|
credentialsPath?: string;
|
|
11
11
|
}
|
|
12
|
+
/** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
|
|
13
|
+
export declare function normalizeEnvVar(value: string | undefined): string | undefined;
|
|
12
14
|
export declare function defaultConfigPath(): string;
|
|
13
15
|
/**
|
|
14
16
|
* Resolves the active profile name and its (apiUrl, apiKey) pair.
|
package/dist/lib/config.js
CHANGED
|
@@ -2,6 +2,10 @@ import { homedir } from 'node:os';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { DEFAULT_PROFILE, defaultCredentialsPath, readProfile } from './credentials.js';
|
|
4
4
|
const DEFAULT_API_URL = 'https://api.testsprite.com';
|
|
5
|
+
/** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
|
|
6
|
+
export function normalizeEnvVar(value) {
|
|
7
|
+
return value?.trim() || undefined;
|
|
8
|
+
}
|
|
5
9
|
export function defaultConfigPath() {
|
|
6
10
|
return join(homedir(), '.testsprite', 'config');
|
|
7
11
|
}
|
|
@@ -21,9 +25,14 @@ export function loadConfig(options = {}) {
|
|
|
21
25
|
const profile = options.profile ?? env.TESTSPRITE_PROFILE ?? DEFAULT_PROFILE;
|
|
22
26
|
const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
|
|
23
27
|
const fileEntry = readProfile(profile, { path: credentialsPath });
|
|
28
|
+
// Empty / whitespace-only env vars are treated as unset so they do not
|
|
29
|
+
// short-circuit the `??` chain (e.g. `export TESTSPRITE_API_URL=` in a shell
|
|
30
|
+
// profile). Matches the normalization in auth configure and init/setup.
|
|
31
|
+
const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
|
|
32
|
+
const envApiKey = normalizeEnvVar(env.TESTSPRITE_API_KEY);
|
|
24
33
|
return {
|
|
25
|
-
apiUrl: options.endpointUrl ??
|
|
26
|
-
apiKey:
|
|
34
|
+
apiUrl: options.endpointUrl ?? envApiUrl ?? fileEntry?.apiUrl ?? DEFAULT_API_URL,
|
|
35
|
+
apiKey: envApiKey ?? fileEntry?.apiKey,
|
|
27
36
|
profile,
|
|
28
37
|
};
|
|
29
38
|
}
|
package/dist/lib/credentials.js
CHANGED
|
@@ -93,7 +93,16 @@ export function serializeCredentials(file) {
|
|
|
93
93
|
const value = entry[field];
|
|
94
94
|
if (value === undefined || value === '')
|
|
95
95
|
continue;
|
|
96
|
-
|
|
96
|
+
// Guard against INI injection: a value containing newline characters
|
|
97
|
+
// would be serialized across multiple lines, allowing an attacker to
|
|
98
|
+
// inject arbitrary key-value pairs (or new section headers) into the
|
|
99
|
+
// credentials file. A valid API key or URL never contains \n or \r.
|
|
100
|
+
// Strip them so a compromised env var or MITM'd backend response
|
|
101
|
+
// cannot override the stored api_key on subsequent reads.
|
|
102
|
+
const sanitized = value.replace(/[\r\n]/g, '');
|
|
103
|
+
if (sanitized === '')
|
|
104
|
+
continue;
|
|
105
|
+
lines.push(`${FIELD_TO_FILE_KEY[field]} = ${sanitized}`);
|
|
97
106
|
}
|
|
98
107
|
lines.push('');
|
|
99
108
|
}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
export declare const SAMPLE_RUN_ID = "run_abc";
|
|
2
2
|
export declare const SAMPLE_DRY_RUN_REQUEST_ID = "req_dry-run";
|
|
3
|
+
/**
|
|
4
|
+
* Canned JUnit XML for batch `--wait --report junit --dry-run`. Mirrors the
|
|
5
|
+
* fresh batch-run sample ids so agents can learn the sidecar shape offline.
|
|
6
|
+
*/
|
|
7
|
+
export declare function sampleJUnitReportXml(projectId?: string, reportSuiteName?: string): string;
|
|
3
8
|
/**
|
|
4
9
|
* Dry-run sample lookup keyed by OpenAPI operationId. Order matters in
|
|
5
10
|
* {@link findSample}: more specific patterns must precede their generic
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { buildJUnitReport } from '../junit-report.js';
|
|
1
2
|
const SAMPLE_USER_ID = '11111111-1111-4111-8111-111111111111';
|
|
2
3
|
const SAMPLE_KEY_ID = 'key_dryrun_2026';
|
|
3
4
|
const SAMPLE_PROJECT_ID = 'project_b3c91efa';
|
|
@@ -25,11 +26,39 @@ const SAMPLE_SNAPSHOT_ID = 'snap_2026_05_05_b2f9a1c8';
|
|
|
25
26
|
const SAMPLE_TARGET_URL = 'https://staging.example.com/checkout';
|
|
26
27
|
const SAMPLE_REQUEST_ID = 'req_dry-run';
|
|
27
28
|
export const SAMPLE_DRY_RUN_REQUEST_ID = SAMPLE_REQUEST_ID;
|
|
29
|
+
/**
|
|
30
|
+
* Canned JUnit XML for batch `--wait --report junit --dry-run`. Mirrors the
|
|
31
|
+
* fresh batch-run sample ids so agents can learn the sidecar shape offline.
|
|
32
|
+
*/
|
|
33
|
+
export function sampleJUnitReportXml(projectId = SAMPLE_PROJECT_ID, reportSuiteName) {
|
|
34
|
+
return buildJUnitReport({
|
|
35
|
+
suiteName: reportSuiteName ?? `testsprite:${projectId}`,
|
|
36
|
+
classname: projectId,
|
|
37
|
+
results: [
|
|
38
|
+
{
|
|
39
|
+
testId: SAMPLE_TEST_ID_FRESH_1,
|
|
40
|
+
runId: SAMPLE_BATCH_FRESH_RUN_ID_1,
|
|
41
|
+
status: 'passed',
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
testId: SAMPLE_TEST_ID_FRESH_2,
|
|
45
|
+
runId: SAMPLE_BATCH_FRESH_RUN_ID_2,
|
|
46
|
+
status: 'failed',
|
|
47
|
+
error: {
|
|
48
|
+
code: 'ASSERTION',
|
|
49
|
+
message: 'Expected checkout heading to be visible',
|
|
50
|
+
exitCode: 1,
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
],
|
|
54
|
+
});
|
|
55
|
+
}
|
|
28
56
|
const me = {
|
|
29
57
|
userId: SAMPLE_USER_ID,
|
|
30
58
|
keyId: SAMPLE_KEY_ID,
|
|
31
59
|
scopes: ['read:projects', 'read:tests', 'write:tests', 'run:tests'],
|
|
32
60
|
env: 'development',
|
|
61
|
+
v3Enabled: true,
|
|
33
62
|
};
|
|
34
63
|
const projects = [
|
|
35
64
|
{
|
|
@@ -276,6 +305,11 @@ const ENTRIES = [
|
|
|
276
305
|
updatedFields: ['name'],
|
|
277
306
|
updatedAt: '2026-05-16T00:00:00.000Z',
|
|
278
307
|
}),
|
|
308
|
+
// DELETE /projects/{id} (cascade delete project + tests + fixtures).
|
|
309
|
+
entry('deleteProject', 'DELETE', '/projects/{projectId}', {
|
|
310
|
+
projectId: SAMPLE_PROJECT_ID,
|
|
311
|
+
deletedAt: '2026-05-16T00:00:00.000Z',
|
|
312
|
+
}),
|
|
279
313
|
entry('listTests', 'GET', '/tests', pageOf(tests)),
|
|
280
314
|
entry('getTestCode', 'GET', '/tests/{testId}/code', testCode),
|
|
281
315
|
entry('listTestSteps', 'GET', '/tests/{testId}/steps', pageOf(testSteps)),
|
|
@@ -626,6 +660,36 @@ const ENTRIES = [
|
|
|
626
660
|
},
|
|
627
661
|
],
|
|
628
662
|
}),
|
|
663
|
+
// DEV-331 piece 3 — POST /runs/{runId}/cancel. Method-guarded in
|
|
664
|
+
// `findSample` (POST vs `getRun`'s GET), so this can't be shadowed by the
|
|
665
|
+
// broader `/runs/{runId}` pattern above despite sharing its path prefix.
|
|
666
|
+
// `alreadyCancelled: false` — a fresh cancel is the more instructive shape
|
|
667
|
+
// for a dry-run learner than the idempotent no-op.
|
|
668
|
+
entry('cancelRun', 'POST', '/runs/{runId}/cancel', {
|
|
669
|
+
runId: SAMPLE_RUN_ID,
|
|
670
|
+
testId: SAMPLE_TEST_ID_PASSED,
|
|
671
|
+
projectId: SAMPLE_PROJECT_ID,
|
|
672
|
+
userId: SAMPLE_USER_ID,
|
|
673
|
+
status: 'cancelled',
|
|
674
|
+
source: 'cli',
|
|
675
|
+
createdAt: '2026-05-15T19:32:00.000Z',
|
|
676
|
+
startedAt: '2026-05-15T19:32:05.000Z',
|
|
677
|
+
finishedAt: '2026-05-15T19:33:12.000Z',
|
|
678
|
+
codeVersion: 'v1',
|
|
679
|
+
targetUrl: SAMPLE_TARGET_URL,
|
|
680
|
+
createdFrom: null,
|
|
681
|
+
failedStepIndex: null,
|
|
682
|
+
failureKind: null,
|
|
683
|
+
error: null,
|
|
684
|
+
videoUrl: null,
|
|
685
|
+
stepSummary: {
|
|
686
|
+
total: 8,
|
|
687
|
+
completed: 3,
|
|
688
|
+
passedCount: 3,
|
|
689
|
+
failedCount: 0,
|
|
690
|
+
},
|
|
691
|
+
alreadyCancelled: false,
|
|
692
|
+
}),
|
|
629
693
|
];
|
|
630
694
|
function entry(operationId, method, pathTemplate, body) {
|
|
631
695
|
// Convert `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/
|
package/dist/lib/errors.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Error codes shared with the backend facade and the MCP plugin.
|
|
3
3
|
* Must stay in sync across all three.
|
|
4
4
|
*/
|
|
5
|
-
export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "UNSUPPORTED", "INTERNAL", "UNAVAILABLE"];
|
|
5
|
+
export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "UNSUPPORTED", "CLIENT_TOO_OLD", "INTERNAL", "UNAVAILABLE"];
|
|
6
6
|
export type ErrorCode = (typeof ERROR_CODES)[number];
|
|
7
7
|
export declare function isErrorCode(value: unknown): value is ErrorCode;
|
|
8
8
|
/**
|
|
@@ -15,6 +15,33 @@ export declare class CLIError extends Error {
|
|
|
15
15
|
readonly exitCode: number;
|
|
16
16
|
constructor(message: string, exitCode?: number);
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* Termination signals with graceful handling, mapped to their conventional
|
|
20
|
+
* `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
|
|
21
|
+
* SIGINT=2, SIGTERM=15). Lives here (not interrupt.ts) so `InterruptError`
|
|
22
|
+
* needs no import cycle; `interrupt.ts` re-exports for back-compat.
|
|
23
|
+
*/
|
|
24
|
+
export declare const TERMINATION_EXIT_CODES: {
|
|
25
|
+
readonly SIGINT: 130;
|
|
26
|
+
readonly SIGTERM: 143;
|
|
27
|
+
readonly SIGHUP: 129;
|
|
28
|
+
};
|
|
29
|
+
export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
|
|
30
|
+
/**
|
|
31
|
+
* User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
|
|
32
|
+
* graceful-detach scope (the `--wait` polling window) was armed — see
|
|
33
|
+
* `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
|
|
34
|
+
* honest partial envelope + re-attach hint, then rethrow to `index.ts`.
|
|
35
|
+
*
|
|
36
|
+
* Deliberately NOT in `ERROR_CODES` — on a signal the CLI
|
|
37
|
+
* exits 130/143 without consulting the error catalog. The JSON-mode stderr
|
|
38
|
+
* envelope uses the out-of-catalog code `"INTERRUPTED"`. Same client-local
|
|
39
|
+
* synthetic category as `RequestTimeoutError`.
|
|
40
|
+
*/
|
|
41
|
+
export declare class InterruptError extends CLIError {
|
|
42
|
+
readonly signal: TerminationSignal;
|
|
43
|
+
constructor(signal: TerminationSignal);
|
|
44
|
+
}
|
|
18
45
|
export declare class NotImplementedError extends CLIError {
|
|
19
46
|
constructor(commandPath: string);
|
|
20
47
|
}
|
package/dist/lib/errors.js
CHANGED
|
@@ -44,6 +44,12 @@ export const ERROR_CODES = [
|
|
|
44
44
|
// so the CLI can drop the client-side detection heuristic.
|
|
45
45
|
'FEATURE_GATED',
|
|
46
46
|
'UNSUPPORTED',
|
|
47
|
+
// The running CLI is older than the backend's minimum supported version.
|
|
48
|
+
// Backend emits this as HTTP 426 when version enforcement is enabled. Exit
|
|
49
|
+
// 14, non-retriable — a too-old client cannot self-heal by retrying; the
|
|
50
|
+
// user must upgrade. `nextAction` carries the upgrade instruction and
|
|
51
|
+
// `details` echoes { minVersion, latestVersion, yourVersion }.
|
|
52
|
+
'CLIENT_TOO_OLD',
|
|
47
53
|
'INTERNAL',
|
|
48
54
|
'UNAVAILABLE',
|
|
49
55
|
];
|
|
@@ -72,6 +78,8 @@ export function exitCodeFor(code) {
|
|
|
72
78
|
return 6;
|
|
73
79
|
case 'UNSUPPORTED':
|
|
74
80
|
return 7;
|
|
81
|
+
case 'CLIENT_TOO_OLD':
|
|
82
|
+
return 14;
|
|
75
83
|
case 'UNAVAILABLE':
|
|
76
84
|
return 10;
|
|
77
85
|
case 'RATE_LIMITED':
|
|
@@ -92,6 +100,36 @@ export class CLIError extends Error {
|
|
|
92
100
|
this.exitCode = exitCode;
|
|
93
101
|
}
|
|
94
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Termination signals with graceful handling, mapped to their conventional
|
|
105
|
+
* `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
|
|
106
|
+
* SIGINT=2, SIGTERM=15). Lives here (not interrupt.ts) so `InterruptError`
|
|
107
|
+
* needs no import cycle; `interrupt.ts` re-exports for back-compat.
|
|
108
|
+
*/
|
|
109
|
+
export const TERMINATION_EXIT_CODES = {
|
|
110
|
+
SIGINT: 130, // 128 + 2
|
|
111
|
+
SIGTERM: 143, // 128 + 15
|
|
112
|
+
SIGHUP: 129, // 128 + 1
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
|
|
116
|
+
* graceful-detach scope (the `--wait` polling window) was armed — see
|
|
117
|
+
* `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
|
|
118
|
+
* honest partial envelope + re-attach hint, then rethrow to `index.ts`.
|
|
119
|
+
*
|
|
120
|
+
* Deliberately NOT in `ERROR_CODES` — on a signal the CLI
|
|
121
|
+
* exits 130/143 without consulting the error catalog. The JSON-mode stderr
|
|
122
|
+
* envelope uses the out-of-catalog code `"INTERRUPTED"`. Same client-local
|
|
123
|
+
* synthetic category as `RequestTimeoutError`.
|
|
124
|
+
*/
|
|
125
|
+
export class InterruptError extends CLIError {
|
|
126
|
+
signal;
|
|
127
|
+
constructor(signal) {
|
|
128
|
+
super(`Interrupted by ${signal}.`, TERMINATION_EXIT_CODES[signal]);
|
|
129
|
+
this.name = 'InterruptError';
|
|
130
|
+
this.signal = signal;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
95
133
|
export class NotImplementedError extends CLIError {
|
|
96
134
|
constructor(commandPath) {
|
|
97
135
|
super(`Command not yet implemented: ${commandPath}`, 2);
|
|
@@ -270,6 +308,8 @@ function codeFromHttpStatus(status) {
|
|
|
270
308
|
return 'PRECONDITION_FAILED';
|
|
271
309
|
case 413:
|
|
272
310
|
return 'PAYLOAD_TOO_LARGE';
|
|
311
|
+
case 426:
|
|
312
|
+
return 'CLIENT_TOO_OLD';
|
|
273
313
|
case 429:
|
|
274
314
|
return 'RATE_LIMITED';
|
|
275
315
|
case 501:
|
|
@@ -43,6 +43,21 @@ export interface ResolverOptions {
|
|
|
43
43
|
* Each page uses pageSize=50, so 5 pages = 250 tests scanned.
|
|
44
44
|
*/
|
|
45
45
|
maxPages?: number;
|
|
46
|
+
/**
|
|
47
|
+
* DEV-393: the operator's pinned `failingFrontendTestId` (the static value
|
|
48
|
+
* from fixtures.local.json). "Freshest failed" alone is fragile in a shared
|
|
49
|
+
* project: any OTHER FE test that fails more recently than a dedicated,
|
|
50
|
+
* permanently-red fixture silently steals the slot (live-reproduced
|
|
51
|
+
* 2026-07-16 — a `passingFrontendTestId` fresh-run flip immediately
|
|
52
|
+
* outranked the dedicated fixture on `updatedAt`). When set, the pinned id
|
|
53
|
+
* is probed directly first (one GET /tests/{id} — immune to the maxPages
|
|
54
|
+
* list-scan cap); if it is currently `status:failed` it wins outright,
|
|
55
|
+
* regardless of timestamp. If the probe errors, the list scan below still
|
|
56
|
+
* prefers the pinned id when it appears among the candidates. Falls through
|
|
57
|
+
* to the existing freshest-wins behavior when unset or no longer failing —
|
|
58
|
+
* fully backward compatible.
|
|
59
|
+
*/
|
|
60
|
+
preferredId?: string;
|
|
46
61
|
}
|
|
47
62
|
export interface ResolverResult {
|
|
48
63
|
/** The resolved failing frontend test id, or null if none found. */
|
|
@@ -24,8 +24,44 @@
|
|
|
24
24
|
* when no Failed test exists — never throws.
|
|
25
25
|
*/
|
|
26
26
|
export async function resolveFailingFrontendTestId(opts) {
|
|
27
|
-
const { baseUrl, apiKey, projectId, maxPages = 5 } = opts;
|
|
27
|
+
const { baseUrl, apiKey, projectId, maxPages = 5, preferredId } = opts;
|
|
28
28
|
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
29
|
+
// DEV-393 (codex F3): probe the pinned fixture directly first, so the
|
|
30
|
+
// preference cannot be defeated by the maxPages list-scan cap (a pinned
|
|
31
|
+
// fixture beyond page `maxPages` would otherwise silently lose the slot to
|
|
32
|
+
// an incidental fresher failure). Any probe error or non-failed status
|
|
33
|
+
// falls through to the list scan; the in-candidates preference there
|
|
34
|
+
// remains as a second chance after a transient probe failure.
|
|
35
|
+
if (preferredId) {
|
|
36
|
+
try {
|
|
37
|
+
const resp = await fetchImpl(`${baseUrl}/tests/${encodeURIComponent(preferredId)}`, {
|
|
38
|
+
headers: {
|
|
39
|
+
'x-api-key': apiKey,
|
|
40
|
+
'x-request-id': `dev-e2e-resolver-preferred-${Date.now()}`,
|
|
41
|
+
accept: 'application/json',
|
|
42
|
+
},
|
|
43
|
+
signal: AbortSignal.timeout(10_000),
|
|
44
|
+
});
|
|
45
|
+
if (resp.ok) {
|
|
46
|
+
const test = (await resp.json());
|
|
47
|
+
// The probe must honor the resolver's project scope (codex round 2):
|
|
48
|
+
// the list path filters by projectId server-side, so a pin that
|
|
49
|
+
// points at a failed FE test in a DIFFERENT project must not win
|
|
50
|
+
// here either. A response without a matching projectId (absent or
|
|
51
|
+
// mismatched) falls through to the project-scoped list scan.
|
|
52
|
+
if (test.type === 'frontend' && test.status === 'failed' && test.projectId === projectId) {
|
|
53
|
+
return {
|
|
54
|
+
testId: preferredId,
|
|
55
|
+
reason: `Preferred pinned failingFrontendTestId (${preferredId}) confirmed status:failed ` +
|
|
56
|
+
`via direct GET (updatedAt=${test.updatedAt ?? 'unknown'}); list scan skipped`,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Transient probe failure — fall through to the list scan below.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
29
65
|
const candidates = [];
|
|
30
66
|
let cursor;
|
|
31
67
|
let pagesFetched = 0;
|
|
@@ -82,6 +118,18 @@ export async function resolveFailingFrontendTestId(opts) {
|
|
|
82
118
|
reason: 'No frontend tests with status=failed found in project; falling back to static fixture',
|
|
83
119
|
};
|
|
84
120
|
}
|
|
121
|
+
// DEV-393: a pinned, dedicated "always red" fixture wins over freshest
|
|
122
|
+
// whenever it is still in the failed set — see the doc comment on
|
|
123
|
+
// ResolverOptions.preferredId for why "freshest" alone is not enough.
|
|
124
|
+
if (preferredId) {
|
|
125
|
+
const pinned = candidates.find(c => c.id === preferredId);
|
|
126
|
+
if (pinned) {
|
|
127
|
+
return {
|
|
128
|
+
testId: pinned.id,
|
|
129
|
+
reason: `Preferred pinned failingFrontendTestId (${pinned.id}) is still status:failed (updatedAt=${pinned.updatedAt}); took priority over freshest-updatedAt candidate`,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
85
133
|
// Pick the most recently updated candidate — freshest failure is the
|
|
86
134
|
// most likely to have a valid failure bundle attached.
|
|
87
135
|
candidates.sort((a, b) => {
|