@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
@@ -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
@@ -1,4 +1,5 @@
1
1
  import { resolvePortalBase } from './facade.js';
2
+ import { redactDeep } from './redact.js';
2
3
  import { classifyBillingRefusal, gateRefusalOf } from './billing-refusal.js';
3
4
  /**
4
5
  * Error codes shared with the backend facade and the MCP plugin.
@@ -227,7 +228,17 @@ export class ApiError extends CLIError {
227
228
  this.requestId = envelope.requestId;
228
229
  this.nextAction = envelope.nextAction;
229
230
  this.serverNextAction = serverNextAction ?? envelope.nextAction;
230
- this.details = envelope.details;
231
+ // Redact at the single point every ApiError is constructed — server
232
+ // envelopes (fromEnvelope), locally-fabricated ones (authRequired,
233
+ // localValidationError), and any future direct `new ApiError(...)` — so
234
+ // `.details` and `.getDetail(...)` are already clean everywhere they are
235
+ // read: `Output.error`'s JSON envelope, `index.ts`'s hand-built ApiError
236
+ // envelope, and the AUTH_FORBIDDEN/CLIENT_TOO_OLD/AMBIGUOUS_ORG text-mode
237
+ // blocks in `index.ts` that print specific detail keys directly (those
238
+ // never go through `Output.error` at all, so redacting only at the
239
+ // render call sites would miss them). Server envelopes are already
240
+ // redacted server-side; this is defence in depth, not the only layer.
241
+ this.details = redactDeep(envelope.details);
231
242
  this.httpStatus = httpStatus;
232
243
  this.apiUrl = apiUrl;
233
244
  this.retryAfterMs = retryAfterMs;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * "You have a project, but no tests yet" signposts.
3
+ *
4
+ * A user who is not driving a coding agent otherwise never learns that
5
+ * `test plan generate` exists: `project create` used to print the record and
6
+ * stop, and the empty-project outputs said only "No tests." Every variant also
7
+ * names the hand-authored fallback, because an account not yet on the new
8
+ * platform is refused by generate and pointed at the Portal.
9
+ *
10
+ * Text mode only at every call site: a JSON caller already holds the project
11
+ * id, and stdout and the JSON error envelope must stay unchanged. Never under
12
+ * --dry-run (the id there is the canned sample). Printing a hint runs and
13
+ * charges nothing; the generation it points at does use credits.
14
+ *
15
+ * Zero requests: each call site branches only on what it already knows.
16
+ * `project create` knows the type and whether the app is local; `test run
17
+ * --all --local` knows it is local. `test list` and a cloud `test run --all`
18
+ * know neither, so their sentence names the backend prerequisite as a clause
19
+ * and leaves a local project to the backend's own pre-charge refusal, which
20
+ * carries the same hand-written-plan next step.
21
+ */
22
+ import { type StoredLocalTarget } from './local-target.js';
23
+ /**
24
+ * How the run that found the project empty chose its local target, so the
25
+ * suggested `test run` reaches the same app with the same environment:
26
+ * `port`/`host` only for an explicit `--local`, `targetUrl` for an explicit
27
+ * `--target-url`, and `environment` for `--env` or the saved environment the
28
+ * tunnel was resolved from.
29
+ */
30
+ export type LocalHint = {
31
+ host?: StoredLocalTarget['host'];
32
+ port?: number;
33
+ targetUrl?: string;
34
+ environment?: string;
35
+ };
36
+ export declare const FIRST_SUITE_FALLBACK = "testsprite test create --plan-template";
37
+ /**
38
+ * Multi-line `[hint]` block for stderr after a real `project create` of a
39
+ * deployed (non-`--local`) project. A `--local` project gets no hint here:
40
+ * its text record already ends with the hand-written-plan next steps (plan
41
+ * generation explores from the cloud with no tunnel, and the backend refuses
42
+ * it for a local-origin project before any charge), and two "Next" blocks
43
+ * would disagree.
44
+ */
45
+ export declare function firstSuiteNextSteps(projectId: string, type: string): string;
46
+ /**
47
+ * One sentence for an EMPTY project; folded into an error message or a hint.
48
+ *
49
+ * Pass `local` only where the caller knows the project runs on this machine
50
+ * (`test run --all --local`); see the module comment for why the other
51
+ * callers cannot.
52
+ */
53
+ export declare function emptyProjectNextStep(projectId: string, local?: LocalHint | null): string;
54
+ /** The same sentence as a stderr `[hint]` line. */
55
+ export declare function emptyProjectHint(projectId: string, local?: LocalHint | null): string;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * "You have a project, but no tests yet" signposts.
3
+ *
4
+ * A user who is not driving a coding agent otherwise never learns that
5
+ * `test plan generate` exists: `project create` used to print the record and
6
+ * stop, and the empty-project outputs said only "No tests." Every variant also
7
+ * names the hand-authored fallback, because an account not yet on the new
8
+ * platform is refused by generate and pointed at the Portal.
9
+ *
10
+ * Text mode only at every call site: a JSON caller already holds the project
11
+ * id, and stdout and the JSON error envelope must stay unchanged. Never under
12
+ * --dry-run (the id there is the canned sample). Printing a hint runs and
13
+ * charges nothing; the generation it points at does use credits.
14
+ *
15
+ * Zero requests: each call site branches only on what it already knows.
16
+ * `project create` knows the type and whether the app is local; `test run
17
+ * --all --local` knows it is local. `test list` and a cloud `test run --all`
18
+ * know neither, so their sentence names the backend prerequisite as a clause
19
+ * and leaves a local project to the backend's own pre-charge refusal, which
20
+ * carries the same hand-written-plan next step.
21
+ */
22
+ import { quoteEnvironmentName } from './environment-tunnel.js';
23
+ import { DEFAULT_LOCAL_HOST } from './local-target.js';
24
+ export const FIRST_SUITE_FALLBACK = 'testsprite test create --plan-template';
25
+ /**
26
+ * `test run <test-id>` with the target flags the empty run was given. A bare
27
+ * `test run` would resolve the project's DEFAULT environment, which may be a
28
+ * deployed site rather than the app on this machine, so the environment is
29
+ * always named when one was used. `--local-host` is carried whenever the host
30
+ * is not the default: without it a `::1` or `localhost` app would be run
31
+ * against 127.0.0.1.
32
+ */
33
+ function localRunCommand(local) {
34
+ const flags = [];
35
+ if (local.targetUrl !== undefined) {
36
+ flags.push(`--target-url ${shellWord(local.targetUrl)}`);
37
+ }
38
+ else if (local.port !== undefined) {
39
+ flags.push(`--local ${local.port}`);
40
+ if (local.host !== undefined && local.host !== DEFAULT_LOCAL_HOST)
41
+ flags.push(`--local-host ${local.host}`);
42
+ }
43
+ if (local.environment !== undefined)
44
+ flags.push(`--env ${quoteEnvironmentName(local.environment)}`);
45
+ return ['testsprite test run <test-id>', ...flags].join(' ');
46
+ }
47
+ /** A URL as one shell word: as typed when it is plain, single-quoted otherwise. */
48
+ function shellWord(value) {
49
+ return /^[\w.:/@%+=,~-]+$/.test(value) ? value : quoteEnvironmentName(value);
50
+ }
51
+ /**
52
+ * Multi-line `[hint]` block for stderr after a real `project create` of a
53
+ * deployed (non-`--local`) project. A `--local` project gets no hint here:
54
+ * its text record already ends with the hand-written-plan next steps (plan
55
+ * generation explores from the cloud with no tunnel, and the backend refuses
56
+ * it for a local-origin project before any charge), and two "Next" blocks
57
+ * would disagree.
58
+ */
59
+ export function firstSuiteNextSteps(projectId, type) {
60
+ const backend = type === 'backend';
61
+ const lead = backend
62
+ ? 'Next: upload your API spec, then let TestSprite propose your first tests (uses credits), review them, then accept:'
63
+ : 'Next: let TestSprite propose your first tests (uses credits), review them, then accept:';
64
+ const steps = [
65
+ ...(backend ? [`testsprite project docs upload <api-spec.yaml> --project ${projectId}`] : []),
66
+ `testsprite test plan generate --project ${projectId}`,
67
+ `testsprite test plan accept --project ${projectId}`,
68
+ ];
69
+ return [
70
+ `[hint] ${lead}`,
71
+ ...steps.map(s => ` ${s}`),
72
+ ` Prefer to write one yourself: ${FIRST_SUITE_FALLBACK}`,
73
+ ].join('\n');
74
+ }
75
+ /**
76
+ * One sentence for an EMPTY project; folded into an error message or a hint.
77
+ *
78
+ * Pass `local` only where the caller knows the project runs on this machine
79
+ * (`test run --all --local`); see the module comment for why the other
80
+ * callers cannot.
81
+ */
82
+ export function emptyProjectNextStep(projectId, local) {
83
+ if (local) {
84
+ return (`This project has no tests yet, and plan generation cannot reach an app on your machine yet. ` +
85
+ `Write a plan yourself: ${FIRST_SUITE_FALLBACK} > first.plan.json, ` +
86
+ `set projectId to ${projectId} in it and edit the steps, create it with ` +
87
+ `testsprite test create --plan-from first.plan.json, ` +
88
+ `then run it with ${localRunCommand(local)}`);
89
+ }
90
+ return (`This project has no tests yet. Get a first set: ` +
91
+ `testsprite test plan generate --project ${projectId}, then ` +
92
+ `testsprite test plan accept --project ${projectId} ` +
93
+ `(generation uses credits; a backend project needs its API spec uploaded first: ` +
94
+ `testsprite project docs upload <spec> --project ${projectId}). ` +
95
+ `Or write one yourself: ${FIRST_SUITE_FALLBACK}`);
96
+ }
97
+ /** The same sentence as a stderr `[hint]` line. */
98
+ export function emptyProjectHint(projectId, local) {
99
+ return `[hint] ${emptyProjectNextStep(projectId, local)}`;
100
+ }
101
+ //# sourceMappingURL=first-suite-hint.js.map