@testsprite/testsprite-cli 0.1.2 → 0.3.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 (58) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +52 -0
  3. package/dist/commands/agent.js +341 -93
  4. package/dist/commands/auth.js +29 -27
  5. package/dist/commands/doctor.d.ts +49 -0
  6. package/dist/commands/doctor.js +211 -0
  7. package/dist/commands/init.d.ts +7 -1
  8. package/dist/commands/init.js +66 -26
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +257 -43
  11. package/dist/commands/test.d.ts +214 -12
  12. package/dist/commands/test.js +1310 -174
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +71 -18
  15. package/dist/lib/agent-targets.d.ts +169 -22
  16. package/dist/lib/agent-targets.js +335 -34
  17. package/dist/lib/bundle.d.ts +51 -1
  18. package/dist/lib/bundle.js +146 -55
  19. package/dist/lib/client-factory.d.ts +43 -0
  20. package/dist/lib/client-factory.js +89 -2
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.d.ts +7 -0
  24. package/dist/lib/credentials.js +40 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +54 -9
  27. package/dist/lib/flaky.d.ts +80 -0
  28. package/dist/lib/flaky.js +76 -0
  29. package/dist/lib/http.d.ts +20 -0
  30. package/dist/lib/http.js +216 -132
  31. package/dist/lib/interrupt.d.ts +61 -0
  32. package/dist/lib/interrupt.js +97 -0
  33. package/dist/lib/junit-report.d.ts +58 -0
  34. package/dist/lib/junit-report.js +210 -0
  35. package/dist/lib/output.d.ts +16 -1
  36. package/dist/lib/output.js +24 -2
  37. package/dist/lib/pagination.d.ts +4 -3
  38. package/dist/lib/pagination.js +34 -6
  39. package/dist/lib/prompt.js +52 -8
  40. package/dist/lib/proxy.d.ts +29 -0
  41. package/dist/lib/proxy.js +30 -0
  42. package/dist/lib/render-error.d.ts +13 -0
  43. package/dist/lib/render-error.js +30 -7
  44. package/dist/lib/skill-nudge.d.ts +2 -2
  45. package/dist/lib/skill-nudge.js +13 -4
  46. package/dist/lib/target-url.js +8 -1
  47. package/dist/lib/ticker.d.ts +11 -1
  48. package/dist/lib/ticker.js +33 -1
  49. package/dist/lib/update-check.d.ts +67 -0
  50. package/dist/lib/update-check.js +246 -0
  51. package/dist/version-guard.d.ts +33 -0
  52. package/dist/version-guard.js +39 -0
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/package.json +3 -2
  56. package/skills/testsprite-onboard.skill.md +183 -0
  57. package/skills/testsprite-verify.codex.md +2 -0
  58. package/skills/testsprite-verify.skill.md +52 -1
