@testsprite/testsprite-cli 0.15.0 → 0.17.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 (207) hide show
  1. package/README.md +53 -141
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +55 -65
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +44 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +297 -489
  8. package/dist/commands/completion.js +2 -1
  9. package/dist/commands/conversation.d.ts +27 -0
  10. package/dist/commands/conversation.js +702 -0
  11. package/dist/commands/doctor.d.ts +5 -1
  12. package/dist/commands/doctor.js +130 -34
  13. package/dist/commands/init.d.ts +4 -45
  14. package/dist/commands/init.js +116 -68
  15. package/dist/commands/project-env.d.ts +62 -2
  16. package/dist/commands/project-env.js +426 -53
  17. package/dist/commands/project-sign-in.d.ts +0 -48
  18. package/dist/commands/project-sign-in.js +1 -224
  19. package/dist/commands/project.d.ts +15 -186
  20. package/dist/commands/project.js +93 -921
  21. package/dist/commands/result.d.ts +10 -0
  22. package/dist/commands/result.js +215 -0
  23. package/dist/commands/schedule.d.ts +0 -29
  24. package/dist/commands/schedule.js +47 -97
  25. package/dist/commands/test.d.ts +315 -1824
  26. package/dist/commands/test.js +1962 -13733
  27. package/dist/commands/testlist.d.ts +128 -5
  28. package/dist/commands/testlist.js +269 -329
  29. package/dist/commands/tunnel.d.ts +2 -2
  30. package/dist/commands/tunnel.js +43 -41
  31. package/dist/commands/usage.d.ts +12 -45
  32. package/dist/commands/usage.js +51 -131
  33. package/dist/index.js +189 -108
  34. package/dist/lib/agent-detect.js +9 -5
  35. package/dist/lib/agent-targets.d.ts +21 -2
  36. package/dist/lib/agent-targets.js +88 -11
  37. package/dist/lib/args.d.ts +13 -0
  38. package/dist/lib/args.js +49 -0
  39. package/dist/lib/basic-auth.d.ts +3 -0
  40. package/dist/lib/basic-auth.js +15 -0
  41. package/dist/lib/billing-refusal.js +4 -3
  42. package/dist/lib/ci-linkage.d.ts +4 -82
  43. package/dist/lib/ci-linkage.js +4 -157
  44. package/dist/lib/ci-run.js +1 -1
  45. package/dist/lib/client-factory.d.ts +10 -2
  46. package/dist/lib/client-factory.js +38 -26
  47. package/dist/lib/commit-signal.d.ts +65 -0
  48. package/dist/lib/commit-signal.js +305 -0
  49. package/dist/lib/concurrency-limiter.d.ts +6 -0
  50. package/dist/lib/concurrency-limiter.js +29 -0
  51. package/dist/lib/config.js +10 -5
  52. package/dist/lib/conflict-reason.d.ts +31 -4
  53. package/dist/lib/conflict-reason.js +38 -4
  54. package/dist/lib/conversation/answers.d.ts +9 -0
  55. package/dist/lib/conversation/answers.js +49 -0
  56. package/dist/lib/conversation/api.d.ts +71 -0
  57. package/dist/lib/conversation/api.js +150 -0
  58. package/dist/lib/conversation/change.d.ts +31 -0
  59. package/dist/lib/conversation/change.js +124 -0
  60. package/dist/lib/conversation/context.d.ts +19 -0
  61. package/dist/lib/conversation/context.js +70 -0
  62. package/dist/lib/conversation/environment.d.ts +15 -0
  63. package/dist/lib/conversation/environment.js +33 -0
  64. package/dist/lib/conversation/follow.d.ts +24 -0
  65. package/dist/lib/conversation/follow.js +42 -0
  66. package/dist/lib/conversation/render.d.ts +33 -0
  67. package/dist/lib/conversation/render.js +315 -0
  68. package/dist/lib/conversation/title.d.ts +2 -0
  69. package/dist/lib/conversation/title.js +18 -0
  70. package/dist/lib/conversation/types.d.ts +156 -0
  71. package/dist/lib/conversation/types.js +6 -0
  72. package/dist/lib/credentials.js +67 -11
  73. package/dist/lib/cron.d.ts +1 -1
  74. package/dist/lib/cron.js +2 -2
  75. package/dist/lib/dispatch-stop.d.ts +20 -0
  76. package/dist/lib/dispatch-stop.js +30 -0
  77. package/dist/lib/download.d.ts +71 -0
  78. package/dist/lib/download.js +274 -0
  79. package/dist/lib/dry-run/fetch.d.ts +10 -0
  80. package/dist/lib/dry-run/fetch.js +20 -0
  81. package/dist/lib/dry-run/samples.d.ts +6 -34
  82. package/dist/lib/dry-run/samples.js +389 -751
  83. package/dist/lib/environment-tunnel.d.ts +16 -26
  84. package/dist/lib/environment-tunnel.js +161 -157
  85. package/dist/lib/errors.d.ts +20 -4
  86. package/dist/lib/errors.js +36 -16
  87. package/dist/lib/facade.d.ts +7 -29
  88. package/dist/lib/facade.js +7 -36
  89. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  90. package/dist/lib/failing-fe-resolver.js +47 -132
  91. package/dist/lib/first-suite-hint.d.ts +16 -22
  92. package/dist/lib/first-suite-hint.js +38 -47
  93. package/dist/lib/gh-output.d.ts +76 -21
  94. package/dist/lib/gh-output.js +171 -90
  95. package/dist/lib/git-utils.d.ts +56 -0
  96. package/dist/lib/git-utils.js +212 -0
  97. package/dist/lib/github-context.d.ts +2 -0
  98. package/dist/lib/github-context.js +40 -8
  99. package/dist/lib/history-retention.d.ts +6 -2
  100. package/dist/lib/history-retention.js +10 -7
  101. package/dist/lib/http.d.ts +58 -134
  102. package/dist/lib/http.js +352 -271
  103. package/dist/lib/interrupt.d.ts +14 -8
  104. package/dist/lib/interrupt.js +28 -10
  105. package/dist/lib/junit-report.d.ts +60 -4
  106. package/dist/lib/junit-report.js +209 -32
  107. package/dist/lib/local-target.d.ts +3 -3
  108. package/dist/lib/local-target.js +3 -3
  109. package/dist/lib/output.d.ts +0 -29
  110. package/dist/lib/output.js +10 -33
  111. package/dist/lib/pagination.d.ts +2 -5
  112. package/dist/lib/pagination.js +2 -5
  113. package/dist/lib/presigned-url.d.ts +22 -0
  114. package/dist/lib/presigned-url.js +90 -0
  115. package/dist/lib/prompt.js +36 -2
  116. package/dist/lib/proxy.js +2 -1
  117. package/dist/lib/redact.d.ts +2 -2
  118. package/dist/lib/redact.js +3 -4
  119. package/dist/lib/removed-commands.d.ts +18 -0
  120. package/dist/lib/removed-commands.js +154 -0
  121. package/dist/lib/render-error.d.ts +31 -6
  122. package/dist/lib/render-error.js +88 -25
  123. package/dist/lib/response-schemas.d.ts +38 -30
  124. package/dist/lib/response-schemas.js +210 -207
  125. package/dist/lib/result/api.d.ts +24 -0
  126. package/dist/lib/result/api.js +28 -0
  127. package/dist/lib/result/evidence.d.ts +71 -0
  128. package/dist/lib/result/evidence.js +420 -0
  129. package/dist/lib/result/render.d.ts +20 -0
  130. package/dist/lib/result/render.js +194 -0
  131. package/dist/lib/result/types.d.ts +122 -0
  132. package/dist/lib/result/types.js +19 -0
  133. package/dist/lib/run-output.d.ts +275 -0
  134. package/dist/lib/run-output.js +227 -0
  135. package/dist/lib/run-render.d.ts +101 -0
  136. package/dist/lib/run-render.js +183 -0
  137. package/dist/lib/run-wait.d.ts +192 -0
  138. package/dist/lib/run-wait.js +452 -0
  139. package/dist/lib/runs.types.d.ts +134 -367
  140. package/dist/lib/runs.types.js +0 -14
  141. package/dist/lib/secret-file.d.ts +1 -1
  142. package/dist/lib/secret-file.js +11 -2
  143. package/dist/lib/skill-nudge.d.ts +7 -27
  144. package/dist/lib/skill-nudge.js +9 -37
  145. package/dist/lib/target-path.d.ts +15 -0
  146. package/dist/lib/target-path.js +35 -0
  147. package/dist/lib/target-url-advisory.d.ts +19 -0
  148. package/dist/lib/target-url-advisory.js +31 -0
  149. package/dist/lib/target-url-preflight.d.ts +9 -0
  150. package/dist/lib/target-url-preflight.js +214 -106
  151. package/dist/lib/target-url.d.ts +1 -1
  152. package/dist/lib/target-url.js +6 -16
  153. package/dist/lib/telemetry.d.ts +32 -12
  154. package/dist/lib/telemetry.js +39 -8
  155. package/dist/lib/terminal-text.d.ts +41 -0
  156. package/dist/lib/terminal-text.js +127 -0
  157. package/dist/lib/testlist.types.d.ts +16 -8
  158. package/dist/lib/testlist.types.js +1 -1
  159. package/dist/lib/text-equality.d.ts +2 -0
  160. package/dist/lib/text-equality.js +5 -0
  161. package/dist/lib/text-file.d.ts +16 -0
  162. package/dist/lib/text-file.js +41 -0
  163. package/dist/lib/text-table.d.ts +46 -0
  164. package/dist/lib/text-table.js +72 -4
  165. package/dist/lib/ticker.d.ts +9 -2
  166. package/dist/lib/ticker.js +16 -3
  167. package/dist/lib/transport-failure.d.ts +22 -0
  168. package/dist/lib/transport-failure.js +126 -0
  169. package/dist/lib/tunnel-session.d.ts +7 -1
  170. package/dist/lib/tunnel-session.js +22 -9
  171. package/dist/lib/update-check.js +3 -2
  172. package/dist/lib/url-template.d.ts +43 -0
  173. package/dist/lib/url-template.js +151 -0
  174. package/dist/lib/validate.d.ts +0 -64
  175. package/dist/lib/validate.js +2 -131
  176. package/dist/lib/version-notice.js +4 -3
  177. package/dist/lib/wait-exit.d.ts +37 -2
  178. package/dist/lib/wait-exit.js +88 -30
  179. package/dist/lib/workspace-status.js +10 -2
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/package.json +3 -4
  183. package/skills/testsprite-ci.skill.md +48 -18
  184. package/skills/testsprite-onboard.skill.md +66 -151
  185. package/skills/testsprite-verify.codex.md +54 -56
  186. package/skills/testsprite-verify.skill.md +194 -358
  187. package/dist/lib/browser.d.ts +0 -6
  188. package/dist/lib/browser.js +0 -54
  189. package/dist/lib/bundle.d.ts +0 -234
  190. package/dist/lib/bundle.js +0 -781
  191. package/dist/lib/deprecate.d.ts +0 -10
  192. package/dist/lib/deprecate.js +0 -13
  193. package/dist/lib/flaky.d.ts +0 -91
  194. package/dist/lib/flaky.js +0 -71
  195. package/dist/lib/plan-poll.d.ts +0 -171
  196. package/dist/lib/plan-poll.js +0 -441
  197. package/dist/lib/plans.types.d.ts +0 -130
  198. package/dist/lib/plans.types.js +0 -31
  199. package/dist/lib/poll.d.ts +0 -100
  200. package/dist/lib/poll.js +0 -290
  201. package/dist/lib/rate-throttle.d.ts +0 -49
  202. package/dist/lib/rate-throttle.js +0 -75
  203. package/dist/lib/run-progress.d.ts +0 -41
  204. package/dist/lib/run-progress.js +0 -56
  205. package/dist/lib/v3-advisory.d.ts +0 -55
  206. package/dist/lib/v3-advisory.js +0 -74
  207. package/schemas/plan.schema.json +0 -61
