@testsprite/testsprite-cli 0.12.0 → 0.14.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 (113) hide show
  1. package/README.md +59 -49
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +34 -20
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.d.ts +11 -1
  11. package/dist/commands/project-env.js +408 -70
  12. package/dist/commands/project-sign-in.d.ts +60 -0
  13. package/dist/commands/project-sign-in.js +289 -0
  14. package/dist/commands/project.d.ts +14 -5
  15. package/dist/commands/project.js +110 -70
  16. package/dist/commands/schedule.d.ts +14 -0
  17. package/dist/commands/schedule.js +193 -15
  18. package/dist/commands/test.d.ts +123 -44
  19. package/dist/commands/test.js +2993 -636
  20. package/dist/commands/testlist.d.ts +10 -5
  21. package/dist/commands/testlist.js +217 -47
  22. package/dist/commands/tunnel.d.ts +26 -3
  23. package/dist/commands/tunnel.js +221 -18
  24. package/dist/commands/usage.d.ts +3 -0
  25. package/dist/commands/usage.js +12 -5
  26. package/dist/index.js +39 -50
  27. package/dist/lib/agent-targets.d.ts +3 -3
  28. package/dist/lib/agent-targets.js +2 -2
  29. package/dist/lib/billing-refusal.d.ts +43 -0
  30. package/dist/lib/billing-refusal.js +171 -0
  31. package/dist/lib/bundle.d.ts +5 -0
  32. package/dist/lib/bundle.js +43 -13
  33. package/dist/lib/ci-linkage.d.ts +90 -0
  34. package/dist/lib/ci-linkage.js +181 -0
  35. package/dist/lib/client-factory.d.ts +16 -2
  36. package/dist/lib/client-factory.js +37 -6
  37. package/dist/lib/config.d.ts +17 -0
  38. package/dist/lib/config.js +20 -1
  39. package/dist/lib/conflict-reason.d.ts +27 -3
  40. package/dist/lib/conflict-reason.js +53 -4
  41. package/dist/lib/credentials.js +56 -14
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +104 -7
  44. package/dist/lib/environment-tunnel.d.ts +109 -0
  45. package/dist/lib/environment-tunnel.js +465 -0
  46. package/dist/lib/errors.d.ts +18 -11
  47. package/dist/lib/errors.js +123 -14
  48. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  49. package/dist/lib/failing-fe-resolver.js +3 -3
  50. package/dist/lib/gh-output.d.ts +1 -0
  51. package/dist/lib/gh-output.js +16 -4
  52. package/dist/lib/history-retention.d.ts +8 -0
  53. package/dist/lib/history-retention.js +24 -0
  54. package/dist/lib/http.d.ts +39 -19
  55. package/dist/lib/http.js +46 -24
  56. package/dist/lib/interrupt.d.ts +21 -13
  57. package/dist/lib/interrupt.js +32 -21
  58. package/dist/lib/junit-report.d.ts +18 -4
  59. package/dist/lib/junit-report.js +23 -5
  60. package/dist/lib/local-target.d.ts +14 -4
  61. package/dist/lib/local-target.js +48 -13
  62. package/dist/lib/output.js +15 -1
  63. package/dist/lib/plan-poll.d.ts +11 -11
  64. package/dist/lib/plan-poll.js +15 -16
  65. package/dist/lib/plans.types.d.ts +9 -9
  66. package/dist/lib/plans.types.js +3 -3
  67. package/dist/lib/poll.d.ts +2 -2
  68. package/dist/lib/poll.js +9 -3
  69. package/dist/lib/redact.d.ts +38 -0
  70. package/dist/lib/redact.js +140 -0
  71. package/dist/lib/render-error.d.ts +21 -5
  72. package/dist/lib/render-error.js +44 -0
  73. package/dist/lib/response-schemas.d.ts +54 -12
  74. package/dist/lib/response-schemas.js +88 -7
  75. package/dist/lib/runs.types.d.ts +68 -11
  76. package/dist/lib/secret-file.js +72 -14
  77. package/dist/lib/skill-nudge.d.ts +6 -1
  78. package/dist/lib/skill-nudge.js +32 -5
  79. package/dist/lib/target-url-preflight.d.ts +6 -4
  80. package/dist/lib/target-url-preflight.js +64 -51
  81. package/dist/lib/target-url.js +11 -11
  82. package/dist/lib/telemetry.d.ts +10 -8
  83. package/dist/lib/telemetry.js +24 -17
  84. package/dist/lib/testlist.types.d.ts +1 -0
  85. package/dist/lib/ticker.d.ts +9 -0
  86. package/dist/lib/ticker.js +111 -4
  87. package/dist/lib/tunnel-session.d.ts +16 -4
  88. package/dist/lib/tunnel-session.js +7 -5
  89. package/dist/lib/tunnel.types.d.ts +12 -2
  90. package/dist/lib/tunnel.types.js +2 -2
  91. package/dist/lib/v3-advisory.js +0 -1
  92. package/dist/lib/wait-exit.d.ts +8 -0
  93. package/dist/lib/wait-exit.js +76 -4
  94. package/dist/lib/workspace-status.d.ts +23 -0
  95. package/dist/lib/workspace-status.js +15 -0
  96. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  97. package/dist/vendor/tunnel-client/client.js +477 -407
  98. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  99. package/dist/vendor/tunnel-client/config.js +5 -5
  100. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  101. package/dist/vendor/tunnel-client/index.js +4 -4
  102. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  103. package/dist/vendor/tunnel-client/types.js +1 -0
  104. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  105. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  106. package/dist/version-guard.d.ts +7 -1
  107. package/dist/version-guard.js +19 -1
  108. package/dist/version.d.ts +1 -1
  109. package/dist/version.js +1 -1
  110. package/package.json +4 -4
  111. package/skills/testsprite-onboard.skill.md +8 -8
  112. package/skills/testsprite-verify.codex.md +59 -57
  113. package/skills/testsprite-verify.skill.md +53 -38
