sedum-cli 0.1.0-alpha.0 → 0.1.0-alpha.10

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.
@@ -0,0 +1,1605 @@
1
+ import {
2
+ openLocatorCache,
3
+ planLanes,
4
+ runPool
5
+ } from "./chunk-EFRMSNBD.js";
6
+ import {
7
+ discoverRunTests
8
+ } from "./chunk-7M7YUTRH.js";
9
+ import {
10
+ canonicalDiagnosticError,
11
+ createCliProvider,
12
+ flowDiagnostic,
13
+ outputDiagnostic,
14
+ setupDiagnostic,
15
+ stopsRun
16
+ } from "./chunk-NOGCXR4U.js";
17
+ import {
18
+ ProjectConfigError,
19
+ loadProjectConfig
20
+ } from "./chunk-VNGIF7AY.js";
21
+
22
+ // src/run-command-implementation.ts
23
+ import {
24
+ RejectionRouter
25
+ } from "@sedum-dev/core";
26
+ import { randomUUID } from "crypto";
27
+ import path10 from "path";
28
+
29
+ // src/run-command-discovery.ts
30
+ import path from "path";
31
+
32
+ // src/run-shard.ts
33
+ import { createHash } from "crypto";
34
+ function hashKey(key) {
35
+ return createHash("sha1").update(key).digest("hex");
36
+ }
37
+ function shardItems(items, keyOf, shard) {
38
+ const { index, count } = shard;
39
+ if (!Number.isSafeInteger(count) || count < 1)
40
+ throw new RangeError("Shard count must be a positive integer");
41
+ if (!Number.isSafeInteger(index) || index < 1 || index > count)
42
+ throw new RangeError("Shard index must be between 1 and the shard count");
43
+ const ordered = items.map((item) => ({ item, key: keyOf(item) })).map((entry) => ({ ...entry, hash: hashKey(entry.key) })).sort(
44
+ (a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : a.key < b.key ? -1 : a.key > b.key ? 1 : 0
45
+ );
46
+ const start = Math.floor((index - 1) * ordered.length / count);
47
+ const end = Math.floor(index * ordered.length / count);
48
+ return ordered.slice(start, end).map((entry) => entry.item);
49
+ }
50
+ function shardTests(tests, shard) {
51
+ return shardItems(tests, (test) => test.id, shard);
52
+ }
53
+ function shardProblems(problems, shard) {
54
+ const files = [...new Set(problems.map((problem) => problem.file))];
55
+ const owned = new Set(shardItems(files, (file) => file, shard));
56
+ return problems.filter((problem) => owned.has(problem.file));
57
+ }
58
+
59
+ // src/run-command-discovery.ts
60
+ async function discoverCommandTests(config, options, safeText2) {
61
+ const selection = await discoverRunTests(
62
+ config,
63
+ options.paths ?? (options.file ? [options.file] : []),
64
+ options.filters
65
+ );
66
+ const selected = options.shard ? shardTests(selection.tests, options.shard) : selection.tests;
67
+ const files = selected.map((test) => ({
68
+ file: path.join(config.projectRoot, test.file),
69
+ id: test.id
70
+ }));
71
+ const problems = [
72
+ ...selection.problems,
73
+ ...selection.invalid.flatMap(
74
+ (entry) => entry.diagnostics.map((item) => ({
75
+ file: entry.file,
76
+ line: item.line,
77
+ col: item.col,
78
+ code: item.code,
79
+ message: safeText2(item.message),
80
+ fix: safeText2(item.fix)
81
+ }))
82
+ )
83
+ ];
84
+ return {
85
+ files,
86
+ globalSelectedTests: selection.tests.length,
87
+ problems: options.shard ? shardProblems(problems, options.shard) : problems
88
+ };
89
+ }
90
+
91
+ // src/run-command-outcome.ts
92
+ import path2 from "path";
93
+ function interruptionConclusion(timedOut) {
94
+ return timedOut ? {
95
+ diagnostic: {
96
+ code: "run_timeout",
97
+ message: "The run deadline expired.",
98
+ fix: "Increase --timeout-minutes or reduce the selected suite."
99
+ },
100
+ state: "error"
101
+ } : {
102
+ diagnostic: {
103
+ code: "canceled",
104
+ message: "The run was interrupted.",
105
+ fix: "Rerun the command when you are ready to continue."
106
+ },
107
+ state: "interrupted"
108
+ };
109
+ }
110
+ function selectionConclusion(request) {
111
+ const {
112
+ config,
113
+ options,
114
+ files,
115
+ globalSelectedTests,
116
+ problems,
117
+ aborted,
118
+ timedOut
119
+ } = request;
120
+ if (aborted)
121
+ return {
122
+ ...interruptionConclusion(timedOut),
123
+ recordDiscoveryProblems: problems.length > 0
124
+ };
125
+ if (files.length > 0) return null;
126
+ if (options.shard && globalSelectedTests > 0)
127
+ return emptyShardConclusion(options.shard, globalSelectedTests, problems);
128
+ if (problems.length > 0) return discoveryProblemConclusion(problems);
129
+ return noTestsConclusion(config);
130
+ }
131
+ function emptyShardConclusion(shard, globalSelectedTests, problems) {
132
+ const { index, count } = shard;
133
+ return {
134
+ diagnostic: {
135
+ code: "empty_shard",
136
+ message: `Shard ${index}/${count} has no tests; the selection has ${globalSelectedTests} test${globalSelectedTests === 1 ? "" : "s"}.`,
137
+ fix: `Use --shard-count ${globalSelectedTests} or fewer.`
138
+ },
139
+ recordDiscoveryProblems: problems.length > 0
140
+ };
141
+ }
142
+ function discoveryProblemConclusion(problems) {
143
+ const [first] = problems;
144
+ return {
145
+ diagnostic: {
146
+ code: "discovery_error",
147
+ message: problems.length === 1 ? `${first.file}: ${first.message}` : `${problems.length} test file or path problem(s) were found; the first: ${first.file}: ${first.message}`,
148
+ fix: first.fix
149
+ },
150
+ recordDiscoveryProblems: true
151
+ };
152
+ }
153
+ function noTestsConclusion(config) {
154
+ const error = new ProjectConfigError([
155
+ {
156
+ code: "no_tests",
157
+ file: config.configPath ?? path2.join(config.projectRoot, "sedum.config.yaml"),
158
+ line: 1,
159
+ col: 1,
160
+ key: "tests.include",
161
+ message: "The selection matched no valid test files.",
162
+ fix: "Add a matching *.test.ts or *.test.yaml file, or correct paths and filters."
163
+ }
164
+ ]);
165
+ return { diagnostic: setupDiagnostic(error) };
166
+ }
167
+ function completedRunConclusion(operational, erroredTests, discoveryProblems) {
168
+ if (operational)
169
+ return erroredTests > 1 ? {
170
+ code: "test_errors",
171
+ message: `${erroredTests} tests could not run. First: ${operational.message}`,
172
+ fix: "Fix the tests named under needs attention, then rerun them."
173
+ } : operational;
174
+ if (discoveryProblems.length)
175
+ return {
176
+ code: "discovery_error",
177
+ message: `${discoveryProblems.length} test file or path problem(s) were found.`,
178
+ fix: "Correct the files named in the run summary and rerun."
179
+ };
180
+ return null;
181
+ }
182
+
183
+ // src/run-command-output.ts
184
+ import {
185
+ RunRecorder,
186
+ validateRunResult as validateRunResult2
187
+ } from "@sedum-dev/core";
188
+ import path5 from "path";
189
+
190
+ // src/evidence-root.ts
191
+ import { realpath } from "fs/promises";
192
+ import path3 from "path";
193
+ import { isEvidenceDirectory } from "@sedum-dev/reporters";
194
+ var CI_ROOTS = [
195
+ { root: "CI_PROJECT_DIR", running: (env) => env.GITLAB_CI === "true" },
196
+ { root: "WORKSPACE", running: (env) => Boolean(env.JENKINS_URL) },
197
+ {
198
+ root: "GITHUB_WORKSPACE",
199
+ running: (env) => env.GITHUB_ACTIONS === "true"
200
+ }
201
+ ];
202
+ async function relativeInside(base, target) {
203
+ let real;
204
+ try {
205
+ real = await realpath(base);
206
+ } catch {
207
+ return null;
208
+ }
209
+ const relative = path3.relative(real, target);
210
+ if (!relative || relative === ".." || relative.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative))
211
+ return null;
212
+ return relative.split(path3.sep).join("/");
213
+ }
214
+ async function junitEvidenceDirectory(runDirectory, projectRoot, env) {
215
+ let run;
216
+ try {
217
+ run = await realpath(runDirectory);
218
+ } catch {
219
+ return null;
220
+ }
221
+ for (const { root, running } of CI_ROOTS) {
222
+ const value = env[root];
223
+ if (!value || !path3.isAbsolute(value) || !running(env)) continue;
224
+ const relative2 = await relativeInside(value, run);
225
+ if (relative2) return isEvidenceDirectory(relative2) ? relative2 : null;
226
+ }
227
+ const relative = await relativeInside(projectRoot, run);
228
+ return relative && isEvidenceDirectory(relative) ? relative : null;
229
+ }
230
+
231
+ // src/progress-writer.ts
232
+ import { open, mkdir, rename, unlink, lstat, readFile } from "fs/promises";
233
+ import { createHash as createHash2 } from "crypto";
234
+ import path4 from "path";
235
+ import { validateRunResult } from "@sedum-dev/core";
236
+ import {
237
+ renderHtml,
238
+ renderJunit,
239
+ renderMarkdown
240
+ } from "@sedum-dev/reporters";
241
+ var ProgressWriterError = class extends Error {
242
+ constructor(path11, options) {
243
+ super(`Could not write run output at ${path11}.`, options);
244
+ this.path = path11;
245
+ this.name = "ProgressWriterError";
246
+ }
247
+ path;
248
+ };
249
+ var ProgressWriter = class _ProgressWriter {
250
+ constructor(directory, files) {
251
+ this.directory = directory;
252
+ this.files = files;
253
+ }
254
+ directory;
255
+ revision = 0;
256
+ pending = Promise.resolve();
257
+ queued = null;
258
+ draining = null;
259
+ attemptFolders = /* @__PURE__ */ new Map();
260
+ files;
261
+ /** How to invoke sedum in report rerun hints. */
262
+ command = "sedum";
263
+ static async create(root, runId, outputDirectory = path4.join(root, ".sedum", "runs"), files = {}) {
264
+ if (!/^[a-zA-Z0-9-]+$/.test(runId)) throw new Error("Invalid run ID");
265
+ const resolvedRoot = path4.resolve(root);
266
+ const base = path4.resolve(outputDirectory);
267
+ const relation = path4.relative(resolvedRoot, base);
268
+ if (relation === ".." || relation.startsWith(`..${path4.sep}`))
269
+ throw new Error("Run output path escapes the project root");
270
+ let part = resolvedRoot;
271
+ for (const segment of relation.split(path4.sep).filter(Boolean)) {
272
+ part = path4.join(part, segment);
273
+ await mkdir(part, { mode: 448 }).catch((error) => {
274
+ if (error.code !== "EEXIST") throw error;
275
+ });
276
+ const info = await lstat(part);
277
+ if (!info.isDirectory() || info.isSymbolicLink())
278
+ throw new Error("Run output parent is not a directory");
279
+ }
280
+ const directory = path4.join(base, runId);
281
+ await mkdir(directory, { mode: 448 });
282
+ return new _ProgressWriter(directory, {
283
+ json: true,
284
+ html: true,
285
+ markdown: false,
286
+ junit: null,
287
+ ...files
288
+ });
289
+ }
290
+ get includeMarkdown() {
291
+ return this.files.markdown;
292
+ }
293
+ get includesJson() {
294
+ return this.files.json;
295
+ }
296
+ get includesJunit() {
297
+ return this.files.junit !== null;
298
+ }
299
+ /** Add `junit.xml`, once the evidence location is known. */
300
+ includeJunit(options) {
301
+ this.files = { ...this.files, junit: options };
302
+ }
303
+ get progressPath() {
304
+ return path4.join(this.directory, "progress.json");
305
+ }
306
+ get resultPath() {
307
+ return path4.join(this.directory, "result.json");
308
+ }
309
+ get htmlPath() {
310
+ return path4.join(this.directory, "report.html");
311
+ }
312
+ get markdownPath() {
313
+ return path4.join(this.directory, "report.md");
314
+ }
315
+ get junitPath() {
316
+ return path4.join(this.directory, "junit.xml");
317
+ }
318
+ async atomicWrite(name, content) {
319
+ const target = path4.join(this.directory, name);
320
+ const temporary = path4.join(
321
+ this.directory,
322
+ `.${name}.${++this.revision}.tmp`
323
+ );
324
+ const handle = await open(temporary, "wx", 384);
325
+ try {
326
+ await handle.writeFile(content);
327
+ await handle.sync();
328
+ } catch (error) {
329
+ await handle.close().catch(() => void 0);
330
+ await unlink(temporary).catch(() => void 0);
331
+ throw error;
332
+ } finally {
333
+ await handle.close().catch(() => void 0);
334
+ }
335
+ try {
336
+ const existing = await lstat(target).catch(() => null);
337
+ if (existing?.isSymbolicLink())
338
+ throw new Error("Output path is a symlink");
339
+ await rename(temporary, target);
340
+ } catch (error) {
341
+ await unlink(temporary).catch(() => void 0);
342
+ throw error;
343
+ }
344
+ }
345
+ /**
346
+ * Parallel lanes publish many snapshots at once. Writes stay serialized and
347
+ * monotonic, but snapshots that queue behind an in-flight write collapse to
348
+ * the newest one, so each step does not cost its own fsync. A failed write
349
+ * stays failed for every later write.
350
+ */
351
+ write(result) {
352
+ const snapshot = validateRunResult(result);
353
+ this.queued = `${JSON.stringify(snapshot, null, 2)}
354
+ `;
355
+ this.draining ??= this.drain();
356
+ return this.draining.catch((cause) => {
357
+ throw cause instanceof ProgressWriterError ? cause : new ProgressWriterError(this.progressPath, { cause });
358
+ });
359
+ }
360
+ async drain() {
361
+ try {
362
+ await this.pending;
363
+ while (this.queued !== null) {
364
+ const content = this.queued;
365
+ this.queued = null;
366
+ this.pending = this.atomicWrite("progress.json", content);
367
+ await this.pending;
368
+ }
369
+ } finally {
370
+ this.draining = null;
371
+ }
372
+ }
373
+ /**
374
+ * Write this writer's files from one validated snapshot: JSON first, then
375
+ * the rendered reports. `reports: false` rewrites only the JSON, and
376
+ * `json: false` renders only the reports.
377
+ */
378
+ async finish(result, only = {}) {
379
+ const json = this.files.json && only.json !== false;
380
+ const reports = only.reports !== false;
381
+ try {
382
+ const snapshot = validateRunResult(result);
383
+ if (json) {
384
+ await this.write(snapshot);
385
+ await this.atomicWrite(
386
+ "result.json",
387
+ `${JSON.stringify(snapshot, null, 2)}
388
+ `
389
+ );
390
+ }
391
+ if (!reports) return;
392
+ if (this.files.html) {
393
+ try {
394
+ const frames = await this.loadReplayFrames(snapshot);
395
+ await this.atomicWrite(
396
+ "report.html",
397
+ renderHtml(snapshot, {
398
+ ...frames ? { replayFrames: frames } : {},
399
+ command: this.command
400
+ })
401
+ );
402
+ } catch (cause) {
403
+ throw new ProgressWriterError(this.htmlPath, { cause });
404
+ }
405
+ }
406
+ if (this.files.markdown) {
407
+ try {
408
+ await this.atomicWrite(
409
+ "report.md",
410
+ renderMarkdown(snapshot, { command: this.command })
411
+ );
412
+ } catch (cause) {
413
+ throw new ProgressWriterError(this.markdownPath, { cause });
414
+ }
415
+ }
416
+ const junit = this.files.junit;
417
+ if (junit) {
418
+ try {
419
+ await this.atomicWrite(
420
+ "junit.xml",
421
+ renderJunit(snapshot, { ...junit, command: this.command })
422
+ );
423
+ } catch (cause) {
424
+ throw new ProgressWriterError(this.junitPath, { cause });
425
+ }
426
+ }
427
+ } catch (cause) {
428
+ throw cause instanceof ProgressWriterError ? cause : new ProgressWriterError(this.resultPath, { cause });
429
+ }
430
+ }
431
+ /** Whether `path` is one of this writer's rendered reports. */
432
+ isReport(target) {
433
+ return [this.htmlPath, this.markdownPath, this.junitPath].includes(target);
434
+ }
435
+ /** Remove this writer's own rendered reports after one of them failed. */
436
+ async removeReports() {
437
+ for (const report of [this.htmlPath, this.markdownPath, this.junitPath])
438
+ await unlink(report).catch((error) => {
439
+ if (error.code !== "ENOENT") throw error;
440
+ });
441
+ }
442
+ /** Remove only this writer's non-authoritative result files after sink failure. */
443
+ async invalidate() {
444
+ await Promise.all([
445
+ unlink(this.progressPath).catch(() => void 0),
446
+ unlink(this.resultPath).catch(() => void 0),
447
+ unlink(this.htmlPath).catch(() => void 0),
448
+ unlink(this.markdownPath).catch(() => void 0),
449
+ unlink(this.junitPath).catch(() => void 0)
450
+ ]);
451
+ }
452
+ async loadReplayFrames(result) {
453
+ const paths = result.tests.flatMap(
454
+ (test) => test.attempts.flatMap(
455
+ (attempt) => attempt.steps.flatMap(
456
+ (step) => step.replayFrame?.status === "captured" ? [step.replayFrame.path] : []
457
+ )
458
+ )
459
+ );
460
+ const hasReplay = result.tests.some(
461
+ (test) => test.attempts.some(
462
+ (attempt) => attempt.steps.some((step) => step.replayFrame !== null)
463
+ )
464
+ );
465
+ if (!hasReplay) return void 0;
466
+ const frames = /* @__PURE__ */ new Map();
467
+ for (const relative of new Set(paths)) {
468
+ try {
469
+ let current = this.directory;
470
+ const segments = relative.split("/");
471
+ for (const [index, segment] of segments.entries()) {
472
+ current = path4.join(current, segment);
473
+ const info = await lstat(current);
474
+ if (info.isSymbolicLink() || (index < segments.length - 1 ? !info.isDirectory() : !info.isFile()))
475
+ throw new Error("Unsafe frame path");
476
+ if (index === segments.length - 1 && info.size > 5 * 1024 * 1024)
477
+ throw new Error("Frame exceeds capture limit");
478
+ }
479
+ const bytes = await readFile(current);
480
+ if (bytes.length > 5 * 1024 * 1024 || bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes[bytes.length - 2] !== 255 || bytes[bytes.length - 1] !== 217)
481
+ throw new Error("Invalid JPEG frame");
482
+ frames.set(relative, bytes.toString("base64"));
483
+ } catch {
484
+ }
485
+ }
486
+ return frames;
487
+ }
488
+ /** Each attempt gets one new folder, so retries and parallel runs never share a frame file. */
489
+ attemptFolder(attempt) {
490
+ const existing = this.attemptFolders.get(attempt.id);
491
+ if (existing) return existing;
492
+ const created = (async () => {
493
+ const evidence = path4.join(this.directory, "evidence");
494
+ await mkdir(evidence, { mode: 448 }).catch((error) => {
495
+ if (error.code !== "EEXIST") throw error;
496
+ });
497
+ const evidenceInfo = await lstat(evidence);
498
+ if (!evidenceInfo.isDirectory() || evidenceInfo.isSymbolicLink())
499
+ throw new Error("Evidence output path is not a directory");
500
+ const name = `a${attempt.ordinal}-${createHash2("sha256").update(attempt.id).digest("hex").slice(0, 12)}`;
501
+ await mkdir(path4.join(evidence, name), { mode: 448 });
502
+ return `evidence/${name}`;
503
+ })();
504
+ this.attemptFolders.set(attempt.id, created);
505
+ return created;
506
+ }
507
+ async saveFrame(attempt, frameId, bytes) {
508
+ if (bytes.byteLength === 0 || bytes.byteLength > 5 * 1024 * 1024)
509
+ return { status: "unavailable", reason: "frame_size" };
510
+ const folder = await this.attemptFolder(attempt);
511
+ const name = `${createHash2("sha256").update(frameId).digest("hex").slice(0, 24)}.jpg`;
512
+ const relative = `${folder}/${name}`;
513
+ const target = path4.join(this.directory, relative);
514
+ const handle = await open(target, "wx", 384);
515
+ try {
516
+ await handle.writeFile(bytes);
517
+ await handle.sync();
518
+ } catch (error) {
519
+ await handle.close().catch(() => void 0);
520
+ await unlink(target).catch(() => void 0);
521
+ throw error;
522
+ } finally {
523
+ await handle.close().catch(() => void 0);
524
+ }
525
+ return {
526
+ status: "captured",
527
+ path: relative,
528
+ mediaType: "image/jpeg"
529
+ };
530
+ }
531
+ };
532
+
533
+ // src/run-command-output.ts
534
+ var ReporterOutputError = class extends Error {
535
+ };
536
+ function reportSelection(options) {
537
+ const reporters = options.reporters ?? [];
538
+ return {
539
+ json: Boolean(options.reporterDir) || reporters.includes("json"),
540
+ markdown: reporters.includes("markdown"),
541
+ junit: reporters.includes("junit")
542
+ };
543
+ }
544
+ async function openReportCopy(request) {
545
+ const { root, runId, canonical, outputDir, reporterDir, selection, strict } = request;
546
+ const junit = selection.junit ? {
547
+ strict,
548
+ evidenceDirectory: await junitEvidenceDirectory(
549
+ canonical.directory,
550
+ root,
551
+ process.env
552
+ )
553
+ } : null;
554
+ if (path5.resolve(reporterDir) === path5.resolve(outputDir)) {
555
+ if (junit) canonical.includeJunit(junit);
556
+ return void 0;
557
+ }
558
+ if (!selection.json && !junit) return void 0;
559
+ const writer = await ProgressWriter.create(root, runId, reporterDir, {
560
+ json: selection.json,
561
+ html: false,
562
+ junit
563
+ });
564
+ writer.command = canonical.command;
565
+ return writer;
566
+ }
567
+ function reportFormat(target) {
568
+ const name = path5.basename(target);
569
+ return name === "report.html" ? "HTML" : name === "report.md" ? "Markdown" : "JUnit";
570
+ }
571
+ async function finishRun(canonical, copy, result, recordCopyFailure) {
572
+ const copied = await finishJsonCopy(copy, result, recordCopyFailure);
573
+ try {
574
+ await canonical.finish(copied.result);
575
+ await finishJunitCopy(copy, copied);
576
+ return {
577
+ result: copied.result,
578
+ diagnostic: copied.diagnostic,
579
+ reportsAvailable: true,
580
+ copyAvailable: copied.available
581
+ };
582
+ } catch (error) {
583
+ if (!isReportFailure(error, canonical, copy, copied.available)) throw error;
584
+ return recoverReportFailure({
585
+ canonical,
586
+ copy,
587
+ current: copied.result,
588
+ error,
589
+ copyAvailable: copied.available
590
+ });
591
+ }
592
+ }
593
+ async function finishJsonCopy(copy, result, recordFailure) {
594
+ if (!copy?.includesJson)
595
+ return { result, diagnostic: null, available: copy !== void 0 };
596
+ try {
597
+ await copy.finish(result, { reports: false });
598
+ return { result, diagnostic: null, available: true };
599
+ } catch {
600
+ const diagnostic = outputDiagnostic(copy.resultPath);
601
+ await copy.invalidate().catch(() => void 0);
602
+ return {
603
+ result: await recordFailure(diagnostic),
604
+ diagnostic,
605
+ available: false
606
+ };
607
+ }
608
+ }
609
+ async function finishJunitCopy(copy, copied) {
610
+ if (!copy) return;
611
+ if (!copied.available) return;
612
+ if (!copy.includesJunit) return;
613
+ await copy.finish(copied.result, { json: false });
614
+ }
615
+ function isReportFailure(error, canonical, copy, copyAvailable) {
616
+ if (!(error instanceof ProgressWriterError)) return false;
617
+ if (canonical.isReport(error.path)) return true;
618
+ if (!copy) return false;
619
+ if (!copyAvailable) return false;
620
+ return copy.isReport(error.path);
621
+ }
622
+ async function recoverReportFailure(request) {
623
+ const { canonical, copy, current, error } = request;
624
+ let { copyAvailable } = request;
625
+ const failure = {
626
+ code: "reporter_output_error",
627
+ message: `The ${reportFormat(error.path)} report could not be written to ${error.path}.`,
628
+ fix: "Check the run output directory and rerun the command."
629
+ };
630
+ const failed = terminalOutputFailure(current, failure, true);
631
+ await canonical.removeReports();
632
+ copyAvailable = await recoverCopy(copy, copyAvailable, failed);
633
+ await canonical.finish(failed, { reports: false });
634
+ return {
635
+ result: failed,
636
+ diagnostic: failure,
637
+ reportsAvailable: false,
638
+ copyAvailable
639
+ };
640
+ }
641
+ async function recoverCopy(copy, available, result) {
642
+ if (!available) return false;
643
+ if (!copy) return false;
644
+ try {
645
+ await copy.removeReports();
646
+ if (copy.includesJson) await copy.finish(result, { reports: false });
647
+ return true;
648
+ } catch {
649
+ await copy.invalidate().catch(() => void 0);
650
+ return false;
651
+ }
652
+ }
653
+ function finishedArtifacts(canonical, copy, selection, finished) {
654
+ const junit = junitWriter(canonical, copy, finished.copyAvailable);
655
+ const json = jsonWriter(canonical, copy, finished.copyAvailable);
656
+ return {
657
+ progressPath: canonical.progressPath,
658
+ resultPath: canonical.resultPath,
659
+ ...renderedArtifacts(canonical, junit, finished.reportsAvailable),
660
+ ...reporterArtifact(selection, json),
661
+ authoritative: true
662
+ };
663
+ }
664
+ function reporterArtifact(selection, writer) {
665
+ if (!selection.json) return {};
666
+ return writer ? { reporterPath: writer.resultPath } : {};
667
+ }
668
+ function junitWriter(canonical, copy, copyAvailable) {
669
+ if (canonical.includesJunit) return canonical;
670
+ if (!copyAvailable) return void 0;
671
+ return copy?.includesJunit ? copy : void 0;
672
+ }
673
+ function jsonWriter(canonical, copy, copyAvailable) {
674
+ if (!copy?.includesJson) return canonical;
675
+ return copyAvailable ? copy : void 0;
676
+ }
677
+ function renderedArtifacts(canonical, junit, available) {
678
+ if (!available) return {};
679
+ return {
680
+ htmlPath: canonical.htmlPath,
681
+ ...canonical.includeMarkdown ? { markdownPath: canonical.markdownPath } : {},
682
+ ...junit ? { junitPath: junit.junitPath } : {}
683
+ };
684
+ }
685
+ function terminalOutputFailure(source, diagnostic, keepExisting = false) {
686
+ if (keepExisting) {
687
+ if (source.error === null) return failedRunResult(source, diagnostic);
688
+ if (source.state !== "running") return source;
689
+ }
690
+ return failedRunResult(source, diagnostic);
691
+ }
692
+ function failedRunResult(source, diagnostic) {
693
+ const at = (/* @__PURE__ */ new Date()).toISOString();
694
+ return validateRunResult2({
695
+ ...source,
696
+ state: "error",
697
+ verdict: null,
698
+ error: canonicalDiagnosticError(diagnostic),
699
+ updatedAt: at,
700
+ finishedAt: at
701
+ });
702
+ }
703
+ async function resultWithoutSink(runId, diagnostic) {
704
+ const recorder = new RunRecorder(async () => void 0, runId);
705
+ await recorder.start();
706
+ await recorder.finish(canonicalDiagnosticError(diagnostic));
707
+ return recorder.snapshot;
708
+ }
709
+ async function preExecutionFailure(request) {
710
+ const { root, runId, outputDir, diagnostic, commit } = request;
711
+ const base = outputDir ?? path5.join(root, ".sedum", "runs");
712
+ const intended = path5.join(base, runId);
713
+ const writer = await createPreExecutionWriter(request, base);
714
+ if (!writer) {
715
+ commit();
716
+ return unavailablePreExecutionResult(runId, intended, diagnostic);
717
+ }
718
+ return finishPreExecutionFailure(request, writer, base);
719
+ }
720
+ async function createPreExecutionWriter(request, base) {
721
+ try {
722
+ return await ProgressWriter.create(request.root, request.runId, base, {
723
+ markdown: request.selection.markdown
724
+ });
725
+ } catch {
726
+ return void 0;
727
+ }
728
+ }
729
+ async function finishPreExecutionFailure(request, writer, base) {
730
+ const { root, runId, reporterDir, selection, strict, diagnostic, commit } = request;
731
+ const copy = await openReportCopy({
732
+ root,
733
+ runId,
734
+ canonical: writer,
735
+ outputDir: base,
736
+ reporterDir,
737
+ selection,
738
+ strict
739
+ }).catch(() => void 0);
740
+ const recorder = new RunRecorder((snapshot) => writer.write(snapshot), runId);
741
+ try {
742
+ await recorder.start();
743
+ commit();
744
+ await recorder.finish(canonicalDiagnosticError(diagnostic));
745
+ const finished = await finishRun(
746
+ writer,
747
+ copy,
748
+ recorder.snapshot,
749
+ async () => recorder.snapshot
750
+ );
751
+ return {
752
+ result: finished.result,
753
+ artifacts: finishedArtifacts(writer, copy, selection, finished),
754
+ diagnostic: finished.diagnostic ?? diagnostic
755
+ };
756
+ } catch {
757
+ commit();
758
+ await writer.invalidate();
759
+ await copy?.invalidate();
760
+ return {
761
+ result: await resultWithoutSink(runId, diagnostic),
762
+ artifacts: {
763
+ progressPath: writer.progressPath,
764
+ resultPath: writer.resultPath,
765
+ authoritative: false
766
+ },
767
+ diagnostic
768
+ };
769
+ }
770
+ }
771
+ async function unavailablePreExecutionResult(runId, intended, diagnostic) {
772
+ return {
773
+ result: await resultWithoutSink(runId, diagnostic),
774
+ artifacts: {
775
+ progressPath: path5.join(intended, "progress.json"),
776
+ resultPath: path5.join(intended, "result.json"),
777
+ authoritative: false
778
+ },
779
+ diagnostic
780
+ };
781
+ }
782
+
783
+ // src/run-command-session.ts
784
+ import { RunRecorder as RunRecorder2 } from "@sedum-dev/core";
785
+ import path6 from "path";
786
+ async function openRunSession(request) {
787
+ let writer;
788
+ try {
789
+ writer = await ProgressWriter.create(
790
+ request.config.projectRoot,
791
+ request.runId,
792
+ request.config.outputDir,
793
+ { markdown: request.reports.markdown }
794
+ );
795
+ writer.command = request.options.command ?? "sedum";
796
+ } catch {
797
+ request.commit();
798
+ const intended = path6.join(request.config.outputDir, request.runId);
799
+ const diagnostic = outputDiagnostic(path6.join(intended, "result.json"));
800
+ return {
801
+ execution: {
802
+ result: await resultWithoutSink(request.runId, diagnostic),
803
+ artifacts: {
804
+ progressPath: path6.join(intended, "progress.json"),
805
+ resultPath: path6.join(intended, "result.json"),
806
+ authoritative: false
807
+ },
808
+ diagnostic
809
+ }
810
+ };
811
+ }
812
+ return { session: new RunOutputSession(writer, request) };
813
+ }
814
+ var RunOutputSession = class {
815
+ constructor(writer, request) {
816
+ this.request = request;
817
+ this.writer = writer;
818
+ this.currentArtifacts = {
819
+ progressPath: writer.progressPath,
820
+ resultPath: writer.resultPath,
821
+ htmlPath: writer.htmlPath,
822
+ ...request.reports.markdown ? { markdownPath: writer.markdownPath } : {},
823
+ authoritative: true
824
+ };
825
+ this.recorder = new RunRecorder2(
826
+ (snapshot) => this.writeSnapshot(snapshot),
827
+ request.runId
828
+ );
829
+ }
830
+ request;
831
+ recorder;
832
+ writer;
833
+ reportWriter;
834
+ currentArtifacts;
835
+ failedReporter = false;
836
+ get reporterFailed() {
837
+ return this.failedReporter;
838
+ }
839
+ get artifacts() {
840
+ return this.currentArtifacts;
841
+ }
842
+ async start() {
843
+ try {
844
+ await this.recorder.start();
845
+ return null;
846
+ } catch (error) {
847
+ if (error instanceof ReporterOutputError) return this.reporterFailure();
848
+ this.request.commit();
849
+ const diagnostic = outputDiagnostic(this.writer.progressPath);
850
+ await this.writer.invalidate();
851
+ return {
852
+ result: await resultWithoutSink(this.request.runId, diagnostic),
853
+ artifacts: { ...this.currentArtifacts, authoritative: false },
854
+ diagnostic
855
+ };
856
+ }
857
+ }
858
+ async openReportCopy() {
859
+ const { config, runId, options, reports, commit } = this.request;
860
+ try {
861
+ this.reportWriter = await openReportCopy({
862
+ root: config.projectRoot,
863
+ runId,
864
+ canonical: this.writer,
865
+ outputDir: config.outputDir,
866
+ reporterDir: config.reporterDir,
867
+ selection: reports,
868
+ strict: options.strict ?? false
869
+ });
870
+ } catch {
871
+ const diagnostic = outputDiagnostic(
872
+ path6.join(config.reporterDir, runId, "result.json")
873
+ );
874
+ commit();
875
+ await this.recorder.finish(canonicalDiagnosticError(diagnostic));
876
+ const finished = await finishRun(
877
+ this.writer,
878
+ void 0,
879
+ this.recorder.snapshot,
880
+ async () => this.recorder.snapshot
881
+ );
882
+ return {
883
+ result: finished.result,
884
+ artifacts: finishedArtifacts(this.writer, void 0, reports, {
885
+ ...finished,
886
+ copyAvailable: false
887
+ }),
888
+ diagnostic: finished.diagnostic ?? diagnostic
889
+ };
890
+ }
891
+ const junitWriter2 = this.writer.includesJunit ? this.writer : this.reportWriter?.includesJunit ? this.reportWriter : void 0;
892
+ if (junitWriter2)
893
+ this.currentArtifacts = {
894
+ ...this.currentArtifacts,
895
+ junitPath: junitWriter2.junitPath
896
+ };
897
+ return null;
898
+ }
899
+ async terminalExecution(diagnostic) {
900
+ try {
901
+ const finished = await finishRun(
902
+ this.writer,
903
+ this.reportWriter,
904
+ this.recorder.snapshot,
905
+ (failure) => this.recordCopyFailure(failure)
906
+ );
907
+ return {
908
+ result: finished.result,
909
+ artifacts: finishedArtifacts(
910
+ this.writer,
911
+ this.reportWriter,
912
+ this.request.reports,
913
+ finished
914
+ ),
915
+ diagnostic: finished.diagnostic ?? diagnostic,
916
+ reporterFailed: this.failedReporter,
917
+ onReporterFailure: () => this.reporterFailure()
918
+ };
919
+ } catch (error) {
920
+ const output = outputDiagnostic(
921
+ error instanceof ProgressWriterError ? error.path : this.writer.resultPath
922
+ );
923
+ const result = terminalOutputFailure(this.recorder.snapshot, output);
924
+ await this.writer.invalidate();
925
+ await this.reportWriter?.invalidate();
926
+ return {
927
+ result,
928
+ artifacts: { ...this.currentArtifacts, authoritative: false },
929
+ diagnostic: output
930
+ };
931
+ }
932
+ }
933
+ async reporterFailure() {
934
+ const diagnostic = {
935
+ code: "reporter_output_error",
936
+ message: "The selected reporter could not write output.",
937
+ fix: "Check terminal output access and rerun the command."
938
+ };
939
+ const result = terminalOutputFailure(this.recorder.snapshot, diagnostic);
940
+ try {
941
+ const finished = await finishRun(
942
+ this.writer,
943
+ this.reportWriter,
944
+ result,
945
+ async () => result
946
+ );
947
+ return {
948
+ result: finished.result,
949
+ artifacts: finishedArtifacts(
950
+ this.writer,
951
+ this.reportWriter,
952
+ this.request.reports,
953
+ finished
954
+ ),
955
+ diagnostic: finished.diagnostic ?? diagnostic,
956
+ reporterFailed: true
957
+ };
958
+ } catch (error) {
959
+ await this.writer.invalidate();
960
+ await this.reportWriter?.invalidate();
961
+ const output = outputDiagnostic(
962
+ error instanceof ProgressWriterError ? error.path : this.writer.resultPath
963
+ );
964
+ return {
965
+ result: terminalOutputFailure(result, output),
966
+ artifacts: { ...this.currentArtifacts, authoritative: false },
967
+ diagnostic: output,
968
+ reporterFailed: true
969
+ };
970
+ }
971
+ }
972
+ async writeSnapshot(snapshot) {
973
+ await this.writer.write(snapshot);
974
+ if (this.failedReporter) return;
975
+ try {
976
+ this.request.options.onSnapshot?.(snapshot, this.currentArtifacts);
977
+ } catch {
978
+ this.failedReporter = true;
979
+ throw new ReporterOutputError(
980
+ "The selected reporter could not write output."
981
+ );
982
+ }
983
+ }
984
+ async recordCopyFailure(diagnostic) {
985
+ if (this.recorder.snapshot.error === null)
986
+ await this.recorder.finish(canonicalDiagnosticError(diagnostic));
987
+ return this.recorder.snapshot;
988
+ }
989
+ };
990
+
991
+ // src/run-command-setup.ts
992
+ import path7 from "path";
993
+ var SUPPORTED_BROWSERS = /* @__PURE__ */ new Set(["chrome", "chromium"]);
994
+ async function resolveRunConfig(invocationRoot, options) {
995
+ validateBrowser(invocationRoot, options.browser);
996
+ validateUrlOverride(invocationRoot, options.urlOverride);
997
+ const config = await loadProjectConfig(invocationRoot, process.env, {
998
+ ...options.environment ? { environment: options.environment } : {},
999
+ ...options.browser ? { browser: options.browser } : {},
1000
+ ...options.outputDir ? { outputDir: options.outputDir } : {},
1001
+ ...options.reporterDir ? { reporterDir: options.reporterDir } : {},
1002
+ ...visionOverride(options)
1003
+ });
1004
+ validateVisionKey(config);
1005
+ return config;
1006
+ }
1007
+ function validateBrowser(invocationRoot, browser) {
1008
+ if (!browser) return;
1009
+ if (SUPPORTED_BROWSERS.has(browser)) return;
1010
+ throw new ProjectConfigError([
1011
+ {
1012
+ code: "invalid_browser",
1013
+ file: path7.join(invocationRoot, "sedum.config.yaml"),
1014
+ line: 1,
1015
+ col: 1,
1016
+ key: "browser",
1017
+ message: "Browser must be chrome or chromium.",
1018
+ fix: "Use --browser chrome or --browser chromium."
1019
+ }
1020
+ ]);
1021
+ }
1022
+ function validateUrlOverride(invocationRoot, override) {
1023
+ if (!override) return;
1024
+ if (isValidOverride(override)) return;
1025
+ throw new ProjectConfigError([
1026
+ {
1027
+ code: "invalid_url_override",
1028
+ file: path7.join(invocationRoot, "sedum.config.yaml"),
1029
+ line: 1,
1030
+ col: 1,
1031
+ key: "urlOverride",
1032
+ message: "The URL override must be an absolute HTTP(S) URL without credentials.",
1033
+ fix: "Use --url-override https://preview.example.com."
1034
+ }
1035
+ ]);
1036
+ }
1037
+ function isValidOverride(value) {
1038
+ try {
1039
+ const url = new URL(value);
1040
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password;
1041
+ } catch {
1042
+ return false;
1043
+ }
1044
+ }
1045
+ function visionOverride(options) {
1046
+ if (options.vision === void 0 && options.visionModel === void 0)
1047
+ return {};
1048
+ return {
1049
+ vision: {
1050
+ ...options.vision !== void 0 ? { enabled: options.vision } : {},
1051
+ ...options.visionModel !== void 0 ? { model: options.visionModel } : {}
1052
+ }
1053
+ };
1054
+ }
1055
+ function validateVisionKey(config) {
1056
+ if (!config.vision.enabled) return;
1057
+ if (config.visionApiKey) return;
1058
+ throw new ProjectConfigError([
1059
+ {
1060
+ code: "missing_vision_api_key",
1061
+ file: path7.join(config.projectRoot, ".env"),
1062
+ line: 1,
1063
+ col: 1,
1064
+ key: "OPEN_ROUTER_API_KEY",
1065
+ message: "Vision fallback requires OPEN_ROUTER_API_KEY.",
1066
+ fix: "Set OPEN_ROUTER_API_KEY in the invoking process or project-root .env, or disable vision."
1067
+ }
1068
+ ]);
1069
+ }
1070
+
1071
+ // src/run-command-support.ts
1072
+ import { safeText } from "@sedum-dev/core";
1073
+ import path8 from "path";
1074
+ function verifyGraceMs(value) {
1075
+ if (value === void 0) return 5e3;
1076
+ const parsed = Number(value);
1077
+ return Number.isFinite(parsed) && parsed >= 0 && parsed <= 12e4 ? parsed : 5e3;
1078
+ }
1079
+ function strayRejectionDiagnostic(strays, config) {
1080
+ const stray = strays[0];
1081
+ const where = stray.source ? `${path8.relative(config.projectRoot, stray.source.file).split(path8.sep).join("/")}:${stray.source.line}: ` : "";
1082
+ const message = safeDiscoveryText(stray.message, config);
1083
+ const more = strays.length > 1 ? ` (${strays.length - 1} more rejected outside their tests; see the terminal.)` : "";
1084
+ if (stray.reason === "internal")
1085
+ return {
1086
+ code: "internal_rejection",
1087
+ message: `Sedum hit an unexpected error during the run: ${message}${more}`,
1088
+ fix: "Rerun the command; if it repeats, report it at https://github.com/sedum-dev/sedum/issues with the run's progress.json."
1089
+ };
1090
+ const what = {
1091
+ finished: `a promise ${stray.test ? `\`${safeDiscoveryText(stray.test, config)}\`` : "a test"} did not await rejected after that test finished`,
1092
+ shared: "a promise nobody awaited rejected in lines several tests share, such as tests declared in a loop, so no test is blamed",
1093
+ outside: "a promise nobody awaited rejected outside any running test, so no test is blamed",
1094
+ unknown: "a promise nobody awaited rejected with a value that has no stack"
1095
+ }[stray.reason];
1096
+ return {
1097
+ code: "stray_rejection",
1098
+ message: `${where}${what}: ${message}${more}`,
1099
+ fix: "Add `await` before the page, expect, API, and ai calls the test starts."
1100
+ };
1101
+ }
1102
+ function safeDiscoveryText(value, config) {
1103
+ const withoutUrls = value.replace(/https?:\/\/[^\s`"'<>]+/giu, "[URL]");
1104
+ return safeText(
1105
+ withoutUrls,
1106
+ {
1107
+ secretValues: Object.values(config.variables).filter(
1108
+ (entry) => typeof entry === "string" && entry.length >= 4
1109
+ )
1110
+ },
1111
+ 512
1112
+ );
1113
+ }
1114
+
1115
+ // src/run-command-tests.ts
1116
+ import {
1117
+ DEFAULT_PROVIDER_CONCURRENCY,
1118
+ FileClassificationCache,
1119
+ OpenRouterVisionResolver,
1120
+ PlaywrightBrowserDriver,
1121
+ ProviderGate,
1122
+ ReusableBrowserDriver,
1123
+ isScriptTestFile,
1124
+ probeOpenRouterKey,
1125
+ runFlow,
1126
+ runScriptTest
1127
+ } from "@sedum-dev/core";
1128
+ import { availableParallelism } from "os";
1129
+ import path9 from "path";
1130
+ import { randomBytes } from "crypto";
1131
+ async function executeSelectedTests(request) {
1132
+ const lanes = planLanes(
1133
+ request.options.parallel ?? 1,
1134
+ request.options.availableParallelism ?? availableParallelism(),
1135
+ request.files.length
1136
+ );
1137
+ const providerConcurrency = request.options.providerConcurrency ?? Math.min(DEFAULT_PROVIDER_CONCURRENCY, lanes * 2);
1138
+ const visionKey = await probeVision(request.config, request.options);
1139
+ await selectTests(request, lanes, providerConcurrency, visionKey);
1140
+ if (request.signal.aborted) throw new Error("canceled");
1141
+ const gate = new ProviderGate({ concurrency: providerConcurrency });
1142
+ const resources = await createExecutionResources(request, gate);
1143
+ const driver = new PlaywrightBrowserDriver();
1144
+ const browsers = Array.from(
1145
+ { length: lanes },
1146
+ () => new ReusableBrowserDriver(driver)
1147
+ );
1148
+ const outcome = { operational: null, erroredTests: 0 };
1149
+ try {
1150
+ await runPool({
1151
+ items: request.files,
1152
+ lanes,
1153
+ signal: request.signal,
1154
+ run: (test, lane, ordinal) => runSelectedTest(
1155
+ request,
1156
+ resources,
1157
+ { browser: browsers[lane], test, lane, ordinal },
1158
+ outcome
1159
+ )
1160
+ });
1161
+ } finally {
1162
+ gate.close();
1163
+ await Promise.all(browsers.map((browser) => browser.recycle()));
1164
+ }
1165
+ return outcome;
1166
+ }
1167
+ async function probeVision(config, options) {
1168
+ if (!config.vision.enabled) return null;
1169
+ return (options.probeVisionKey ?? probeOpenRouterKey)(
1170
+ config.visionApiKey
1171
+ ).catch(() => "unreachable");
1172
+ }
1173
+ async function selectTests(request, lanes, providerConcurrency, visionKey) {
1174
+ await request.recorder.selectTests(request.files.length, {
1175
+ parallel: { requested: request.options.parallel ?? 1, lanes },
1176
+ shard: request.options.shard ? {
1177
+ ...request.options.shard,
1178
+ globalSelectedTests: request.globalSelectedTests
1179
+ } : null,
1180
+ providerConcurrency,
1181
+ ...visionKey ? { vision: { model: request.config.vision.model, key: visionKey } } : {}
1182
+ });
1183
+ if (request.discoveryProblems.length)
1184
+ await request.recorder.addDiscoveryProblems(request.discoveryProblems);
1185
+ }
1186
+ async function createExecutionResources(request, gate) {
1187
+ const { config, options } = request;
1188
+ return {
1189
+ provider: await createCliProvider(config, { gate }),
1190
+ classificationCache: await FileClassificationCache.load(
1191
+ path9.join(config.projectRoot, ".sedum", "classifications.json"),
1192
+ config.providerModel,
1193
+ config.providerName
1194
+ ),
1195
+ locatorCache: await openLocatorCache(config.projectRoot, {
1196
+ disabled: options.locatorCacheDisabled ?? false,
1197
+ ciOptIn: options.locatorCacheCi ?? false,
1198
+ env: process.env
1199
+ }),
1200
+ ...config.vision.enabled ? {
1201
+ visionResolver: new OpenRouterVisionResolver({
1202
+ apiKey: config.visionApiKey,
1203
+ model: config.vision.model,
1204
+ timeoutMs: config.vision.timeoutMs
1205
+ })
1206
+ } : {}
1207
+ };
1208
+ }
1209
+ async function runSelectedTest(request, resources, slot, outcome) {
1210
+ for (let attempt = 0; attempt <= (request.options.retries ?? 0); attempt++) {
1211
+ await startRetryAttempt(request, slot, attempt);
1212
+ const result = await executeTest(request, resources, slot);
1213
+ const directive = await attemptDirective(request, slot, result, outcome);
1214
+ if (directive === "stop") return "stop";
1215
+ if (directive === "complete") break;
1216
+ }
1217
+ return "continue";
1218
+ }
1219
+ async function startRetryAttempt(request, slot, attempt) {
1220
+ if (attempt === 0) return;
1221
+ await request.recorder.testAt(slot.ordinal)?.startAttempt(slot.lane);
1222
+ }
1223
+ async function attemptDirective(request, slot, result, outcome) {
1224
+ if (request.reporterFailed()) throw new ReporterOutputError();
1225
+ if (request.signal.aborted) return "stop";
1226
+ if (result.status === "could_not_run")
1227
+ return handleOperationalFailure(request, slot, result, outcome);
1228
+ if (result.status === "passed") return "complete";
1229
+ return result.retryable === false ? "complete" : "retry";
1230
+ }
1231
+ async function executeTest(request, resources, slot) {
1232
+ const dependencies = testDependencies(request, resources, slot);
1233
+ return isScriptTestFile(slot.test.file) ? runScriptTest(slot.test.file, slot.test.id, dependencies) : runFlow(slot.test.file, dependencies);
1234
+ }
1235
+ function testDependencies(request, resources, slot) {
1236
+ const { config, options } = request;
1237
+ const { browser, lane, ordinal } = slot;
1238
+ return {
1239
+ repoRoot: config.projectRoot,
1240
+ browser,
1241
+ provider: resources.provider,
1242
+ classificationCache: resources.classificationCache,
1243
+ locatorCache: resources.locatorCache,
1244
+ ...resources.visionResolver ? { visionResolver: resources.visionResolver } : {},
1245
+ env: {
1246
+ ...config.variables,
1247
+ SEDUM_PARALLEL_INDEX: String(lane),
1248
+ SEDUM_SHARD_INDEX: String(options.shard?.index ?? 1),
1249
+ SEDUM_ATTEMPT_KEY: randomBytes(6).toString("hex")
1250
+ },
1251
+ browserKind: config.browser,
1252
+ viewport: config.viewport,
1253
+ verifyPolicy: config.thresholds,
1254
+ verifyGraceMs: verifyGraceMs(process.env.SEDUM_VERIFY_GRACE_MS),
1255
+ ...config.baseUrl ? { baseUrl: config.baseUrl } : {},
1256
+ ...options.urlOverride ? { urlOverride: options.urlOverride } : {},
1257
+ ...options.headed ? { headless: false, headedOverlay: true } : {},
1258
+ ...options.slowMoMs !== void 0 ? { slowMoMs: options.slowMoMs } : {},
1259
+ signal: request.signal,
1260
+ rejections: request.rejections,
1261
+ report: {
1262
+ recorder: request.recorder,
1263
+ slot: { ordinal, lane },
1264
+ privacy: {
1265
+ secretValues: [],
1266
+ sensitiveOrigins: options.sensitiveOrigins
1267
+ },
1268
+ evidenceEnabled: options.evidence,
1269
+ replay: options.replay,
1270
+ saveFrame: (attempt, frameId, bytes) => request.writer.saveFrame(attempt, frameId, bytes)
1271
+ }
1272
+ };
1273
+ }
1274
+ async function handleOperationalFailure(request, slot, result, outcome) {
1275
+ await slot.browser.recycle();
1276
+ const diagnostic = flowDiagnostic(result, request.config.providerName);
1277
+ outcome.operational ??= diagnostic;
1278
+ if (stopsRun(result.code)) return "stop";
1279
+ outcome.erroredTests += 1;
1280
+ await request.recorder.testAt(slot.ordinal)?.errorTest(canonicalDiagnosticError(diagnostic));
1281
+ return "complete";
1282
+ }
1283
+
1284
+ // src/run-command-implementation.ts
1285
+ var SUPPORTED_REPORTERS = [
1286
+ "terminal",
1287
+ "json",
1288
+ "list",
1289
+ "steps",
1290
+ "markdown",
1291
+ "junit"
1292
+ ];
1293
+ async function executeRunCommandImplementation(options) {
1294
+ const context = commandContext(options);
1295
+ const prepared = await prepareRun(context);
1296
+ if (prepared.execution) return prepared.execution;
1297
+ const deadline = new RunDeadline(options);
1298
+ try {
1299
+ return await executeConfiguredRun(context, prepared.config, deadline);
1300
+ } finally {
1301
+ deadline.dispose();
1302
+ disposeRejections(context);
1303
+ }
1304
+ }
1305
+ function commandContext(options) {
1306
+ let committed = false;
1307
+ return {
1308
+ options,
1309
+ invocationRoot: process.cwd(),
1310
+ reports: reportSelection(options),
1311
+ runId: randomUUID(),
1312
+ reportedStrays: 0,
1313
+ commit: () => {
1314
+ if (committed) return;
1315
+ committed = true;
1316
+ options.onCommitted?.();
1317
+ }
1318
+ };
1319
+ }
1320
+ async function prepareRun(context) {
1321
+ let config;
1322
+ try {
1323
+ config = await resolveRunConfig(context.invocationRoot, context.options);
1324
+ } catch (error) {
1325
+ return { execution: await setupFailure(context, error) };
1326
+ }
1327
+ const unavailable = unsupportedReporter(context.options.reporters);
1328
+ if (!unavailable) return { config };
1329
+ return {
1330
+ execution: await preExecutionFailure({
1331
+ root: config.projectRoot,
1332
+ runId: context.runId,
1333
+ outputDir: config.outputDir,
1334
+ reporterDir: config.reporterDir,
1335
+ selection: context.reports,
1336
+ strict: context.options.strict ?? false,
1337
+ diagnostic: {
1338
+ code: "unsupported_reporter",
1339
+ message: `Reporter ${JSON.stringify(unavailable)} is not available in this build.`,
1340
+ fix: "Use --reporter list, steps, terminal, json, markdown, or junit."
1341
+ },
1342
+ commit: context.commit
1343
+ })
1344
+ };
1345
+ }
1346
+ function unsupportedReporter(reporters) {
1347
+ return (reporters ?? []).find(
1348
+ (reporter) => !SUPPORTED_REPORTERS.includes(reporter)
1349
+ );
1350
+ }
1351
+ async function setupFailure(context, error) {
1352
+ const diagnostic = setupDiagnostic(error);
1353
+ const root = fallbackRoot(context.invocationRoot, error);
1354
+ return preExecutionFailure({
1355
+ root,
1356
+ runId: context.runId,
1357
+ outputDir: void 0,
1358
+ reporterDir: context.options.reporterDir ? path10.resolve(root, context.options.reporterDir) : path10.join(root, ".sedum", "reports"),
1359
+ selection: context.reports,
1360
+ strict: context.options.strict ?? false,
1361
+ diagnostic,
1362
+ commit: context.commit
1363
+ });
1364
+ }
1365
+ function fallbackRoot(invocationRoot, error) {
1366
+ if (!(error instanceof ProjectConfigError)) return invocationRoot;
1367
+ const file = error.diagnostics[0]?.file;
1368
+ return file ? path10.dirname(file) : invocationRoot;
1369
+ }
1370
+ var RunDeadline = class {
1371
+ constructor(options) {
1372
+ this.options = options;
1373
+ if (options.signal?.aborted) this.abortFromExternal();
1374
+ else
1375
+ options.signal?.addEventListener("abort", this.abortFromExternal, {
1376
+ once: true
1377
+ });
1378
+ if (options.timeoutMinutes !== void 0)
1379
+ this.timeout = setTimeout(
1380
+ () => this.expire(),
1381
+ options.timeoutMinutes * 6e4
1382
+ );
1383
+ }
1384
+ options;
1385
+ controller = new AbortController();
1386
+ timeout;
1387
+ timedOut = false;
1388
+ get signal() {
1389
+ return this.controller.signal;
1390
+ }
1391
+ dispose() {
1392
+ if (this.timeout) clearTimeout(this.timeout);
1393
+ this.options.signal?.removeEventListener("abort", this.abortFromExternal);
1394
+ }
1395
+ abortFromExternal = () => {
1396
+ this.controller.abort(this.options.signal?.reason);
1397
+ };
1398
+ expire() {
1399
+ if (this.signal.aborted) return;
1400
+ this.timedOut = true;
1401
+ this.controller.abort(new Error("run_timeout"));
1402
+ this.options.onDeadline?.();
1403
+ }
1404
+ };
1405
+ async function executeConfiguredRun(context, config, deadline) {
1406
+ const opened = await openRunSession({
1407
+ config,
1408
+ runId: context.runId,
1409
+ options: context.options,
1410
+ reports: context.reports,
1411
+ commit: context.commit
1412
+ });
1413
+ if (opened.execution) return opened.execution;
1414
+ const startFailure = await opened.session.start();
1415
+ if (startFailure) return startFailure;
1416
+ const copyFailure = await opened.session.openReportCopy();
1417
+ if (copyFailure) return copyFailure;
1418
+ return executeOpenSession(context, config, deadline, opened.session);
1419
+ }
1420
+ async function executeOpenSession(context, config, deadline, session) {
1421
+ const execution = { command: context, config, deadline, session };
1422
+ context.config = config;
1423
+ context.rejections = new RejectionRouter(config.projectRoot);
1424
+ context.rejections.install();
1425
+ const discovered = await discoverRun(context, config, session);
1426
+ if (discovered.execution) return discovered.execution;
1427
+ const selectionFailure = selectionConclusion({
1428
+ config,
1429
+ options: context.options,
1430
+ files: discovered.discovery.files,
1431
+ globalSelectedTests: discovered.discovery.globalSelectedTests,
1432
+ problems: discovered.discovery.problems,
1433
+ aborted: deadline.signal.aborted,
1434
+ timedOut: deadline.timedOut
1435
+ });
1436
+ if (selectionFailure)
1437
+ return finishConclusion(
1438
+ context,
1439
+ session,
1440
+ discovered.discovery.problems,
1441
+ selectionFailure
1442
+ );
1443
+ return executeDiscoveredRun(execution, discovered.discovery);
1444
+ }
1445
+ async function discoverRun(context, config, session) {
1446
+ try {
1447
+ return {
1448
+ discovery: await discoverCommandTests(
1449
+ config,
1450
+ context.options,
1451
+ (value) => safeDiscoveryText(value, config)
1452
+ )
1453
+ };
1454
+ } catch {
1455
+ const diagnostic = discoveryDiagnostic(config);
1456
+ context.commit();
1457
+ await session.recorder.finish(canonicalDiagnosticError(diagnostic));
1458
+ return { execution: await session.terminalExecution(diagnostic) };
1459
+ }
1460
+ }
1461
+ function discoveryDiagnostic(config) {
1462
+ return setupDiagnostic(
1463
+ new ProjectConfigError([
1464
+ {
1465
+ code: "test_discovery_error",
1466
+ file: config.configPath ?? config.testDirectory,
1467
+ line: 1,
1468
+ col: 1,
1469
+ key: "tests.directory",
1470
+ message: "The configured test directory could not be read.",
1471
+ fix: "Check the test directory path and permissions, then try again."
1472
+ }
1473
+ ])
1474
+ );
1475
+ }
1476
+ async function finishConclusion(context, session, problems, conclusion) {
1477
+ if (conclusion.recordDiscoveryProblems)
1478
+ await session.recorder.addDiscoveryProblems(problems);
1479
+ context.commit();
1480
+ await session.recorder.finish(
1481
+ canonicalDiagnosticError(conclusion.diagnostic),
1482
+ conclusion.state
1483
+ );
1484
+ return session.terminalExecution(conclusion.diagnostic);
1485
+ }
1486
+ async function executeDiscoveredRun(execution, discovery) {
1487
+ try {
1488
+ return await runSelected(execution, discovery);
1489
+ } catch (error) {
1490
+ return handleRunError(execution, error);
1491
+ }
1492
+ }
1493
+ async function runSelected(execution, discovery) {
1494
+ const { command: context, config, deadline, session } = execution;
1495
+ const router = context.rejections;
1496
+ const outcome = await executeSelectedTests({
1497
+ config,
1498
+ options: context.options,
1499
+ files: discovery.files,
1500
+ globalSelectedTests: discovery.globalSelectedTests,
1501
+ discoveryProblems: discovery.problems,
1502
+ signal: deadline.signal,
1503
+ recorder: session.recorder,
1504
+ writer: session.writer,
1505
+ rejections: router,
1506
+ reporterFailed: () => session.reporterFailed
1507
+ });
1508
+ const operational = includeStrayRejections(
1509
+ context,
1510
+ config,
1511
+ outcome.operational
1512
+ );
1513
+ if (deadline.signal.aborted)
1514
+ return finishConclusion(
1515
+ context,
1516
+ session,
1517
+ discovery.problems,
1518
+ interruptionConclusion(deadline.timedOut)
1519
+ );
1520
+ const diagnostic = completedRunConclusion(
1521
+ operational,
1522
+ outcome.erroredTests,
1523
+ discovery.problems
1524
+ );
1525
+ context.commit();
1526
+ await finishRecorder(session.recorder, diagnostic);
1527
+ return session.terminalExecution(diagnostic);
1528
+ }
1529
+ function includeStrayRejections(context, config, operational) {
1530
+ if (operational) return operational;
1531
+ const strays = context.rejections.unattributed;
1532
+ if (strays.length === 0) return null;
1533
+ context.reportedStrays = strays.length;
1534
+ return strayRejectionDiagnostic(strays, config);
1535
+ }
1536
+ async function finishRecorder(recorder, diagnostic) {
1537
+ if (diagnostic) await recorder.finish(canonicalDiagnosticError(diagnostic));
1538
+ else await recorder.finish();
1539
+ }
1540
+ async function handleRunError(execution, error) {
1541
+ const { command: context, config, deadline, session } = execution;
1542
+ context.commit();
1543
+ if (error instanceof ReporterOutputError) return session.reporterFailure();
1544
+ if (error instanceof ProgressWriterError)
1545
+ return progressWriteFailure(session, error);
1546
+ const diagnostic = deadline.signal.aborted ? interruptionConclusion(deadline.timedOut).diagnostic : setupDiagnostic(error, config.providerName);
1547
+ return finishUnexpectedError(session, deadline, diagnostic);
1548
+ }
1549
+ async function progressWriteFailure(session, error) {
1550
+ const diagnostic = outputDiagnostic(error.path);
1551
+ const result = terminalOutputFailure(session.recorder.snapshot, diagnostic);
1552
+ await session.writer.invalidate();
1553
+ return {
1554
+ result,
1555
+ artifacts: { ...session.artifacts, authoritative: false },
1556
+ diagnostic
1557
+ };
1558
+ }
1559
+ async function finishUnexpectedError(session, deadline, diagnostic) {
1560
+ try {
1561
+ if (session.recorder.snapshot.state === "running")
1562
+ await session.recorder.finish(
1563
+ canonicalDiagnosticError(diagnostic),
1564
+ failureState(deadline)
1565
+ );
1566
+ return session.terminalExecution(diagnostic);
1567
+ } catch (error) {
1568
+ return finalWriteFailure(session, error);
1569
+ }
1570
+ }
1571
+ function failureState(deadline) {
1572
+ if (!deadline.signal.aborted) return "error";
1573
+ return deadline.timedOut ? "error" : "interrupted";
1574
+ }
1575
+ async function finalWriteFailure(session, error) {
1576
+ const output = outputDiagnostic(
1577
+ error instanceof ProgressWriterError ? error.path : session.writer.resultPath
1578
+ );
1579
+ const result = terminalOutputFailure(session.recorder.snapshot, output);
1580
+ await session.writer.invalidate();
1581
+ return {
1582
+ result,
1583
+ artifacts: { ...session.artifacts, authoritative: false },
1584
+ diagnostic: output
1585
+ };
1586
+ }
1587
+ function disposeRejections(context) {
1588
+ context.rejections?.dispose();
1589
+ const late = context.rejections?.unattributed.slice(context.reportedStrays) ?? [];
1590
+ if (!context.config) return;
1591
+ for (const stray of late)
1592
+ context.options.onStrayRejection?.(
1593
+ strayRejectionDiagnostic([stray], context.config).message
1594
+ );
1595
+ }
1596
+
1597
+ // src/run-command.ts
1598
+ function executeRunCommand(options) {
1599
+ return executeRunCommandImplementation(options);
1600
+ }
1601
+ export {
1602
+ executeRunCommand,
1603
+ strayRejectionDiagnostic,
1604
+ verifyGraceMs
1605
+ };