@testsprite/testsprite-cli 0.13.0 → 0.15.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 (81) hide show
  1. package/README.md +54 -49
  2. package/dist/commands/ci.d.ts +66 -17
  3. package/dist/commands/ci.js +466 -104
  4. package/dist/commands/doctor.d.ts +3 -0
  5. package/dist/commands/doctor.js +62 -20
  6. package/dist/commands/init.js +17 -3
  7. package/dist/commands/project-env.d.ts +11 -1
  8. package/dist/commands/project-env.js +399 -61
  9. package/dist/commands/project-sign-in.d.ts +60 -0
  10. package/dist/commands/project-sign-in.js +289 -0
  11. package/dist/commands/project.d.ts +9 -0
  12. package/dist/commands/project.js +82 -28
  13. package/dist/commands/schedule.d.ts +12 -0
  14. package/dist/commands/schedule.js +175 -5
  15. package/dist/commands/test.d.ts +126 -30
  16. package/dist/commands/test.js +1928 -447
  17. package/dist/commands/testlist.d.ts +10 -5
  18. package/dist/commands/testlist.js +170 -30
  19. package/dist/commands/tunnel.js +11 -5
  20. package/dist/index.js +17 -38
  21. package/dist/lib/agent-targets.d.ts +8 -3
  22. package/dist/lib/agent-targets.js +15 -4
  23. package/dist/lib/ci-run.d.ts +11 -0
  24. package/dist/lib/ci-run.js +34 -0
  25. package/dist/lib/client-factory.d.ts +35 -1
  26. package/dist/lib/client-factory.js +21 -10
  27. package/dist/lib/config.d.ts +1 -0
  28. package/dist/lib/config.js +1 -1
  29. package/dist/lib/credentials.d.ts +0 -1
  30. package/dist/lib/credentials.js +51 -14
  31. package/dist/lib/dry-run/samples.js +95 -1
  32. package/dist/lib/environment-tunnel.d.ts +109 -0
  33. package/dist/lib/environment-tunnel.js +465 -0
  34. package/dist/lib/errors.js +12 -1
  35. package/dist/lib/first-suite-hint.d.ts +55 -0
  36. package/dist/lib/first-suite-hint.js +101 -0
  37. package/dist/lib/gh-output.d.ts +62 -4
  38. package/dist/lib/gh-output.js +152 -7
  39. package/dist/lib/github-context.d.ts +21 -0
  40. package/dist/lib/github-context.js +153 -0
  41. package/dist/lib/http.d.ts +12 -1
  42. package/dist/lib/http.js +9 -1
  43. package/dist/lib/junit-report.d.ts +11 -7
  44. package/dist/lib/junit-report.js +13 -7
  45. package/dist/lib/local-target.d.ts +13 -3
  46. package/dist/lib/local-target.js +47 -12
  47. package/dist/lib/output.js +15 -1
  48. package/dist/lib/plan-poll.js +3 -4
  49. package/dist/lib/plans.types.d.ts +1 -1
  50. package/dist/lib/redact.d.ts +38 -0
  51. package/dist/lib/redact.js +140 -0
  52. package/dist/lib/render-error.d.ts +19 -5
  53. package/dist/lib/render-error.js +31 -0
  54. package/dist/lib/response-schemas.d.ts +5 -1
  55. package/dist/lib/response-schemas.js +54 -0
  56. package/dist/lib/runs.types.d.ts +115 -1
  57. package/dist/lib/target-url.js +5 -5
  58. package/dist/lib/telemetry.d.ts +31 -8
  59. package/dist/lib/telemetry.js +55 -7
  60. package/dist/lib/testlist.types.d.ts +1 -0
  61. package/dist/lib/ticker.d.ts +9 -0
  62. package/dist/lib/ticker.js +18 -0
  63. package/dist/lib/tunnel-session.d.ts +3 -4
  64. package/dist/lib/tunnel-session.js +3 -4
  65. package/dist/lib/v3-advisory.js +0 -1
  66. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  67. package/dist/vendor/tunnel-client/client.js +477 -407
  68. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  69. package/dist/vendor/tunnel-client/config.js +5 -5
  70. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  71. package/dist/vendor/tunnel-client/index.js +4 -4
  72. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  73. package/dist/vendor/tunnel-client/types.js +1 -0
  74. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  75. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  76. package/dist/version.d.ts +1 -1
  77. package/dist/version.js +1 -1
  78. package/package.json +1 -1
  79. package/schemas/plan.schema.json +2 -2
  80. package/skills/testsprite-ci.skill.md +154 -0
  81. package/skills/testsprite-onboard.skill.md +4 -4
