@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.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +190 -0
  3. package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
  4. package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
  5. package/dist/commands/agent.d.ts +51 -0
  6. package/dist/commands/agent.js +552 -0
  7. package/dist/commands/auth.d.ts +38 -0
  8. package/dist/commands/auth.js +247 -0
  9. package/dist/commands/init.d.ts +63 -0
  10. package/dist/commands/init.js +350 -0
  11. package/dist/commands/project.d.ts +72 -0
  12. package/dist/commands/project.js +400 -0
  13. package/dist/commands/test.d.ts +1245 -0
  14. package/dist/commands/test.js +6214 -0
  15. package/dist/commands/usage.d.ts +63 -0
  16. package/dist/commands/usage.js +156 -0
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +146 -0
  19. package/dist/lib/agent-targets.d.ts +50 -0
  20. package/dist/lib/agent-targets.js +99 -0
  21. package/dist/lib/bundle.d.ts +178 -0
  22. package/dist/lib/bundle.js +600 -0
  23. package/dist/lib/client-factory.d.ts +72 -0
  24. package/dist/lib/client-factory.js +120 -0
  25. package/dist/lib/config.d.ts +24 -0
  26. package/dist/lib/config.js +30 -0
  27. package/dist/lib/credentials.d.ts +17 -0
  28. package/dist/lib/credentials.js +122 -0
  29. package/dist/lib/dry-run/fetch.d.ts +18 -0
  30. package/dist/lib/dry-run/fetch.js +52 -0
  31. package/dist/lib/dry-run/samples.d.ts +50 -0
  32. package/dist/lib/dry-run/samples.js +676 -0
  33. package/dist/lib/errors.d.ts +118 -0
  34. package/dist/lib/errors.js +388 -0
  35. package/dist/lib/facade.d.ts +48 -0
  36. package/dist/lib/facade.js +104 -0
  37. package/dist/lib/failing-fe-resolver.d.ts +60 -0
  38. package/dist/lib/failing-fe-resolver.js +103 -0
  39. package/dist/lib/http.d.ts +255 -0
  40. package/dist/lib/http.js +608 -0
  41. package/dist/lib/output.d.ts +55 -0
  42. package/dist/lib/output.js +70 -0
  43. package/dist/lib/pagination.d.ts +56 -0
  44. package/dist/lib/pagination.js +81 -0
  45. package/dist/lib/poll.d.ts +88 -0
  46. package/dist/lib/poll.js +221 -0
  47. package/dist/lib/prompt.d.ts +8 -0
  48. package/dist/lib/prompt.js +97 -0
  49. package/dist/lib/rate-throttle.d.ts +49 -0
  50. package/dist/lib/rate-throttle.js +75 -0
  51. package/dist/lib/render-error.d.ts +15 -0
  52. package/dist/lib/render-error.js +44 -0
  53. package/dist/lib/runs.types.d.ts +344 -0
  54. package/dist/lib/runs.types.js +25 -0
  55. package/dist/lib/target-url.d.ts +25 -0
  56. package/dist/lib/target-url.js +127 -0
  57. package/dist/lib/ticker.d.ts +37 -0
  58. package/dist/lib/ticker.js +63 -0
  59. package/dist/lib/validate.d.ts +82 -0
  60. package/dist/lib/validate.js +165 -0
  61. package/dist/version.d.ts +1 -0
  62. package/dist/version.js +2 -0
  63. package/package.json +65 -0
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Auto-discovery helper for `failingFrontendTestId`.
3
+ *
4
+ * Queries the dev backend's test-list endpoint for the most recently
5
+ * updated frontend test with status `failed`, scoped to the project
6
+ * declared in fixtures.local.json (`paginationProjectId`). Returns the
7
+ * discovered id on success, or `null` when no Failed test is found, the
8
+ * API call fails, or the required env / fixture preconditions are absent.
9
+ *
10
+ * The `null` path is intentionally non-throwing: callers fall back to the
11
+ * static `fixtures.local.json` value so the suite degrades gracefully on
12
+ * transient network issues.
13
+ *
14
+ * @see test/dev-e2e/global-setup.ts — invokes this at suite start and
15
+ * writes the result to `process.env.TESTSPRITE_DEV_FAILING_FE_TEST_ID`.
16
+ * @see test/dev-e2e/_shared.ts — `loadFixtures()` reads that env var and
17
+ * prefers it over the static fixture file value.
18
+ */
19
+ /**
20
+ * Minimal shape of an item returned by GET /tests.
21
+ * Only the fields we need for discovery; the full shape is in tests.dev-e2e.test.ts.
22
+ */
23
+ export interface TestListItem {
24
+ id: string;
25
+ type: 'frontend' | 'backend';
26
+ status: string;
27
+ updatedAt: string;
28
+ }
29
+ export interface ResolverOptions {
30
+ /** Base URL for the CLI v1 API (e.g. https://api.testsprite.com/api/cli/v1) */
31
+ baseUrl: string;
32
+ /** API key sent as x-api-key header */
33
+ apiKey: string;
34
+ /** Project to search within */
35
+ projectId: string;
36
+ /**
37
+ * Optional fetch override for unit tests.
38
+ * Defaults to the global `fetch` when not provided.
39
+ */
40
+ fetchImpl?: typeof fetch;
41
+ /**
42
+ * Maximum number of pages to walk (safety guard, default 5).
43
+ * Each page uses pageSize=50, so 5 pages = 250 tests scanned.
44
+ */
45
+ maxPages?: number;
46
+ }
47
+ export interface ResolverResult {
48
+ /** The resolved failing frontend test id, or null if none found. */
49
+ testId: string | null;
50
+ /** Human-readable description of how the result was obtained. */
51
+ reason: string;
52
+ }
53
+ /**
54
+ * Walk up to `maxPages` pages of GET /tests?projectId=...&type=frontend&status=failed
55
+ * and return the item with the greatest `updatedAt` timestamp.
56
+ *
57
+ * Returns `{ testId: null, reason: <explanation> }` on any error or
58
+ * when no Failed test exists — never throws.
59
+ */
60
+ export declare function resolveFailingFrontendTestId(opts: ResolverOptions): Promise<ResolverResult>;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Auto-discovery helper for `failingFrontendTestId`.
3
+ *
4
+ * Queries the dev backend's test-list endpoint for the most recently
5
+ * updated frontend test with status `failed`, scoped to the project
6
+ * declared in fixtures.local.json (`paginationProjectId`). Returns the
7
+ * discovered id on success, or `null` when no Failed test is found, the
8
+ * API call fails, or the required env / fixture preconditions are absent.
9
+ *
10
+ * The `null` path is intentionally non-throwing: callers fall back to the
11
+ * static `fixtures.local.json` value so the suite degrades gracefully on
12
+ * transient network issues.
13
+ *
14
+ * @see test/dev-e2e/global-setup.ts — invokes this at suite start and
15
+ * writes the result to `process.env.TESTSPRITE_DEV_FAILING_FE_TEST_ID`.
16
+ * @see test/dev-e2e/_shared.ts — `loadFixtures()` reads that env var and
17
+ * prefers it over the static fixture file value.
18
+ */
19
+ /**
20
+ * Walk up to `maxPages` pages of GET /tests?projectId=...&type=frontend&status=failed
21
+ * and return the item with the greatest `updatedAt` timestamp.
22
+ *
23
+ * Returns `{ testId: null, reason: <explanation> }` on any error or
24
+ * when no Failed test exists — never throws.
25
+ */
26
+ export async function resolveFailingFrontendTestId(opts) {
27
+ const { baseUrl, apiKey, projectId, maxPages = 5 } = opts;
28
+ const fetchImpl = opts.fetchImpl ?? fetch;
29
+ const candidates = [];
30
+ let cursor;
31
+ let pagesFetched = 0;
32
+ try {
33
+ do {
34
+ const url = new URL(`${baseUrl}/tests`);
35
+ url.searchParams.set('projectId', projectId);
36
+ url.searchParams.set('type', 'frontend');
37
+ url.searchParams.set('status', 'failed');
38
+ url.searchParams.set('pageSize', '50');
39
+ if (cursor)
40
+ url.searchParams.set('cursor', cursor);
41
+ const resp = await fetchImpl(url.toString(), {
42
+ headers: {
43
+ 'x-api-key': apiKey,
44
+ 'x-request-id': `dev-e2e-resolver-page${pagesFetched}-${Date.now()}`,
45
+ accept: 'application/json',
46
+ },
47
+ signal: AbortSignal.timeout(10_000),
48
+ });
49
+ if (!resp.ok) {
50
+ return {
51
+ testId: null,
52
+ reason: `GET /tests returned HTTP ${resp.status}; falling back to static fixture`,
53
+ };
54
+ }
55
+ const body = (await resp.json());
56
+ if (!Array.isArray(body.items)) {
57
+ return {
58
+ testId: null,
59
+ reason: 'GET /tests response missing items array; falling back to static fixture',
60
+ };
61
+ }
62
+ // Only keep frontend+failed items (the query params should filter, but be defensive)
63
+ for (const item of body.items) {
64
+ if (item.type === 'frontend' && item.status === 'failed') {
65
+ candidates.push(item);
66
+ }
67
+ }
68
+ cursor = body.nextToken ?? undefined;
69
+ pagesFetched++;
70
+ } while (cursor && pagesFetched < maxPages);
71
+ }
72
+ catch (err) {
73
+ const message = err instanceof Error ? err.message : String(err);
74
+ return {
75
+ testId: null,
76
+ reason: `GET /tests threw: ${message}; falling back to static fixture`,
77
+ };
78
+ }
79
+ if (candidates.length === 0) {
80
+ return {
81
+ testId: null,
82
+ reason: 'No frontend tests with status=failed found in project; falling back to static fixture',
83
+ };
84
+ }
85
+ // Pick the most recently updated candidate — freshest failure is the
86
+ // most likely to have a valid failure bundle attached.
87
+ candidates.sort((a, b) => {
88
+ const ta = new Date(a.updatedAt).getTime();
89
+ const tb = new Date(b.updatedAt).getTime();
90
+ return tb - ta; // descending: freshest first
91
+ });
92
+ const best = candidates[0];
93
+ if (!best) {
94
+ // Unreachable: the early return above guards candidates.length === 0,
95
+ // but TypeScript requires the narrowing here due to noUncheckedIndexedAccess.
96
+ return { testId: null, reason: 'No candidates after sort (unexpected)' };
97
+ }
98
+ return {
99
+ testId: best.id,
100
+ reason: `Discovered from ${pagesFetched} page(s) of GET /tests; freshest failed test updatedAt=${best.updatedAt}`,
101
+ };
102
+ }
103
+ //# sourceMappingURL=failing-fe-resolver.js.map
@@ -0,0 +1,255 @@
1
+ import type { ErrorCode } from './errors.js';
2
+ import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse } from './runs.types.js';
3
+ export type FetchImpl = typeof globalThis.fetch;
4
+ export type DebugEventKind = 'request' | 'response' | 'retry' | 'error';
5
+ export interface DebugEvent {
6
+ kind: DebugEventKind;
7
+ method: string;
8
+ url: string;
9
+ attempt: number;
10
+ status?: number;
11
+ errorCode?: ErrorCode | 'TRANSPORT';
12
+ durationMs?: number;
13
+ requestId: string;
14
+ delayMs?: number;
15
+ }
16
+ /**
17
+ * Default per-request timeout (120s). Comfortably covers every metadata/read
18
+ * request and every <=25s long-poll request (`?waitSeconds` is capped at 25
19
+ * by the polling layer), while still failing fast on a dead backend.
20
+ *
21
+ * The 15-minute test-execution ceiling is enforced separately by the `--timeout`
22
+ * / polling path (`poll.ts`) which supplies its own `AbortSignal` per iteration.
23
+ * That path is unaffected — each 25s long-poll request still falls well within
24
+ * this 120s per-request guard.
25
+ *
26
+ * Override via `--request-timeout <s>` (flag, in seconds) or
27
+ * `TESTSPRITE_REQUEST_TIMEOUT_MS` (env var, in milliseconds).
28
+ * Precedence: flag > env > default.
29
+ */
30
+ export declare const REQUEST_TIMEOUT_DEFAULT_MS = 120000;
31
+ /**
32
+ * Minimum accepted value: 1 second. Below this the timeout fires before a
33
+ * TLS handshake can complete on a healthy connection.
34
+ */
35
+ export declare const REQUEST_TIMEOUT_MIN_MS = 1000;
36
+ /**
37
+ * Maximum accepted value: 10 minutes. Values above this cap are clamped
38
+ * rather than rejected, so scripts that forward large numbers still work.
39
+ */
40
+ export declare const REQUEST_TIMEOUT_MAX_MS = 600000;
41
+ export interface HttpClientOptions {
42
+ baseUrl: string;
43
+ apiKey?: string;
44
+ fetchImpl?: FetchImpl;
45
+ sleep?: (ms: number) => Promise<void>;
46
+ random?: () => number;
47
+ onDebug?: (event: DebugEvent) => void;
48
+ /**
49
+ * Optional callback for user-relevant state transitions (verbose tier).
50
+ * Emits human-readable messages for HTTP retries, rate-limit backoff,
51
+ * and polling-mode switches without dumping the full debug JSON.
52
+ * Stays silent when absent; wired to stderr at `--verbose` level.
53
+ */
54
+ onTransition?: (msg: string) => void;
55
+ /**
56
+ * Per-request wall-clock timeout in milliseconds applied to every outgoing
57
+ * fetch. The signal fires independently of any caller-supplied signal — the
58
+ * request aborts on whichever fires first.
59
+ *
60
+ * Defaults to {@link REQUEST_TIMEOUT_DEFAULT_MS} (120 000 ms). Override
61
+ * via `--request-timeout <s>` flag or `TESTSPRITE_REQUEST_TIMEOUT_MS` env var.
62
+ *
63
+ * This timeout is intentionally NOT applied to the polling path's own
64
+ * long-poll `AbortSignal` (which is deadline-aware); each 25s long-poll
65
+ * request is well within the 120s default.
66
+ */
67
+ requestTimeoutMs?: number;
68
+ }
69
+ export interface RequestOptions {
70
+ query?: Record<string, string | number | boolean | undefined>;
71
+ signal?: AbortSignal;
72
+ requestId?: string;
73
+ /**
74
+ * Optional JSON body for non-GET requests. Serialized with
75
+ * `JSON.stringify`; `Content-Type: application/json` is auto-attached
76
+ * when present.
77
+ */
78
+ body?: unknown;
79
+ /**
80
+ * Per-request header overrides merged on top of the defaults
81
+ * (`x-api-key`, `x-request-id`, `accept`, `user-agent`). Used for
82
+ * mutation routes that need `Idempotency-Key` / `If-Match`.
83
+ */
84
+ headers?: Record<string, string>;
85
+ /**
86
+ * Whether to retry on 409 CONFLICT.
87
+ *
88
+ * The shared retry policy retries CONFLICT once by default (read paths
89
+ * where 409 = mid-mutation snapshot). Set to `false` for write paths
90
+ * where 409 is a persistent condition (e.g. POST /tests/{testId}/runs
91
+ * when another run is already in flight) — retrying there would enqueue
92
+ * a second run once the first finishes.
93
+ *
94
+ * Defaults to `true` to preserve the original M2 read-path behavior.
95
+ */
96
+ retryOnConflict?: boolean;
97
+ /**
98
+ * Whether the HTTP layer should retry internally on 429 RATE_LIMITED.
99
+ *
100
+ * Set to `false` for the batch-run trigger path where the outer
101
+ * `runBatchRun` loop is the single owner of rate-limit handling —
102
+ * keeping the HTTP layer from adding up to 3 extra retries per outer
103
+ * attempt, which would multiply trigger POSTs per spec (e.g. 50×3 = 150/min)
104
+ * instead of staying within the client throttle's 50/min.
105
+ *
106
+ * Defaults to `true` to preserve backward-compatible behavior for all
107
+ * other callers.
108
+ */
109
+ retryOnRateLimit?: boolean;
110
+ }
111
+ /**
112
+ * Result of a successful HTTP request, including the parsed body and the
113
+ * `x-request-id` that was sent (useful for surfacing in happy-path output).
114
+ */
115
+ export interface RequestResult<T> {
116
+ body: T;
117
+ requestId: string;
118
+ status: number;
119
+ }
120
+ export declare class HttpClient {
121
+ private readonly baseUrl;
122
+ private readonly apiKey?;
123
+ private readonly fetchImpl;
124
+ private readonly sleep;
125
+ private readonly random;
126
+ private readonly onDebug?;
127
+ private readonly onTransition?;
128
+ private readonly requestTimeoutMs;
129
+ constructor(options: HttpClientOptions);
130
+ get<T>(path: string, options?: RequestOptions): Promise<T>;
131
+ post<T>(path: string, options?: RequestOptions): Promise<T>;
132
+ put<T>(path: string, options?: RequestOptions): Promise<T>;
133
+ patch<T>(path: string, options?: RequestOptions): Promise<T>;
134
+ delete<T>(path: string, options?: RequestOptions): Promise<T>;
135
+ /**
136
+ * Like `get` / `post` / etc. but returns the full `RequestResult` including
137
+ * `requestId` and `status`, so callers can surface the requestId in
138
+ * happy-path output (dogfood item 1).
139
+ */
140
+ getWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
141
+ postWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
142
+ putWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
143
+ patchWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
144
+ deleteWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
145
+ /**
146
+ * POST /api/cli/v1/tests/{testId}/runs
147
+ * Trigger a run and return the queued-run envelope.
148
+ * The caller must supply an `idempotencyKey` which is sent as the
149
+ * `Idempotency-Key` header per M3.2 piece-1 §2 contract.
150
+ */
151
+ triggerRun(testId: string, body: TriggerRunBody, options: {
152
+ idempotencyKey: string;
153
+ signal?: AbortSignal;
154
+ }): Promise<TriggerRunResponse>;
155
+ /**
156
+ * Like `triggerRun` but returns the full `RequestResult` so the caller
157
+ * can surface the `requestId` in happy-path CLI output.
158
+ *
159
+ * `retryOnRateLimit` defaults to `true` so single `test run` and
160
+ * `test create --run` retain the standard HTTP-layer 429 retry budget.
161
+ *
162
+ * Pass `retryOnRateLimit: false` ONLY at the batch fan-out call site
163
+ * (`runBatchRun` / `triggerOne`) where the outer loop is the single owner
164
+ * of rate-limit handling — preventing the HTTP layer from adding up to 3
165
+ * extra retries per outer attempt, which would multiply POSTs per spec (e.g. 50×3 = 150/min).
166
+ */
167
+ triggerRunWithMeta(testId: string, body: TriggerRunBody, options: {
168
+ idempotencyKey: string;
169
+ signal?: AbortSignal;
170
+ retryOnRateLimit?: boolean;
171
+ }): Promise<RequestResult<TriggerRunResponse>>;
172
+ /**
173
+ * POST /api/cli/v1/tests/{testId}/runs/rerun
174
+ * Trigger a rerun (replay) for a single test. FE: verbatim script replay (no credits).
175
+ * BE: dependency-closure re-run. Returns `runId` + optional `closure` (BE).
176
+ *
177
+ * `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
178
+ * a persistent condition. Retrying would race against the running test.
179
+ */
180
+ triggerRerun(testId: string, body: RerunRequest, options: {
181
+ idempotencyKey: string;
182
+ signal?: AbortSignal;
183
+ }): Promise<RerunResponse>;
184
+ /**
185
+ * POST /api/cli/v1/tests/batch/rerun
186
+ * Trigger a batch rerun across multiple tests (mixed FE/BE allowed).
187
+ * BE closure is deduped server-side per project.
188
+ *
189
+ * `retryOnConflict: false` — 409 on batch rerun is persistent ("in flight").
190
+ */
191
+ triggerBatchRerun(body: BatchRerunRequest, options: {
192
+ idempotencyKey: string;
193
+ signal?: AbortSignal;
194
+ }): Promise<BatchRerunResponse>;
195
+ /**
196
+ * POST /api/cli/v1/tests/batch/run
197
+ * Trigger a fresh wave-ordered batch run across all (or a subset of) BE tests
198
+ * in a project. FE tests in the set are skipped server-side (advisory).
199
+ * `testIds` absent / empty → run ALL BE tests in the project.
200
+ *
201
+ * `retryOnConflict: false` — 409 on batch run means a run is already in flight.
202
+ */
203
+ triggerBatchRunFresh(body: BatchRunFreshRequest, options: {
204
+ idempotencyKey: string;
205
+ signal?: AbortSignal;
206
+ }): Promise<BatchRunFreshResponse>;
207
+ /**
208
+ * GET /api/cli/v1/tests/{testId}/runs
209
+ * List a test's prior run history, newest-first.
210
+ *
211
+ * Limit-before-filter caveat: a `source`-filtered page may return fewer
212
+ * than `pageSize` rows while still yielding a non-null `nextCursor`.
213
+ * That means "none in THIS window", not end-of-history.
214
+ */
215
+ listTestRuns(testId: string, query: ListRunsQuery): Promise<ListRunsResponse>;
216
+ /**
217
+ * GET /api/cli/v1/runs/{runId}
218
+ * Fetch the current state of a run. When `waitSeconds` is provided
219
+ * (1–25) the server performs a bounded long-poll and returns when the
220
+ * run is terminal or when `waitSeconds` elapses, whichever comes
221
+ * first. On `400 VALIDATION_ERROR` (server doesn't support
222
+ * `waitSeconds`) the caller should retry without the param and switch
223
+ * to client-side backoff — see `src/lib/poll.ts`.
224
+ *
225
+ * When `includeSteps` is `true`, the server appends the full ordered
226
+ * `steps[]` array (M3.4 piece-4). Default (absent/false) is byte-
227
+ * identical to the M3.3 summary shape — the polling path is unaffected.
228
+ */
229
+ getRun(runId: string, options?: {
230
+ waitSeconds?: number;
231
+ includeSteps?: boolean;
232
+ signal?: AbortSignal;
233
+ }): Promise<RunResponse>;
234
+ /**
235
+ * Classify an error thrown while issuing OR reading a request. When it is an
236
+ * abort/timeout and our per-request timeout signal fired (and the caller had
237
+ * not already aborted), surface a clear RequestTimeoutError; when it is a
238
+ * caller-supplied abort (SIGINT, poll-iteration deadline), rethrow it
239
+ * unmodified. Returns normally when `err` is not an abort, so the caller can
240
+ * continue its own error handling (transport retry / envelope parse).
241
+ */
242
+ private rethrowIfAbort;
243
+ requestWithMeta<T>(method: string, path: string, options?: RequestOptions): Promise<RequestResult<T>>;
244
+ private buildHeaders;
245
+ private debug;
246
+ private transition;
247
+ /**
248
+ * Legacy alias kept for backward-compat with test files that call
249
+ * `client.request(...)` directly. New callers should use
250
+ * `requestWithMeta` or the typed helpers (`get`, `post`, etc.).
251
+ */
252
+ request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
253
+ }
254
+ export declare function buildUrl(baseUrl: string, path: string, query?: Record<string, string | number | boolean | undefined>): string;
255
+ export declare function parseRetryAfter(headerValue: string | null): number | undefined;