@testsprite/testsprite-cli 0.16.0 → 0.18.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 (206) hide show
  1. package/README.md +52 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +40 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +741 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +434 -43
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +19 -186
  19. package/dist/commands/project.js +108 -926
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +216 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1838
  25. package/dist/commands/test.js +1880 -13917
  26. package/dist/commands/testlist.d.ts +130 -5
  27. package/dist/commands/testlist.js +300 -342
  28. package/dist/commands/tunnel.d.ts +3 -3
  29. package/dist/commands/tunnel.js +23 -20
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +191 -110
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +12 -4
  45. package/dist/lib/client-factory.js +41 -30
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +75 -0
  56. package/dist/lib/conversation/api.js +151 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +29 -0
  60. package/dist/lib/conversation/context.js +82 -0
  61. package/dist/lib/conversation/environment.d.ts +16 -0
  62. package/dist/lib/conversation/environment.js +21 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +318 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +158 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +100 -0
  77. package/dist/lib/download.js +408 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +19 -30
  83. package/dist/lib/environment-tunnel.js +168 -202
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +20 -30
  91. package/dist/lib/first-suite-hint.js +57 -72
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +354 -291
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +8 -7
  107. package/dist/lib/local-target.js +14 -13
  108. package/dist/lib/output.d.ts +2 -41
  109. package/dist/lib/output.js +13 -51
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +170 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +73 -0
  127. package/dist/lib/result/evidence.js +422 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +8 -8
  151. package/dist/lib/target-url.js +14 -24
  152. package/dist/lib/telemetry.d.ts +35 -15
  153. package/dist/lib/telemetry.js +38 -9
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +8 -2
  169. package/dist/lib/tunnel-session.js +24 -11
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +52 -23
  183. package/skills/testsprite-onboard.skill.md +70 -153
  184. package/skills/testsprite-verify.codex.md +54 -58
  185. package/skills/testsprite-verify.skill.md +189 -358
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Downloads to the user's disk: a signed storage link streamed to a file, and
3
+ * the guards on where files land (the `--out` directory the user chose, and
4
+ * every name composed under it).
5
+ */
6
+ import { createWriteStream } from 'node:fs';
7
+ import { mkdir, rm, stat, writeFile } from 'node:fs/promises';
8
+ import { Readable, Writable } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
11
+ import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
12
+ import { REQUEST_TIMEOUT_DEFAULT_MS } from './http.js';
13
+ import { globalShutdown } from './interrupt.js';
14
+ import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
15
+ import { disallowedIpReason } from './target-url.js';
16
+ /** Max fetch attempts for each presigned URL (initial + retries). */
17
+ export const STREAM_URL_MAX_RETRIES = 3;
18
+ /** Delay between retries for transient transport failures (ms). */
19
+ export const STREAM_URL_RETRY_DELAY_MS = 1000;
20
+ /** Recording container extensions trusted from a video link. */
21
+ export const KNOWN_VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'mkv', 'avi']);
22
+ /**
23
+ * Strip trailing path separators, tolerating both `/` and `\` since a
24
+ * native Windows `--out` value (typed or pasted from Explorer) commonly
25
+ * ends in a backslash. Preserves a bare drive root (`C:\`) — stripping
26
+ * its separator would turn it into `C:`, which Windows resolves as
27
+ * "current directory on drive C", not the drive root.
28
+ */
29
+ function stripTrailingSeparators(rawPath) {
30
+ if (rawPath.length <= 1)
31
+ return rawPath;
32
+ let end = rawPath.length;
33
+ while (end > 1 && (rawPath[end - 1] === '/' || rawPath[end - 1] === '\\')) {
34
+ if (end === 3 && rawPath[1] === ':' && /[A-Za-z]/.test(rawPath[0]))
35
+ break;
36
+ end--;
37
+ }
38
+ return rawPath.slice(0, end);
39
+ }
40
+ /**
41
+ * Resolve the user-supplied `--out` path into an absolute directory.
42
+ * Empty strings are rejected with `VALIDATION_ERROR`.
43
+ * Nothing is created here: the writer makes
44
+ * the directory once the response has been read, so a failed read never
45
+ * modifies the operator's filesystem.
46
+ */
47
+ export function resolveOutDir(rawPath) {
48
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
49
+ throw ApiError.fromEnvelope({
50
+ error: {
51
+ code: 'VALIDATION_ERROR',
52
+ message: 'Invalid request.',
53
+ nextAction: 'Flag `--out` is invalid: must be a non-empty directory path.',
54
+ requestId: 'local',
55
+ details: { field: 'out', reason: 'must be a non-empty directory path' },
56
+ },
57
+ });
58
+ }
59
+ const trimmed = stripTrailingSeparators(rawPath);
60
+ return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
61
+ }
62
+ /**
63
+ * Validate the `--out` directory before any request goes out. Surfaces
64
+ * `VALIDATION_ERROR` (exit 5) — matches the convention from `closeOutputFile`
65
+ * for single-file `--out` flags.
66
+ *
67
+ * Missing parent directories are fine: the writer creates the whole tree
68
+ * with `mkdir(dir, { recursive: true })` once the response has been read,
69
+ * so a failed read still leaves nothing on disk. What is refused here is a
70
+ * path that can never become a directory: `--out` pointing at an existing
71
+ * file, or a file where one of its parent directories should be.
72
+ *
73
+ * The directory itself (`resolvedDir`) may or may not exist; the writer
74
+ * creates it if absent.
75
+ */
76
+ export async function assertOutDirParentExists(resolvedDir) {
77
+ const closest = await closestExistingPath(dirname(resolvedDir));
78
+ if (!closest.stats.isDirectory()) {
79
+ throw localValidationError('out', `parent path is not a directory: ${closest.path}`);
80
+ }
81
+ // Also guard against --out pointing at an existing FILE (not a dir).
82
+ let targetStat;
83
+ try {
84
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the --out directory the user chose.
85
+ targetStat = await stat(resolvedDir);
86
+ }
87
+ catch {
88
+ // Does not exist yet — fine; the writer will create it.
89
+ return;
90
+ }
91
+ if (!targetStat.isDirectory()) {
92
+ throw localValidationError('out', `must point to a directory, not a file: ${resolvedDir}`);
93
+ }
94
+ }
95
+ /**
96
+ * The nearest path at or above `target` that exists, with its stats. Missing
97
+ * components are skipped. So is a file in the middle of the path (ENOTDIR on
98
+ * POSIX, ENOENT on Windows): the walk stops at that file, and the caller
99
+ * reports it as "not a directory".
100
+ */
101
+ async function closestExistingPath(target) {
102
+ let current = target;
103
+ for (;;) {
104
+ try {
105
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- this is the guard itself: walks up from the parent of the user-supplied --out path after resolve(); stat() only, nothing is read or written.
106
+ return { path: current, stats: await stat(current) };
107
+ }
108
+ catch (err) {
109
+ const code = err.code;
110
+ const up = dirname(current);
111
+ if ((code !== 'ENOENT' && code !== 'ENOTDIR') || up === current) {
112
+ throw localValidationError('out', `cannot access parent path: ${current}`);
113
+ }
114
+ current = up;
115
+ }
116
+ }
117
+ }
118
+ /**
119
+ * Pick the on-disk extension for `video.<ext>` from the actual video link,
120
+ * instead of hardcoding `mp4` (the recording is sometimes a `.webm`
121
+ * container; saving it under a `video.mp4` name misleads strict-extension
122
+ * consumers). Falls back to `mp4` when the URL is malformed or its extension
123
+ * isn't a recognized container, so a response-controlled field can never
124
+ * smuggle an arbitrary suffix onto disk.
125
+ */
126
+ export function pickVideoExtension(url) {
127
+ try {
128
+ const match = /\.([A-Za-z0-9]+)$/.exec(new URL(url).pathname);
129
+ const ext = match?.[1]?.toLowerCase();
130
+ if (ext !== undefined && KNOWN_VIDEO_EXTENSIONS.has(ext))
131
+ return ext;
132
+ }
133
+ catch {
134
+ // Malformed URL — fall through to the default below.
135
+ }
136
+ return 'mp4';
137
+ }
138
+ /**
139
+ * Refuse a composed artifact path that escapes `baseDir`. This is the final
140
+ * containment check before any write. Returns the validated absolute path.
141
+ */
142
+ export function assertNoEscape(baseDir, segment) {
143
+ const composed = resolve(baseDir, segment);
144
+ const rel = relative(baseDir, composed);
145
+ if (rel.startsWith('..') || isAbsolute(rel)) {
146
+ throw localValidationError('out', 'resolved artifact path escapes the --out directory', undefined, 'field');
147
+ }
148
+ return composed;
149
+ }
150
+ /**
151
+ * Stream a presigned URL into a file with bounded retry on transport
152
+ * failures. 4xx (presigned URL expired or unauthorized) is NOT
153
+ * retried — the URL won't recover on its own; an upstream re-fetch
154
+ * is the only fix. Maps to `UNAVAILABLE` so `index.ts` exits 10.
155
+ *
156
+ * Streaming uses `pipeline` to honor backpressure: a slow disk pauses
157
+ * the upstream reader rather than buffering chunks in V8 heap. This
158
+ * matters for video files (multi-MB) and for very large HTML
159
+ * snapshots.
160
+ *
161
+ * Transport failures (network reset, DNS blip, mid-stream EOF) are
162
+ * retried up to STREAM_URL_MAX_RETRIES times with a fixed delay, well
163
+ * inside a signed link's lifetime. A file whose last attempt broke off
164
+ * mid-stream is left as far as it got: the caller removes it.
165
+ *
166
+ * Only an `https` link to a host that is not a literal local or private
167
+ * address is fetched; any other link is refused before a request is made.
168
+ *
169
+ * `stallTimeoutMs` bounds each wait for data: for the response to start, and
170
+ * between two chunks of its body. It does not bound the whole download, so a
171
+ * large file that keeps arriving is never cut off. A stalled download is not
172
+ * retried.
173
+ */
174
+ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
175
+ const refusal = refusedDownloadUrl(url);
176
+ if (refusal !== undefined) {
177
+ throw ApiError.fromEnvelope({
178
+ error: {
179
+ code: 'UNAVAILABLE',
180
+ message: `Refused to download ${redactArtifactUrlForDetails(url)}: ${refusal}.`,
181
+ nextAction: 'Evidence is downloaded only from https storage links. If this result came from the TestSprite API, report it.',
182
+ requestId: 'local',
183
+ details: { artifactUrl: redactArtifactUrlForDetails(url) },
184
+ },
185
+ });
186
+ }
187
+ const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
188
+ const shutdown = deps?.shutdown ?? globalShutdown;
189
+ return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal, deps?.stallTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS));
190
+ }
191
+ /**
192
+ * Why a link is not downloaded, or `undefined` when it may be. The host is
193
+ * judged as written: a name is not resolved, so a proxy or a private storage
194
+ * endpoint reached by name keeps working.
195
+ */
196
+ export function refusedDownloadUrl(url) {
197
+ let parsed;
198
+ try {
199
+ parsed = new URL(url);
200
+ }
201
+ catch {
202
+ return 'it is not a URL';
203
+ }
204
+ if (parsed.protocol !== 'https:')
205
+ return 'only https links are downloaded';
206
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
207
+ const local = host === 'localhost' || host.endsWith('.localhost') || disallowedIpReason(host) !== undefined;
208
+ return local ? 'it points at a local or private address' : undefined;
209
+ }
210
+ /** A download that stopped receiving data. Never retried. */
211
+ class DownloadStalledError extends TransportError {
212
+ constructor(artifactUrl, stallTimeoutMs) {
213
+ super(`Download of ${artifactUrl} stalled: no data for ${Math.round(stallTimeoutMs / 1000)}s.`, 'local', {
214
+ nextAction: 'Re-run the command. Use --request-timeout <seconds> or TESTSPRITE_REQUEST_TIMEOUT_MS to wait longer for a slow link.',
215
+ });
216
+ }
217
+ }
218
+ /** One attempt's stall clock: `signal` aborts when `arm` is not called again in time. */
219
+ export function stallClock(stallTimeoutMs) {
220
+ const stalled = new AbortController();
221
+ let timer;
222
+ const stop = () => clearTimeout(timer);
223
+ const arm = () => {
224
+ stop();
225
+ timer = setTimeout(() => stalled.abort(), stallTimeoutMs);
226
+ };
227
+ return { signal: stalled.signal, arm, stop };
228
+ }
229
+ async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal, stallTimeoutMs) {
230
+ const artifactUrl = redactArtifactUrlForDetails(url);
231
+ for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
232
+ if (shutdownSignal.aborted)
233
+ throw shutdownSignal.reason;
234
+ const clock = stallClock(stallTimeoutMs);
235
+ try {
236
+ const done = await streamAttempt(url, filePath, fetchImpl, sleepFn, shutdownSignal, clock, artifactUrl, attempt);
237
+ if (done)
238
+ return;
239
+ }
240
+ catch (err) {
241
+ if (clock.signal.aborted && !shutdownSignal.aborted) {
242
+ throw new DownloadStalledError(artifactUrl, stallTimeoutMs);
243
+ }
244
+ throw err;
245
+ }
246
+ finally {
247
+ clock.stop();
248
+ }
249
+ }
250
+ }
251
+ /**
252
+ * A sink that writes each chunk to `file` with the stall clock stopped, and
253
+ * starts it again once the write is done: the clock runs only while the next
254
+ * chunk is awaited, so time the disk takes is not time the link was silent.
255
+ * A failed write is the stream's error, and no further write is started.
256
+ */
257
+ export function stallTimedSink(file, clock) {
258
+ const sink = new Writable({
259
+ write(chunk, _encoding, callback) {
260
+ clock.stop();
261
+ file.write(chunk, err => {
262
+ if (!err)
263
+ clock.arm();
264
+ callback(err);
265
+ });
266
+ },
267
+ final(callback) {
268
+ clock.stop();
269
+ file.end(callback);
270
+ },
271
+ destroy(err, callback) {
272
+ clock.stop();
273
+ file.destroy();
274
+ callback(err);
275
+ },
276
+ });
277
+ // A failure outside a write (the file could not be opened) ends the download too.
278
+ file.on('error', err => sink.destroy(err));
279
+ return sink;
280
+ }
281
+ /** `work`, unless `stalled` aborts first. */
282
+ function orStalled(work, stalled) {
283
+ return new Promise((resolve, reject) => {
284
+ const onStall = () => reject(new Error('stalled'));
285
+ stalled.addEventListener('abort', onStall, { once: true });
286
+ work.then(resolve, reject).finally(() => stalled.removeEventListener('abort', onStall));
287
+ });
288
+ }
289
+ /** One attempt: true when the file is written, false when the next attempt is due. */
290
+ async function streamAttempt(url, filePath, fetchImpl, sleepFn, shutdownSignal, clock, artifactUrl, attempt) {
291
+ let response;
292
+ clock.arm();
293
+ try {
294
+ response = await fetchImpl(url, {
295
+ redirect: 'error',
296
+ signal: AbortSignal.any([shutdownSignal, clock.signal]),
297
+ });
298
+ }
299
+ catch (err) {
300
+ if (err instanceof InterruptError || shutdownSignal.aborted)
301
+ throw shutdownSignal.reason ?? err;
302
+ if (clock.signal.aborted)
303
+ throw err;
304
+ const message = err instanceof Error ? err.message : String(err);
305
+ if (attempt < STREAM_URL_MAX_RETRIES) {
306
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
307
+ return false;
308
+ }
309
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
310
+ }
311
+ // The response has started: that wait is over, and the body's waits are its own.
312
+ clock.stop();
313
+ if (shutdownSignal.aborted)
314
+ throw shutdownSignal.reason;
315
+ if (!response.ok) {
316
+ // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
317
+ // Retrying the same URL won't help — surface immediately.
318
+ throw ApiError.fromEnvelope({
319
+ error: {
320
+ code: 'UNAVAILABLE',
321
+ message: `Failed to download presigned URL (HTTP ${response.status}).`,
322
+ nextAction: 'Signed links expire. Re-run `testsprite result get <result-id> --out <dir>`: each read signs new ones.',
323
+ requestId: 'local',
324
+ details: { status: response.status, artifactUrl },
325
+ },
326
+ });
327
+ }
328
+ if (!response.body) {
329
+ // Some test runtimes / fetch polyfills don't expose `body` as a
330
+ // ReadableStream. Fall back to a buffered write — same correctness,
331
+ // just no streaming benefit. Even a multi-MB video buffers fully in
332
+ // a tolerable amount of memory.
333
+ try {
334
+ clock.arm();
335
+ const buffer = Buffer.from(await orStalled(response.arrayBuffer(), clock.signal));
336
+ clock.stop();
337
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
338
+ await writeFile(filePath, buffer);
339
+ if (shutdownSignal.aborted) {
340
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
341
+ await rm(filePath, { force: true }).catch(() => undefined);
342
+ throw shutdownSignal.reason;
343
+ }
344
+ return true;
345
+ }
346
+ catch (err) {
347
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
348
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
349
+ await rm(filePath, { force: true }).catch(() => undefined);
350
+ throw shutdownSignal.reason ?? err;
351
+ }
352
+ if (clock.signal.aborted)
353
+ throw err;
354
+ const message = err instanceof Error ? err.message : String(err);
355
+ if (attempt < STREAM_URL_MAX_RETRIES) {
356
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
357
+ return false;
358
+ }
359
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
360
+ }
361
+ }
362
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the directory of a file under the --out directory the user chose.
363
+ await mkdir(dirname(filePath), { recursive: true });
364
+ // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
365
+ // it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
366
+ // from the stream propagates as a TransportError, preserving the
367
+ // exit-code contract. `pipeline` destroys both streams on error, so
368
+ // a new WriteStream on retry starts clean.
369
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
370
+ const fileSink = createWriteStream(filePath);
371
+ try {
372
+ const webBody = response.body;
373
+ clock.arm();
374
+ await pipeline(Readable.fromWeb(webBody), stallTimedSink(fileSink, clock));
375
+ if (shutdownSignal.aborted)
376
+ throw shutdownSignal.reason;
377
+ return true;
378
+ }
379
+ catch (err) {
380
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
381
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
382
+ await rm(filePath, { force: true }).catch(() => undefined);
383
+ throw shutdownSignal.reason ?? err;
384
+ }
385
+ if (clock.signal.aborted)
386
+ throw err;
387
+ const message = err instanceof Error ? err.message : String(err);
388
+ if (attempt < STREAM_URL_MAX_RETRIES) {
389
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
390
+ return false;
391
+ }
392
+ throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
393
+ }
394
+ }
395
+ function redactArtifactUrlForDetails(url) {
396
+ try {
397
+ const parsed = new URL(url);
398
+ // A `data:` link is its own content, and a `file:` one a local path.
399
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
400
+ return `<${parsed.protocol.slice(0, -1)} link>`;
401
+ }
402
+ return `${parsed.origin}${parsed.pathname}`;
403
+ }
404
+ catch {
405
+ return '<invalid-url>';
406
+ }
407
+ }
408
+ //# sourceMappingURL=download.js.map
@@ -16,3 +16,13 @@
16
16
  */