@@ -1,4 +1,20 @@
1
- import type { FetchImpl, HttpClientOptions } from './http.js';
1
+ /**
2
+ * Shared `HttpClient` factory used by every M2 command. Two reasons for
3
+ * the extraction:
4
+ *
5
+ * 1. Three command files (`auth`, `project`, `test`) had byte-equivalent
6
+ * `makeClient` helpers — drift between them would silently change
7
+ * behavior depending on which command you called.
8
+ * 2. P6's `--dry-run` branch needs to bypass `loadConfig` (so it works
9
+ * with no `~/.testsprite/credentials`) and substitute a canned-fetch
10
+ * impl. Doing that once here is safer than three near-copies.
11
+ *
12
+ * The factory is intentionally narrow: it only takes the HTTP-relevant
13
+ * deps. Per-command deps (auth's `prompt`, test's `rawStdout`) stay
14
+ * with the command.
15
+ */
16
+ import { type Config } from './config.js';
17
+ import type { DebugEvent, FetchImpl, HttpClientOptions } from './http.js';
2
18
  import { HttpClient } from './http.js';
3
19
  import { type ShutdownHandle } from './interrupt.js';
4
20
  import type { OutputMode } from './output.js';
@@ -48,6 +64,13 @@ export interface ClientFactoryDeps {
48
64
  * in-flight request; tests inject their own controller's signal.
49
65
  */
50
66
  shutdownSignal?: AbortSignal;
67
+ /**
68
+ * Pre-resolved config. When supplied, the factory skips its own `loadConfig`
69
+ * call entirely. Callers that already resolved config (e.g. doctor, which
70
+ * must survive an unreadable credentials file) pass it through so the client
71
+ * never re-reads — and re-fails on — the file.
72
+ */
73
+ config?: Config;
51
74
  /** Defaults to `globalShutdown` so disarmed signals can see in-flight requests. */
52
75
  shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
53
76
  }
@@ -148,3 +171,14 @@ export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactory
148
171
  export type HttpClientFactory = (overrides?: Pick<HttpClientOptions, 'requestTimeoutMs' | 'shutdownSignal'>) => HttpClient;
149
172
  /** Resolve the profile once so related requests share an identity and endpoint. */
