@testsprite/testsprite-cli 0.1.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/LICENSE +201 -0
- package/README.md +190 -0
- package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
- package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
- package/dist/commands/agent.d.ts +51 -0
- package/dist/commands/agent.js +552 -0
- package/dist/commands/auth.d.ts +38 -0
- package/dist/commands/auth.js +247 -0
- package/dist/commands/init.d.ts +63 -0
- package/dist/commands/init.js +350 -0
- package/dist/commands/project.d.ts +72 -0
- package/dist/commands/project.js +400 -0
- package/dist/commands/test.d.ts +1245 -0
- package/dist/commands/test.js +6214 -0
- package/dist/commands/usage.d.ts +63 -0
- package/dist/commands/usage.js +156 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +146 -0
- package/dist/lib/agent-targets.d.ts +50 -0
- package/dist/lib/agent-targets.js +99 -0
- package/dist/lib/bundle.d.ts +178 -0
- package/dist/lib/bundle.js +600 -0
- package/dist/lib/client-factory.d.ts +72 -0
- package/dist/lib/client-factory.js +120 -0
- package/dist/lib/config.d.ts +24 -0
- package/dist/lib/config.js +30 -0
- package/dist/lib/credentials.d.ts +17 -0
- package/dist/lib/credentials.js +122 -0
- package/dist/lib/dry-run/fetch.d.ts +18 -0
- package/dist/lib/dry-run/fetch.js +52 -0
- package/dist/lib/dry-run/samples.d.ts +50 -0
- package/dist/lib/dry-run/samples.js +676 -0
- package/dist/lib/errors.d.ts +118 -0
- package/dist/lib/errors.js +388 -0
- package/dist/lib/facade.d.ts +48 -0
- package/dist/lib/facade.js +104 -0
- package/dist/lib/failing-fe-resolver.d.ts +60 -0
- package/dist/lib/failing-fe-resolver.js +103 -0
- package/dist/lib/http.d.ts +255 -0
- package/dist/lib/http.js +608 -0
- package/dist/lib/output.d.ts +55 -0
- package/dist/lib/output.js +70 -0
- package/dist/lib/pagination.d.ts +56 -0
- package/dist/lib/pagination.js +81 -0
- package/dist/lib/poll.d.ts +88 -0
- package/dist/lib/poll.js +221 -0
- package/dist/lib/prompt.d.ts +8 -0
- package/dist/lib/prompt.js +97 -0
- package/dist/lib/rate-throttle.d.ts +49 -0
- package/dist/lib/rate-throttle.js +75 -0
- package/dist/lib/render-error.d.ts +15 -0
- package/dist/lib/render-error.js +44 -0
- package/dist/lib/runs.types.d.ts +344 -0
- package/dist/lib/runs.types.js +25 -0
- package/dist/lib/target-url.d.ts +25 -0
- package/dist/lib/target-url.js +127 -0
- package/dist/lib/ticker.d.ts +37 -0
- package/dist/lib/ticker.js +63 -0
- package/dist/lib/validate.d.ts +82 -0
- package/dist/lib/validate.js +165 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/package.json +65 -0
package/dist/lib/http.js
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ApiError, RequestTimeoutError, TransportError } from './errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* Default per-request timeout (120s). Comfortably covers every metadata/read
|
|
5
|
+
* request and every <=25s long-poll request (`?waitSeconds` is capped at 25
|
|
6
|
+
* by the polling layer), while still failing fast on a dead backend.
|
|
7
|
+
*
|
|
8
|
+
* The 15-minute test-execution ceiling is enforced separately by the `--timeout`
|
|
9
|
+
* / polling path (`poll.ts`) which supplies its own `AbortSignal` per iteration.
|
|
10
|
+
* That path is unaffected — each 25s long-poll request still falls well within
|
|
11
|
+
* this 120s per-request guard.
|
|
12
|
+
*
|
|
13
|
+
* Override via `--request-timeout <s>` (flag, in seconds) or
|
|
14
|
+
* `TESTSPRITE_REQUEST_TIMEOUT_MS` (env var, in milliseconds).
|
|
15
|
+
* Precedence: flag > env > default.
|
|
16
|
+
*/
|
|
17
|
+
export const REQUEST_TIMEOUT_DEFAULT_MS = 120_000;
|
|
18
|
+
/**
|
|
19
|
+
* Minimum accepted value: 1 second. Below this the timeout fires before a
|
|
20
|
+
* TLS handshake can complete on a healthy connection.
|
|
21
|
+
*/
|
|
22
|
+
export const REQUEST_TIMEOUT_MIN_MS = 1_000;
|
|
23
|
+
/**
|
|
24
|
+
* Maximum accepted value: 10 minutes. Values above this cap are clamped
|
|
25
|
+
* rather than rejected, so scripts that forward large numbers still work.
|
|
26
|
+
*/
|
|
27
|
+
export const REQUEST_TIMEOUT_MAX_MS = 600_000;
|
|
28
|
+
const RETRY_BASE_MS = 250;
|
|
29
|
+
const RETRY_JITTER_MS = 250;
|
|
30
|
+
const RETRY_MAX_DELAY_MS = 4000;
|
|
31
|
+
const MAX_ATTEMPTS_TRANSPORT = 4;
|
|
32
|
+
const MAX_ATTEMPTS_UNAVAILABLE = 4;
|
|
33
|
+
const MAX_ATTEMPTS_RATE_LIMITED = 3;
|
|
34
|
+
const MAX_ATTEMPTS_CONFLICT = 2;
|
|
35
|
+
const MAX_ATTEMPTS_INTERNAL = 2;
|
|
36
|
+
// Cap server-directed RATE_LIMITED waits so a hostile or misconfigured
|
|
37
|
+
// `Retry-After` (e.g. 86400) can't hang the CLI inside the retry sleep.
|
|
38
|
+
const MAX_RATE_LIMITED_DELAY_MS = 60_000;
|
|
39
|
+
const CONFLICT_DELAY_MS = 1000;
|
|
40
|
+
const INTERNAL_DELAY_MS = 500;
|
|
41
|
+
export class HttpClient {
|
|
42
|
+
baseUrl;
|
|
43
|
+
apiKey;
|
|
44
|
+
fetchImpl;
|
|
45
|
+
sleep;
|
|
46
|
+
random;
|
|
47
|
+
onDebug;
|
|
48
|
+
onTransition;
|
|
49
|
+
requestTimeoutMs;
|
|
50
|
+
constructor(options) {
|
|
51
|
+
this.baseUrl = trimTrailingSlash(options.baseUrl);
|
|
52
|
+
this.apiKey = options.apiKey;
|
|
53
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
54
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
55
|
+
this.random = options.random ?? Math.random;
|
|
56
|
+
this.onDebug = options.onDebug;
|
|
57
|
+
this.onTransition = options.onTransition;
|
|
58
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
|
|
59
|
+
}
|
|
60
|
+
async get(path, options = {}) {
|
|
61
|
+
return this.requestWithMeta('GET', path, options).then(r => r.body);
|
|
62
|
+
}
|
|
63
|
+
async post(path, options = {}) {
|
|
64
|
+
return this.requestWithMeta('POST', path, options).then(r => r.body);
|
|
65
|
+
}
|
|
66
|
+
async put(path, options = {}) {
|
|
67
|
+
return this.requestWithMeta('PUT', path, options).then(r => r.body);
|
|
68
|
+
}
|
|
69
|
+
async patch(path, options = {}) {
|
|
70
|
+
return this.requestWithMeta('PATCH', path, options).then(r => r.body);
|
|
71
|
+
}
|
|
72
|
+
async delete(path, options = {}) {
|
|
73
|
+
return this.requestWithMeta('DELETE', path, options).then(r => r.body);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Like `get` / `post` / etc. but returns the full `RequestResult` including
|
|
77
|
+
* `requestId` and `status`, so callers can surface the requestId in
|
|
78
|
+
* happy-path output (dogfood item 1).
|
|
79
|
+
*/
|
|
80
|
+
async getWithMeta(path, options = {}) {
|
|
81
|
+
return this.requestWithMeta('GET', path, options);
|
|
82
|
+
}
|
|
83
|
+
async postWithMeta(path, options = {}) {
|
|
84
|
+
return this.requestWithMeta('POST', path, options);
|
|
85
|
+
}
|
|
86
|
+
async putWithMeta(path, options = {}) {
|
|
87
|
+
return this.requestWithMeta('PUT', path, options);
|
|
88
|
+
}
|
|
89
|
+
async patchWithMeta(path, options = {}) {
|
|
90
|
+
return this.requestWithMeta('PATCH', path, options);
|
|
91
|
+
}
|
|
92
|
+
async deleteWithMeta(path, options = {}) {
|
|
93
|
+
return this.requestWithMeta('DELETE', path, options);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* POST /api/cli/v1/tests/{testId}/runs
|
|
97
|
+
* Trigger a run and return the queued-run envelope.
|
|
98
|
+
* The caller must supply an `idempotencyKey` which is sent as the
|
|
99
|
+
* `Idempotency-Key` header per M3.2 piece-1 §2 contract.
|
|
100
|
+
*/
|
|
101
|
+
async triggerRun(testId, body, options) {
|
|
102
|
+
return this.postWithMeta(`/tests/${encodeURIComponent(testId)}/runs`, {
|
|
103
|
+
body,
|
|
104
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
105
|
+
signal: options.signal,
|
|
106
|
+
// 409 on POST /runs means "another run is already in flight" — a
|
|
107
|
+
// persistent condition, not a transient snapshot conflict. Retrying
|
|
108
|
+
// would enqueue a second run once the first finishes.
|
|
109
|
+
retryOnConflict: false,
|
|
110
|
+
}).then(r => r.body);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Like `triggerRun` but returns the full `RequestResult` so the caller
|
|
114
|
+
* can surface the `requestId` in happy-path CLI output.
|
|
115
|
+
*
|
|
116
|
+
* `retryOnRateLimit` defaults to `true` so single `test run` and
|
|
117
|
+
* `test create --run` retain the standard HTTP-layer 429 retry budget.
|
|
118
|
+
*
|
|
119
|
+
* Pass `retryOnRateLimit: false` ONLY at the batch fan-out call site
|
|
120
|
+
* (`runBatchRun` / `triggerOne`) where the outer loop is the single owner
|
|
121
|
+
* of rate-limit handling — preventing the HTTP layer from adding up to 3
|
|
122
|
+
* extra retries per outer attempt, which would multiply POSTs per spec (e.g. 50×3 = 150/min).
|
|
123
|
+
*/
|
|
124
|
+
async triggerRunWithMeta(testId, body, options) {
|
|
125
|
+
return this.postWithMeta(`/tests/${encodeURIComponent(testId)}/runs`, {
|
|
126
|
+
body,
|
|
127
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
128
|
+
signal: options.signal,
|
|
129
|
+
retryOnConflict: false,
|
|
130
|
+
// Default true: single `test run` / `test create --run` retain 429 retry.
|
|
131
|
+
// Batch call site passes false to keep outer-loop as sole rate-limit owner.
|
|
132
|
+
retryOnRateLimit: options.retryOnRateLimit ?? true,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* POST /api/cli/v1/tests/{testId}/runs/rerun
|
|
137
|
+
* Trigger a rerun (replay) for a single test. FE: verbatim script replay (no credits).
|
|
138
|
+
* BE: dependency-closure re-run. Returns `runId` + optional `closure` (BE).
|
|
139
|
+
*
|
|
140
|
+
* `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
|
|
141
|
+
* a persistent condition. Retrying would race against the running test.
|
|
142
|
+
*/
|
|
143
|
+
async triggerRerun(testId, body, options) {
|
|
144
|
+
return this.postWithMeta(`/tests/${encodeURIComponent(testId)}/runs/rerun`, {
|
|
145
|
+
body,
|
|
146
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
147
|
+
signal: options.signal,
|
|
148
|
+
retryOnConflict: false,
|
|
149
|
+
}).then(r => r.body);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* POST /api/cli/v1/tests/batch/rerun
|
|
153
|
+
* Trigger a batch rerun across multiple tests (mixed FE/BE allowed).
|
|
154
|
+
* BE closure is deduped server-side per project.
|
|
155
|
+
*
|
|
156
|
+
* `retryOnConflict: false` — 409 on batch rerun is persistent ("in flight").
|
|
157
|
+
*/
|
|
158
|
+
async triggerBatchRerun(body, options) {
|
|
159
|
+
return this.postWithMeta('/tests/batch/rerun', {
|
|
160
|
+
body,
|
|
161
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
162
|
+
signal: options.signal,
|
|
163
|
+
retryOnConflict: false,
|
|
164
|
+
}).then(r => r.body);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* POST /api/cli/v1/tests/batch/run
|
|
168
|
+
* Trigger a fresh wave-ordered batch run across all (or a subset of) BE tests
|
|
169
|
+
* in a project. FE tests in the set are skipped server-side (advisory).
|
|
170
|
+
* `testIds` absent / empty → run ALL BE tests in the project.
|
|
171
|
+
*
|
|
172
|
+
* `retryOnConflict: false` — 409 on batch run means a run is already in flight.
|
|
173
|
+
*/
|
|
174
|
+
async triggerBatchRunFresh(body, options) {
|
|
175
|
+
return this.postWithMeta('/tests/batch/run', {
|
|
176
|
+
body,
|
|
177
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
178
|
+
signal: options.signal,
|
|
179
|
+
retryOnConflict: false,
|
|
180
|
+
}).then(r => r.body);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* GET /api/cli/v1/tests/{testId}/runs
|
|
184
|
+
* List a test's prior run history, newest-first.
|
|
185
|
+
*
|
|
186
|
+
* Limit-before-filter caveat: a `source`-filtered page may return fewer
|
|
187
|
+
* than `pageSize` rows while still yielding a non-null `nextCursor`.
|
|
188
|
+
* That means "none in THIS window", not end-of-history.
|
|
189
|
+
*/
|
|
190
|
+
async listTestRuns(testId, query) {
|
|
191
|
+
const q = {};
|
|
192
|
+
if (query.cursor !== undefined)
|
|
193
|
+
q.cursor = query.cursor;
|
|
194
|
+
if (query.pageSize !== undefined)
|
|
195
|
+
q.pageSize = query.pageSize;
|
|
196
|
+
if (query.source !== undefined)
|
|
197
|
+
q.source = query.source;
|
|
198
|
+
if (query.since !== undefined)
|
|
199
|
+
q.since = query.since;
|
|
200
|
+
return this.get(`/tests/${encodeURIComponent(testId)}/runs`, { query: q });
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* GET /api/cli/v1/runs/{runId}
|
|
204
|
+
* Fetch the current state of a run. When `waitSeconds` is provided
|
|
205
|
+
* (1–25) the server performs a bounded long-poll and returns when the
|
|
206
|
+
* run is terminal or when `waitSeconds` elapses, whichever comes
|
|
207
|
+
* first. On `400 VALIDATION_ERROR` (server doesn't support
|
|
208
|
+
* `waitSeconds`) the caller should retry without the param and switch
|
|
209
|
+
* to client-side backoff — see `src/lib/poll.ts`.
|
|
210
|
+
*
|
|
211
|
+
* When `includeSteps` is `true`, the server appends the full ordered
|
|
212
|
+
* `steps[]` array (M3.4 piece-4). Default (absent/false) is byte-
|
|
213
|
+
* identical to the M3.3 summary shape — the polling path is unaffected.
|
|
214
|
+
*/
|
|
215
|
+
async getRun(runId, options) {
|
|
216
|
+
const query = {};
|
|
217
|
+
if (options?.waitSeconds !== undefined) {
|
|
218
|
+
query.waitSeconds = options.waitSeconds;
|
|
219
|
+
}
|
|
220
|
+
if (options?.includeSteps === true) {
|
|
221
|
+
query.includeSteps = true;
|
|
222
|
+
}
|
|
223
|
+
return this.get(`/runs/${encodeURIComponent(runId)}`, {
|
|
224
|
+
query: Object.keys(query).length > 0 ? query : undefined,
|
|
225
|
+
signal: options?.signal,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Classify an error thrown while issuing OR reading a request. When it is an
|
|
230
|
+
* abort/timeout and our per-request timeout signal fired (and the caller had
|
|
231
|
+
* not already aborted), surface a clear RequestTimeoutError; when it is a
|
|
232
|
+
* caller-supplied abort (SIGINT, poll-iteration deadline), rethrow it
|
|
233
|
+
* unmodified. Returns normally when `err` is not an abort, so the caller can
|
|
234
|
+
* continue its own error handling (transport retry / envelope parse).
|
|
235
|
+
*/
|
|
236
|
+
rethrowIfAbort(err, timeoutSignal, callerSignal, requestId) {
|
|
237
|
+
if (isAbortError(err) || isTimeoutError(err)) {
|
|
238
|
+
if (timeoutSignal.aborted && (callerSignal == null || !callerSignal.aborted)) {
|
|
239
|
+
throw new RequestTimeoutError(this.requestTimeoutMs, requestId);
|
|
240
|
+
}
|
|
241
|
+
throw err;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async requestWithMeta(method, path, options = {}) {
|
|
245
|
+
if (!this.apiKey)
|
|
246
|
+
throw ApiError.authRequired();
|
|
247
|
+
const url = buildUrl(this.baseUrl, path, options.query);
|
|
248
|
+
const requestId = options.requestId ?? newRequestId();
|
|
249
|
+
let attempt = 0;
|
|
250
|
+
while (true) {
|
|
251
|
+
attempt += 1;
|
|
252
|
+
this.debug({ kind: 'request', method, url, attempt, requestId });
|
|
253
|
+
const startedAt = Date.now();
|
|
254
|
+
let response;
|
|
255
|
+
// Compose the per-request timeout signal with any caller-supplied signal.
|
|
256
|
+
// The fetch aborts on whichever fires first. This ensures every one-shot
|
|
257
|
+
// request (test create/update/delete/list/get, auth whoami, code put/get,
|
|
258
|
+
// plan put) has a client-side deadline even when the caller supplies no
|
|
259
|
+
// signal. The polling path supplies its own deadline-aware signal per
|
|
260
|
+
// iteration — this timeout (120s default) is safely larger than any single
|
|
261
|
+
// long-poll window (<=25s via ?waitSeconds), so it never bites polling.
|
|
262
|
+
const timeoutSignal = AbortSignal.timeout(this.requestTimeoutMs);
|
|
263
|
+
const effectiveSignal = options.signal != null ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
|
|
264
|
+
try {
|
|
265
|
+
response = await this.fetchImpl(url, {
|
|
266
|
+
method,
|
|
267
|
+
headers: this.buildHeaders(requestId, options),
|
|
268
|
+
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
|
269
|
+
signal: effectiveSignal,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
// Distinguish a client-side request timeout from a caller-supplied abort.
|
|
274
|
+
//
|
|
275
|
+
// Node 22 `AbortSignal.timeout()` throws a `DOMException` with
|
|
276
|
+
// `name === 'TimeoutError'` (not 'AbortError') when the signal fires.
|
|
277
|
+
// A caller-supplied abort sets `name === 'AbortError'`.
|
|
278
|
+
// We treat both abort variants together: if the timeout signal fired and
|
|
279
|
+
// the caller hadn't already aborted, surface a clear RequestTimeoutError.
|
|
280
|
+
// A timeout/abort during the fetch itself: classify it (RequestTimeoutError
|
|
281
|
+
// when our deadline fired; otherwise rethrow the caller's abort unmodified).
|
|
282
|
+
this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
|
|
283
|
+
// If a RequestTimeoutError already propagated from somewhere (e.g. from a
|
|
284
|
+
// nested call or from a test-injected fetchImpl), pass it through unchanged
|
|
285
|
+
// rather than re-wrapping it as a TransportError.
|
|
286
|
+
if (err instanceof RequestTimeoutError)
|
|
287
|
+
throw err;
|
|
288
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
289
|
+
this.debug({
|
|
290
|
+
kind: 'error',
|
|
291
|
+
method,
|
|
292
|
+
url,
|
|
293
|
+
attempt,
|
|
294
|
+
requestId,
|
|
295
|
+
errorCode: 'TRANSPORT',
|
|
296
|
+
durationMs: Date.now() - startedAt,
|
|
297
|
+
});
|
|
298
|
+
const decision = transportRetryDecision(attempt, this.random);
|
|
299
|
+
if (!decision.retry)
|
|
300
|
+
throw new TransportError(message, requestId);
|
|
301
|
+
this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
|
|
302
|
+
this.debug({
|
|
303
|
+
kind: 'retry',
|
|
304
|
+
method,
|
|
305
|
+
url,
|
|
306
|
+
attempt,
|
|
307
|
+
requestId,
|
|
308
|
+
errorCode: 'TRANSPORT',
|
|
309
|
+
delayMs: decision.delayMs,
|
|
310
|
+
});
|
|
311
|
+
await this.sleep(decision.delayMs);
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
const durationMs = Date.now() - startedAt;
|
|
315
|
+
if (response.ok) {
|
|
316
|
+
this.debug({
|
|
317
|
+
kind: 'response',
|
|
318
|
+
method,
|
|
319
|
+
url,
|
|
320
|
+
attempt,
|
|
321
|
+
status: response.status,
|
|
322
|
+
requestId,
|
|
323
|
+
durationMs,
|
|
324
|
+
});
|
|
325
|
+
try {
|
|
326
|
+
return { body: (await response.json()), requestId, status: response.status };
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
// A timeout/abort can fire mid-body-read (headers received, stream stalls).
|
|
330
|
+
this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
|
|
331
|
+
throw err;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
let rawBody;
|
|
335
|
+
try {
|
|
336
|
+
rawBody = await safeReadJson(response);
|
|
337
|
+
}
|
|
338
|
+
catch (err) {
|
|
339
|
+
// safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
|
|
340
|
+
// errors), so a timeout fired mid-body-read on a non-OK response lands here.
|
|
341
|
+
this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
|
|
342
|
+
throw err;
|
|
343
|
+
}
|
|
344
|
+
// Edge proxies / load balancers return 408/502/504 without our error
|
|
345
|
+
// envelope on transient outages. Per the CLI error spec §7 these are
|
|
346
|
+
// transport-level retries, not facade errors — fold them in here so
|
|
347
|
+
// we get the bounded backoff budget instead of a single INTERNAL bail.
|
|
348
|
+
if (rawBody === null && isTransportEdgeStatus(response.status)) {
|
|
349
|
+
this.debug({
|
|
350
|
+
kind: 'error',
|
|
351
|
+
method,
|
|
352
|
+
url,
|
|
353
|
+
attempt,
|
|
354
|
+
status: response.status,
|
|
355
|
+
requestId,
|
|
356
|
+
errorCode: 'TRANSPORT',
|
|
357
|
+
durationMs,
|
|
358
|
+
});
|
|
359
|
+
const decision = transportRetryDecision(attempt, this.random);
|
|
360
|
+
if (!decision.retry) {
|
|
361
|
+
throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
|
|
362
|
+
}
|
|
363
|
+
this.transition(`HTTP ${response.status} from ${shortPath(path)} — transport error, retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
|
|
364
|
+
this.debug({
|
|
365
|
+
kind: 'retry',
|
|
366
|
+
method,
|
|
367
|
+
url,
|
|
368
|
+
attempt,
|
|
369
|
+
requestId,
|
|
370
|
+
errorCode: 'TRANSPORT',
|
|
371
|
+
delayMs: decision.delayMs,
|
|
372
|
+
});
|
|
373
|
+
await this.sleep(decision.delayMs);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
|
|
377
|
+
// Clamp server-directed Retry-After to [1s, 300s] and surface on the
|
|
378
|
+
// thrown error so outer callers (e.g. runBatchRun outer retry loop)
|
|
379
|
+
// can honor it without re-reading the now-consumed HTTP response.
|
|
380
|
+
const retryAfterMsForError = retryAfterSec !== undefined ? Math.min(Math.max(retryAfterSec, 1), 300) * 1000 : undefined;
|
|
381
|
+
const apiError = ApiError.fromEnvelope(rawBody, response.status, retryAfterMsForError,
|
|
382
|
+
// Lets synthesized nextAction text (e.g. INSUFFICIENT_CREDITS billing
|
|
383
|
+
// links) resolve the environment-correct portal domain.
|
|
384
|
+
this.baseUrl);
|
|
385
|
+
this.debug({
|
|
386
|
+
kind: 'error',
|
|
387
|
+
method,
|
|
388
|
+
url,
|
|
389
|
+
attempt,
|
|
390
|
+
status: response.status,
|
|
391
|
+
errorCode: apiError.code,
|
|
392
|
+
requestId,
|
|
393
|
+
durationMs,
|
|
394
|
+
});
|
|
395
|
+
const retryOnConflict = options.retryOnConflict !== false;
|
|
396
|
+
const retryOnRateLimit = options.retryOnRateLimit !== false;
|
|
397
|
+
const decision = apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit);
|
|
398
|
+
if (!decision.retry)
|
|
399
|
+
throw apiError;
|
|
400
|
+
const delaySec = Math.round(decision.delayMs / 1000);
|
|
401
|
+
if (apiError.code === 'RATE_LIMITED') {
|
|
402
|
+
this.transition(`Rate limited (HTTP 429) — waiting ${delaySec}s before retry (attempt ${attempt})`);
|
|
403
|
+
}
|
|
404
|
+
else if (apiError.code === 'INTERNAL') {
|
|
405
|
+
this.transition(`Server error (HTTP 5xx, requestId: ${requestId}) — retrying in ${delaySec}s (attempt ${attempt})`);
|
|
406
|
+
}
|
|
407
|
+
else if (apiError.code === 'UNAVAILABLE') {
|
|
408
|
+
this.transition(`Service unavailable (HTTP 503) — retrying in ${delaySec}s (attempt ${attempt})`);
|
|
409
|
+
}
|
|
410
|
+
this.debug({
|
|
411
|
+
kind: 'retry',
|
|
412
|
+
method,
|
|
413
|
+
url,
|
|
414
|
+
attempt,
|
|
415
|
+
requestId,
|
|
416
|
+
errorCode: apiError.code,
|
|
417
|
+
delayMs: decision.delayMs,
|
|
418
|
+
});
|
|
419
|
+
await this.sleep(decision.delayMs);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
buildHeaders(requestId, options) {
|
|
423
|
+
const headers = {
|
|
424
|
+
'x-request-id': requestId,
|
|
425
|
+
accept: 'application/json',
|
|
426
|
+
'user-agent': 'testsprite-cli',
|
|
427
|
+
};
|
|
428
|
+
// The CLI v1 facade authenticates via `x-api-key`.
|
|
429
|
+
// (securitySchemes.ApiKeyAuth). Sending only Authorization Bearer would be
|
|
430
|
+
// treated as a missing key by the backend.
|
|
431
|
+
if (this.apiKey)
|
|
432
|
+
headers['x-api-key'] = this.apiKey;
|
|
433
|
+
if (options.body !== undefined)
|
|
434
|
+
headers['content-type'] = 'application/json';
|
|
435
|
+
// Mutation-route headers (Idempotency-Key, If-Match) get merged last
|
|
436
|
+
// so callers cannot accidentally strip the auth or request-id keys.
|
|
437
|
+
if (options.headers) {
|
|
438
|
+
for (const [name, value] of Object.entries(options.headers)) {
|
|
439
|
+
headers[name.toLowerCase()] = value;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return headers;
|
|
443
|
+
}
|
|
444
|
+
debug(event) {
|
|
445
|
+
if (this.onDebug)
|
|
446
|
+
this.onDebug(event);
|
|
447
|
+
}
|
|
448
|
+
transition(msg) {
|
|
449
|
+
if (this.onTransition)
|
|
450
|
+
this.onTransition(msg);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Legacy alias kept for backward-compat with test files that call
|
|
454
|
+
* `client.request(...)` directly. New callers should use
|
|
455
|
+
* `requestWithMeta` or the typed helpers (`get`, `post`, etc.).
|
|
456
|
+
*/
|
|
457
|
+
async request(method, path, options = {}) {
|
|
458
|
+
return this.requestWithMeta(method, path, options).then(r => r.body);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
function trimTrailingSlash(url) {
|
|
462
|
+
return url.endsWith('/') ? url.slice(0, -1) : url;
|
|
463
|
+
}
|
|
464
|
+
/** Extracts the path component from a full URL for concise log messages. */
|
|
465
|
+
function shortPath(pathOrUrl) {
|
|
466
|
+
try {
|
|
467
|
+
return new URL(pathOrUrl).pathname;
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
return pathOrUrl;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
export function buildUrl(baseUrl, path, query) {
|
|
474
|
+
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
|
475
|
+
const url = new URL(`${trimTrailingSlash(baseUrl)}${normalizedPath}`);
|
|
476
|
+
if (query) {
|
|
477
|
+
for (const [key, value] of Object.entries(query)) {
|
|
478
|
+
if (value === undefined)
|
|
479
|
+
continue;
|
|
480
|
+
url.searchParams.set(key, String(value));
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return url.toString();
|
|
484
|
+
}
|
|
485
|
+
function newRequestId() {
|
|
486
|
+
return `cli_${randomUUID()}`;
|
|
487
|
+
}
|
|
488
|
+
async function safeReadJson(response) {
|
|
489
|
+
try {
|
|
490
|
+
return await response.json();
|
|
491
|
+
}
|
|
492
|
+
catch (err) {
|
|
493
|
+
// Don't swallow client-side aborts/timeouts as a null body — the caller must
|
|
494
|
+
// be able to classify a mid-body-read timeout as a RequestTimeoutError.
|
|
495
|
+
if (isAbortError(err) || isTimeoutError(err))
|
|
496
|
+
throw err;
|
|
497
|
+
return null;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
export function parseRetryAfter(headerValue) {
|
|
501
|
+
if (!headerValue)
|
|
502
|
+
return undefined;
|
|
503
|
+
const numeric = Number(headerValue);
|
|
504
|
+
if (Number.isFinite(numeric) && numeric >= 0)
|
|
505
|
+
return Math.ceil(numeric);
|
|
506
|
+
const date = Date.parse(headerValue);
|
|
507
|
+
if (!Number.isNaN(date)) {
|
|
508
|
+
const diffMs = date - Date.now();
|
|
509
|
+
return diffMs > 0 ? Math.ceil(diffMs / 1000) : 0;
|
|
510
|
+
}
|
|
511
|
+
return undefined;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* HTTP statuses that arrive without our error envelope on transient
|
|
515
|
+
* upstream outages (edge LB returning HTML, etc.). Treated as transport
|
|
516
|
+
* failures.
|
|
517
|
+
*/
|
|
518
|
+
function isTransportEdgeStatus(status) {
|
|
519
|
+
return status === 408 || status === 502 || status === 504;
|
|
520
|
+
}
|
|
521
|
+
function transportRetryDecision(attempt, random) {
|
|
522
|
+
if (attempt >= MAX_ATTEMPTS_TRANSPORT)
|
|
523
|
+
return { retry: false, delayMs: 0 };
|
|
524
|
+
return { retry: true, delayMs: backoffDelay(attempt, random) };
|
|
525
|
+
}
|
|
526
|
+
function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict = true, retryOnRateLimit = true) {
|
|
527
|
+
switch (code) {
|
|
528
|
+
// M3.2 piece-1 / piece-2: `PRECONDITION_FAILED` (etag mismatch),
|
|
529
|
+
// `IDEMPOTENCY_BODY_MISMATCH` (caller mutated body across retries),
|
|
530
|
+
// and `PAYLOAD_TOO_LARGE` (350 KB cap) are all caller-side bugs —
|
|
531
|
+
// never retry, exit immediately with the typed envelope.
|
|
532
|
+
// INSUFFICIENT_CREDITS is non-retriable: out-of-credits cannot self-heal.
|
|
533
|
+
// The RATE_LIMITED credits sub-case is re-mapped to INSUFFICIENT_CREDITS
|
|
534
|
+
// in parseEnvelopeBody (errors.ts) before apiRetryDecision is called,
|
|
535
|
+
// so the genuine per-minute throttle (RATE_LIMITED) reaches the RATE_LIMITED
|
|
536
|
+
// case below and retries normally.
|
|
537
|
+
// FEATURE_GATED is non-retriable: a paid-feature gate can't self-heal with
|
|
538
|
+
// retries — the caller must upgrade their plan first.
|
|
539
|
+
case 'AUTH_REQUIRED':
|
|
540
|
+
case 'AUTH_INVALID':
|
|
541
|
+
case 'AUTH_FORBIDDEN':
|
|
542
|
+
case 'NOT_FOUND':
|
|
543
|
+
case 'VALIDATION_ERROR':
|
|
544
|
+
case 'PAYLOAD_TOO_LARGE':
|
|
545
|
+
case 'PRECONDITION_FAILED':
|
|
546
|
+
case 'IDEMPOTENCY_BODY_MISMATCH':
|
|
547
|
+
case 'UNSUPPORTED':
|
|
548
|
+
case 'INSUFFICIENT_CREDITS':
|
|
549
|
+
case 'FEATURE_GATED':
|
|
550
|
+
return { retry: false, delayMs: 0 };
|
|
551
|
+
case 'CONFLICT':
|
|
552
|
+
// Read paths (e.g. GET /failure) retry once: 409 = mid-mutation snapshot.
|
|
553
|
+
// Write paths (e.g. POST /runs) must NOT retry: 409 = another run is in
|
|
554
|
+
// flight (persistent), retrying would enqueue a second run.
|
|
555
|
+
if (!retryOnConflict)
|
|
556
|
+
return { retry: false, delayMs: 0 };
|
|
557
|
+
if (attempt >= MAX_ATTEMPTS_CONFLICT)
|
|
558
|
+
return { retry: false, delayMs: 0 };
|
|
559
|
+
return { retry: true, delayMs: CONFLICT_DELAY_MS };
|
|
560
|
+
case 'INTERNAL':
|
|
561
|
+
if (attempt >= MAX_ATTEMPTS_INTERNAL)
|
|
562
|
+
return { retry: false, delayMs: 0 };
|
|
563
|
+
return { retry: true, delayMs: INTERNAL_DELAY_MS };
|
|
564
|
+
case 'RATE_LIMITED':
|
|
565
|
+
if (!retryOnRateLimit)
|
|
566
|
+
return { retry: false, delayMs: 0 };
|
|
567
|
+
if (attempt >= MAX_ATTEMPTS_RATE_LIMITED)
|
|
568
|
+
return { retry: false, delayMs: 0 };
|
|
569
|
+
return {
|
|
570
|
+
retry: true,
|
|
571
|
+
delayMs: Math.min(Math.max(0, (retryAfterSec ?? 1) * 1000), MAX_RATE_LIMITED_DELAY_MS),
|
|
572
|
+
};
|
|
573
|
+
case 'UNAVAILABLE':
|
|
574
|
+
if (attempt >= MAX_ATTEMPTS_UNAVAILABLE)
|
|
575
|
+
return { retry: false, delayMs: 0 };
|
|
576
|
+
return { retry: true, delayMs: backoffDelay(attempt, random) };
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
function backoffDelay(attempt, random) {
|
|
580
|
+
const base = RETRY_BASE_MS * Math.pow(2, attempt - 1);
|
|
581
|
+
const jitter = Math.floor(random() * RETRY_JITTER_MS);
|
|
582
|
+
return Math.min(base + jitter, RETRY_MAX_DELAY_MS);
|
|
583
|
+
}
|
|
584
|
+
function defaultSleep(ms) {
|
|
585
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
586
|
+
}
|
|
587
|
+
function isAbortError(err) {
|
|
588
|
+
if (err instanceof Error && err.name === 'AbortError')
|
|
589
|
+
return true;
|
|
590
|
+
if (typeof err === 'object' && err !== null && 'name' in err) {
|
|
591
|
+
return err.name === 'AbortError';
|
|
592
|
+
}
|
|
593
|
+
return false;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Detects the `TimeoutError` thrown by `AbortSignal.timeout()` in Node 22+.
|
|
597
|
+
* Node's `fetch` aborts with a `DOMException` whose `.name === 'TimeoutError'`
|
|
598
|
+
* (distinct from `'AbortError'` used for explicit `AbortController.abort()`).
|
|
599
|
+
*/
|
|
600
|
+
function isTimeoutError(err) {
|
|
601
|
+
if (err instanceof Error && err.name === 'TimeoutError')
|
|
602
|
+
return true;
|
|
603
|
+
if (typeof err === 'object' && err !== null && 'name' in err) {
|
|
604
|
+
return err.name === 'TimeoutError';
|
|
605
|
+
}
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
//# sourceMappingURL=http.js.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export type OutputMode = 'json' | 'text';
|
|
2
|
+
/**
|
|
3
|
+
* Help-text footer pointing at the global options surface so users
|
|
4
|
+
* looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
|
|
5
|
+
* `--profile`, `--endpoint-url`, `--debug`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const GLOBAL_OPTS_HINT: string;
|
|
8
|
+
export declare function isOutputMode(value: unknown): value is OutputMode;
|
|
9
|
+
export interface OutputStreams {
|
|
10
|
+
/**
|
|
11
|
+
* Line-oriented stdout writer. Each call is one logical line; the
|
|
12
|
+
* default (`console.log`) appends a newline. Use this for JSON
|
|
13
|
+
* envelopes, headers, summaries, and any output where the framework
|
|
14
|
+
* owns line termination.
|
|
15
|
+
*/
|
|
16
|
+
stdout?: (line: string) => void;
|
|
17
|
+
stderr?: (line: string) => void;
|
|
18
|
+
/**
|
|
19
|
+
* Raw byte-oriented stdout writer. Each call writes its argument
|
|
20
|
+
* verbatim, no trailing newline. Use {@link Output.writeChunk} to
|
|
21
|
+
* stream content where preserving the exact byte stream matters —
|
|
22
|
+
* e.g. dumping presigned source code to stdout for `> file.ts`
|
|
23
|
+
* piping.
|
|
24
|
+
*
|
|
25
|
+
* Returning a `Promise` is the contract for honoring backpressure:
|
|
26
|
+
* the default implementation returns a promise that resolves when
|
|
27
|
+
* `process.stdout.write` returns `true` synchronously, or when the
|
|
28
|
+
* stream's `'drain'` event fires if the kernel buffer was full.
|
|
29
|
+
* Callers (e.g. the streaming loop in `streamPresignedBody`) MUST
|
|
30
|
+
* `await` `writeChunk` so the upstream reader pauses instead of
|
|
31
|
+
* silently piling chunks into V8's heap. Tests that ignore
|
|
32
|
+
* backpressure may pass a sync `(text) => void` impl — the
|
|
33
|
+
* `void | Promise<void>` return type is intentionally loose so
|
|
34
|
+
* trivial in-memory test sinks don't have to manufacture
|
|
35
|
+
* Promises.
|
|
36
|
+
*/
|
|
37
|
+
rawStdout?: (text: string) => void | Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
export declare class Output {
|
|
40
|
+
private readonly mode;
|
|
41
|
+
private readonly stdoutWrite;
|
|
42
|
+
private readonly stderrWrite;
|
|
43
|
+
private readonly rawStdoutWrite;
|
|
44
|
+
constructor(mode?: OutputMode, streams?: OutputStreams);
|
|
45
|
+
print(data: unknown, textRenderer?: (data: unknown) => string): void;
|
|
46
|
+
/**
|
|
47
|
+
* Write a chunk of bytes to stdout verbatim. Awaits any
|
|
48
|
+
* Promise the rawStdout writer returns so a slow downstream
|
|
49
|
+
* consumer pauses the upstream reader instead of buffering chunks
|
|
50
|
+
* in memory. See `OutputStreams.rawStdout` for the backpressure
|
|
51
|
+
* contract.
|
|
52
|
+
*/
|
|
53
|
+
writeChunk(text: string): Promise<void>;
|
|
54
|
+
error(message: string): void;
|
|
55
|
+
}
|