17
17
  import type { FetchImpl } from '../http.js';
18
18
  export declare function createDryRunFetch(): FetchImpl;
19
+ /**
20
+ * Wrap a dry-run fetch implementation so `onFirstResponse` fires exactly
21
+ * once — after the first request actually returns a response. The client
22
+ * factory applies this to whichever fetch is in use (the default canned
23
+ * fetch or an injected test fetch), so the dry-run banner is announced
24
+ * lazily: never at client construction, and never when local validation
25
+ * fails before any dry-run response is produced. If the wrapped fetch
26
+ * rejects, no banner fires.
27
+ */
28
+ export declare function withDryRunBannerOnce(fetch: FetchImpl, onFirstResponse: () => void): FetchImpl;
@@ -40,6 +40,26 @@ export function createDryRunFetch() {
40
40
  return new Response(JSON.stringify(sample.body()), { status: 200, headers: JSON_HEADERS });
41
41
  };
42
42
  }
43
+ /**
44
+ * Wrap a dry-run fetch implementation so `onFirstResponse` fires exactly
45
+ * once — after the first request actually returns a response. The client
46
+ * factory applies this to whichever fetch is in use (the default canned
47
+ * fetch or an injected test fetch), so the dry-run banner is announced
48
+ * lazily: never at client construction, and never when local validation
49
+ * fails before any dry-run response is produced. If the wrapped fetch
50
+ * rejects, no banner fires.
51
+ */
52
+ export function withDryRunBannerOnce(fetch, onFirstResponse) {
53
+ let fired = false;
54
+ return async (input, init) => {
55
+ const res = await fetch(input, init);
56
+ if (!fired) {
57
+ fired = true;
58
+ onFirstResponse();
59
+ }
60
+ return res;
61
+ };
62
+ }
43
63
  function resolveUrl(input) {
44
64
  if (typeof input === 'string')
45
65
  return input;
@@ -1,4 +1,3 @@
1
- export declare const SAMPLE_RUN_ID = "run_abc";
2
1
  export declare const SAMPLE_DRY_RUN_REQUEST_ID = "req_dry-run";
3
2
  /**
4
3
  * Canned JUnit XML for batch `--wait --report junit --dry-run`. Mirrors the
@@ -8,16 +7,10 @@ export declare function sampleJUnitReportXml(projectId?: string, reportSuiteName
8
7
  /**
9
8
  * Dry-run sample lookup keyed by OpenAPI operationId. Order matters in
10
9
  * {@link findSample}: more specific patterns must precede their generic
11
- * siblings (e.g. `/tests/{id}/code` before `/tests/{id}`).
10
+ * siblings (e.g. `/projects/{id}/env` before `/projects/{id}`).
12
11
  */
13
12
  /**
14
- * HTTP methods accepted by the dry-run registry. GET covered the M2
15
- * read surface; POST landed with M3.2 piece-2 (`POST /api/cli/v1/tests`)
16
- * and gained `/tests/batch` with M3.2 piece-5; PUT + DELETE landed with
17
- * M3.2 piece-3 (`PUT/DELETE /api/cli/v1/tests/{id}`); piece-4 added
18
- * `PUT /api/cli/v1/tests/{id}/code`; piece-6 added
19
- * `PUT /api/cli/v1/tests/{id}/plan-steps`. The list grows as new
20
- * mutation routes ship.
13
+ * HTTP methods accepted by the dry-run registry.
21
14
  */
22
15
  export type DryRunMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
23
16
  export interface DryRunSampleEntry {
@@ -33,41 +26,20 @@ export interface DryRunSampleEntry {
33
26
  * receives the parsed request body so the sample can echo back the
34
27
  * user's actual field values instead of a static canned placeholder.
35
28
  * Simple read-only endpoints use a zero-arity factory that ignores the
36
- * argument.
29
+ * argument. A read whose answer depends on its query (`GET /results`)
30
+ * receives the query too; the query never takes part in matching.
37
31
  */
38
- body: (requestBody?: unknown) => unknown;
32
+ body: (requestBody?: unknown, query?: URLSearchParams) => unknown;
39
33
  }
40
34
  /**
41
35
  * Build the matcher RegExp for a route template, e.g.
42
- * `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/. Splits on the
36
+ * `/results/{resultId}` → /^\/results\/[^/]+$/. Splits on the
43
37
  * `{param}` placeholders first, then regex-escapes every literal segment in
44
38
  * between (including any literal backslash) so a route literal containing a
45
39
  * regex metacharacter is matched literally instead of being reinterpreted as
46
40
  * part of the pattern.
47
41
  */
48
42
  declare function buildPathPattern(pathTemplate: string): RegExp;
49
- /**
50
- * Resolve a fetch URL to its canned sample. Matches against the path
51
- * portion only (query string is ignored — auto-pagination's `cursor`
52
- * query is intentionally a no-op in M2 dry-run; see {@link pageOf}).
53
- *
54
- * Returns `undefined` when no pattern matches; the caller (the dry-run
55
- * fetch impl) surfaces this as a 500 INTERNAL envelope so a missing
56
- * sample is loud, not silent.
57
- *
58
- * `requestBody` is forwarded to input-derived entries (`updateTest`,
59
- * `putPlanSteps`, `createTestBatch`) so their responses reflect the
60
- * user's actual flags rather than static canned values.
61
- */
62
- /**
63
- * Like {@link findSample}, but a missing sample throws instead of returning
64
- * `undefined`. For dry-run paths that resolve samples DIRECTLY (bypassing the
65
- * dry-run fetch impl, which has its own loud INTERNAL envelope for this):
66
- * without the throw, a lost registry entry surfaces as a raw TypeError deep
67
- * in a renderer (`samples.ts` is a real merge-conflict
68
- * hotspot, so a silently dropped entry is a live hazard, not a hypothetical).
69
- */
70
- export declare function findSampleOrThrow(method: string, url: string, requestBody?: unknown): DryRunSampleEntry;
71
43
  export declare function findSample(method: string, url: string, requestBody?: unknown): DryRunSampleEntry | undefined;
72
44
  /** Test-only export so `samples.test.ts` can iterate the catalog. */
73
45
  export declare const DRY_RUN_SAMPLE_ENTRIES: ReadonlyArray<DryRunSampleEntry>;