package/dist/lib/http.js CHANGED
@@ -234,9 +234,13 @@ export class HttpClient {
234
234
  * unmodified. Returns normally when `err` is not an abort, so the caller can
235
235
  * continue its own error handling (transport retry / envelope parse).
236
236
  */
237
- rethrowIfAbort(err, timeoutSignal, callerSignal, requestId) {
237
+ rethrowIfAbort(err, timeoutSignal, callerSignal, requestId, effectiveSignal = timeoutSignal) {
238
238
  if (isAbortError(err) || isTimeoutError(err)) {
239
- if (timeoutSignal.aborted && (callerSignal == null || !callerSignal.aborted)) {
239
+ const timeoutWon = timeoutSignal.aborted &&
240
+ (callerSignal == null ||
241
+ !callerSignal.aborted ||
242
+ effectiveSignal.reason === timeoutSignal.reason);
243
+ if (timeoutWon) {
240
244
  throw new RequestTimeoutError(this.requestTimeoutMs, requestId);
241
245
  }
242
246
  throw err;
@@ -260,164 +264,181 @@ export class HttpClient {
260
264
  // signal. The polling path supplies its own deadline-aware signal per
261
265
  // iteration — this timeout (120s default) is safely larger than any single
262
266
  // long-poll window (<=25s via ?waitSeconds), so it never bites polling.
263
- const timeoutSignal = AbortSignal.timeout(this.requestTimeoutMs);
267
+ const requestTimeout = createRequestTimeout(this.requestTimeoutMs);
268
+ const timeoutSignal = requestTimeout.signal;
264
269
  const effectiveSignal = options.signal != null ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
265
270
  try {
266
- response = await this.fetchImpl(url, {
267
- method,
268
- headers: this.buildHeaders(requestId, options),
269
- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
270
- signal: effectiveSignal,
271
- });
272
- }
273
- catch (err) {
274
- // Distinguish a client-side request timeout from a caller-supplied abort.
275
- //
276
- // Node 22 `AbortSignal.timeout()` throws a `DOMException` with
277
- // `name === 'TimeoutError'` (not 'AbortError') when the signal fires.
278
- // A caller-supplied abort sets `name === 'AbortError'`.
279
- // We treat both abort variants together: if the timeout signal fired and
280
- // the caller hadn't already aborted, surface a clear RequestTimeoutError.
281
- // A timeout/abort during the fetch itself: classify it (RequestTimeoutError
282
- // when our deadline fired; otherwise rethrow the caller's abort unmodified).
283
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
284
- // If a RequestTimeoutError already propagated from somewhere (e.g. from a
285
- // nested call or from a test-injected fetchImpl), pass it through unchanged
286
- // rather than re-wrapping it as a TransportError.
287
- if (err instanceof RequestTimeoutError)
288
- throw err;
289
- const message = err instanceof Error ? err.message : String(err);
290
- this.debug({
291
- kind: 'error',
292
- method,
293
- url,
294
- attempt,
295
- requestId,
296
- errorCode: 'TRANSPORT',
297
- durationMs: Date.now() - startedAt,
298
- });
299
- const decision = transportRetryDecision(attempt, this.random);
300
- if (!decision.retry)
301
- throw new TransportError(message, requestId);
302
- this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
303
- this.debug({
304
- kind: 'retry',
305
- method,
306
- url,
307
- attempt,
308
- requestId,
309
- errorCode: 'TRANSPORT',
310
- delayMs: decision.delayMs,
311
- });
312
- await this.sleep(decision.delayMs);
313
- continue;
314
- }
315
- const durationMs = Date.now() - startedAt;
316
- if (response.ok) {
317
- this.debug({
318
- kind: 'response',
319
- method,
320
- url,
321
- attempt,
322
- status: response.status,
323
- requestId,
324
- durationMs,
325
- });
326
271
  try {
327
- return { body: (await response.json()), requestId, status: response.status };
272
+ response = await this.fetchImpl(url, {
273
+ method,
274
+ headers: this.buildHeaders(requestId, options),
275
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
276
+ signal: effectiveSignal,
277
+ });
278
+ }
279
+ catch (err) {
280
+ // Distinguish a client-side request timeout from a caller-supplied abort.
281
+ //
282
+ // The request-timeout controller aborts with an Error/DOMException whose
283
+ // `name === 'TimeoutError'` (not 'AbortError') when the signal fires.
284
+ // A caller-supplied abort sets `name === 'AbortError'`.
285
+ // We treat both abort variants together: if the timeout signal fired and
286
+ // the caller hadn't already aborted, surface a clear RequestTimeoutError.
287
+ // A timeout/abort during the fetch itself: classify it (RequestTimeoutError
288
+ // when our deadline fired; otherwise rethrow the caller's abort unmodified).
289
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
290
+ // If a RequestTimeoutError already propagated from somewhere (e.g. from a
291
+ // nested call or from a test-injected fetchImpl), pass it through unchanged
292
+ // rather than re-wrapping it as a TransportError.
293
+ if (err instanceof RequestTimeoutError)
294
+ throw err;
295
+ const message = err instanceof Error ? err.message : String(err);
296
+ this.debug({
297
+ kind: 'error',
298
+ method,
299
+ url,
300
+ attempt,
301
+ requestId,
302
+ errorCode: 'TRANSPORT',
303
+ durationMs: Date.now() - startedAt,
304
+ });
305
+ const decision = transportRetryDecision(attempt, this.random);
306
+ if (!decision.retry)
307
+ throw new TransportError(message, requestId);
308
+ this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
309
+ this.debug({
310
+ kind: 'retry',
311
+ method,
312
+ url,
313
+ attempt,
314
+ requestId,
315
+ errorCode: 'TRANSPORT',
316
+ delayMs: decision.delayMs,
317
+ });
318
+ requestTimeout.clear();
319
+ await this.sleep(decision.delayMs);
320
+ continue;
321
+ }
322
+ const durationMs = Date.now() - startedAt;
323
+ if (response.ok) {
324
+ this.debug({
325
+ kind: 'response',
326
+ method,
327
+ url,
328
+ attempt,
329
+ status: response.status,
330
+ requestId,
331
+ durationMs,
332
+ });
333
+ try {
334
+ return { body: (await response.json()), requestId, status: response.status };
335
+ }
336
+ catch (err) {
337
+ // A timeout/abort can fire mid-body-read (headers received, stream stalls).
338
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
339
+ // Otherwise the successful response body was not valid JSON — a
340
+ // misconfigured endpoint, a proxy / captive-portal / login page that
341
+ // returns HTML with a 200 status, or an empty body. Surface a typed
342
+ // error carrying the requestId instead of letting the raw SyntaxError
343
+ // escape to index.ts, where it would print a bare `{"error":"..."}`
344
+ // and break the --output json envelope contract.
345
+ throw malformedResponseError(response, requestId, err);
346
+ }
347
+ }
348
+ let rawBody;
349
+ try {
350
+ rawBody = await safeReadJson(response);
328
351
  }
329
352
  catch (err) {
330
- // A timeout/abort can fire mid-body-read (headers received, stream stalls).
331
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
353
+ // safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
354
+ // errors), so a timeout fired mid-body-read on a non-OK response lands here.
355
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
332
356
  throw err;
333
357
  }
334
- }
335
- let rawBody;
336
- try {
337
- rawBody = await safeReadJson(response);
338
- }
339
- catch (err) {
340
- // safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
341
- // errors), so a timeout fired mid-body-read on a non-OK response lands here.
342
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
343
- throw err;
344
- }
345
- // Edge proxies / load balancers return 408/502/504 without our error
346
- // envelope on transient outages. Per the CLI error spec §7 these are
347
- // transport-level retries, not facade errors — fold them in here so
348
- // we get the bounded backoff budget instead of a single INTERNAL bail.
349
- if (rawBody === null && isTransportEdgeStatus(response.status)) {
358
+ // Edge proxies / load balancers return 408/502/504 without our error
359
+ // envelope on transient outages. These are transport-level retries,
360
+ // not facade errors — fold them in here so we get the bounded backoff
361
+ // budget instead of a single INTERNAL bail.
362
+ if (rawBody === null && isTransportEdgeStatus(response.status)) {
363
+ this.debug({
364
+ kind: 'error',
365
+ method,
366
+ url,
367
+ attempt,
368
+ status: response.status,
369
+ requestId,
370
+ errorCode: 'TRANSPORT',
371
+ durationMs,
372
+ });
373
+ const decision = transportRetryDecision(attempt, this.random);
374
+ if (!decision.retry) {
375
+ throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
376
+ }
377
+ this.transition(`HTTP ${response.status} from ${shortPath(path)} — transport error, retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
378
+ this.debug({
379
+ kind: 'retry',
380
+ method,
381
+ url,
382
+ attempt,
383
+ requestId,
384
+ errorCode: 'TRANSPORT',
385
+ delayMs: decision.delayMs,
386
+ });
387
+ requestTimeout.clear();
388
+ await this.sleep(decision.delayMs);
389
+ continue;
390
+ }
391
+ const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
392
+ // Clamp server-directed Retry-After to [1s, 300s] and surface on the
393
+ // thrown error so outer callers (e.g. runBatchRun outer retry loop)
394
+ // can honor it without re-reading the now-consumed HTTP response.
395
+ const retryAfterMsForError = retryAfterSec !== undefined
396
+ ? Math.min(Math.max(retryAfterSec, 1), 300) * 1000
397
+ : undefined;
398
+ const apiError = ApiError.fromEnvelope(rawBody, response.status, retryAfterMsForError,
399
+ // Lets synthesized nextAction text (e.g. INSUFFICIENT_CREDITS billing
400
+ // links) resolve the environment-correct portal domain.
401
+ this.baseUrl);
350
402
  this.debug({
351
403
  kind: 'error',
352
404
  method,
353
405
  url,
354
406
  attempt,
355
407
  status: response.status,
408
+ errorCode: apiError.code,
356
409
  requestId,
357
- errorCode: 'TRANSPORT',
358
410
  durationMs,
359
411
  });
360
- const decision = transportRetryDecision(attempt, this.random);
361
- if (!decision.retry) {
362
- throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
412
+ const retryOnConflict = options.retryOnConflict !== false;
413
+ const retryOnRateLimit = options.retryOnRateLimit !== false;
414
+ const decision = apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit);
415
+ if (!decision.retry)
416
+ throw apiError;
417
+ const delaySec = Math.round(decision.delayMs / 1000);
418
+ if (apiError.code === 'RATE_LIMITED') {
419
+ this.transition(`Rate limited (HTTP 429) — waiting ${delaySec}s before retry (attempt ${attempt})`);
420
+ }
421
+ else if (apiError.code === 'INTERNAL') {
422
+ this.transition(`Server error (HTTP 5xx, requestId: ${requestId}) — retrying in ${delaySec}s (attempt ${attempt})`);
423
+ }
424
+ else if (apiError.code === 'UNAVAILABLE') {
425
+ this.transition(`Service unavailable (HTTP 503) — retrying in ${delaySec}s (attempt ${attempt})`);
363
426
  }
364
- this.transition(`HTTP ${response.status} from ${shortPath(path)} — transport error, retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
365
427
  this.debug({
366
428
  kind: 'retry',
367
429
  method,
368
430
  url,
369
431
  attempt,
370
432
  requestId,
371
- errorCode: 'TRANSPORT',
433
+ errorCode: apiError.code,
372
434
  delayMs: decision.delayMs,
373
435
  });
436
+ requestTimeout.clear();
374
437
  await this.sleep(decision.delayMs);
375
- continue;
376
- }
377
- const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
378
- // Clamp server-directed Retry-After to [1s, 300s] and surface on the
379
- // thrown error so outer callers (e.g. runBatchRun outer retry loop)
380
- // can honor it without re-reading the now-consumed HTTP response.
381
- const retryAfterMsForError = retryAfterSec !== undefined ? Math.min(Math.max(retryAfterSec, 1), 300) * 1000 : undefined;
382
- const apiError = ApiError.fromEnvelope(rawBody, response.status, retryAfterMsForError,
383
- // Lets synthesized nextAction text (e.g. INSUFFICIENT_CREDITS billing
384
- // links) resolve the environment-correct portal domain.
385
- this.baseUrl);
386
- this.debug({
387
- kind: 'error',
388
- method,
389
- url,
390
- attempt,
391
- status: response.status,
392
- errorCode: apiError.code,
393
- requestId,
394
- durationMs,
395
- });
396
- const retryOnConflict = options.retryOnConflict !== false;
397
- const retryOnRateLimit = options.retryOnRateLimit !== false;
398
- const decision = apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit);
399
- if (!decision.retry)
400
- throw apiError;
401
- const delaySec = Math.round(decision.delayMs / 1000);
402
- if (apiError.code === 'RATE_LIMITED') {
403
- this.transition(`Rate limited (HTTP 429) — waiting ${delaySec}s before retry (attempt ${attempt})`);
404
438
  }
405
- else if (apiError.code === 'INTERNAL') {
406
- this.transition(`Server error (HTTP 5xx, requestId: ${requestId}) — retrying in ${delaySec}s (attempt ${attempt})`);
439
+ finally {
440
+ requestTimeout.clear();
407
441
  }
408
- else if (apiError.code === 'UNAVAILABLE') {
409
- this.transition(`Service unavailable (HTTP 503) — retrying in ${delaySec}s (attempt ${attempt})`);
410
- }
411
- this.debug({
412
- kind: 'retry',
413
- method,
414
- url,
415
- attempt,
416
- requestId,
417
- errorCode: apiError.code,
418
- delayMs: decision.delayMs,
419
- });
420
- await this.sleep(decision.delayMs);
421
442
  }
422
443
  }
423
444
  buildHeaders(requestId, options) {
@@ -486,6 +507,32 @@ export function buildUrl(baseUrl, path, query) {
486
507
  function newRequestId() {
487
508
  return `cli_${randomUUID()}`;
488
509
  }
510
+ function createRequestTimeout(timeoutMs) {
511
+ const controller = new AbortController();
512
+ const timer = setTimeout(() => {
513
+ controller.abort(makeTimeoutReason());
514
+ }, timeoutMs);
515
+ unrefTimer(timer);
516
+ return {
517
+ signal: controller.signal,
518
+ clear: () => clearTimeout(timer),
519
+ };
520
+ }
521
+ function makeTimeoutReason() {
522
+ if (typeof DOMException !== 'undefined') {
523
+ return new DOMException('The operation timed out.', 'TimeoutError');
524
+ }
525
+ const err = new Error('The operation timed out.');
526
+ err.name = 'TimeoutError';
527
+ return err;
528
+ }
529
+ function unrefTimer(timer) {
530
+ if (typeof timer !== 'object' || timer === null || !('unref' in timer))
531
+ return;
532
+ const unref = timer.unref;
533
+ if (typeof unref === 'function')
534
+ unref.call(timer);
535
+ }
489
536
  async function safeReadJson(response) {
490
537
  try {
491
538
  return await response.json();
@@ -498,6 +545,43 @@ async function safeReadJson(response) {
498
545
  return null;
499
546
  }
500
547
  }
548
+ /**
549
+ * Build a typed error for a successful response whose body could not be parsed
550
+ * as JSON.
551
+ *
552
+ * The CLI expects every API response to be a JSON envelope. When a `200 OK`
553
+ * carries a non-JSON body — a misconfigured endpoint, a proxy / captive-portal
554
+ * / SSO login page returning HTML with a success status, or an empty body —
555
+ * `response.json()` throws a raw `SyntaxError`. Left unhandled it escapes to
556
+ * the top-level handler in `index.ts`, which prints a bare
557
+ * `{"error":"<parse message>"}` under `--output json` (breaking the
558
+ * typed-envelope contract every other error honors) and gives the operator no
559
+ * actionable context.
560
+ *
561
+ * This wraps it in a typed `INTERNAL` `ApiError` (exit 1, unchanged) that
562
+ * carries the `requestId`, names the likely cause, and points the operator at
563
+ * their endpoint configuration. `details` includes the HTTP status, the
564
+ * response `content-type` (when present), and the underlying parse message.
565
+ */
566
+ export function malformedResponseError(response, requestId, cause) {
567
+ const contentType = response.headers.get('content-type') ?? undefined;
568
+ const parseError = cause instanceof Error ? cause.message : String(cause);
569
+ const contentTypeNote = contentType ? ` (content-type: ${contentType})` : '';
570
+ return new ApiError({
571
+ code: 'INTERNAL',
572
+ message: `The server returned a non-JSON response${contentTypeNote} for an HTTP ${response.status}. ` +
573
+ `This usually means the endpoint is not the TestSprite API — a proxy, captive portal, or ` +
574
+ `login page can return HTML with a success status.`,
575
+ nextAction: 'Check that --endpoint-url / TESTSPRITE_API_URL points at the TestSprite API ' +
576
+ '(default https://api.testsprite.com), then retry.',
577
+ requestId,
578
+ details: {
579
+ httpStatus: response.status,
580
+ ...(contentType ? { contentType } : {}),
581
+ parseError,
582
+ },
583
+ }, response.status);
584
+ }
501
585
  export function parseRetryAfter(headerValue) {
502
586
  if (!headerValue)
503
587
  return undefined;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Process lifecycle hardening: graceful termination signals and broken-pipe.
3
+ *
4
+ * Termination signals: without a handler, Node terminates the process abruptly
5
+ * with no output, so a user (Ctrl+C), a CI runner or `docker stop` (SIGTERM), or
6
+ * a closed terminal/SSH session (SIGHUP) that interrupts a long
7
+ * `test run --wait` is left unsure whether the run was cancelled or is still
8
+ * executing server-side (it is: the CLI only polls; the run lives on the
9
+ * backend). The handler prints a one-line explanation plus how to resume, then
10
+ * exits with the conventional `128 + signal` code.
11
+ *
12
+ * Broken pipe: when output is piped to a reader that closes early
13
+ * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
+ * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
+ * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
+ * conventional SIGPIPE-equivalent result for "the reader went away".
17
+ *
18
+ * `process` and the streams are injectable so the wiring is unit-testable
19
+ * without spawning a subprocess or sending a real signal.
20
+ */
21
+ /**
22
+ * Termination signals handled, mapped to their conventional `128 + signum`
23
+ * exit code. sourceRef: POSIX signal numbers (SIGHUP=1, SIGINT=2, SIGTERM=15).
24
+ */
25
+ export declare const TERMINATION_EXIT_CODES: {
26
+ readonly SIGINT: 130;
27
+ readonly SIGTERM: 143;
28
+ readonly SIGHUP: 129;
29
+ };
30
+ export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
31
+ /** Back-compat alias: SIGINT's conventional exit code. */
32
+ export declare const SIGINT_EXIT_CODE: 130;
33
+ export declare function formatInterruptMessage(signal?: TerminationSignal): string;
34
+ export interface InterruptDeps {
35
+ /** Signal registrar. Defaults to `process.on`. */
36
+ on?: (signal: TerminationSignal, handler: () => void) => void;
37
+ /** Line-oriented stderr writer (appends a newline). */
38
+ stderr?: (line: string) => void;
39
+ /** Process exit. Defaults to `process.exit`. */
40
+ exit?: (code: number) => void;
41
+ }
42
+ /**
43
+ * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
44
+ * single top-level call in `index.ts`; not designed to be installed twice.
45
+ */
46
+ export declare function installSignalHandlers(deps?: InterruptDeps): void;
47
+ export interface BrokenPipeDeps {
48
+ /** stdout stream. Defaults to `process.stdout`. */
49
+ stdout?: NodeJS.EventEmitter;
50
+ /** stderr stream. Defaults to `process.stderr`. */
51
+ stderr?: NodeJS.EventEmitter;
52
+ /** Process exit. Defaults to `process.exit`. */
53
+ exit?: (code: number) => void;
54
+ }
55
+ /**
56
+ * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
57
+ * early (`testsprite ... | head`) exits cleanly instead of crashing with an
58
+ * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
59
+ * error is left to surface normally.
60
+ */
61
+ export declare function installBrokenPipeGuard(deps?: BrokenPipeDeps): void;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Process lifecycle hardening: graceful termination signals and broken-pipe.
3
+ *
4
+ * Termination signals: without a handler, Node terminates the process abruptly
5
+ * with no output, so a user (Ctrl+C), a CI runner or `docker stop` (SIGTERM), or
6
+ * a closed terminal/SSH session (SIGHUP) that interrupts a long
7
+ * `test run --wait` is left unsure whether the run was cancelled or is still
8
+ * executing server-side (it is: the CLI only polls; the run lives on the
9
+ * backend). The handler prints a one-line explanation plus how to resume, then
10
+ * exits with the conventional `128 + signal` code.
11
+ *
12
+ * Broken pipe: when output is piped to a reader that closes early
13
+ * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
+ * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
+ * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
+ * conventional SIGPIPE-equivalent result for "the reader went away".
17
+ *
18
+ * `process` and the streams are injectable so the wiring is unit-testable
19
+ * without spawning a subprocess or sending a real signal.
20
+ */
21
+ import { writeSync } from 'node:fs';
22
+ /**
23
+ * Termination signals handled, mapped to their conventional `128 + signum`
24
+ * exit code. sourceRef: POSIX signal numbers (SIGHUP=1, SIGINT=2, SIGTERM=15).
25
+ */
26
+ export const TERMINATION_EXIT_CODES = {
27
+ SIGINT: 130, // 128 + 2
28
+ SIGTERM: 143, // 128 + 15
29
+ SIGHUP: 129, // 128 + 1
30
+ };
31
+ /** Back-compat alias: SIGINT's conventional exit code. */
32
+ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
33
+ export function formatInterruptMessage(signal = 'SIGINT') {
34
+ return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
35
+ 'check it with `testsprite test list` or `testsprite test wait <runId>`.');
36
+ }
37
+ /**
38
+ * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
39
+ * single top-level call in `index.ts`; not designed to be installed twice.
40
+ */
41
+ export function installSignalHandlers(deps = {}) {
42
+ const on = deps.on ??
43
+ ((signal, handler) => {
44
+ process.on(signal, handler);
45
+ });
46
+ const stderr = deps.stderr ??
47
+ ((line) => {
48
+ // A signal handler calls process.exit() right after writing, which can
49
+ // truncate an async process.stderr.write() when stderr is a pipe. Write
50
+ // synchronously so the interrupt hint is flushed before the process exits.
51
+ try {
52
+ writeSync(process.stderr.fd, `${line}\n`);
53
+ }
54
+ catch {
55
+ // Best-effort: if stderr is already gone (EPIPE), still exit cleanly.
56
+ }
57
+ });
58
+ const exit = deps.exit ?? ((code) => process.exit(code));
59
+ for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
60
+ on(signal, () => {
61
+ // Blank line first so the message starts on its own row rather than
62
+ // trailing the progress ticker's in-place line.
63
+ stderr('');
64
+ stderr(formatInterruptMessage(signal));
65
+ exit(TERMINATION_EXIT_CODES[signal]);
66
+ });
67
+ }
68
+ }
69
+ /**
70
+ * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
71
+ * early (`testsprite ... | head`) exits cleanly instead of crashing with an
72
+ * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
73
+ * error is left to surface normally.
74
+ */
75
+ export function installBrokenPipeGuard(deps = {}) {
76
+ const stdout = deps.stdout ?? process.stdout;
77
+ const stderr = deps.stderr ?? process.stderr;
78
+ const exit = deps.exit ?? ((code) => process.exit(code));
79
+ stdout.on('error', (error) => {
80
+ // Reader went away (`| head`, `| less` then q): exit cleanly like SIGPIPE
81
+ // rather than dumping an unhandled `write EPIPE` stack. Any other stdout
82
+ // error is a genuine, actionable failure, so re-throw it (Node's default).
83
+ if (error.code === 'EPIPE') {
84
+ exit(0);
85
+ return;
86
+ }
87
+ throw error;
88
+ });
89
+ stderr.on('error', (error) => {
90
+ // stderr closed: nothing can be reported over it, so swallow EPIPE. Any
91
+ // other error re-throws so a genuine failure is not silently hidden.
92
+ if (error.code === 'EPIPE')
93
+ return;
94
+ throw error;
95
+ });
96
+ }
97
+ //# sourceMappingURL=interrupt.js.map
@@ -0,0 +1,58 @@
1
+ export type JUnitReportFormat = 'junit';
2
+ /** Minimal testcase input shared by batch run and batch rerun poll results. */
3
+ export interface JUnitTestResult {
4
+ testId: string;
5
+ runId?: string;
6
+ status: string;
7
+ /** Observed on polled runs; used for classname when --project is omitted. */
8
+ projectId?: string;
9
+ error?: {
10
+ code: string;
11
+ message: string;
12
+ exitCode?: number;
13
+ };
14
+ }
15
+ export interface JUnitReportBuildOptions {
16
+ suiteName: string;
17
+ classname: string;
18
+ results: readonly JUnitTestResult[];
19
+ }
20
+ export interface JUnitReportFlagOptions {
21
+ report?: JUnitReportFormat;
22
+ reportFile?: string;
23
+ reportSuiteName?: string;
24
+ wait: boolean;
25
+ /** True when the invocation is a batch path (run --all or rerun batch). */
26
+ batchPath: boolean;
27
+ }
28
+ /**
29
+ * Parse `--report <format>`. Only `junit` is accepted in v1.
30
+ */
31
+ export declare function parseJUnitReportFormat(raw: string | undefined): JUnitReportFormat | undefined;
32
+ /**
33
+ * Validate `--report` / `--report-file` / `--report-suite-name` combinations.
34
+ * Report export is a sidecar artifact for batch `--wait` runs only.
35
+ */
36
+ export declare function assertJUnitReportOptions(opts: JUnitReportFlagOptions): void;
37
+ /**
38
+ * Resolve the project id used for JUnit classname / default suite naming.
39
+ * Prefer explicit `--project`, then ids observed on polled run rows.
40
+ */
41
+ export declare function resolveBatchReportProjectId(opts: {
42
+ projectId?: string;
43
+ }, results: ReadonlyArray<{
44
+ projectId?: string;
45
+ }>): string;
46
+ /**
47
+ * Escape text for inclusion in XML element bodies and double-quoted attributes.
48
+ */
49
+ export declare function escapeXml(text: string): string;
50
+ /**
51
+ * Build a JUnit XML document from batch poll results. Duration is `0` in v1
52
+ * because batch poll envelopes do not carry per-run timing.
53
+ */
54
+ export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
55
+ /**
56
+ * Atomically write JUnit XML to `--report-file` (temp sibling + rename).
57
+ */
58
+ export declare function writeJUnitReportFile(rawPath: string, xml: string): Promise<void>;