@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,118 @@
1
+ /**
2
+ * Error codes shared with the backend facade and the MCP plugin.
3
+ * Must stay in sync across all three.
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"];
6
+ export type ErrorCode = (typeof ERROR_CODES)[number];
7
+ export declare function isErrorCode(value: unknown): value is ErrorCode;
8
+ /**
9
+ * Exit-code mapping. INTERNAL maps to 1
10
+ * (generic CLI failure) intentionally — operators triage by `requestId`,
11
+ * not by exit code.
12
+ */
13
+ export declare function exitCodeFor(code: ErrorCode): number;
14
+ export declare class CLIError extends Error {
15
+ readonly exitCode: number;
16
+ constructor(message: string, exitCode?: number);
17
+ }
18
+ export declare class NotImplementedError extends CLIError {
19
+ constructor(commandPath: string);
20
+ }
21
+ export interface ErrorEnvelopeBody {
22
+ code: ErrorCode;
23
+ message: string;
24
+ nextAction: string;
25
+ requestId: string;
26
+ details: Record<string, unknown>;
27
+ }
28
+ export interface ErrorEnvelope {
29
+ error: ErrorEnvelopeBody;
30
+ }
31
+ /**
32
+ * Server-returned API error. The CLI never invents `code`, `nextAction`,
33
+ * or `requestId` — it forwards what the facade returned (or, for
34
+ * locally-detected pre-flight conditions like a missing API key,
35
+ * constructs an envelope with the same shape so the user sees identical
36
+ * wording across paths).
37
+ */
38
+ export declare class ApiError extends CLIError {
39
+ readonly code: ErrorCode;
40
+ readonly requestId: string;
41
+ readonly nextAction: string;
42
+ readonly details: Record<string, unknown>;
43
+ readonly httpStatus: number | undefined;
44
+ /**
45
+ * Parsed `Retry-After` header value in milliseconds, when present on the
46
+ * HTTP response. Only set for `RATE_LIMITED` (429) responses where the
47
+ * server is telling the caller how long to wait. Clamped to `[1s, 300s]`
48
+ * per the outer retry loop contract. `undefined` when the header was
49
+ * absent or unparseable.
50
+ */
51
+ readonly retryAfterMs: number | undefined;
52
+ constructor(envelope: ErrorEnvelopeBody, httpStatus?: number, retryAfterMs?: number);
53
+ /**
54
+ * @param apiUrl Optional API endpoint the failing request targeted. Used to
55
+ * resolve environment-correct portal links in synthesized `nextAction`
56
+ * text (dev and prod portals live on different domains — never hardcode).
57
+ */
58
+ static fromEnvelope(raw: unknown, httpStatus?: number, retryAfterMs?: number, apiUrl?: string): ApiError;
59
+ /**
60
+ * Type-safe accessor for a single key inside `details`. Avoids the
61
+ * `(err.details as { foo?: unknown })?.foo` cast pattern that every
62
+ * 412 / CONFLICT handler had to repeat.
63
+ *
64
+ * @param key The key to read from `details`.
65
+ * @param validator Optional type-guard. When provided, returns
66
+ * `undefined` if the guard rejects the value.
67
+ *
68
+ * @example
69
+ * const ver = err.getDetail<string>(
70
+ * 'currentCodeVersion',
71
+ * (v): v is string => typeof v === 'string',
72
+ * );
73
+ */
74
+ getDetail<T = unknown>(key: string, validator?: (v: unknown) => v is T): T | undefined;
75
+ /**
76
+ * Local fabrication of a missing-key error. Wording matches the server
77
+ * AUTH_REQUIRED template so the user sees the same thing whether the
78
+ * miss was detected before or after sending the request.
79
+ */
80
+ static authRequired(requestId?: string): ApiError;
81
+ }
82
+ /**
83
+ * Fabricate a locally-detected VALIDATION_ERROR envelope using the same
84
+ * shape the backend facade emits, so callers see identical wording whether
85
+ * the error is caught before or after a network round-trip.
86
+ *
87
+ * `kind` controls how `nextAction` is phrased:
88
+ *
89
+ * - `'flag'` (default) — wraps the field name as a CLI flag:
90
+ * `Flag \`--page-size\` is invalid: must be a positive integer.`
91
+ * - `'field'` — uses the bare field path:
92
+ * `Field \`planSteps[0].description\` is invalid: must be a string.`
93
+ *
94
+ * Use `'field'` for JSON-body paths to avoid fabricating a `--fieldName`
95
+ * flag that doesn't exist in the CLI surface.
96
+ */
97
+ export declare function localValidationError(field: string, reason: string, accepted?: unknown, kind?: 'flag' | 'field'): ApiError;
98
+ /**
99
+ * Network/transport failure not associated with a server envelope. Treated
100
+ * as `UNAVAILABLE` for exit-code purposes per design §8.2.
101
+ */
102
+ export declare class TransportError extends ApiError {
103
+ constructor(message: string, requestId?: string);
104
+ }
105
+ /**
106
+ * Client-side per-request timeout. The fetch was aborted because the
107
+ * configurable per-request deadline elapsed before the server responded.
108
+ *
109
+ * Maps to `UNSUPPORTED` for exit-code purposes (exit 7) — the same bucket
110
+ * as `TimeoutError` from the polling path. Use `--request-timeout <s>` or
111
+ * `TESTSPRITE_REQUEST_TIMEOUT_MS` to extend the deadline when targeting a
112
+ * slow backend.
113
+ */
114
+ export declare class RequestTimeoutError extends CLIError {
115
+ readonly requestId: string;
116
+ readonly timeoutMs: number;
117
+ constructor(timeoutMs: number, requestId?: string);
118
+ }
@@ -0,0 +1,388 @@
1
+ import { resolvePortalBase } from './facade.js';
2
+ /**
3
+ * Error codes shared with the backend facade and the MCP plugin.
4
+ * Must stay in sync across all three.
5
+ */
6
+ export const ERROR_CODES = [
7
+ 'AUTH_REQUIRED',
8
+ 'AUTH_INVALID',
9
+ 'AUTH_FORBIDDEN',
10
+ 'NOT_FOUND',
11
+ 'VALIDATION_ERROR',
12
+ // M3.2 piece-2 — inline `code` body cap (350 KB) exceeded. Exit 5
13
+ // (validation family) — the request is well-formed but oversized;
14
+ // `nextAction` points the operator at the Portal upload flow.
15
+ 'PAYLOAD_TOO_LARGE',
16
+ 'CONFLICT',
17
+ // M3.2 piece-1 / piece-4 — `If-Match: <codeVersion>` etag mismatch on
18
+ // `test code put`. Exit 6, same family as CONFLICT (the caller should
19
+ // re-fetch and retry); kept distinct so machine consumers can route on
20
+ // it without parsing message strings.
21
+ 'PRECONDITION_FAILED',
22
+ // M3.2 piece-1 — `Idempotency-Key` reused with a different request
23
+ // body. Exit 6; distinct from CONFLICT (snapshot-in-flight) so
24
+ // automation can tell "you mutated the body between retries" from
25
+ // "a Portal write is in flight."
26
+ 'IDEMPOTENCY_BODY_MISMATCH',
27
+ 'RATE_LIMITED',
28
+ // Client-side re-map of the credits sub-case of a RATE_LIMITED envelope.
29
+ // Detected when the backend returns RATE_LIMITED (HTTP 429) with a
30
+ // message matching /insufficient credits/i or details.required present.
31
+ // Exit 12: non-retriable — out-of-credits cannot self-heal with retries.
32
+ // The genuine per-minute throttle, 60/min/key ("Run trigger rate limit exceeded")
33
+ // retains code RATE_LIMITED / exit 11 / retriable.
34
+ // Note: backend will emit a distinct code in a future release; this is
35
+ // CLI-side detection only, bridging the gap.
36
+ 'INSUFFICIENT_CREDITS',
37
+ // Client-side code for plan-gated features that the server silently downgrades
38
+ // rather than emitting a 4xx. Used when the CLI detects a paid-tier feature was
39
+ // requested but the response shows it was not applied (e.g. autoHeal: false when
40
+ // autoHeal: true was sent on a Free key). This is NOT thrown as an error by
41
+ // default (the command still succeeds with verbatim replay) — it is used by
42
+ // callers that want to programmatically detect plan-downgrade events.
43
+ // Exit code: 13 (non-retriable). Backend follow-up: emit natively from the server
44
+ // so the CLI can drop the client-side detection heuristic.
45
+ 'FEATURE_GATED',
46
+ 'UNSUPPORTED',
47
+ 'INTERNAL',
48
+ 'UNAVAILABLE',
49
+ ];
50
+ export function isErrorCode(value) {
51
+ return typeof value === 'string' && ERROR_CODES.includes(value);
52
+ }
53
+ /**
54
+ * Exit-code mapping. INTERNAL maps to 1
55
+ * (generic CLI failure) intentionally — operators triage by `requestId`,
56
+ * not by exit code.
57
+ */
58
+ export function exitCodeFor(code) {
59
+ switch (code) {
60
+ case 'AUTH_REQUIRED':
61
+ case 'AUTH_INVALID':
62
+ case 'AUTH_FORBIDDEN':
63
+ return 3;
64
+ case 'NOT_FOUND':
65
+ return 4;
66
+ case 'VALIDATION_ERROR':
67
+ case 'PAYLOAD_TOO_LARGE':
68
+ return 5;
69
+ case 'CONFLICT':
70
+ case 'PRECONDITION_FAILED':
71
+ case 'IDEMPOTENCY_BODY_MISMATCH':
72
+ return 6;
73
+ case 'UNSUPPORTED':
74
+ return 7;
75
+ case 'UNAVAILABLE':
76
+ return 10;
77
+ case 'RATE_LIMITED':
78
+ return 11;
79
+ case 'INSUFFICIENT_CREDITS':
80
+ return 12;
81
+ case 'FEATURE_GATED':
82
+ return 13;
83
+ case 'INTERNAL':
84
+ return 1;
85
+ }
86
+ }
87
+ export class CLIError extends Error {
88
+ exitCode;
89
+ constructor(message, exitCode = 1) {
90
+ super(message);
91
+ this.name = 'CLIError';
92
+ this.exitCode = exitCode;
93
+ }
94
+ }
95
+ export class NotImplementedError extends CLIError {
96
+ constructor(commandPath) {
97
+ super(`Command not yet implemented: ${commandPath}`, 2);
98
+ this.name = 'NotImplementedError';
99
+ }
100
+ }
101
+ /**
102
+ * Server-returned API error. The CLI never invents `code`, `nextAction`,
103
+ * or `requestId` — it forwards what the facade returned (or, for
104
+ * locally-detected pre-flight conditions like a missing API key,
105
+ * constructs an envelope with the same shape so the user sees identical
106
+ * wording across paths).
107
+ */
108
+ export class ApiError extends CLIError {
109
+ code;
110
+ requestId;
111
+ nextAction;
112
+ details;
113
+ httpStatus;
114
+ /**
115
+ * Parsed `Retry-After` header value in milliseconds, when present on the
116
+ * HTTP response. Only set for `RATE_LIMITED` (429) responses where the
117
+ * server is telling the caller how long to wait. Clamped to `[1s, 300s]`
118
+ * per the outer retry loop contract. `undefined` when the header was
119
+ * absent or unparseable.
120
+ */
121
+ retryAfterMs;
122
+ constructor(envelope, httpStatus, retryAfterMs) {
123
+ super(envelope.message, exitCodeFor(envelope.code));
124
+ this.name = 'ApiError';
125
+ this.code = envelope.code;
126
+ this.requestId = envelope.requestId;
127
+ this.nextAction = envelope.nextAction;
128
+ this.details = envelope.details;
129
+ this.httpStatus = httpStatus;
130
+ this.retryAfterMs = retryAfterMs;
131
+ }
132
+ /**
133
+ * @param apiUrl Optional API endpoint the failing request targeted. Used to
134
+ * resolve environment-correct portal links in synthesized `nextAction`
135
+ * text (dev and prod portals live on different domains — never hardcode).
136
+ */
137
+ static fromEnvelope(raw, httpStatus, retryAfterMs, apiUrl) {
138
+ const envelope = parseEnvelopeBody(raw, httpStatus, apiUrl);
139
+ return new ApiError(envelope, httpStatus, retryAfterMs);
140
+ }
141
+ /**
142
+ * Type-safe accessor for a single key inside `details`. Avoids the
143
+ * `(err.details as { foo?: unknown })?.foo` cast pattern that every
144
+ * 412 / CONFLICT handler had to repeat.
145
+ *
146
+ * @param key The key to read from `details`.
147
+ * @param validator Optional type-guard. When provided, returns
148
+ * `undefined` if the guard rejects the value.
149
+ *
150
+ * @example
151
+ * const ver = err.getDetail<string>(
152
+ * 'currentCodeVersion',
153
+ * (v): v is string => typeof v === 'string',
154
+ * );
155
+ */
156
+ getDetail(key, validator) {
157
+ const details = this.details;
158
+ if (details === undefined || details === null || typeof details !== 'object') {
159
+ return undefined;
160
+ }
161
+ const value = details[key];
162
+ if (value === undefined)
163
+ return undefined;
164
+ if (validator && !validator(value))
165
+ return undefined;
166
+ return value;
167
+ }
168
+ /**
169
+ * Local fabrication of a missing-key error. Wording matches the server
170
+ * AUTH_REQUIRED template so the user sees the same thing whether the
171
+ * miss was detected before or after sending the request.
172
+ */
173
+ static authRequired(requestId = 'local') {
174
+ return new ApiError({
175
+ code: 'AUTH_REQUIRED',
176
+ message: 'Authentication is required.',
177
+ nextAction: 'Run `testsprite auth configure` (interactive — prompts for your API key),' +
178
+ ' or set TESTSPRITE_API_KEY and run `testsprite auth configure --from-env` for non-interactive flows.',
179
+ requestId,
180
+ details: {},
181
+ });
182
+ }
183
+ }
184
+ /**
185
+ * Fabricate a locally-detected VALIDATION_ERROR envelope using the same
186
+ * shape the backend facade emits, so callers see identical wording whether
187
+ * the error is caught before or after a network round-trip.
188
+ *
189
+ * `kind` controls how `nextAction` is phrased:
190
+ *
191
+ * - `'flag'` (default) — wraps the field name as a CLI flag:
192
+ * `Flag \`--page-size\` is invalid: must be a positive integer.`
193
+ * - `'field'` — uses the bare field path:
194
+ * `Field \`planSteps[0].description\` is invalid: must be a string.`
195
+ *
196
+ * Use `'field'` for JSON-body paths to avoid fabricating a `--fieldName`
197
+ * flag that doesn't exist in the CLI surface.
198
+ */
199
+ export function localValidationError(field, reason, accepted, kind = 'flag') {
200
+ const subject = kind === 'flag'
201
+ ? `Flag \`--${field.replace(/[A-Z]/g, ch => `-${ch.toLowerCase()}`)}\``
202
+ : `Field \`${field}\``;
203
+ return ApiError.fromEnvelope({
204
+ error: {
205
+ code: 'VALIDATION_ERROR',
206
+ message: 'Invalid request.',
207
+ nextAction: `${subject} is invalid: ${reason}.`,
208
+ requestId: 'local',
209
+ details: accepted === undefined ? { field, reason } : { field, reason, accepted },
210
+ },
211
+ });
212
+ }
213
+ /**
214
+ * Network/transport failure not associated with a server envelope. Treated
215
+ * as `UNAVAILABLE` for exit-code purposes per design §8.2.
216
+ */
217
+ export class TransportError extends ApiError {
218
+ constructor(message, requestId = 'local') {
219
+ super({
220
+ code: 'UNAVAILABLE',
221
+ message,
222
+ nextAction: 'Service is temporarily unavailable. The CLI retries with exponential backoff; if this persists, report it.',
223
+ requestId,
224
+ details: {},
225
+ });
226
+ this.name = 'TransportError';
227
+ }
228
+ }
229
+ /**
230
+ * Client-side per-request timeout. The fetch was aborted because the
231
+ * configurable per-request deadline elapsed before the server responded.
232
+ *
233
+ * Maps to `UNSUPPORTED` for exit-code purposes (exit 7) — the same bucket
234
+ * as `TimeoutError` from the polling path. Use `--request-timeout <s>` or
235
+ * `TESTSPRITE_REQUEST_TIMEOUT_MS` to extend the deadline when targeting a
236
+ * slow backend.
237
+ */
238
+ export class RequestTimeoutError extends CLIError {
239
+ requestId;
240
+ timeoutMs;
241
+ constructor(timeoutMs, requestId = 'local') {
242
+ const timeoutSec = Math.round(timeoutMs / 1000);
243
+ super(`Request timed out after ${timeoutSec}s (client-side). ` +
244
+ `Use --request-timeout <seconds> or TESTSPRITE_REQUEST_TIMEOUT_MS to extend the deadline.`, 7);
245
+ this.name = 'RequestTimeoutError';
246
+ this.requestId = requestId;
247
+ this.timeoutMs = timeoutMs;
248
+ }
249
+ }
250
+ /**
251
+ * Every facade-emitted HTTP status maps to a
252
+ * known error code. When the envelope is missing or its `code` field is
253
+ * unrecognized (proxy returned an empty body, content was mangled), we fall
254
+ * back to the status-derived code so the retry budget and exit code match
255
+ * what the contract promises.
256
+ */
257
+ function codeFromHttpStatus(status) {
258
+ switch (status) {
259
+ case 400:
260
+ return 'VALIDATION_ERROR';
261
+ case 401:
262
+ return 'AUTH_INVALID';
263
+ case 403:
264
+ return 'AUTH_FORBIDDEN';
265
+ case 404:
266
+ return 'NOT_FOUND';
267
+ case 409:
268
+ return 'CONFLICT';
269
+ case 412:
270
+ return 'PRECONDITION_FAILED';
271
+ case 413:
272
+ return 'PAYLOAD_TOO_LARGE';
273
+ case 429:
274
+ return 'RATE_LIMITED';
275
+ case 501:
276
+ return 'UNSUPPORTED';
277
+ case 503:
278
+ return 'UNAVAILABLE';
279
+ default:
280
+ return 'INTERNAL';
281
+ }
282
+ }
283
+ /**
284
+ * Detect the "insufficient credits" sub-case of a RATE_LIMITED (429) envelope.
285
+ *
286
+ * Detection signals (require at least one strong signal):
287
+ * 1. `details.required` is present (a number > 0) — the credit cost field
288
+ * that the backend attaches only to the credits error, not to throttle.
289
+ * 2. `message` matches /insufficient credits/i — the backend's stable
290
+ * template for this error.
291
+ *
292
+ * The genuine per-minute throttle has message "Run trigger rate limit exceeded: …"
293
+ * and no `details.required`, so it cannot match either signal.
294
+ *
295
+ * This is a CLIENT-SIDE detection bridge. The backend will emit a distinct
296
+ * `INSUFFICIENT_CREDITS` code in a future release at which point this
297
+ * function becomes unreachable for new backends.
298
+ */
299
+ function isInsufficientCredits(rawCode, message, details) {
300
+ if (rawCode !== 'RATE_LIMITED')
301
+ return false;
302
+ const hasRequiredField = typeof details.required === 'number' && details.required > 0;
303
+ const hasCreditsMessage = /insufficient credits/i.test(message);
304
+ return hasRequiredField || hasCreditsMessage;
305
+ }
306
+ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
307
+ if (typeof raw !== 'object' || raw === null) {
308
+ const fallbackCode = codeFromHttpStatus(httpStatus);
309
+ return {
310
+ code: fallbackCode,
311
+ message: fallbackCode === 'INTERNAL'
312
+ ? 'Server returned a malformed error response.'
313
+ : `Server returned ${httpStatus} without an error envelope.`,
314
+ nextAction: fallbackCode === 'INTERNAL'
315
+ ? 'Server error. Retry once; if it persists, report the `requestId` to support@testsprite.com.'
316
+ : '',
317
+ requestId: 'unknown',
318
+ details: {},
319
+ };
320
+ }
321
+ const obj = raw;
322
+ // Raw Nest/Express 404 shape: `{ message, error: "Not Found", statusCode }`.
323
+ // The current parser was matching `obj.error` (a string) and falling to
324
+ // `Server error.` while losing the actual `message` from the body
325
+ // (e.g. `Cannot POST /api/cli/v1/tests/{id}/runs`). Detect this shape
326
+ // explicitly so the user sees something actionable like
327
+ // "endpoint not deployed" instead of the generic CLI failure text.
328
+ if (typeof obj.error === 'string' && typeof obj.message === 'string') {
329
+ const message = obj.message;
330
+ const cannotMethod = /^Cannot (GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) /.exec(message);
331
+ const isRouteMissing404 = (httpStatus === 404 || obj.statusCode === 404) && !!cannotMethod;
332
+ return {
333
+ code: codeFromHttpStatus(httpStatus),
334
+ message: isRouteMissing404
335
+ ? `${message} — endpoint not available on the current backend deployment.`
336
+ : message,
337
+ nextAction: isRouteMissing404
338
+ ? 'Verify the CLI is targeting the right environment (check `testsprite auth whoami` for `env`), and confirm the backend has the corresponding M3.3 piece deployed.'
339
+ : '',
340
+ requestId: 'unknown',
341
+ details: { statusCode: obj.statusCode },
342
+ };
343
+ }
344
+ const errorObj = (obj.error ?? obj);
345
+ const rawCode = isErrorCode(errorObj.code) ? errorObj.code : codeFromHttpStatus(httpStatus);
346
+ const message = typeof errorObj.message === 'string' ? errorObj.message : 'Server error.';
347
+ const details = typeof errorObj.details === 'object' && errorObj.details !== null
348
+ ? errorObj.details
349
+ : {};
350
+ const nextAction = typeof errorObj.nextAction === 'string' ? errorObj.nextAction : '';
351
+ const requestId = typeof errorObj.requestId === 'string' ? errorObj.requestId : 'unknown';
352
+ // Client-side re-map: RATE_LIMITED with credits signal -> INSUFFICIENT_CREDITS.
353
+ // This makes the code non-retriable and sets exit 12 before the retry
354
+ // decision in http.ts sees it, so BOTH retry and exit-code paths are correct.
355
+ // A nextAction pointing to the billing page is synthesized when the backend
356
+ // didn't supply one (older backend versions).
357
+ if (isInsufficientCredits(rawCode, message, details)) {
358
+ // Synthesize a nextAction when the backend did not supply one, or when
359
+ // the backend-supplied nextAction lacks the CLI pre-flight hint.
360
+ // The `testsprite usage` command is the CLI-native way to check balance
361
+ // before a large run fan-out (dogfood L1868 + L1890).
362
+ // Portal links resolve per environment from the API endpoint (dev and
363
+ // prod portals live on different domains); unknown hosts get the route
364
+ // only — a hardcoded domain would point at the wrong environment.
365
+ const portalBase = apiUrl === undefined ? undefined : resolvePortalBase(apiUrl);
366
+ const billingNextAction = nextAction !== ''
367
+ ? nextAction
368
+ : (portalBase !== undefined
369
+ ? `Top up your credits at ${portalBase}/dashboard/settings/billing or upgrade your plan at ${portalBase}/pricing.`
370
+ : 'Top up your credits on the portal Billing page (/dashboard/settings/billing) or upgrade your plan (/pricing).') +
371
+ ' Run `testsprite usage` to check your current balance before the next run.';
372
+ return {
373
+ code: 'INSUFFICIENT_CREDITS',
374
+ message,
375
+ nextAction: billingNextAction,
376
+ requestId,
377
+ details,
378
+ };
379
+ }
380
+ return {
381
+ code: rawCode,
382
+ message,
383
+ nextAction,
384
+ requestId,
385
+ details,
386
+ };
387
+ }
388
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The CLI talks to a single facade rooted under `/api/cli/v1`. Users
3
+ * configure the endpoint as a host (e.g., `https://api.testsprite.com`);
4
+ * the CLI prepends the facade path internally so we never store the path
5
+ * in the credentials file.
6
+ */
7
+ export declare const FACADE_PATH = "/api/cli/v1";
8
+ export declare function facadeBaseUrl(endpointUrl: string): string;
9
+ /**
10
+ * Resolve the Portal dashboard deep-link for a test, given the API endpoint URL
11
+ * already known to the CLI (from the user's credential profile).
12
+ *
13
+ * Coverage rule: only emit a dashboardUrl where BOTH projectId AND testId are
14
+ * already known client-side from the create/run response — no extra network calls.
15
+ * Currently covered commands:
16
+ * - `test create` / `test create-batch` (projectId from opts/spec — or, on the
17
+ * `--plan-from` path, from the validated plan body; testId from response).
18
+ * - `test run --wait`, `test wait`, `test rerun --wait` terminal output —
19
+ * `GET /runs/{runId}` carries both projectId and testId on the wire.
20
+ * - `test run --all` accepted items (projectId from opts, testId per item).
21
+ * NOT covered (wire gap, no lookup round-trip allowed): no-wait `test run` /
22
+ * `test rerun` trigger output (TriggerRunResponse lacks projectId) and
23
+ * `test result` (CliLatestResult lacks projectId).
24
+ *
25
+ * Normalization uses `new URL()` semantics (R2):
26
+ * - Protocol and hostname are lowercased.
27
+ * - An explicit `:443` on https is treated as the default port (omitted).
28
+ * - Trailing slashes and FACADE_PATH suffix are stripped before parsing.
29
+ * - URL parse failures → undefined (no crash).
30
+ *
31
+ * Mapping (match on normalized protocol, hostname, and port):
32
+ * TESTSPRITE_PORTAL_URL env var set → that origin verbatim (highest
33
+ * precedence; an invalid or non-http(s) value → undefined, so a typo
34
+ * never produces a wrong-environment link)
35
+ * https://api.testsprite.com (port absent or 443) → https://www.testsprite.com
36
+ * anything else (unknown host, non-https on prod, parse failure) → undefined
37
+ *
38
+ * Deep-link path: {portalBase}/dashboard/tests/{projectId}/test/{testId}
39
+ */
40
+ export declare function resolvePortalUrl(apiUrl: string, projectId: string, testId: string): string | undefined;
41
+ /**
42
+ * Map the configured API endpoint to the matching Portal origin (no path).
43
+ * Honors the TESTSPRITE_PORTAL_URL override first; otherwise same
44
+ * normalization and host mapping as `resolvePortalUrl` (which delegates
45
+ * here); returns undefined for unknown hosts so callers emit nothing rather
46
+ * than a wrong-environment link.
47
+ */
48
+ export declare function resolvePortalBase(apiUrl: string): string | undefined;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The CLI talks to a single facade rooted under `/api/cli/v1`. Users
3
+ * configure the endpoint as a host (e.g., `https://api.testsprite.com`);
4
+ * the CLI prepends the facade path internally so we never store the path
5
+ * in the credentials file.
6
+ */
7
+ export const FACADE_PATH = '/api/cli/v1';
8
+ export function facadeBaseUrl(endpointUrl) {
9
+ const trimmed = endpointUrl.endsWith('/') ? endpointUrl.slice(0, -1) : endpointUrl;
10
+ if (trimmed.endsWith(FACADE_PATH))
11
+ return trimmed;
12
+ return `${trimmed}${FACADE_PATH}`;
13
+ }
14
+ /**
15
+ * Resolve the Portal dashboard deep-link for a test, given the API endpoint URL
16
+ * already known to the CLI (from the user's credential profile).
17
+ *
18
+ * Coverage rule: only emit a dashboardUrl where BOTH projectId AND testId are
19
+ * already known client-side from the create/run response — no extra network calls.
20
+ * Currently covered commands:
21
+ * - `test create` / `test create-batch` (projectId from opts/spec — or, on the
22
+ * `--plan-from` path, from the validated plan body; testId from response).
23
+ * - `test run --wait`, `test wait`, `test rerun --wait` terminal output —
24
+ * `GET /runs/{runId}` carries both projectId and testId on the wire.
25
+ * - `test run --all` accepted items (projectId from opts, testId per item).
26
+ * NOT covered (wire gap, no lookup round-trip allowed): no-wait `test run` /
27
+ * `test rerun` trigger output (TriggerRunResponse lacks projectId) and
28
+ * `test result` (CliLatestResult lacks projectId).
29
+ *
30
+ * Normalization uses `new URL()` semantics (R2):
31
+ * - Protocol and hostname are lowercased.
32
+ * - An explicit `:443` on https is treated as the default port (omitted).
33
+ * - Trailing slashes and FACADE_PATH suffix are stripped before parsing.
34
+ * - URL parse failures → undefined (no crash).
35
+ *
36
+ * Mapping (match on normalized protocol, hostname, and port):
37
+ * TESTSPRITE_PORTAL_URL env var set → that origin verbatim (highest
38
+ * precedence; an invalid or non-http(s) value → undefined, so a typo
39
+ * never produces a wrong-environment link)
40
+ * https://api.testsprite.com (port absent or 443) → https://www.testsprite.com
41
+ * anything else (unknown host, non-https on prod, parse failure) → undefined
42
+ *
43
+ * Deep-link path: {portalBase}/dashboard/tests/{projectId}/test/{testId}
44
+ */
45
+ export function resolvePortalUrl(apiUrl, projectId, testId) {
46
+ const portalBase = resolvePortalBase(apiUrl);
47
+ if (portalBase === undefined)
48
+ return undefined;
49
+ // R4: encode path segments so future opaque ids (e.g. containing '#' or '?')
50
+ // produce a valid URL without breaking the path structure.
51
+ return `${portalBase}/dashboard/tests/${encodeURIComponent(projectId)}/test/${encodeURIComponent(testId)}`;
52
+ }
53
+ /**
54
+ * Map the configured API endpoint to the matching Portal origin (no path).
55
+ * Honors the TESTSPRITE_PORTAL_URL override first; otherwise same
56
+ * normalization and host mapping as `resolvePortalUrl` (which delegates
57
+ * here); returns undefined for unknown hosts so callers emit nothing rather
58
+ * than a wrong-environment link.
59
+ */
60
+ export function resolvePortalBase(apiUrl) {
61
+ // Operator override: lets any non-prod environment point dashboard links at
62
+ // its own Portal without a code mapping. Set-but-invalid → undefined: when
63
+ // the caller explicitly chose an origin, falling back to the host mapping
64
+ // could emit a wrong-environment link, which is worse than none.
65
+ const override = process.env.TESTSPRITE_PORTAL_URL?.trim();
66
+ if (override !== undefined && override !== '') {
67
+ try {
68
+ const parsedOverride = new URL(override);
69
+ if (parsedOverride.protocol === 'https:' || parsedOverride.protocol === 'http:') {
70
+ return override.endsWith('/') ? override.slice(0, -1) : override;
71
+ }
72
+ }
73
+ catch {
74
+ // fall through to undefined below
75
+ }
76
+ return undefined;
77
+ }
78
+ // Strip trailing slash, then strip FACADE_PATH suffix if present so callers
79
+ // can pass either the raw apiUrl or the result of facadeBaseUrl().
80
+ let raw = apiUrl.endsWith('/') ? apiUrl.slice(0, -1) : apiUrl;
81
+ if (raw.endsWith(FACADE_PATH)) {
82
+ raw = raw.slice(0, -FACADE_PATH.length);
83
+ }
84
+ // Parse with URL() for case-normalisation and port canonicalisation.
85
+ let parsed;
86
+ try {
87
+ parsed = new URL(raw);
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ const protocol = parsed.protocol; // already lowercase, ends with ':'
93
+ const hostname = parsed.hostname.toLowerCase();
94
+ // `URL.port` is '' when the port is the scheme default (443 for https,
95
+ // 80 for http). An explicit ':443' on an https URL normalises to ''.
96
+ const port = parsed.port;
97
+ if (protocol === 'https:' &&
98
+ hostname === 'api.testsprite.com' &&
99
+ (port === '' || port === '443')) {
100
+ return 'https://www.testsprite.com';
101
+ }
102
+ return undefined;
103
+ }
104
+ //# sourceMappingURL=facade.js.map