@@ -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 {};
@@ -0,0 +1,465 @@
1
+ import { makeHttpClient, resolveRequestTimeoutMs, } from './client-factory.js';
2
+ import { globalShutdown } from './interrupt.js';
3
+ import { openTunnelSession, TunnelLostError } from './tunnel-session.js';
4
+ import { TunnelClient } from '../vendor/tunnel-client/index.js';
5
+ import { assertLocalPortListening } from './local-target.js';
6
+ import { recordTelemetryTunnelOpened } from './telemetry.js';
7
+ import { Output } from './output.js';
8
+ import { emitCiArtifacts, summarizeAcceptedPayload } from './gh-output.js';
9
+ import { buildJUnitReport, writeJUnitReportFile } from './junit-report.js';
10
+ import { pollRunUntilTerminal, TimeoutError, isTerminalStatus } from './poll.js';
11
+ import { ApiError, InterruptError, RequestTimeoutError, localValidationError } from './errors.js';
12
+ import { buildLocalTargetUrl, DEFAULT_LOCAL_HOST, parseLoopbackTargetUrl, } from './local-target.js';
13
+ export const ENVIRONMENT_PREFLIGHT_TIMEOUT_MS = 5_000;
14
+ /** Advisory-only reads must not inherit the run's long wait or retry budget. */
15
+ export function readEnvironmentPreflight(client, path) {
16
+ return client.get(path, {
17
+ retry: false,
18
+ signal: AbortSignal.timeout(ENVIRONMENT_PREFLIGHT_TIMEOUT_MS),
19
+ });
20
+ }
21
+ export function assertNoTunnelOptions(args) {
22
+ if (args.tunnelClientId !== undefined)
23
+ throw localValidationError('tunnel-client', '--tunnel-client only applies with --local (it attaches the run to an already-running ' +
24
+ 'tunnel). Add --local <port>, or remove --tunnel-client');
25
+ if (args.cancelOnInterrupt === false)
26
+ throw localValidationError('cancel-on-interrupt', '--no-cancel-on-interrupt only applies with --local. An ordinary run is never ' +
27
+ 'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
28
+ 'cancel <run-id>` is the way to stop one');
29
+ }
30
+ export function severalIdsWithoutTunnel() {
31
+ throw localValidationError('test-id', 'several test ids run through one tunnel with --local <port>. For tests the runner can already reach, use `testsprite test run --all --project <id> [--filter <text>]`, or run them one at a time.');
32
+ }
33
+ const announcedEnvironments = new WeakMap();
34
+ /** One resolver for fresh runs, replay, chained creation and test-list runs. */
35
+ export async function resolveEnvironmentRunTarget(args) {
36
+ const explicitUrl = args.targetUrl === undefined ? undefined : parseLoopbackTargetUrl(args.targetUrl);
37
+ const explicit = args.localPort !== undefined || explicitUrl !== undefined;
38
+ if (args.targetUrl !== undefined && !explicitUrl)
39
+ return undefined;
40
+ let test = args.knownTest;
41
+ if (!test && args.testId && !args.skipTestLookup) {
42
+ try {
43
+ test = await readEnvironmentPreflight(args.client, `/tests/${encodeURIComponent(args.testId)}`);
44
+ }
45
+ catch (err) {
46
+ if (err instanceof InterruptError)
47
+ throw err;
48
+ if (explicit) {
49
+ if (err instanceof ApiError &&
50
+ (err.httpStatus === 403 || err.httpStatus === 404 || err.code === 'UNAVAILABLE')) {
51
+ throw new ApiError({
52
+ code: err.code,
53
+ message: `Cannot read test ${args.testId} for --local preflight.`,
54
+ nextAction: 'Check the test ID and read:tests permission, then retry.',
55
+ requestId: err.requestId,
56
+ details: {},
57
+ }, err.httpStatus);
58
+ }
59
+ throw err;
60
+ }
61
+ return undefined;
62
+ }
63
+ }
64
+ if (test?.type === 'backend' && !args.includeBackend) {
65
+ if (explicit)
66
+ throw localValidationError('local', `backend tests don't open a browser; the tunnel is not used. Run: testsprite test run ${args.testId}`);
67
+ return undefined;
68
+ }
69
+ const projectId = test?.projectId ?? args.projectId;
70
+ let environments;
71
+ if (projectId) {
72
+ if (args.cache?.has(projectId))
73
+ environments = args.cache.get(projectId);
74
+ else {
75
+ try {
76
+ const listing = await readEnvironmentPreflight(args.client, `/projects/${encodeURIComponent(projectId)}/env`);
77
+ if (Array.isArray(listing.environments))
78
+ environments = listing.environments;
79
+ }
80
+ catch (err) {
81
+ if (err instanceof InterruptError)
82
+ throw err;
83
+ // Read scope, old routes and transient failures do not change legacy runs.
84
+ if (args.verbose)
85
+ args.stderr('[verbose] environment preflight skipped: project environments unavailable; the server will validate this run.');
86
+ }
87
+ args.cache?.set(projectId, environments);
88
+ }
89
+ }
90
+ const selected = args.environment === undefined
91
+ ? (environments?.find(row => row.isDefault) ?? environments?.find(row => !row.isTemporary))
92
+ : environments?.find(row => row.name === args.environment);
93
+ if (explicit && args.environment !== undefined && environments && !selected) {
94
+ const available = environments.map(row => row.name).sort();
95
+ throw localValidationError('env', `unknown environment '${args.environment}'; use one of: ${available.join(', ')}`, available);
96
+ }
97
+ const localOf = (row) => {
98
+ if (!row || typeof row.url !== 'string')
99
+ return undefined;
100
+ try {
101
+ return parseLoopbackTargetUrl(row.url);
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ };
107
+ const announced = args.cache
108
+ ? (announcedEnvironments.get(args.cache) ?? new Set())
109
+ : new Set();
110
+ if (args.cache)
111
+ announcedEnvironments.set(args.cache, announced);
112
+ const announce = (key, line) => {
113
+ if (!announced.has(key))
114
+ args.stderr(line);
115
+ announced.add(key);
116
+ };
117
+ const explicitTarget = (target) => {
118
+ if (args.environment !== undefined && selected && !localOf(selected))
119
+ announce(`sign-in:${projectId}:${selected.name}:${target.targetUrl}`, `Using environment "${selected.name}" sign-in against ${target.targetUrl} through a tunnel.`);
120
+ return target;
121
+ };
122
+ if (explicitUrl)
123
+ return explicitTarget({ ...explicitUrl, targetUrl: args.targetUrl, automatic: false });
124
+ if (args.localPort !== undefined) {
125
+ const selectedHost = localOf(selected)?.host;
126
+ const matching = environments?.filter(row => !row.isTemporary && localOf(row)?.port === args.localPort) ?? [];
127
+ const hosts = new Set(matching.map(row => localOf(row).host));
128
+ const host = args.localHost ??
129
+ selectedHost ??
130
+ (hosts.size === 1 ? [...hosts][0] : undefined) ??
131
+ (environments === undefined ? '127.0.0.1' : DEFAULT_LOCAL_HOST);
132
+ return explicitTarget({
133
+ host,
134
+ port: args.localPort,
135
+ targetUrl: buildLocalTargetUrl(host, args.localPort),
136
+ automatic: false,
137
+ });
138
+ }
139
+ const local = localOf(selected);
140
+ if (!local)
141
+ return undefined;
142
+ if (args.noWait) {
143
+ announce(`no-wait:${projectId}:${selected.name}:${selected.url}`, '[hint] This environment needs a tunnel; drop --no-wait to run through a tunnel.');
144
+ return undefined;
145
+ }
146
+ if (!args.tunnelClientId && test?.type !== 'backend') {
147
+ const key = `${projectId}:${selected.name}:${selected.url}`;
148
+ announce(key, args.dryRun
149
+ ? `Would open a tunnel to ${selected.url} (environment "${selected.name}").`
150
+ : `Environment "${selected.name}" is on this machine (${selected.url}) — opening a tunnel.`);
151
+ }
152
+ return {
153
+ ...local,
154
+ targetUrl: selected.url,
155
+ automatic: args.tunnelClientId === undefined,
156
+ environmentName: selected.name,
157
+ };
158
+ }
159
+ export function tunnelScopeError(err) {
160
+ if (!(err instanceof ApiError) || err.httpStatus !== 403)
161
+ return err;
162
+ return new ApiError({
163
+ code: err.code,
164
+ message: err.message,
165
+ requestId: err.requestId,
166
+ details: err.details,
167
+ nextAction: `${err.nextAction ?? ''} A tunnel is required for this environment; use an API key with run:tunnel permission.`,
168
+ }, err.httpStatus);
169
+ }
170
+ export function unsupportedTunnelError(command) {
171
+ return new ApiError({
172
+ code: 'UNSUPPORTED',
173
+ message: `This server did not confirm tunnel use for ${command}. Cancellation was attempted for the started runs; no tunnel-free result can be trusted.`,
174
+ nextAction: 'Update the server, or use testsprite test run <id> with the saved environment.',
175
+ requestId: 'local',
176
+ details: {},
177
+ });
178
+ }
179
+ /** Replay and list dispatch keep their existing envelopes under one owned tunnel. */
180
+ export async function withEnvironmentTunnel(opts, deps, targets, command, operation) {
181
+ const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
182
+ const shutdown = deps.shutdown ?? globalShutdown;
183
+ const seen = new Set();
184
+ for (const target of targets) {
185
+ if (seen.has(target.targetUrl))
186
+ continue;
187
+ seen.add(target.targetUrl);
188
+ await assertLocalPortListening(target.host, target.port, { ...opts, ...(target.automatic ? { environmentName: target.environmentName } : {}) }, stderr);
189
+ }
190
+ const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
191
+ const request = async (timeoutMs, operation) => {
192
+ const deadline = new AbortController();
193
+ const timer = setTimeout(() => deadline.abort(new RequestTimeoutError(timeoutMs)), timeoutMs);
194
+ timer.unref?.();
195
+ try {
196
+ return await operation(makeHttpClient({ ...opts, requestTimeoutMs: timeoutMs }, { ...deps, shutdownSignal: deadline.signal, shutdown }));
197
+ }
198
+ finally {
199
+ clearTimeout(timer);
200
+ }
201
+ };
202
+ const cleanup = (operation) => request(10_000, operation);
203
+ const client = makeHttpClient(opts, { ...deps, shutdownSignal: shutdown.signal, shutdown });
204
+ const active = new Set();
205
+ const terminalRuns = new Map();
206
+ const getRun = client.getRun.bind(client);
207
+ client.getRun = async (runId, options) => {
208
+ const cached = terminalRuns.get(runId);
209
+ if (cached)
210
+ return cached;
211
+ const run = await getRun(runId, options);
212
+ if (isTerminalStatus(run.status))
213
+ terminalRuns.set(runId, run);
214
+ return run;
215
+ };
216
+ const cancellations = new Map();
217
+ let failure;
218
+ let context;
219
+ const cancel = async () => {
220
+ for (const runId of active) {
221
+ try {
222
+ await cleanup(transport => transport.cancelRun(runId));
223
+ cancellations.set(runId, 'cancelled');
224
+ stderr(`[tunnel] Cancellation requested for ${runId}; the owned tunnel is closing.`);
225
+ }
226
+ catch (err) {
227
+ cancellations.set(runId, 'failed');
228
+ stderr(`[tunnel] Could not cancel ${runId}: ${err instanceof Error ? err.message : String(err)}. Use testsprite test cancel ${runId}.`);
229
+ }
230
+ active.delete(runId);
231
+ }
232
+ };
233
+ const disarm = shutdown.arm();
234
+ let session;
235
+ try {
236
+ try {
237
+ session = await openTunnelSession({ log: stderr, logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error' }, {
238
+ mint: ttlSeconds => request(requestTimeoutMs, transport => transport.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
239
+ destroy: clientId => cleanup(transport => transport.deleteTunnel(clientId)),
240
+ createClient: shutdownAwareTunnelClient(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
241
+ });
242
+ }
243
+ catch (err) {
244
+ throw tunnelScopeError(err);
245
+ }
246
+ recordTelemetryTunnelOpened(true);
247
+ if (shutdown.signal.aborted)
248
+ throw shutdown.signal.reason;
249
+ const checkDispatch = () => {
250
+ if (shutdown.signal.aborted)
251
+ throw shutdown.signal.reason;
252
+ if (session.fatalReason())
253
+ throw new TunnelLostError(session.fatalReason(), '', session.fatalMessage());
254
+ };
255
+ // Retain a charged response across the first interrupt, with a total retry deadline.
256
+ const dispatch = (operation) => {
257
+ checkDispatch();
258
+ return request(requestTimeoutMs, operation);
259
+ };
260
+ client.triggerRerun = (...args) => dispatch(transport => transport.triggerRerun(...args));
261
+ client.triggerBatchRerun = (...args) => dispatch(transport => transport.triggerBatchRerun(...args));
262
+ client.triggerTestListRun = (...args) => dispatch(transport => transport.triggerTestListRun(...args));
263
+ client.triggerRunWithMeta = (...args) => dispatch(transport => transport.triggerRunWithMeta(...args));
264
+ const deadlineMs = Date.now() + (opts.timeoutSeconds ?? 600) * 1000;
265
+ const assertCapacityDeadline = () => {
266
+ if (Date.now() >= deadlineMs)
267
+ throw new ApiError({
268
+ code: 'UNSUPPORTED',
269
+ message: `Timed out after ${opts.timeoutSeconds ?? 600}s waiting for tunnel batch capacity.`,
270
+ nextAction: 'The owned tunnel is closing; inspect cancellation with testsprite test cancel <run-id>.',
271
+ requestId: 'local',
272
+ details: {},
273
+ });
274
+ };
275
+ context = {
276
+ client,
277
+ session,
278
+ deadlineMs,
279
+ cancellation: id => {
280
+ const outcome = cancellations.get(id);
281
+ return outcome === 'failed' ? 'cancel-failed' : outcome;
282
+ },
283
+ clientId: session.clientId,
284
+ maxConcurrency: opts.maxConcurrency ?? 5,
285
+ terminalRun: runId => terminalRuns.get(runId),
286
+ waitForCapacity: async (incoming) => {
287
+ assertCapacityDeadline();
288
+ while (active.size + incoming > (opts.maxConcurrency ?? 5)) {
289
+ const runId = active.values().next().value;
290
+ try {
291
+ await pollRunUntilTerminal(client, runId, {
292
+ timeoutSeconds: Math.max(0, (deadlineMs - Date.now()) / 1000),
293
+ shutdown,
294
+ sleep: deps.sleep,
295
+ onTick: run => context.onPoll(run),
296
+ });
297
+ }
298
+ catch (err) {
299
+ if (!(err instanceof TimeoutError))
300
+ throw err;
301
+ throw new ApiError({
302
+ code: 'UNSUPPORTED',
303
+ message: err.message,
304
+ nextAction: `The owned tunnel is closing; inspect cancellation with testsprite test cancel ${runId}.`,
305
+ requestId: 'local',
306
+ details: { runId },
307
+ });
308
+ }
309
+ }
310
+ assertCapacityDeadline();
311
+ },
312
+ confirm: async (response, runIds, requireEcho = true) => {
313
+ for (const id of runIds)
314
+ active.add(id);
315
+ if (requireEcho && runIds.length && response.tunnelClientId !== session.clientId) {
316
+ await cancel();
317
+ throw unsupportedTunnelError(command);
318
+ }
319
+ },
320
+ onPoll: run => {
321
+ if (['passed', 'failed', 'blocked', 'cancelled'].includes(run.status))
322
+ active.delete(run.runId);
323
+ else if (active.has(run.runId) && session.fatalReason())
324
+ throw new TunnelLostError(session.fatalReason(), run.runId, session.fatalMessage());
325
+ },
326
+ };
327
+ return await operation(context);
328
+ }
329
+ catch (err) {
330
+ failure = err;
331
+ throw err;
332
+ }
333
+ finally {
334
+ const closing = [...active];
335
+ await cancel();
336
+ if (failure instanceof InterruptError && closing.length) {
337
+ const runId = closing[0];
338
+ const cancelOutcome = closing.every(id => cancellations.get(id) === 'cancelled')
339
+ ? 'cancelled'
340
+ : 'failed';
341
+ const retry = [...(context?.targets ?? [])]
342
+ .map(([id, target]) => `testsprite test run ${id}${target.environmentName ? ` --env ${quoteEnvironmentName(target.environmentName)}` : ''}`)
343
+ .join('; ') || 'testsprite test run <id>';
344
+ const nextAction = `The owned tunnel is closing; cancellation was ${cancelOutcome === 'cancelled' ? 'requested' : 'attempted'} for ${closing.join(' ')}. Inspect with testsprite test cancel ${closing.join(' ')}. Start a new run with ${retry}.`;
345
+ Object.assign(failure, {
346
+ runWaitContext: true,
347
+ tunnelDetach: { runId, cancel: cancelOutcome, nextAction },
348
+ });
349
+ }
350
+ try {
351
+ await session?.close();
352
+ }
353
+ finally {
354
+ disarm();
355
+ }
356
+ }
357
+ }
358
+ function shutdownAwareTunnelClient(create, signal) {
359
+ return options => {
360
+ const client = create(options);
361
+ return {
362
+ start: async () => {
363
+ if (signal.aborted)
364
+ throw signal.reason;
365
+ await new Promise((resolve, reject) => {
366
+ const abort = () => reject(signal.reason);
367
+ signal.addEventListener('abort', abort, { once: true });
368
+ client
369
+ .start()
370
+ .then(resolve, reject)
371
+ .finally(() => signal.removeEventListener('abort', abort));
372
+ });
373
+ },
374
+ stop: () => {
375
+ const stopped = client.stop();
376
+ if (!signal.aborted)
377
+ return stopped;
378
+ void stopped.catch(() => { });
379
+ return Promise.resolve();
380
+ },
381
+ };
382
+ };
383
+ }
384
+ /** Keep each dispatch on one verbatim loopback URL; public runs omit tunnel fields. */
385
+ export function groupEnvironmentTargets(ids, targets, maxLocalGroupSize = Infinity) {
386
+ const groups = new Map();
387
+ for (const id of ids) {
388
+ const key = targets.get(id)?.targetUrl;
389
+ const group = groups.get(key) ?? [];
390
+ group.push(id);
391
+ groups.set(key, group);
392
+ }
393
+ return [...groups.values()].flatMap(group => {
394
+ if (!targets.has(group[0]) || !Number.isFinite(maxLocalGroupSize))
395
+ return [group];
396
+ const chunks = [];
397
+ for (let index = 0; index < group.length; index += maxLocalGroupSize)
398
+ chunks.push(group.slice(index, index + maxLocalGroupSize));
399
+ return chunks;
400
+ });
401
+ }
402
+ export function quoteEnvironmentName(name) {
403
+ return "'" + name.replaceAll("'", "'\\''") + "'";
404
+ }
405
+ export async function emitEnvironmentDispatchPartial(responses, testIds, opts, deps, label, error, context) {
406
+ const message = error instanceof Error ? error.message : String(error);
407
+ const timedOut = error instanceof RequestTimeoutError ||
408
+ (error instanceof ApiError && error.code === 'UNSUPPORTED' && message.startsWith('Timed out'));
409
+ const accepted = responses
410
+ .flatMap(response => response.accepted)
411
+ .map(row => ({
412
+ ...row,
413
+ status: context.cancellation(row.runId) ??
414
+ context.terminalRun(row.runId)?.status ??
415
+ (timedOut ? 'timeout' : 'running'),
416
+ }));
417
+ const conflicts = responses.flatMap(response => response.conflicts);
418
+ const deferred = responses.flatMap(response => response.deferred);
419
+ const notFound = responses.flatMap(response => response.notFound ?? []);
420
+ const seen = new Set([...accepted, ...conflicts, ...deferred].map(row => row.testId));
421
+ for (const id of notFound)
422
+ seen.add(id);
423
+ const notRunTestIds = testIds.filter(id => !seen.has(id));
424
+ const partial = {
425
+ accepted,
426
+ conflicts,
427
+ deferred,
428
+ ...(context.skipped?.length ? { skipped: context.skipped } : {}),
429
+ notRunTestIds,
430
+ ...(responses.some(response => response.notFound) ? { notFound } : {}),
431
+ };
432
+ const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
433
+ new Output(opts.output, { stdout: deps.stdout, stderr: deps.stderr }).print(partial, () => accepted.map(row => `${row.runId} ${row.status}`).join('\n'));
434
+ const summary = summarizeAcceptedPayload(JSON.stringify(partial));
435
+ summary.runs.push(...notRunTestIds.map(testId => ({
436
+ testId,
437
+ status: 'skipped',
438
+ error: 'not dispatched before the owned tunnel closed',
439
+ })));
440
+ summary.total += notRunTestIds.length;
441
+ summary.skipped += notRunTestIds.length;
442
+ emitCiArtifacts(summary, opts, {
443
+ env: deps.env ?? process.env,
444
+ stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
445
+ stderr,
446
+ }, label);
447
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
448
+ try {
449
+ await writeJUnitReportFile(opts.reportFile, buildJUnitReport({
450
+ suiteName: opts.reportSuiteName ?? `testsprite:${label}`,
451
+ classname: label,
452
+ results: summary.runs.map(row => ({
453
+ testId: row.testId,
454
+ runId: row.runId,
455
+ status: row.status,
456
+ error: { code: error instanceof ApiError ? error.code : 'UNSUPPORTED', message },
457
+ })),
458
+ }));
459
+ }
460
+ catch (err) {
461
+ stderr(`Could not write the partial JUnit report: ${err instanceof Error ? err.message : String(err)}`);
462
+ }
463
+ }
464
+ }
465
+ //# sourceMappingURL=environment-tunnel.js.map
@@ -63,10 +63,9 @@ export declare const TERMINATION_EXIT_CODES: {
63
63
  };
64
64
  export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
65
65
  /**
66
- * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
67
- * graceful-detach scope (the `--wait` polling window) was armed — see
68
- * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
69
- * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
66
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed during an armed
67
+ * wait or a disarmed request. Run/wait paths mark the error so `index.ts` can give
68
+ * recovery guidance only when there is a run to re-attach to.
70
69
  *
71
70
  * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
72
71
  * exits 130/143 without consulting the error catalog. The JSON-mode stderr
@@ -75,6 +74,7 @@ export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
75
74
  */
76
75
  export declare class InterruptError extends CLIError {
77
76
  readonly signal: TerminationSignal;
77
+ runWaitContext: boolean;
78
78
  constructor(signal: TerminationSignal);
79
79
  }
80
80
  export declare class NotImplementedError extends CLIError {
@@ -91,18 +91,18 @@ export interface ErrorEnvelope {
91
91
  error: ErrorEnvelopeBody;
92
92
  }
93
93
  /**
94
- * Server-returned API error. The CLI never invents `code`, `nextAction`,
95
- * or `requestId` — it forwards what the facade returned (or, for
96
- * locally-detected pre-flight conditions like a missing API key,
97
- * constructs an envelope with the same shape so the user sees identical
98
- * wording across paths).
94
+ * Server-returned API error. The CLI preserves the facade's nonempty
95
+ * `nextAction` and synthesizes one for billing refusals that omit it.
96
+ * Locally-detected pre-flight conditions use the same envelope shape.
99
97
  */
100
98
  export declare class ApiError extends CLIError {
101
99
  readonly code: ErrorCode;
102
100
  readonly requestId: string;
103
101
  readonly nextAction: string;
102
+ readonly serverNextAction: string;
104
103
  readonly details: Record<string, unknown>;
105
104
  readonly httpStatus: number | undefined;
105
+ readonly apiUrl: string | undefined;
106
106
  /**
107
107
  * Parsed `Retry-After` header value in milliseconds, when present on the
108
108
  * HTTP response. Only set for `RATE_LIMITED` (429) responses where the
@@ -111,7 +111,7 @@ export declare class ApiError extends CLIError {
111
111
  * absent or unparseable.
112
112
  */
113
113
  readonly retryAfterMs: number | undefined;
114
- constructor(envelope: ErrorEnvelopeBody, httpStatus?: number, retryAfterMs?: number);
114
+ constructor(envelope: ErrorEnvelopeBody, httpStatus?: number, retryAfterMs?: number, apiUrl?: string, serverNextAction?: string);
115
115
  /**
116
116
  * @param apiUrl Optional API endpoint the failing request targeted. Used to
117
117
  * resolve environment-correct portal links in synthesized `nextAction`
@@ -139,7 +139,14 @@ export declare class ApiError extends CLIError {
139
139
  * AUTH_REQUIRED template so the user sees the same thing whether the
140
140
  * miss was detected before or after sending the request.
141
141
  */
142
- static authRequired(requestId?: string): ApiError;
142
+ /**
143
+ * `profile` is supplied only when a NON-default profile was selected — by
144
+ * `--profile` or by `TESTSPRITE_PROFILE`. Naming it matters because the
145
+ * selection is invisible otherwise: a typo in either one picks a profile
146
+ * that has no credentials, and the generic message sends the reader off to
147
+ * configure the default profile they already have.
148
+ */
149
+ static authRequired(requestId?: string, profile?: string): ApiError;
143
150
  }
144
151
  /**
145
152
  * Fabricate a locally-detected VALIDATION_ERROR envelope using the same