150
173
  export declare function createHttpClientFactory(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClientFactory;
174
+ /**
175
+ * `DebugEvent` today carries only method/url/attempt/status/errorCode/
176
+ * durationMs/requestId/delayMs — no headers or body — so there is nothing to
177
+ * redact in the current shape. This still routes through `redactDeep` so a
178
+ * future field (request/response headers or body added to `DebugEvent` for
179
+ * richer `--debug` tracing) is protected from day one rather than needing a
180
+ * second fix when that lands. Exported for direct unit coverage of that
181
+ * forward-compatibility contract.
182
+ */
183
+ export declare function formatDebug(event: DebugEvent): string;
184
+ export declare function formatDryRunDebug(event: DebugEvent): string;
@@ -20,6 +20,7 @@ import { facadeBaseUrl } from './facade.js';
20
20
  import { HttpClient, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, REQUEST_TIMEOUT_MIN_MS, } from './http.js';
21
21
  import { globalShutdown } from './interrupt.js';
22
22
  import { createDryRunFetch } from './dry-run/fetch.js';
23
+ import { redactDeep } from './redact.js';
23
24
  import { noteServerVersion } from './version-notice.js';
24
25
  import { VERSION } from '../version.js';
25
26
  /**
@@ -241,12 +242,13 @@ function resolveHttpClientOptions(opts, deps) {
241
242
  };
242
243
  }
243
244
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
244
- const config = loadConfig({
245
- profile: opts.profile,
246
- endpointUrl: opts.endpointUrl,
247
- env,
248
- credentialsPath,
249
- });
245
+ const config = deps.config ??
246
+ loadConfig({
247
+ profile: opts.profile,
248
+ endpointUrl: opts.endpointUrl,
249
+ env,
250
+ credentialsPath,
251
+ });
250
252
  // Catch a malformed endpoint (from --endpoint-url / TESTSPRITE_API_URL /
251
253
  // credentials) before the auth check so a config typo surfaces as a clear
252
254
  // VALIDATION_ERROR rather than an opaque URL throw or a retried "fetch failed".
@@ -277,10 +279,19 @@ function resolveHttpClientOptions(opts, deps) {
277
279
  shutdown: deps.shutdown ?? globalShutdown,
278
280
  };
279
281
  }
280
- function formatDebug(event) {
281
- return `[debug ${new Date().toISOString()}] ${JSON.stringify(event)}`;
282
+ /**
283
+ * `DebugEvent` today carries only method/url/attempt/status/errorCode/
284
+ * durationMs/requestId/delayMs — no headers or body — so there is nothing to
285
+ * redact in the current shape. This still routes through `redactDeep` so a
286
+ * future field (request/response headers or body added to `DebugEvent` for
287
+ * richer `--debug` tracing) is protected from day one rather than needing a
288
+ * second fix when that lands. Exported for direct unit coverage of that
289
+ * forward-compatibility contract.
290
+ */
291
+ export function formatDebug(event) {
292
+ return `[debug ${new Date().toISOString()}] ${JSON.stringify(redactDeep(event))}`;
282
293
  }
283
- function formatDryRunDebug(event) {
284
- return `[debug ${new Date().toISOString()}] ${JSON.stringify({ ...event, mode: 'dry-run' })}`;
294
+ export function formatDryRunDebug(event) {
295
+ return `[debug ${new Date().toISOString()}] ${JSON.stringify(redactDeep({ ...event, mode: 'dry-run' }))}`;
285
296
  }
286
297
  //# sourceMappingURL=client-factory.js.map
@@ -9,6 +9,7 @@ export interface LoadConfigOptions {
9
9
  env?: NodeJS.ProcessEnv;
10
10
  credentialsPath?: string;
11
11
  }
12
+ export declare const DEFAULT_API_URL = "https://api.testsprite.com";
12
13
  /** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
13
14
  export declare function normalizeEnvVar(value: string | undefined): string | undefined;
14
15
  export declare function defaultConfigPath(): string;
@@ -1,7 +1,7 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import { DEFAULT_PROFILE, defaultCredentialsPath, readProfile } from './credentials.js';
4
- const DEFAULT_API_URL = 'https://api.testsprite.com';
4
+ export const DEFAULT_API_URL = 'https://api.testsprite.com';
5
5
  /** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
6
6
  export function normalizeEnvVar(value) {
7
7
  return value?.trim() || undefined;
@@ -22,7 +22,6 @@ type CredentialsWritePermissionError = NodeJS.ErrnoException & {
22
22
  export declare function isCredentialsWritePermissionError(error: unknown): error is CredentialsWritePermissionError;
23
23
  interface RestrictiveModeOptions {
24
24
  platform?: NodeJS.Platform;
25
- env?: NodeJS.ProcessEnv;
26
25
  spawnSync?: (command: string, args: readonly string[], options: {
27
26
  shell: false;
28
27
  stdio: 'ignore';
@@ -63,6 +63,8 @@ const CREDENTIALS_LOCK_WAIT_MS = 5_000;
63
63
  // problem and is surfaced as such.
64
64
  const CREDENTIALS_LOCK_TRANSIENT_WAIT_MS = 1_000;
65
65
  const CREDENTIALS_LOCK_STALE_MS = 30_000;
66
+ // How long a transient Windows error on replacing the credentials file is retried.
67
+ const CREDENTIALS_RENAME_TRANSIENT_WAIT_MS = 2_000;
66
68
  export function parseCredentials(content) {
67
69
  const result = {};
68
70
  let currentEntry = null;
@@ -181,27 +183,43 @@ export function ensureRestrictiveMode(path, options = {}) {
181
183
  chmodSync(path, 0o600);
182
184
  }
183
185
  /**
184
- * Restrict a Windows credentials file to the current user using icacls.
186
+ * Restrict a Windows credentials file to the file owner using icacls.
185
187
  * The command is invoked with an args array so credential paths are never shell-interpreted.
188
+ *
189
+ * Uses /reset to clear any broken inheritance state, followed by
190
+ * /inheritance:r /grant:r *S-1-3-4:F which decouples the file from parent ACLs
191
+ * and grants Full Control to the OWNER RIGHTS SID (S-1-3-4). This avoids
192
+ * dependency on resolving %USERNAME% (which fails on Microsoft Account or
193
+ * domain-joined machines).
186
194
  */
187
195
  function ensureWindowsRestrictiveAcl(path, options) {
188
- const username = (options.env ?? process.env).USERNAME?.trim();
189
- if (!username) {
190
- warnWindowsAcl('could not determine the Windows username; credentials file permissions were not tightened', options);
191
- return;
192
- }
193
196
  const run = options.spawnSync ?? spawnSync;
194
- const result = run('icacls', [path, '/inheritance:r', '/grant:r', `${username}:F`], {
197
+ const icaclsOptions = {
195
198
  shell: false,
196
199
  stdio: 'ignore',
197
200
  windowsHide: true,
198
- });
199
- if (result.error) {
200
- warnWindowsAcl(`icacls failed while tightening credentials file permissions: ${result.error.message}`, options);
201
+ };
202
+ const resetResult = run('icacls', [path, '/reset'], icaclsOptions);
203
+ if (resetResult.error) {
204
+ warnWindowsAcl(`icacls failed while resetting credentials file permissions: ${resetResult.error.message}`, options);
201
205
  return;
202
206
  }
203
- if (result.status !== 0) {
204
- warnWindowsAcl(`icacls exited with status ${result.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
207
+ if (resetResult.status !== 0) {
208
+ warnWindowsAcl(`icacls /reset exited with status ${resetResult.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
209
+ return;
210
+ }
211
+ // The trailing :F is load-bearing, not incidental: after /inheritance:r the
212
+ // file carries exactly this one ACE, and Full Control is what leaves
213
+ // WRITE_DAC with the owner — which is what makes a later `icacls /reset`
214
+ // possible at all. Tightening this to :R would leave the file unrepairable
215
+ // without taking ownership.
216
+ const grantResult = run('icacls', [path, '/inheritance:r', '/grant:r', '*S-1-3-4:F'], icaclsOptions);
217
+ if (grantResult.error) {
218
+ warnWindowsAcl(`icacls failed while tightening credentials file permissions: ${grantResult.error.message}`, options);
219
+ return;
220
+ }
221
+ if (grantResult.status !== 0) {
222
+ warnWindowsAcl(`icacls exited with status ${grantResult.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
205
223
  }
206
224
  }
207
225
  /** Emit an explicit warning when Windows ACL tightening cannot be completed. */
@@ -238,8 +256,7 @@ function writeCredentialsAtomic(path, file) {
238
256
  try {
239
257
  // eslint-disable-next-line security/detect-non-literal-fs-filename -- `tmp` is `${path}.tmp.${pid}`, derived from the same internal credentials-file path; same baselined risk profile as the other fs calls in this file.
240
258
  writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
241
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- both operands derive from the internal credentials-file path (see above).
242
- renameSync(tmp, path);
259
+ renameCredentialsFile(tmp, path);
243
260
  }
244
261
  catch (error) {
245
262
  try {
@@ -259,6 +276,26 @@ function writeCredentialsAtomic(path, file) {
259
276
  }
260
277
  ensureRestrictiveMode(path);
261
278
  }
279
+ /**
280
+ * Replace the credentials file with the temp file. On Windows a transient
281
+ * EPERM/EBUSY/EACCES (another program briefly holding the file) is retried for a
282
+ * short window; anything else, or an error that persists, is thrown.
283
+ */
284
+ function renameCredentialsFile(tmp, path) {
285
+ const deadline = Date.now() + CREDENTIALS_RENAME_TRANSIENT_WAIT_MS;
286
+ while (true) {
287
+ try {
288
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- both operands derive from the internal credentials-file path (see writeCredentialsAtomic).
289
+ renameSync(tmp, path);
290
+ return;
291
+ }
292
+ catch (error) {
293
+ if (!isWindowsLockContention(error) || Date.now() >= deadline)
294
+ throw error;
295
+ sleepSync(CREDENTIALS_LOCK_RETRY_MS);
296
+ }
297
+ }
298
+ }
262
299
  function acquireCredentialsLock(path) {
263
300
  const lockPath = `${path}.lock`;
264
301
  const deadline = Date.now() + CREDENTIALS_LOCK_WAIT_MS;
@@ -134,7 +134,7 @@ const tests = [
134
134
  createdFrom: 'portal',
135
135
  status: 'failed',
136
136
  // G1a — priority label shown on one row so dry-run learners see the field.
137
- priority: 'p1',
137
+ priority: 'Medium',
138
138
  createdAt: '2026-04-20T11:00:00.000Z',
139
139
  updatedAt: '2026-05-05T12:34:56.000Z',
140
140
  details: {
@@ -331,6 +331,44 @@ const failureSummary = {
331
331
  rootCauseHypothesis: failureContext.failure.rootCauseHypothesis,
332
332
  recommendedFixTarget: failureContext.failure.recommendedFixTarget,
333
333
  };
334
+ const SAMPLE_EXECUTION_ID = 'exec_dryrun0001';
335
+ /** A ready execution report: one failed and one passed row, the App's Markdown shape in miniature. */
336
+ const executionReportSample = {
337
+ ready: true,
338
+ report: {
339
+ projectId: SAMPLE_PROJECT_ID,
340
+ executionId: SAMPLE_EXECUTION_ID,
341
+ projectName: 'Sample project',
342
+ orgId: null,
343
+ stats: { passed: 1, failed: 1, blocked: 0, total: 2 },
344
+ allPassed: false,
345
+ narrative: 'Dry-run sample: one regression in checkout, login passed.',
346
+ whatCouldBeBetter: 'Add coverage for password reset.',
347
+ recommendedNextStep: 'Fix the checkout selector and rerun.',
348
+ tests: [
349
+ {
350
+ id: SAMPLE_RUN_ID,
351
+ title: 'Checkout applies a coupon',
352
+ slug: 'CHK-002',
353
+ status: 'FAILED',
354
+ screenshotUrl: null,
355
+ error: 'AssertionError: expected the order total to drop',
356
+ fix: 'Apply the coupon before computing the total.',
357
+ },
358
+ {
359
+ id: `${SAMPLE_RUN_ID}-2`,
360
+ title: 'Login with a valid account',
361
+ slug: 'AUTH-001',
362
+ status: 'PASSED',
363
+ screenshotUrl: null,
364
+ error: null,
365
+ fix: null,
366
+ },
367
+ ],
368
+ resultUrl: `https://www.testsprite.com/dashboard-v3/projects/${SAMPLE_PROJECT_ID}/execution/${SAMPLE_EXECUTION_ID}`,
369
+ },
370
+ markdown: '> [!WARNING]\n> ### Ran into trouble — 1 failed\n>\n> Dry-run sample: one regression in checkout, login passed.\n',
371
+ };
334
372
  const passedRunSample = {
335
373
  runId: SAMPLE_RUN_ID,
336
374
  testId: SAMPLE_TEST_ID_PASSED,
@@ -466,6 +504,59 @@ function buildPathPattern(pathTemplate) {
466
504
  const ENTRIES = [
467
505
  entry('whoami', 'GET', '/me', me),
468
506
  entry('listProjects', 'GET', '/projects', pageOf(projects)),
507
+ entry('getProjectSignIn', 'GET', '/projects/{projectId}/sign-in', {
508
+ projectId: SAMPLE_PROJECT_ID,
509
+ environment: {
510
+ id: 'env_dryrun',
511
+ name: 'default',
512
+ url: 'https://app.example.com',
513
+ isDefault: true,
514
+ authMode: 'public',
515
+ hasCredentials: false,
516
+ username: null,
517
+ enableOtp: false,
518
+ updatedAt: '2026-09-25T00:00:00.000Z',
519
+ },
520
+ signIn: { mode: 'public', account: null, otp: null, manual: null },
521
+ nextAction: null,
522
+ }),
523
+ entry('setProjectSignIn', 'PUT', '/projects/{projectId}/sign-in', (request) => {
524
+ const body = request;
525
+ const mode = body?.mode ?? 'manual';
526
+ return {
527
+ projectId: SAMPLE_PROJECT_ID,
528
+ environment: {
529
+ id: 'env_dryrun',
530
+ name: 'default',
531
+ url: 'https://app.example.com',
532
+ isDefault: true,
533
+ authMode: mode,
534
+ hasCredentials: mode === 'account',
535
+ username: mode === 'account' ? 'qa@example.com' : null,
536
+ enableOtp: mode === 'otp',
537
+ updatedAt: '2026-09-25T00:00:00.000Z',
538
+ },
539
+ signIn: {
540
+ mode,
541
+ account: mode === 'account' ? { username: 'qa@example.com', passwordSet: true } : null,
542
+ otp: mode === 'otp'
543
+ ? { channels: ['email'], email: 'dryrun@inbox.example', phone: null }
544
+ : null,
545
+ manual: mode === 'manual'
546
+ ? {
547
+ sessionReuseTtlSeconds: 3600,
548
+ hasValidSession: false,
549
+ needsReauth: true,
550
+ reason: 'never',
551
+ capturedAt: null,
552
+ expiresAt: null,
553
+ }
554
+ : null,
555
+ },
556
+ changed: mode !== 'otp',
557
+ nextAction: mode === 'manual' ? 'Log in once in the Portal.' : null,
558
+ };
559
+ }),
469
560
  // Plan-generation surface. All three MUST be registered
470
561
  // BEFORE `getProject`: findSample is first-match-wins and the projects/*
471
562
  // family shares the `/projects/…` prefix, so the more specific plans
@@ -594,6 +685,9 @@ const ENTRIES = [
594
685
  entry('getTestCode', 'GET', '/tests/{testId}/code', testCode),
595
686
  entry('listTestSteps', 'GET', '/tests/{testId}/steps', pageOf(testSteps)),
596
687
  entry('getTestResult', 'GET', '/tests/{testId}/result', latestResult),
688
+ // Execution report — static `executions/` prefix, four segments, so no
689
+ // `/tests/{testId}/…` pattern can shadow it; kept beside the other reads.
690
+ entry('getExecutionReport', 'GET', '/tests/executions/{executionId}/report', executionReportSample),
597
691
  // `/failure/summary` MUST come before `/failure` so the regex matcher
598
692
  // doesn't shadow it with the bundle endpoint.
599
693
  entry('getTestFailureSummary', 'GET', '/tests/{testId}/failure/summary', failureSummary),
@@ -0,0 +1,109 @@
1
+ import { type CommonOptions, type ClientFactoryDeps } from './client-factory.js';
2
+ import { type ShutdownHandle } from './interrupt.js';
3
+ import { openTunnelSession, type TunnelClientHandle } from './tunnel-session.js';
4
+ import { type TunnelClientOptions } from '../vendor/tunnel-client/index.js';
5
+ import type { HttpClient } from './http.js';
6
+ import type { RunResponse } from './runs.types.js';
7
+ import { ApiError } from './errors.js';
8
+ import { type LoopbackHost, type StoredLocalTarget } from './local-target.js';
9
+ export interface RunTargetTest {
10
+ type: 'frontend' | 'backend';
11
+ projectId: string;
12
+ }
13
+ interface Environment {
14
+ name: string;
15
+ url: string;
16
+ isDefault?: boolean;
17
+ isTemporary?: boolean;
18
+ }
19
+ export interface ResolvedRunTarget extends StoredLocalTarget {
20
+ targetUrl: string;
21
+ automatic: boolean;
22
+ environmentName?: string;
23
+ }
24
+ export declare const ENVIRONMENT_PREFLIGHT_TIMEOUT_MS = 5000;
25
+ /** Advisory-only reads must not inherit the run's long wait or retry budget. */
26
+ export declare function readEnvironmentPreflight<T>(client: Pick<HttpClient, 'get'>, path: string): Promise<T>;
27
+ export declare function assertNoTunnelOptions(args: {
28
+ tunnelClientId?: string;
29
+ cancelOnInterrupt?: boolean;
30
+ }): void;
31
+ export declare function severalIdsWithoutTunnel(): never;
32
+ /** One resolver for fresh runs, replay, chained creation and test-list runs. */
33
+ export declare function resolveEnvironmentRunTarget(args: {
34
+ client: Pick<HttpClient, 'get'>;
35
+ testId?: string;
36
+ knownTest?: RunTargetTest;
37
+ skipTestLookup?: boolean;
38
+ includeBackend?: boolean;
39
+ dryRun?: boolean;
40
+ projectId?: string;
41
+ environment?: string;
42
+ localPort?: number;
43
+ localHost?: LoopbackHost;
44
+ targetUrl?: string;
45
+ tunnelClientId?: string;
46
+ noWait?: boolean;
47
+ verbose?: boolean;
48
+ stderr: (line: string) => void;
49
+ cache?: Map<string, Environment[] | undefined>;
50
+ }): Promise<ResolvedRunTarget | undefined>;
51
+ export declare function tunnelScopeError(err: unknown): unknown;
52
+ export declare function unsupportedTunnelError(command: string): ApiError;
53
+ export interface EnvironmentTunnelContext {
54
+ client: HttpClient;
55
+ clientId: string;
56
+ targets?: ReadonlyMap<string, ResolvedRunTarget>;
57
+ maxConcurrency: number;
58
+ deadlineMs: number;
59
+ session: Awaited<ReturnType<typeof openTunnelSession>>;
60
+ cancellation: (runId: string) => 'cancelled' | 'cancel-failed' | undefined;
61
+ skipped?: Array<{
62
+ testId: string;
63
+ reason: 'backend-test';
64
+ }>;
65
+ terminalRun: (runId: string) => RunResponse | undefined;
66
+ waitForCapacity: (incoming: number) => Promise<void>;
67
+ confirm: (response: {
68
+ tunnelClientId?: string;
69
+ }, runIds: string[], requireEcho?: boolean) => Promise<void>;
70
+ onPoll: (run: {
71
+ runId: string;
72
+ status: string;
73
+ }) => void;
74
+ }
75
+ /** Replay and list dispatch keep their existing envelopes under one owned tunnel. */
76
+ export declare function withEnvironmentTunnel<T>(opts: CommonOptions & {
77
+ skipPreflight?: boolean;
78
+ maxConcurrency?: number;
79
+ timeoutSeconds?: number;
80
+ }, deps: ClientFactoryDeps & {
81
+ shutdown?: ShutdownHandle;
82
+ createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
83
+ sleep?: (ms: number) => Promise<void>;
84
+ }, targets: ResolvedRunTarget[], command: string, operation: (context: EnvironmentTunnelContext) => Promise<T>): Promise<T>;
85
+ /** Keep each dispatch on one verbatim loopback URL; public runs omit tunnel fields. */
86
+ export declare function groupEnvironmentTargets(ids: string[], targets: ReadonlyMap<string, ResolvedRunTarget>, maxLocalGroupSize?: number): string[][];
87
+ export declare function quoteEnvironmentName(name: string): string;
88
+ export declare function emitEnvironmentDispatchPartial(responses: Array<{
89
+ accepted: Array<{
90
+ testId: string;
91
+ runId: string;
92
+ }>;
93
+ conflicts: Array<{
94
+ testId: string;
95
+ }>;
96
+ deferred: Array<{
97
+ testId: string;
98
+ }>;
99
+ notFound?: string[];
100
+ }>, testIds: string[], opts: CommonOptions & {
101
+ report?: 'junit';
102
+ reportFile?: string;
103
+ reportSuiteName?: string;
104
+ ghOutput?: boolean;
105
+ summaryFile?: string;
106
+ }, deps: ClientFactoryDeps & {
107
+ stdout?: (line: string) => void;
108
+ }, label: string, error: unknown, context: EnvironmentTunnelContext): Promise<void>;
109
+ export {};