@@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto';
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { localValidationError } from './errors.js';
7
+ import { readTextFileBomAware } from './text-file.js';
7
8
  export const DEFAULT_PROFILE = 'default';
8
9
  /**
9
10
  * Allowed profile-name characters. A profile name is written verbatim as an
@@ -65,8 +66,33 @@ const CREDENTIALS_LOCK_TRANSIENT_WAIT_MS = 1_000;
65
66
  const CREDENTIALS_LOCK_STALE_MS = 30_000;
66
67
  // How long a transient Windows error on replacing the credentials file is retried.
67
68
  const CREDENTIALS_RENAME_TRANSIENT_WAIT_MS = 2_000;
69
+ /**
70
+ * Section names that are never a profile. Used as a key on an ordinary object,
71
+ * `__proto__` and `constructor` reach the object's prototype and the shared
72
+ * `Object` function instead of naming an entry, so the key/value lines under
73
+ * such a header would be written onto a built-in the whole process shares
74
+ * (for `__proto__`, onto every object). Neither ever worked as a profile name.
75
+ * `prototype` is not among them: an ordinary object has no such member, and a
76
+ * profile by that name has always read and written normally. The parser drops
77
+ * these sections, the serialiser never writes them, and `writeProfile` refuses
78
+ * them, so the three agree on what can be stored.
79
+ */
80
+ const RESERVED_SECTION_NAMES = new Set(['__proto__', 'constructor']);
81
+ /**
82
+ * Look a profile up by name without consulting the prototype chain. A name
83
+ * that comes from the file, a flag or an environment variable can spell an
84
+ * inherited member (`toString`, `hasOwnProperty`, `__proto__`); a plain
85
+ * `file[name]` would then hand back that built-in as if it were a profile.
86
+ */
87
+ function ownProfile(file, profile) {
88
+ return Object.hasOwn(file, profile) ? file[profile] : undefined;
89
+ }
68
90
  export function parseCredentials(content) {
69
- const result = {};
91
+ // Sections are collected on an object with no prototype, so a name read from
92
+ // the file can only ever find a section this loop stored itself. On an
93
+ // ordinary object `[toString]` would find the inherited function and the
94
+ // lines under it would be written onto that shared built-in.
95
+ const sections = Object.create(null);
70
96
  let currentEntry = null;
71
97
  for (const rawLine of content.split('\n')) {
72
98
  const line = rawLine.trim();
@@ -75,13 +101,19 @@ export function parseCredentials(content) {
75
101
  const sectionMatch = /^\[([^\]]+)\]$/.exec(line);
76
102
  if (sectionMatch) {
77
103
  const sectionName = sectionMatch[1].trim();
78
- const existing = result[sectionName];
104
+ if (RESERVED_SECTION_NAMES.has(sectionName)) {
105
+ // Not a profile: leave no current section, so the key/value lines under
106
+ // this header are skipped rather than applied to the section above it.
107
+ currentEntry = null;
108
+ continue;
109
+ }
110
+ const existing = sections[sectionName];
79
111
  if (existing) {
80
112
  currentEntry = existing;
81
113
  }
82
114
  else {
83
115
  const newEntry = {};
84
- result[sectionName] = newEntry;
116
+ sections[sectionName] = newEntry;
85
117
  currentEntry = newEntry;
86
118
  }
87
119
  continue;
@@ -93,14 +125,22 @@ export function parseCredentials(content) {
93
125
  continue;
94
126
  const rawKey = line.slice(0, eqIndex).trim();
95
127
  const rawValue = line.slice(eqIndex + 1).trim();
96
- const field = FILE_KEY_TO_FIELD[rawKey];
128
+ // Own-property lookup: a key such as `constructor` must not match the
129
+ // inherited `Object` function and be taken for a known field.
130
+ const field = Object.hasOwn(FILE_KEY_TO_FIELD, rawKey) ? FILE_KEY_TO_FIELD[rawKey] : undefined;
97
131
  if (field)
98
132
  currentEntry[field] = rawValue;
99
133
  }
100
- return result;
134
+ // Callers and test matchers expect ordinary objects, so hand the sections
135
+ // back on one. `Object.fromEntries` defines each as an own property.
136
+ return Object.fromEntries(Object.entries(sections));
101
137
  }
102
138
  export function serializeCredentials(file) {
103
- const orderedSections = Object.keys(file).sort((a, b) => {
139
+ const orderedSections = Object.keys(file)
140
+ // The parser drops these sections, so writing one would store a profile
141
+ // that can never be read back.
142
+ .filter(section => !RESERVED_SECTION_NAMES.has(section))
143
+ .sort((a, b) => {
104
144
  if (a === DEFAULT_PROFILE)
105
145
  return -1;
106
146
  if (b === DEFAULT_PROFILE)
@@ -115,6 +155,11 @@ export function serializeCredentials(file) {
115
155
  lines.push(`[${section}]`);
116
156
  const fields = Object.keys(entry).sort();
117
157
  for (const field of fields) {
158
+ // Own-property lookup: an entry key the file format does not know has no
159
+ // line to be written as, and one that spells an inherited member
160
+ // (`constructor`) would otherwise print that built-in as the key.
161
+ if (!Object.hasOwn(FIELD_TO_FILE_KEY, field))
162
+ continue;
118
163
  const value = entry[field];
119
164
  if (value === undefined || value === '')
120
165
  continue;
@@ -137,18 +182,26 @@ export function readCredentialsFile(options = {}) {
137
182
  const path = resolvePath(options);
138
183
  if (!existsSync(path))
139
184
  return {};
140
- return parseCredentials(readFileSync(path, 'utf-8'));
185
+ // Shared BOM sniff (UTF-8, UTF-16LE, UTF-16BE). Writes stay UTF-8 with no BOM,
186
+ // so a UTF-16 file is normalised on the next save. The parser is unchanged.
187
+ return parseCredentials(readTextFileBomAware(path));
141
188
  }
142
189
  export function readProfile(profile, options = {}) {
143
190
  assertValidProfileName(profile);
144
- const file = readCredentialsFile(options);
145
- return file[profile];
191
+ return ownProfile(readCredentialsFile(options), profile);
146
192
  }
147
193
  export function writeProfile(profile, entry, options = {}) {
148
194
  assertValidProfileName(profile);
195
+ // Refused before the directory, lock or file is touched: the parser drops a
196
+ // section with one of these names, so the profile could never be read back,
197
+ // and assigning to `__proto__` would swap the file object's prototype
198
+ // instead of adding an entry.
199
+ if (RESERVED_SECTION_NAMES.has(profile)) {
200
+ throw localValidationError('profile', 'must not be __proto__ or constructor (reserved names that cannot be stored)', undefined, 'flag');
201
+ }
149
202
  const path = resolvePath(options);
150
203
  mutateCredentialsFile(path, file => {
151
- file[profile] = { ...file[profile], ...entry };
204
+ file[profile] = { ...ownProfile(file, profile), ...entry };
152
205
  return file;
153
206
  });
154
207
  }
@@ -159,7 +212,10 @@ export function deleteProfile(profile, options = {}) {
159
212
  return false;
160
213
  let removed = false;
161
214
  mutateCredentialsFile(path, file => {
162
- if (!(profile in file))
215
+ // Own-property check: `in` also sees inherited members, so a name such as
216
+ // `__proto__` or `toString` would be reported as removed and the file
217
+ // rewritten although no such profile was ever stored.
218
+ if (!Object.hasOwn(file, profile))
163
219
  return undefined;
164
220
  removed = true;
165
221
  delete file[profile];
@@ -26,7 +26,7 @@ export declare function runsPerMonth(cron: string): number | null;
26
26
  export declare function describeCron(cron: string): string;
27
27
  /**
28
28
  * Advisory shown before a schedule is created: how often it will run, and that
29
- * each run is a full test run.
29
+ * each run is a full run.
30
30
  *
31
31
  * States frequency only. Credit cost is deliberately not quoted — the API does
32
32
  * not expose a per-action rate for the workspace wallet, and a figure derived
package/dist/lib/cron.js CHANGED
@@ -162,7 +162,7 @@ function frequencyClause(runs) {
162
162
  }
163
163
  /**
164
164
  * Advisory shown before a schedule is created: how often it will run, and that
165
- * each run is a full test run.
165
+ * each run is a full run.
166
166
  *
167
167
  * States frequency only. Credit cost is deliberately not quoted — the API does
168
168
  * not expose a per-action rate for the workspace wallet, and a figure derived
@@ -174,7 +174,7 @@ function frequencyClause(runs) {
174
174
  * schedule we are about to create would be worse than saying less.
175
175
  */
176
176
  export function formatScheduleFrequencyAdvisory(cron) {
177
- const tail = 'Each run is a full test run. Check your balance with `testsprite usage`.';
177
+ const tail = 'Each run is a full run. Check your balance with `testsprite usage`.';
178
178
  const runs = runsPerMonth(cron);
179
179
  if (runs === null) {
180
180
  return `This schedule will run on the cron \`${cron.trim()}\`. ${tail}`;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * What a batch dispatch that stopped part-way says on stderr: the stop lines
3
+ * and the hint naming the tests it never sent. `run`'s batch uses them
4
+ * all; its local (tunnel) batch shares the hint and the line for a stop that
5
+ * still awaits accepted runs, so the two cannot drift there.
6
+ *
7
+ * The reports differ. {@link NOT_SENT_REASON} is the cloud batch's reason for
8
+ * a test it never sent while it awaited the runs already accepted, or after
9
+ * an unconfirmed first request. A stop it does not await (a first request
10
+ * that failed, say) gives the error instead (`not dispatched: <error>`), and
11
+ * the local batch lists such a test as skipped with no reason.
12
+ */
13
+ /** `N tests were not dispatched: <ids>`, the hint for the tests a stopped dispatch never sent. */
14
+ export declare function notDispatchedHint(testIds: readonly string[]): string;
15
+ /** The stderr line of a dispatch that stopped part-way: why, then each hint given, as sentences. */
16
+ export declare function dispatchStoppedLine(reason: string, hints: ReadonlyArray<string | undefined>): string;
17
+ /** The cloud batch's reason for a test it never sent, in the summary file and the report. */
18
+ export declare const NOT_SENT_REASON = "not dispatched: the dispatch stopped before this test was sent";
19
+ /** The stderr line of a dispatch that stopped while it still awaits the runs already accepted. */
20
+ export declare function awaitingStoppedLine(reason: string, neverSent: readonly string[]): string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * What a batch dispatch that stopped part-way says on stderr: the stop lines
3
+ * and the hint naming the tests it never sent. `run`'s batch uses them
4
+ * all; its local (tunnel) batch shares the hint and the line for a stop that
5
+ * still awaits accepted runs, so the two cannot drift there.
6
+ *
7
+ * The reports differ. {@link NOT_SENT_REASON} is the cloud batch's reason for
8
+ * a test it never sent while it awaited the runs already accepted, or after
9
+ * an unconfirmed first request. A stop it does not await (a first request
10
+ * that failed, say) gives the error instead (`not dispatched: <error>`), and
11
+ * the local batch lists such a test as skipped with no reason.
12
+ */
13
+ import { terminalSafeLine } from './terminal-text.js';
14
+ /** `N tests were not dispatched: <ids>`, the hint for the tests a stopped dispatch never sent. */
15
+ export function notDispatchedHint(testIds) {
16
+ return (`${testIds.length} test${testIds.length !== 1 ? 's were' : ' was'} not dispatched: ` +
17
+ testIds.map(terminalSafeLine).join(' '));
18
+ }
19
+ /** The stderr line of a dispatch that stopped part-way: why, then each hint given, as sentences. */
20
+ export function dispatchStoppedLine(reason, hints) {
21
+ return `[run] Dispatch stopped (${terminalSafeLine(reason)}). ${hints.filter(Boolean).join('. ')}.`;
22
+ }
23
+ /** The cloud batch's reason for a test it never sent, in the summary file and the report. */
24
+ export const NOT_SENT_REASON = 'not dispatched: the dispatch stopped before this test was sent';
25
+ /** The stderr line of a dispatch that stopped while it still awaits the runs already accepted. */
26
+ export function awaitingStoppedLine(reason, neverSent) {
27
+ return (`[run] Dispatch stopped (${terminalSafeLine(reason)}); awaiting the runs already accepted. ` +
28
+ `${notDispatchedHint(neverSent)}.`);
29
+ }
30
+ //# sourceMappingURL=dispatch-stop.js.map
@@ -0,0 +1,71 @@
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 type { FetchImpl } from './http.js';
7
+ import { type ShutdownHandle } from './interrupt.js';
8
+ /** Max fetch attempts for each presigned URL (initial + retries). */
9
+ export declare const STREAM_URL_MAX_RETRIES = 3;
10
+ /** Delay between retries for transient transport failures (ms). */
11
+ export declare const STREAM_URL_RETRY_DELAY_MS = 1000;
12
+ /** Recording container extensions trusted from a video link. */
13
+ export declare const KNOWN_VIDEO_EXTENSIONS: Set<string>;
14
+ /**
15
+ * Resolve the user-supplied `--out` path into an absolute directory.
16
+ * Empty strings are rejected with `VALIDATION_ERROR`.
17
+ * Nothing is created here: the writer makes
18
+ * the directory once the response has been read, so a failed read never
19
+ * modifies the operator's filesystem.
20
+ */
21
+ export declare function resolveOutDir(rawPath: string): string;
22
+ /**
23
+ * Validate the `--out` directory before any request goes out. Surfaces
24
+ * `VALIDATION_ERROR` (exit 5) — matches the convention from `closeOutputFile`
25
+ * for single-file `--out` flags.
26
+ *
27
+ * Missing parent directories are fine: the writer creates the whole tree
28
+ * with `mkdir(dir, { recursive: true })` once the response has been read,
29
+ * so a failed read still leaves nothing on disk. What is refused here is a
30
+ * path that can never become a directory: `--out` pointing at an existing
31
+ * file, or a file where one of its parent directories should be.
32
+ *
33
+ * The directory itself (`resolvedDir`) may or may not exist; the writer
34
+ * creates it if absent.
35
+ */
36
+ export declare function assertOutDirParentExists(resolvedDir: string): Promise<void>;
37
+ /**
38
+ * Pick the on-disk extension for `video.<ext>` from the actual video link,
39
+ * instead of hardcoding `mp4` (the recording is sometimes a `.webm`
40
+ * container; saving it under a `video.mp4` name misleads strict-extension
41
+ * consumers). Falls back to `mp4` when the URL is malformed or its extension
42
+ * isn't a recognized container, so a response-controlled field can never
43
+ * smuggle an arbitrary suffix onto disk.
44
+ */
45
+ export declare function pickVideoExtension(url: string): string;
46
+ /**
47
+ * Refuse a composed artifact path that escapes `baseDir`. This is the final
48
+ * containment check before any write. Returns the validated absolute path.
49
+ */
50
+ export declare function assertNoEscape(baseDir: string, segment: string): string;
51
+ /**
52
+ * Stream a presigned URL into a file with bounded retry on transport
53
+ * failures. 4xx (presigned URL expired or unauthorized) is NOT
54
+ * retried — the URL won't recover on its own; an upstream re-fetch
55
+ * is the only fix. Maps to `UNAVAILABLE` so `index.ts` exits 10.
56
+ *
57
+ * Streaming uses `pipeline` to honor backpressure: a slow disk pauses
58
+ * the upstream reader rather than buffering chunks in V8 heap. This
59
+ * matters for video files (multi-MB) and for very large HTML
60
+ * snapshots.
61
+ *
62
+ * Transport failures (network reset, DNS blip, mid-stream EOF) are
63
+ * retried up to STREAM_URL_MAX_RETRIES times with a fixed delay, well
64
+ * inside a signed link's lifetime. A file whose last attempt broke off
65
+ * mid-stream is left as far as it got: the caller removes it.
66
+ */
67
+ export declare function streamUrlToFile(url: string, filePath: string, fetchImpl: FetchImpl, deps?: {
68
+ sleep?: (ms: number) => Promise<void>;
69
+ shutdownSignal?: AbortSignal;
70
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
71
+ }): Promise<void>;
@@ -0,0 +1,274 @@
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 { pipeline } from 'node:stream/promises';
9
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
10
+ import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
11
+ import { globalShutdown } from './interrupt.js';
12
+ import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
13
+ /** Max fetch attempts for each presigned URL (initial + retries). */
14
+ export const STREAM_URL_MAX_RETRIES = 3;
15
+ /** Delay between retries for transient transport failures (ms). */
16
+ export const STREAM_URL_RETRY_DELAY_MS = 1000;
17
+ /** Recording container extensions trusted from a video link. */
18
+ export const KNOWN_VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'mkv', 'avi']);
19
+ /**
20
+ * Strip trailing path separators, tolerating both `/` and `\` since a
21
+ * native Windows `--out` value (typed or pasted from Explorer) commonly
22
+ * ends in a backslash. Preserves a bare drive root (`C:\`) — stripping
23
+ * its separator would turn it into `C:`, which Windows resolves as
24
+ * "current directory on drive C", not the drive root.
25
+ */
26
+ function stripTrailingSeparators(rawPath) {
27
+ if (rawPath.length <= 1)
28
+ return rawPath;
29
+ let end = rawPath.length;
30
+ while (end > 1 && (rawPath[end - 1] === '/' || rawPath[end - 1] === '\\')) {
31
+ if (end === 3 && rawPath[1] === ':' && /[A-Za-z]/.test(rawPath[0]))
32
+ break;
33
+ end--;
34
+ }
35
+ return rawPath.slice(0, end);
36
+ }
37
+ /**
38
+ * Resolve the user-supplied `--out` path into an absolute directory.
39
+ * Empty strings are rejected with `VALIDATION_ERROR`.
40
+ * Nothing is created here: the writer makes
41
+ * the directory once the response has been read, so a failed read never
42
+ * modifies the operator's filesystem.
43
+ */
44
+ export function resolveOutDir(rawPath) {
45
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
46
+ throw ApiError.fromEnvelope({
47
+ error: {
48
+ code: 'VALIDATION_ERROR',
49
+ message: 'Invalid request.',
50
+ nextAction: 'Flag `--out` is invalid: must be a non-empty directory path.',
51
+ requestId: 'local',
52
+ details: { field: 'out', reason: 'must be a non-empty directory path' },
53
+ },
54
+ });
55
+ }
56
+ const trimmed = stripTrailingSeparators(rawPath);
57
+ return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
58
+ }
59
+ /**
60
+ * Validate the `--out` directory before any request goes out. Surfaces
61
+ * `VALIDATION_ERROR` (exit 5) — matches the convention from `closeOutputFile`
62
+ * for single-file `--out` flags.
63
+ *
64
+ * Missing parent directories are fine: the writer creates the whole tree
65
+ * with `mkdir(dir, { recursive: true })` once the response has been read,
66
+ * so a failed read still leaves nothing on disk. What is refused here is a
67
+ * path that can never become a directory: `--out` pointing at an existing
68
+ * file, or a file where one of its parent directories should be.
69
+ *
70
+ * The directory itself (`resolvedDir`) may or may not exist; the writer
71
+ * creates it if absent.
72
+ */
73
+ export async function assertOutDirParentExists(resolvedDir) {
74
+ const closest = await closestExistingPath(dirname(resolvedDir));
75
+ if (!closest.stats.isDirectory()) {
76
+ throw localValidationError('out', `parent path is not a directory: ${closest.path}`);
77
+ }
78
+ // Also guard against --out pointing at an existing FILE (not a dir).
79
+ let targetStat;
80
+ try {
81
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the --out directory the user chose.
82
+ targetStat = await stat(resolvedDir);
83
+ }
84
+ catch {
85
+ // Does not exist yet — fine; the writer will create it.
86
+ return;
87
+ }
88
+ if (!targetStat.isDirectory()) {
89
+ throw localValidationError('out', `must point to a directory, not a file: ${resolvedDir}`);
90
+ }
91
+ }
92
+ /**
93
+ * The nearest path at or above `target` that exists, with its stats. Missing
94
+ * components are skipped. So is a file in the middle of the path (ENOTDIR on
95
+ * POSIX, ENOENT on Windows): the walk stops at that file, and the caller
96
+ * reports it as "not a directory".
97
+ */
98
+ async function closestExistingPath(target) {
99
+ let current = target;
100
+ for (;;) {
101
+ try {
102
+ // 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.
103
+ return { path: current, stats: await stat(current) };
104
+ }
105
+ catch (err) {
106
+ const code = err.code;
107
+ const up = dirname(current);
108
+ if ((code !== 'ENOENT' && code !== 'ENOTDIR') || up === current) {
109
+ throw localValidationError('out', `cannot access parent path: ${current}`);
110
+ }
111
+ current = up;
112
+ }
113
+ }
114
+ }
115
+ /**
116
+ * Pick the on-disk extension for `video.<ext>` from the actual video link,
117
+ * instead of hardcoding `mp4` (the recording is sometimes a `.webm`
118
+ * container; saving it under a `video.mp4` name misleads strict-extension
119
+ * consumers). Falls back to `mp4` when the URL is malformed or its extension
120
+ * isn't a recognized container, so a response-controlled field can never
121
+ * smuggle an arbitrary suffix onto disk.
122
+ */
123
+ export function pickVideoExtension(url) {
124
+ try {
125
+ const match = /\.([A-Za-z0-9]+)$/.exec(new URL(url).pathname);
126
+ const ext = match?.[1]?.toLowerCase();
127
+ if (ext !== undefined && KNOWN_VIDEO_EXTENSIONS.has(ext))
128
+ return ext;
129
+ }
130
+ catch {
131
+ // Malformed URL — fall through to the default below.
132
+ }
133
+ return 'mp4';
134
+ }
135
+ /**
136
+ * Refuse a composed artifact path that escapes `baseDir`. This is the final
137
+ * containment check before any write. Returns the validated absolute path.
138
+ */
139
+ export function assertNoEscape(baseDir, segment) {
140
+ const composed = resolve(baseDir, segment);
141
+ const rel = relative(baseDir, composed);
142
+ if (rel.startsWith('..') || isAbsolute(rel)) {
143
+ throw localValidationError('out', 'resolved artifact path escapes the --out directory', undefined, 'field');
144
+ }
145
+ return composed;
146
+ }
147
+ /**
148
+ * Stream a presigned URL into a file with bounded retry on transport
149
+ * failures. 4xx (presigned URL expired or unauthorized) is NOT
150
+ * retried — the URL won't recover on its own; an upstream re-fetch
151
+ * is the only fix. Maps to `UNAVAILABLE` so `index.ts` exits 10.
152
+ *
153
+ * Streaming uses `pipeline` to honor backpressure: a slow disk pauses
154
+ * the upstream reader rather than buffering chunks in V8 heap. This
155
+ * matters for video files (multi-MB) and for very large HTML
156
+ * snapshots.
157
+ *
158
+ * Transport failures (network reset, DNS blip, mid-stream EOF) are
159
+ * retried up to STREAM_URL_MAX_RETRIES times with a fixed delay, well
160
+ * inside a signed link's lifetime. A file whose last attempt broke off
161
+ * mid-stream is left as far as it got: the caller removes it.
162
+ */
163
+ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
164
+ const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
165
+ const shutdown = deps?.shutdown ?? globalShutdown;
166
+ return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal));
167
+ }
168
+ async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal) {
169
+ const artifactUrl = redactArtifactUrlForDetails(url);
170
+ for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
171
+ if (shutdownSignal.aborted)
172
+ throw shutdownSignal.reason;
173
+ let response;
174
+ try {
175
+ response = await fetchImpl(url, { redirect: 'error', signal: shutdownSignal });
176
+ }
177
+ catch (err) {
178
+ if (err instanceof InterruptError || shutdownSignal.aborted)
179
+ throw shutdownSignal.reason ?? err;
180
+ const message = err instanceof Error ? err.message : String(err);
181
+ if (attempt < STREAM_URL_MAX_RETRIES) {
182
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
183
+ continue;
184
+ }
185
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
186
+ }
187
+ if (shutdownSignal.aborted)
188
+ throw shutdownSignal.reason;
189
+ if (!response.ok) {
190
+ // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
191
+ // Retrying the same URL won't help — surface immediately.
192
+ throw ApiError.fromEnvelope({
193
+ error: {
194
+ code: 'UNAVAILABLE',
195
+ message: `Failed to download presigned URL (HTTP ${response.status}).`,
196
+ nextAction: 'Signed links expire. Re-run `testsprite result get <result-id> --out <dir>`: each read signs new ones.',
197
+ requestId: 'local',
198
+ details: { status: response.status, artifactUrl },
199
+ },
200
+ });
201
+ }
202
+ if (!response.body) {
203
+ // Some test runtimes / fetch polyfills don't expose `body` as a
204
+ // ReadableStream. Fall back to a buffered write — same correctness,
205
+ // just no streaming benefit. Even a multi-MB video buffers fully in
206
+ // a tolerable amount of memory.
207
+ try {
208
+ const buffer = Buffer.from(await response.arrayBuffer());
209
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
210
+ await writeFile(filePath, buffer);
211
+ if (shutdownSignal.aborted) {
212
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
213
+ await rm(filePath, { force: true }).catch(() => undefined);
214
+ throw shutdownSignal.reason;
215
+ }
216
+ return;
217
+ }
218
+ catch (err) {
219
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
220
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
221
+ await rm(filePath, { force: true }).catch(() => undefined);
222
+ throw shutdownSignal.reason ?? err;
223
+ }
224
+ const message = err instanceof Error ? err.message : String(err);
225
+ if (attempt < STREAM_URL_MAX_RETRIES) {
226
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
227
+ continue;
228
+ }
229
+ throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
230
+ }
231
+ }
232
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the directory of a file under the --out directory the user chose.
233
+ await mkdir(dirname(filePath), { recursive: true });
234
+ // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
235
+ // it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
236
+ // from the stream propagates as a TransportError, preserving the
237
+ // exit-code contract. `pipeline` destroys both streams on error, so
238
+ // a new WriteStream on retry starts clean.
239
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a path its caller composed under the --out directory.
240
+ const fileSink = createWriteStream(filePath);
241
+ try {
242
+ const webBody = response.body;
243
+ const { Readable } = await import('node:stream');
244
+ const nodeStream = Readable.fromWeb(webBody);
245
+ await pipeline(nodeStream, fileSink);
246
+ if (shutdownSignal.aborted)
247
+ throw shutdownSignal.reason;
248
+ return;
249
+ }
250
+ catch (err) {
251
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
252
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the partial file this download just wrote.
253
+ await rm(filePath, { force: true }).catch(() => undefined);
254
+ throw shutdownSignal.reason ?? err;
255
+ }
256
+ const message = err instanceof Error ? err.message : String(err);
257
+ if (attempt < STREAM_URL_MAX_RETRIES) {
258
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
259
+ continue;
260
+ }
261
+ throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
262
+ }
263
+ }
264
+ }
265
+ function redactArtifactUrlForDetails(url) {
266
+ try {
267
+ const parsed = new URL(url);
268
+ return `${parsed.origin}${parsed.pathname}`;
269
+ }
270
+ catch {
271
+ return '<invalid-url>';
272
+ }
273
+ }
274
+ //# 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;