sedum-cli 0.1.0-alpha.4 → 0.1.0-alpha.6

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.
@@ -1,16 +1,20 @@
1
1
  import {
2
2
  discoverRunTests
3
- } from "./chunk-UVCFRFDV.js";
3
+ } from "./chunk-DRCPO7W3.js";
4
4
  import {
5
5
  loadProjectConfig
6
- } from "./chunk-W2BEUHUB.js";
6
+ } from "./chunk-GYFQYSYT.js";
7
7
 
8
8
  // src/affected-selection.ts
9
9
  import { execFile } from "child_process";
10
10
  import { readFile, realpath } from "fs/promises";
11
11
  import path from "path";
12
12
  import { promisify } from "util";
13
- import { loadFlowFile, resolveFlowModules } from "@sedum-dev/core";
13
+ import {
14
+ isScriptTestFile,
15
+ loadFlowFile,
16
+ resolveFlowModules
17
+ } from "@sedum-dev/core";
14
18
  import {
15
19
  TypeSafeAdapter
16
20
  } from "@sedum-dev/provider-typesafe";
@@ -128,6 +132,16 @@ async function selectAffectedTests(options) {
128
132
  const forced = [];
129
133
  for (const test of selection.tests) {
130
134
  const file = path.join(config.projectRoot, test.file);
135
+ if (isScriptTestFile(file)) {
136
+ if (tests.some((scored) => scored.file === test.file)) continue;
137
+ forced.push(changed.has(await realpath(file)));
138
+ tests.push({
139
+ file: test.file,
140
+ source: await readFile(file, "utf8"),
141
+ modules: []
142
+ });
143
+ continue;
144
+ }
131
145
  const parsed = await loadFlowFile(file, {
132
146
  repoRoot: config.projectRoot,
133
147
  rejectSymlinks: true
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ProjectConfigError
3
- } from "./chunk-W2BEUHUB.js";
3
+ } from "./chunk-GYFQYSYT.js";
4
4
 
5
5
  // src/diagnostics.ts
6
6
  import { BrowserDriverError, ProviderError } from "@sedum-dev/core";
@@ -103,17 +103,37 @@ function flowDiagnostic(result) {
103
103
  };
104
104
  const diagnostic = known[result.code];
105
105
  if (diagnostic) return { code: result.code, ...diagnostic };
106
+ if (result.code === "navigation_failed")
107
+ return {
108
+ code: result.code,
109
+ message: bounded(result.message),
110
+ fix: bounded(
111
+ result.fix ?? "Check the test's url (or baseUrl), your network or VPN, and that the site is up."
112
+ )
113
+ };
106
114
  if (result.code === "provider_rate_limited")
107
115
  return {
108
116
  code: result.code,
109
117
  message: "The model provider kept rate limiting requests for five minutes.",
110
118
  fix: "Lower --parallel or --provider-concurrency, or retry later."
111
119
  };
120
+ if (result.code === "provider_authentication")
121
+ return {
122
+ code: result.code,
123
+ message: "The model provider rejected the API key.",
124
+ fix: "Set TYPESAFE_API_KEY to a valid key, check it with `sedum doctor`, then rerun."
125
+ };
126
+ if (result.code === "provider_configuration")
127
+ return {
128
+ code: result.code,
129
+ message: "The model provider is not configured correctly.",
130
+ fix: "Check TYPESAFE_API_KEY, TYPESAFE_BASE_URL and the model with `sedum doctor`, then rerun."
131
+ };
112
132
  if (result.code.startsWith("provider_"))
113
133
  return {
114
134
  code: result.code,
115
135
  message: "The model provider could not complete the run safely.",
116
- fix: result.code === "provider_configuration" || result.code === "provider_authentication" ? "Check the provider configuration and API access, then rerun the test." : "Check provider availability and the test input, then rerun the test."
136
+ fix: "Check provider availability and the test input, then rerun the test."
117
137
  };
118
138
  return {
119
139
  code: "execution_error",
@@ -121,6 +141,17 @@ function flowDiagnostic(result) {
121
141
  fix: "Check the browser, provider, and test input, then rerun the test."
122
142
  };
123
143
  }
144
+ var RUN_STOPPING_CODES = /* @__PURE__ */ new Set([
145
+ "browser-missing",
146
+ "browser-launch-failed",
147
+ "script-missing",
148
+ "provider_configuration",
149
+ "provider_authentication",
150
+ "provider_rate_limited"
151
+ ]);
152
+ function stopsRun(code) {
153
+ return RUN_STOPPING_CODES.has(code);
154
+ }
124
155
  function renderDiagnostic(diagnostic) {
125
156
  return `${diagnostic.message}
126
157
  Fix: ${diagnostic.fix}
@@ -434,6 +465,7 @@ export {
434
465
  outputDiagnostic,
435
466
  canonicalDiagnosticError,
436
467
  flowDiagnostic,
468
+ stopsRun,
437
469
  renderDiagnostic,
438
470
  MAX_PARALLEL,
439
471
  planLanes,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  discoverConfiguredTests
3
- } from "./chunk-W2BEUHUB.js";
3
+ } from "./chunk-GYFQYSYT.js";
4
4
 
5
5
  // src/run-selection.ts
6
6
  import { lstat, realpath } from "fs/promises";
@@ -8,7 +8,8 @@ import path from "path";
8
8
  import { minimatch } from "minimatch";
9
9
  import {
10
10
  listTests,
11
- loadFlowFile,
11
+ loadListingEntries,
12
+ TEST_SUFFIXES,
12
13
  walkSuiteFiles
13
14
  } from "@sedum-dev/core";
14
15
  function contained(root, target) {
@@ -20,8 +21,9 @@ function selectRunTests(tests, filters) {
20
21
  const excludes = filters.exclude ?? [];
21
22
  const labels = filters.labels ?? [];
22
23
  const names = filters.names ?? [];
24
+ const ids = filters.ids ?? [];
23
25
  return tests.filter(
24
- (test) => (includes.length === 0 || includes.some((glob) => minimatch(test.file, glob))) && !excludes.some((glob) => minimatch(test.file, glob)) && labels.every((label) => test.tags.includes(label)) && (names.length === 0 || names.some(
26
+ (test) => (includes.length === 0 || includes.some((glob) => minimatch(test.file, glob))) && !excludes.some((glob) => minimatch(test.file, glob)) && labels.every((label) => test.tags.includes(label)) && (ids.length === 0 || ids.includes(test.id)) && (names.length === 0 || names.some(
25
27
  (name) => `${test.id}
26
28
  ${test.description ?? ""}`.toLowerCase().includes(name.toLowerCase())
27
29
  ))
@@ -91,7 +93,7 @@ async function discoverRunTests(config, paths, filters = {}) {
91
93
  if (info.isDirectory()) {
92
94
  for (const file2 of await walkSuiteFiles(
93
95
  target,
94
- [".test.yaml"],
96
+ TEST_SUFFIXES,
95
97
  (folder) => {
96
98
  problems.push({
97
99
  file: path.relative(root, folder),
@@ -102,27 +104,21 @@ async function discoverRunTests(config, paths, filters = {}) {
102
104
  }
103
105
  ))
104
106
  files.add(file2);
105
- } else if (info.isFile() && candidate.endsWith(".test.yaml"))
107
+ } else if (info.isFile() && TEST_SUFFIXES.some((suffix) => candidate.endsWith(suffix)))
106
108
  files.add(target);
107
109
  else
108
110
  problems.push({
109
111
  file,
110
112
  code: "unsupported_file",
111
- message: "Expected a *.test.yaml file or directory.",
113
+ message: "Expected a *.test.ts or *.test.yaml file, or a directory.",
112
114
  fix: "Choose a test path."
113
115
  });
114
116
  }
115
117
  }
116
- const parsed = [];
117
- for (const file of [...files].sort()) {
118
- parsed.push({
119
- file,
120
- result: await loadFlowFile(file, {
121
- repoRoot: root,
122
- rejectSymlinks: true
123
- })
124
- });
125
- }
118
+ const parsed = await loadListingEntries([...files].sort(), {
119
+ repoRoot: root,
120
+ rejectSymlinks: true
121
+ });
126
122
  const listing = listTests(parsed, { repoRoot: root });
127
123
  return {
128
124
  tests: selectRunTests(listing.tests, filters),
@@ -15,7 +15,7 @@ var ProjectConfigError = class extends Error {
15
15
  };
16
16
  var DEFAULTS = {
17
17
  testDirectory: "tests",
18
- include: ["**/*.test.yaml"],
18
+ include: ["**/*.test.ts", "**/*.test.yaml"],
19
19
  exclude: [],
20
20
  browser: "chrome",
21
21
  viewport: { width: 1280, height: 900 },
@@ -80,10 +80,31 @@ function mapUnknownKeys(value, names, prefix, file, counter, diagnostics) {
80
80
  prefix ? `${prefix}.${key}` : key,
81
81
  "unknown_config_key",
82
82
  `Unknown configuration key \`${prefix ? `${prefix}.` : ""}${key}\`.`,
83
- "Remove the key or use one documented by `sedum run --help`."
83
+ keyFix(key, names)
84
84
  );
85
85
  }
86
86
  }
87
+ function distance(left, right) {
88
+ const row = Array.from({ length: right.length + 1 }, (_, i) => i);
89
+ for (let i = 1; i <= left.length; i++) {
90
+ let previous = row[0];
91
+ row[0] = i;
92
+ for (let j = 1; j <= right.length; j++) {
93
+ const saved = row[j];
94
+ row[j] = Math.min(
95
+ row[j] + 1,
96
+ row[j - 1] + 1,
97
+ previous + (left[i - 1] === right[j - 1] ? 0 : 1)
98
+ );
99
+ previous = saved;
100
+ }
101
+ }
102
+ return row[right.length];
103
+ }
104
+ function keyFix(key, names) {
105
+ const [closest] = [...names].map((known) => ({ known, score: distance(key, known) })).sort((a, b) => a.score - b.score || a.known.localeCompare(b.known));
106
+ return closest && closest.score <= 2 ? `Did you mean \`${closest.known}\`?` : "Remove the key or use one documented in docs/configuration.md.";
107
+ }
87
108
  function object(value) {
88
109
  return value !== null && typeof value === "object" && !Array.isArray(value);
89
110
  }
@@ -210,7 +231,7 @@ function stringList(value, fallback, key, diagnostics, file, counter, node) {
210
231
  key,
211
232
  "invalid_config_globs",
212
233
  `Configuration key \`${key}\` must be a list of nonempty glob strings.`,
213
- `Write \`${key}: ["**/*.test.yaml"]\`.`
234
+ `Write \`${key}: ["**/*.test.ts", "**/*.test.yaml"]\`.`
214
235
  );
215
236
  return [...fallback];
216
237
  }
@@ -610,7 +631,7 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
610
631
  "tests.include",
611
632
  "empty_config_globs",
612
633
  "Configuration key `tests.include` must select at least one pattern.",
613
- "Add `**/*.test.yaml` or another test glob."
634
+ "Add `**/*.test.ts` or another test glob."
614
635
  );
615
636
  const variables = {
616
637
  ...rootVariables,
@@ -774,7 +795,7 @@ async function discoverConfiguredTests(config) {
774
795
  if (entry.isDirectory()) await visit2(absolute);
775
796
  else if (entry.isFile()) {
776
797
  const relative = path.relative(config.testDirectory, absolute).split(path.sep).join("/");
777
- if (relative.endsWith(".test.yaml") && config.include.some((pattern) => minimatch(relative, pattern)) && !config.exclude.some((pattern) => minimatch(relative, pattern)))
798
+ if ((relative.endsWith(".test.ts") || relative.endsWith(".test.yaml")) && config.include.some((pattern) => minimatch(relative, pattern)) && !config.exclude.some((pattern) => minimatch(relative, pattern)))
778
799
  files.push(absolute);
779
800
  }
780
801
  }
@@ -2,12 +2,15 @@ import {
2
2
  DEFAULT_PROVIDER_BASE_URL,
3
3
  DEFAULT_PROVIDER_MODEL,
4
4
  loadProjectConfig
5
- } from "./chunk-W2BEUHUB.js";
5
+ } from "./chunk-GYFQYSYT.js";
6
6
 
7
7
  // src/doctor-command.ts
8
8
  import { lstat, mkdir, mkdtemp, rm, rmdir, writeFile } from "fs/promises";
9
9
  import path from "path";
10
- import { findBrowserExecutable } from "@sedum-dev/core";
10
+ import {
11
+ findBrowserExecutable,
12
+ probeOpenRouterKey
13
+ } from "@sedum-dev/core";
11
14
  import {
12
15
  probeTypeSafeApiKey
13
16
  } from "@sedum-dev/provider-typesafe";
@@ -79,7 +82,7 @@ async function checkOutputWritable(config) {
79
82
  }
80
83
  }
81
84
  }
82
- async function executeDoctorCommand(cwd, probes = {}) {
85
+ async function executeDoctorCommand(cwd, probes = {}, options = {}) {
83
86
  const checks = [];
84
87
  const version = probes.nodeVersion ?? process.versions.node;
85
88
  checks.push(
@@ -207,6 +210,42 @@ async function executeDoctorCommand(cwd, probes = {}) {
207
210
  )
208
211
  );
209
212
  }
213
+ if (config && (options.vision || config.vision.enabled)) {
214
+ const visionKey = config.visionApiKey?.trim();
215
+ checks.push(
216
+ visionKey ? pass(
217
+ "vision_key",
218
+ "OpenRouter API key for vision fallback is present."
219
+ ) : fail(
220
+ "vision_key",
221
+ "Vision fallback is enabled but OPEN_ROUTER_API_KEY is missing.",
222
+ "Set OPEN_ROUTER_API_KEY in the environment or the project-root .env."
223
+ )
224
+ );
225
+ if (visionKey) {
226
+ const result = await (probes.visionAuth ?? probeOpenRouterKey)(
227
+ visionKey
228
+ ).catch(() => "unreachable");
229
+ checks.push(
230
+ result === "accepted" ? pass("vision_auth", "OpenRouter accepted the vision key.") : result === "rejected" ? fail(
231
+ "vision_auth",
232
+ "OpenRouter rejected OPEN_ROUTER_API_KEY.",
233
+ "Replace OPEN_ROUTER_API_KEY with a valid OpenRouter key and rerun doctor."
234
+ ) : fail(
235
+ "vision_auth",
236
+ "OpenRouter could not be reached to check the vision key.",
237
+ "Check access to https://openrouter.ai and retry."
238
+ )
239
+ );
240
+ } else
241
+ checks.push(
242
+ fail(
243
+ "vision_auth",
244
+ "The vision key could not be checked without a key.",
245
+ "Set OPEN_ROUTER_API_KEY, then rerun doctor."
246
+ )
247
+ );
248
+ }
210
249
  if (config) {
211
250
  try {
212
251
  await (probes.output ?? checkOutputWritable)(config);
@@ -3,12 +3,23 @@ import {
3
3
  clearLocatorCache,
4
4
  parseParallel,
5
5
  renderDiagnostic
6
- } from "./chunk-72CYPRWT.js";
6
+ } from "./chunk-BEY4UNIW.js";
7
7
  import {
8
8
  ProjectConfigError,
9
9
  discoverConfiguredTests,
10
10
  loadProjectConfig
11
- } from "./chunk-W2BEUHUB.js";
11
+ } from "./chunk-GYFQYSYT.js";
12
+
13
+ // src/invocation.ts
14
+ function sedumCommand(env = process.env, script = process.argv[1] ?? "") {
15
+ if (env.npm_command === "exec" || env.npm_lifecycle_event === "npx")
16
+ return "npx sedum";
17
+ return /[\\/]node_modules[\\/]/.test(script) ? "npx sedum" : "sedum";
18
+ }
19
+ var SUBCOMMAND = /(?<![\w./-]|npx )sedum (?=(?:run|browsers|doctor|validate|init|list)\b|--help\b|--version\b)/g;
20
+ function withCommand(text, command) {
21
+ return command === "sedum" ? text : text.replace(SUBCOMMAND, `${command} `);
22
+ }
12
23
 
13
24
  // src/exit-policy.ts
14
25
  import {
@@ -33,7 +44,7 @@ function listExitCode(listing, failedBeforeListing) {
33
44
 
34
45
  // src/output.ts
35
46
  import { validateRunResult as validateRunResult2 } from "@sedum-dev/core";
36
- import { usageLines, visionSummary } from "@sedum-dev/reporters";
47
+ import { testLabel, usageLines, visionSummary } from "@sedum-dev/reporters";
37
48
  var ansi = {
38
49
  green: "\x1B[32m",
39
50
  red: "\x1B[31m",
@@ -69,6 +80,42 @@ function executionLines(value) {
69
80
  ])
70
81
  )
71
82
  ];
83
+ if (execution?.vision) {
84
+ const steps = value.tests.flatMap(
85
+ (test) => test.attempts.flatMap((attempt) => attempt.steps)
86
+ );
87
+ const attempts = steps.flatMap(
88
+ (step) => step.locator?.vision ? [step.locator.vision] : []
89
+ );
90
+ const selected = attempts.filter(
91
+ (vision) => vision.outcome === "selected"
92
+ ).length;
93
+ const abstained = attempts.filter(
94
+ (vision) => vision.outcome === "abstained"
95
+ ).length;
96
+ const failed = attempts.filter(
97
+ (vision) => vision.outcome === "failed" || !vision.outcome && vision.failure
98
+ ).length;
99
+ const unrecorded = attempts.length - selected - abstained - failed;
100
+ lines.push(
101
+ attempts.length ? `vision ${execution.vision.model}: attempted on ${attempts.length} step(s); ${selected} selected, ${abstained} abstained, ${failed} failed${unrecorded ? `, ${unrecorded} outcome unrecorded` : ""}` : `vision ${execution.vision.model}: enabled, no fallback attempted`
102
+ );
103
+ const failedWithoutVision = steps.filter(
104
+ (step) => step.operation === "click" && (step.verdict === "failed" || step.state === "error") && !step.locator?.vision
105
+ ).length;
106
+ if (failedWithoutVision)
107
+ lines.push(
108
+ `vision not attempted on ${failedWithoutVision} failed click step(s); see step errors for details`
109
+ );
110
+ if (execution.vision.key === "rejected")
111
+ lines.push(
112
+ "vision warning: OpenRouter rejected OPEN_ROUTER_API_KEY, so vision fallback cannot work. Check it with `sedum doctor --vision`."
113
+ );
114
+ else if (execution.vision.key === "unreachable")
115
+ lines.push(
116
+ "vision warning: OpenRouter could not be reached to check OPEN_ROUTER_API_KEY."
117
+ );
118
+ }
72
119
  const limited = calls.filter((call) => call.rateLimited).length;
73
120
  const waitMs = calls.reduce(
74
121
  (sum, call) => sum + (call.rateLimitWaitMs ?? 0),
@@ -91,13 +138,9 @@ function renderRunSummary(result, capabilities, artifacts, showCosts) {
91
138
  const lines = [];
92
139
  const flagCounts = { low_confidence: 0, contradiction: 0 };
93
140
  for (const test of value.tests) {
94
- const label = stateLabel(test.state, test.verdict);
95
- const flags = test.flags.length ? ` [${test.flags.join(", ")}]` : "";
96
- lines.push(
97
- `test ${paint(label.text, label.color, color)} ${test.file}${flags}`
98
- );
141
+ const details = [];
99
142
  if (test.attempts.length > 1)
100
- lines.push(
143
+ details.push(
101
144
  ` attempts ${test.attempts.length} (${test.attempts.map((attempt) => attempt.verdict ?? attempt.state).join(" -> ")})`
102
145
  );
103
146
  const selected = test.attempts.find(
@@ -110,23 +153,38 @@ function renderRunSummary(result, capabilities, artifacts, showCosts) {
110
153
  const reason = cache.reason ? ` (${cache.reason})` : "";
111
154
  const fallback = cache.fallbackCalledModel ? ", model fallback" : "";
112
155
  const changed = cache.targetChanged ? ", target changed" : "";
113
- lines.push(
156
+ details.push(
114
157
  ` step ${step.index}: cache ${cache.outcome}${reason}${fallback}${changed}`
115
158
  );
116
159
  }
117
160
  }
161
+ if (details.length) lines.push(testLabel(test), ...details);
118
162
  }
163
+ const outsideGit = value.tests.some(
164
+ (test) => test.attempts.some(
165
+ (attempt) => attempt.steps.some(
166
+ (step) => step.locator?.cache?.reason === "outside_git"
167
+ )
168
+ )
169
+ );
170
+ if (outsideGit)
171
+ lines.push(
172
+ "cache off: this project is not a Git checkout; run `git init` to cache locator results"
173
+ );
119
174
  const runLabel = stateLabel(value.state, value.verdict);
120
175
  lines.push(`run ${paint(runLabel.text, runLabel.color, color)}`);
121
176
  for (const problem of value.discoveryProblems ?? [])
122
177
  lines.push(
123
178
  `discovery ${problem.file}${problem.line === void 0 ? "" : `:${problem.line}:${problem.col ?? 1}`}: ${problem.message} Fix: ${problem.fix}`
124
179
  );
180
+ const erroredTests = value.tests.filter(
181
+ (test) => test.state === "error"
182
+ ).length;
125
183
  lines.push(
126
- `tests ${value.totals.selectedTests} selected, ${value.totals.executedTests} executed, ${value.totals.passedTests} passed, ${value.totals.failedTests} failed`
184
+ `tests ${value.totals.selectedTests} selected, ${value.totals.executedTests} executed, ${value.totals.passedTests} passed, ${value.totals.failedTests} failed${erroredTests ? `, ${erroredTests} could not run` : ""}`
127
185
  );
128
186
  lines.push(
129
- `flags ${value.totals.flaggedSteps} flagged step(s), low_confidence ${flagCounts.low_confidence}, contradiction ${flagCounts.contradiction}`
187
+ `flags ${value.totals.flaggedSteps} flagged step(s), low_confidence ${flagCounts.low_confidence}, contradiction ${flagCounts.contradiction}, flaky ${value.tests.filter((test) => test.flags.includes("flaky")).length} test(s)`
130
188
  );
131
189
  lines.push(...executionLines(value));
132
190
  for (const test of value.tests)
@@ -144,7 +202,6 @@ function renderRunSummary(result, capabilities, artifacts, showCosts) {
144
202
  );
145
203
  }
146
204
  if (artifacts.authoritative) {
147
- lines.push(`progress ${artifacts.progressPath}`);
148
205
  lines.push(`result ${artifacts.resultPath}`);
149
206
  if (artifacts.htmlPath) lines.push(`html ${artifacts.htmlPath}`);
150
207
  if (artifacts.markdownPath)
@@ -157,12 +214,8 @@ function renderRunSummary(result, capabilities, artifacts, showCosts) {
157
214
  }
158
215
  if (capabilities.stdoutIsTTY || showCosts) {
159
216
  lines.push(...usageLines(value));
160
- lines.push(
161
- `model ${value.totals.modelCalls} call(s), ${value.totals.inputTokens} input tokens, ${value.totals.outputTokens} output tokens`
162
- );
163
- lines.push(
164
- value.totals.costComplete && value.totals.costUsd !== null ? `cost $${value.totals.costUsd.toFixed(6)}` : "cost unknown or incomplete"
165
- );
217
+ if (!value.totals.costComplete || value.totals.costUsd === null)
218
+ lines.push("cost unknown or incomplete");
166
219
  }
167
220
  return `${lines.join("\n")}
168
221
  `;
@@ -178,7 +231,7 @@ import {
178
231
  // src/list-command.ts
179
232
  import {
180
233
  listTests,
181
- loadFlowFile
234
+ loadListingEntries
182
235
  } from "@sedum-dev/core";
183
236
 
184
237
  // src/project-context.ts
@@ -281,12 +334,9 @@ async function executeListCommand(options) {
281
334
  const { discovery } = context;
282
335
  if (discovery.problems.length)
283
336
  return { discovery, configErrors: [], listing: null };
284
- const parsed = [];
285
- for (const file of discovery.tests)
286
- parsed.push({
287
- file,
288
- result: await loadFlowFile(file, { repoRoot: discovery.root })
289
- });
337
+ const parsed = await loadListingEntries(discovery.tests, {
338
+ repoRoot: discovery.root
339
+ });
290
340
  return {
291
341
  discovery,
292
342
  configErrors: [],
@@ -314,7 +364,7 @@ function emptyProjectProblem(paths, testDirectory) {
314
364
  return {
315
365
  code: "missing_path",
316
366
  path: shown,
317
- message: `No *.test.yaml or *.module.yaml files were found under ${shown}.`,
367
+ message: `No *.test.ts, *.test.yaml, or *.module.yaml files were found under ${shown}.`,
318
368
  fix: paths.length ? "Pass paths relative to the project root that contain tests or modules." : "Add tests under tests.directory, or correct tests.directory/include/exclude in sedum.config.yaml."
319
369
  };
320
370
  }
@@ -608,10 +658,13 @@ function commandHelp(command, writeErr) {
608
658
  async function runCli(args, version, runtime = {}) {
609
659
  const stdout = [];
610
660
  const stderr = [];
611
- const writeOut = runtime.stdout ?? ((value) => stdout.push(value));
612
- const writeErr = runtime.stderr ?? ((value) => stderr.push(value));
661
+ const command = runtime.command ?? "sedum";
662
+ const rawOut = runtime.stdout ?? ((value) => stdout.push(value));
663
+ const rawErr = runtime.stderr ?? ((value) => stderr.push(value));
664
+ const writeOut = (value) => rawOut(withCommand(value, command));
665
+ const writeErr = (value) => rawErr(withCommand(value, command));
613
666
  const capabilities = runtime.capabilities ?? plainOutput;
614
- const executeRun = runtime.executeRun ?? (async (options) => (await import("./run-command-SUPJIEY5.js")).executeRunCommand(options));
667
+ const executeRun = runtime.executeRun ?? (async (options) => (await import("./run-command-YNDKEUUU.js")).executeRunCommand(options));
615
668
  const cwd = runtime.cwd ?? process.cwd();
616
669
  let exitCode = 3;
617
670
  const program = new Command().name("sedum").description(
@@ -629,7 +682,7 @@ async function runCli(args, version, runtime = {}) {
629
682
  "after",
630
683
  "\nCreates a config, a SauceDemo example, .env.example, and ignore rules.\nExisting files are never replaced.\n"
631
684
  ).action(async () => {
632
- const { executeInitCommand } = await import("./init-command-4RYOB737.js");
685
+ const { executeInitCommand } = await import("./init-command-CTZAAPJ5.js");
633
686
  const interactive = capabilities.stdoutIsTTY && (process.stdin.isTTY === true || runtime.confirmInit !== void 0);
634
687
  const confirm = runtime.confirmInit ?? (interactive ? async (question) => {
635
688
  const { createInterface } = await import("readline/promises");
@@ -690,6 +743,11 @@ async function runCli(args, version, runtime = {}) {
690
743
  "match id or description substring (repeatable)",
691
744
  collectValue,
692
745
  []
746
+ ).option(
747
+ "--id <id>",
748
+ "select a test by its exact id (repeatable)",
749
+ collectValue,
750
+ []
693
751
  ).option("--env <name>", "select a named environment").option("--browser <kind>", "chrome or chromium").option("--vision", "enable vision fallback for ambiguous clicks").option("--no-vision", "disable vision fallback").option("--vision-model <model>", "override the OpenRouter vision model").option(
694
752
  "--url-override <url>",
695
753
  "replace entry URL origin for preview deployments"
@@ -738,7 +796,7 @@ async function runCli(args, version, runtime = {}) {
738
796
  false
739
797
  ).addHelpText(
740
798
  "after",
741
- "\nPrerequisites:\n Install Chromium with `sedum browsers install chromium` and set TYPESAFE_API_KEY (and TYPESAFE_BASE_URL for a compatible provider).\n\nExamples:\n sedum run tests/login.test.yaml\n sedum run tests/login.test.yaml --strict --costs\n"
799
+ "\nPrerequisites:\n Install Chromium with `sedum browsers install chromium` and set TYPESAFE_API_KEY (and TYPESAFE_BASE_URL for a compatible provider).\n\nExamples:\n sedum run tests/login.test.ts\n sedum run tests/login.test.ts --id 'tests/login.test.ts#signs in'\n sedum run tests/login.test.yaml --strict --costs\n"
742
800
  ).action(
743
801
  async (paths, options) => {
744
802
  if (options.shardIndex === void 0 !== (options.shardCount === void 0) || options.shardIndex !== void 0 && options.shardIndex > options.shardCount) {
@@ -771,7 +829,7 @@ async function runCli(args, version, runtime = {}) {
771
829
  return;
772
830
  }
773
831
  if (options.affected) {
774
- const { selectAffectedTests, AffectedSelectionError } = await import("./affected-selection-5YF7ZHKG.js");
832
+ const { selectAffectedTests, AffectedSelectionError } = await import("./affected-selection-OHKZUPYG.js");
775
833
  const { ProviderError: ProviderError2 } = await import("@sedum-dev/core");
776
834
  writeErr(
777
835
  "Experimental selection sends the tracked Git diff and test/module sources to the configured TypeSafe provider. Full CI is still recommended.\n"
@@ -784,7 +842,8 @@ async function runCli(args, version, runtime = {}) {
784
842
  include: options.include,
785
843
  exclude: options.exclude,
786
844
  labels: options.labels,
787
- names: options.name
845
+ names: options.name,
846
+ ids: options.id
788
847
  },
789
848
  threshold: options.threshold ?? 0.1,
790
849
  ...options.base !== void 0 ? { base: options.base } : {},
@@ -859,12 +918,15 @@ No tests were run. Fix the selection error or run without --affected.
859
918
  }
860
919
  };
861
920
  const execution = await executeRun({
921
+ command,
922
+ ...runtime.onStrayRejection ? { onStrayRejection: runtime.onStrayRejection } : {},
862
923
  paths,
863
924
  filters: {
864
925
  include: options.include,
865
926
  exclude: options.exclude,
866
927
  labels: options.labels,
867
- names: options.name
928
+ names: options.name,
929
+ ids: options.id
868
930
  },
869
931
  ...options.env ? { environment: options.env } : {},
870
932
  ...options.browser ? { browser: options.browser } : {},
@@ -951,12 +1013,18 @@ No tests were run. Fix the selection error or run without --affected.
951
1013
  );
952
1014
  exitCode = 0;
953
1015
  });
954
- program.command("doctor").description("check whether this environment can run Sedum").option("--json", "print versioned JSON checks on stdout", false).addHelpText(
1016
+ program.command("doctor").description("check whether this environment can run Sedum").option("--json", "print versioned JSON checks on stdout", false).option(
1017
+ "--vision",
1018
+ "also check the vision fallback's OPEN_ROUTER_API_KEY (automatic when vision.enabled is true)",
1019
+ false
1020
+ ).addHelpText(
955
1021
  "after",
956
1022
  "\nThe authenticated API check makes one small, potentially billable request.\n\nExit codes:\n 0 all checks passed\n 3 one or more prerequisites failed\n"
957
1023
  ).action(async (options) => {
958
- const { executeDoctorCommand, renderDoctorText } = await import("./doctor-command-EU5OJJ5P.js");
959
- const result = await executeDoctorCommand(cwd, runtime.doctorProbes);
1024
+ const { executeDoctorCommand, renderDoctorText } = await import("./doctor-command-5HKQX3DN.js");
1025
+ const result = await executeDoctorCommand(cwd, runtime.doctorProbes, {
1026
+ vision: options.vision
1027
+ });
960
1028
  writeOut(
961
1029
  options.json ? `${JSON.stringify(result)}
962
1030
  ` : renderDoctorText(result)
@@ -1064,8 +1132,11 @@ Fix: use \`sedum browsers install chromium\`.
1064
1132
  "Fix: correct the command shown above and rerun it, or use `sedum --help`.\n"
1065
1133
  );
1066
1134
  } else {
1135
+ const detail = error instanceof Error ? `${error.name}: ${error.message.split("\n")[0].slice(0, 200)}` : "unknown error";
1067
1136
  writeErr(
1068
- "The command could not be parsed safely.\nFix: run `sedum --help` and correct the command.\n"
1137
+ `Sedum stopped on an unexpected internal error (${detail}).
1138
+ Fix: rerun the command; if it happens again, report it with the run's result.json.
1139
+ `
1069
1140
  );
1070
1141
  exitCode = 3;
1071
1142
  }
@@ -1074,6 +1145,7 @@ Fix: use \`sedum browsers install chromium\`.
1074
1145
  }
1075
1146
 
1076
1147
  export {
1148
+ sedumCommand,
1077
1149
  runExitCode,
1078
1150
  renderRunSummary,
1079
1151
  runCli
package/dist/cli.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- runCli
4
- } from "./chunk-V4JF5CPE.js";
5
- import "./chunk-72CYPRWT.js";
6
- import "./chunk-W2BEUHUB.js";
3
+ runCli,
4
+ sedumCommand
5
+ } from "./chunk-ONJZI3ER.js";
6
+ import "./chunk-BEY4UNIW.js";
7
+ import "./chunk-GYFQYSYT.js";
7
8
 
8
9
  // src/cli.ts
9
10
  import { createRequire } from "module";
11
+ import { fileURLToPath } from "url";
10
12
 
11
13
  // src/interrupts.ts
12
14
  function createInterruptState() {
@@ -35,10 +37,26 @@ function startDeadlineWatchdog(delayMs = 1e4, exit = (code) => process.exit(code
35
37
  }
36
38
 
37
39
  // src/cli.ts
40
+ import { describeRejection, RejectionRouter } from "@sedum-dev/core";
38
41
  var require2 = createRequire(import.meta.url);
39
42
  var pkg = require2("../package.json");
40
43
  var interrupts = createInterruptState();
41
44
  var deadlineWatchdog;
45
+ var strayRejection = false;
46
+ var reportStray = (message) => {
47
+ strayRejection = true;
48
+ process.stderr.write(
49
+ `${message}
50
+ Fix: Add \`await\` before the page, expect, API, and ai calls in your tests.
51
+ `
52
+ );
53
+ };
54
+ process.on("unhandledRejection", (reason) => {
55
+ if (RejectionRouter.routing) return;
56
+ reportStray(
57
+ `A promise nobody awaited rejected outside any running test: ${describeRejection(reason)}`
58
+ );
59
+ });
42
60
  var onSigint = () => interrupts.request("SIGINT");
43
61
  var onSigterm = () => interrupts.request("SIGTERM");
44
62
  process.on("SIGINT", onSigint);
@@ -46,6 +64,7 @@ process.on("SIGTERM", onSigterm);
46
64
  var output = await runCli(process.argv.slice(2), pkg.version, {
47
65
  signal: interrupts.signal,
48
66
  onRunCommitted: interrupts.commit,
67
+ onStrayRejection: reportStray,
49
68
  onRunDeadline: () => {
50
69
  deadlineWatchdog = startDeadlineWatchdog();
51
70
  },
@@ -55,6 +74,7 @@ var output = await runCli(process.argv.slice(2), pkg.version, {
55
74
  color: process.stdout.isTTY === true && !("NO_COLOR" in process.env),
56
75
  ...process.stdout.columns ? { columns: process.stdout.columns } : {}
57
76
  },
77
+ command: sedumCommand(process.env, fileURLToPath(import.meta.url)),
58
78
  stdout: (value) => process.stdout.write(value),
59
79
  stderr: (value) => process.stderr.write(value)
60
80
  });
@@ -63,4 +83,9 @@ process.off("SIGINT", onSigint);
63
83
  process.off("SIGTERM", onSigterm);
64
84
  if (output.stdout) process.stdout.write(output.stdout);
65
85
  if (output.stderr) process.stderr.write(output.stderr);
66
- process.exitCode = interrupts.exitCode(output.exitCode);
86
+ var exitCode = interrupts.exitCode(output.exitCode);
87
+ process.exitCode = strayRejection ? Math.max(exitCode, 3) : exitCode;
88
+ process.on("beforeExit", () => {
89
+ if (strayRejection)
90
+ process.exitCode = Math.max(Number(process.exitCode ?? 0), 3);
91
+ });
@@ -5,8 +5,8 @@ import {
5
5
  keyPresent,
6
6
  renderDoctorText,
7
7
  supportedNode
8
- } from "./chunk-UACA6VAM.js";
9
- import "./chunk-W2BEUHUB.js";
8
+ } from "./chunk-NMAMFLDA.js";
9
+ import "./chunk-GYFQYSYT.js";
10
10
  export {
11
11
  browserAvailable,
12
12
  checkOutputWritable,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { RunResult, BrowserKind, VerifyPolicy, ClassificationProvider, BrowserInstallResult } from '@sedum-dev/core';
1
+ import { RunResult, BrowserKind, VerifyPolicy, VisionKeyProbe, ClassificationProvider, BrowserInstallResult } from '@sedum-dev/core';
2
2
  import { TypeSafeAdapter, AuthProbeResult } from '@sedum-dev/provider-typesafe';
3
+ export { Ai, AiValue, AiValues, BrowserContext, Locator, Page, Parser, SecretValue, TestBody, TestContext, TestInfo, TestOptions, expect, secret, test } from '@sedum-dev/core/script';
3
4
 
4
5
  interface OutputCapabilities {
5
6
  readonly stdoutIsTTY: boolean;
@@ -95,6 +96,8 @@ interface RunFilters {
95
96
  readonly exclude?: readonly string[];
96
97
  readonly labels?: readonly string[];
97
98
  readonly names?: readonly string[];
99
+ /** Exact test ids; rerun commands use these to select one test. */
100
+ readonly ids?: readonly string[];
98
101
  }
99
102
 
100
103
  type ParallelRequest = number | "auto";
@@ -106,6 +109,11 @@ interface ShardSpec {
106
109
  }
107
110
 
108
111
  interface RunCommandOptions {
112
+ /**
113
+ * Receives a stray rejection from test code that arrived after the run was
114
+ * reported; the `sedum` binary prints it and fails the exit code.
115
+ */
116
+ readonly onStrayRejection?: (message: string) => void;
109
117
  readonly file?: string;
110
118
  readonly paths?: readonly string[];
111
119
  readonly filters?: RunFilters;
@@ -131,12 +139,16 @@ interface RunCommandOptions {
131
139
  readonly providerConcurrency?: number;
132
140
  /** Injected for tests; defaults to `os.availableParallelism()`. */
133
141
  readonly availableParallelism?: number;
142
+ /** Injected for tests; defaults to OpenRouter's unbilled key endpoint. */
143
+ readonly probeVisionKey?: (apiKey: string) => Promise<VisionKeyProbe>;
134
144
  readonly replay: boolean;
135
145
  readonly evidence: boolean;
136
146
  readonly sensitiveOrigins: readonly string[];
137
147
  readonly locatorCacheDisabled?: boolean;
138
148
  readonly locatorCacheCi?: boolean;
139
149
  readonly signal?: AbortSignal;
150
+ /** How to invoke sedum in report rerun hints, e.g. `npx sedum`. */
151
+ readonly command?: string;
140
152
  readonly onSnapshot?: (snapshot: RunResult, artifacts: RunArtifactPaths) => void;
141
153
  readonly onCommitted?: () => void;
142
154
  readonly onDeadline?: () => void;
@@ -161,6 +173,7 @@ interface DoctorProbes {
161
173
  readonly model: string;
162
174
  }) => Promise<AuthProbeResult>;
163
175
  readonly output?: (config: ResolvedProjectConfig) => Promise<void>;
176
+ readonly visionAuth?: (apiKey: string) => Promise<VisionKeyProbe>;
164
177
  }
165
178
 
166
179
  type ClassificationProviderFactory = (options: {
@@ -181,6 +194,8 @@ interface CliRuntime {
181
194
  readonly signal?: AbortSignal;
182
195
  readonly onRunCommitted?: () => void;
183
196
  readonly onRunDeadline?: () => void;
197
+ /** A stray rejection from test code after the run was reported. */
198
+ readonly onStrayRejection?: (message: string) => void;
184
199
  readonly executeRun?: (options: RunCommandOptions) => Promise<RunCommandExecution>;
185
200
  readonly installChromium?: (withDependencies: boolean) => BrowserInstallResult;
186
201
  /** Project root for `validate` and `list`; defaults to the process cwd. */
@@ -189,6 +204,8 @@ interface CliRuntime {
189
204
  readonly createClassificationProvider?: ClassificationProviderFactory;
190
205
  readonly createRelevanceProvider?: RelevanceProviderFactory;
191
206
  readonly doctorProbes?: DoctorProbes;
207
+ /** How the user invokes sedum, for hints; the entry point detects it. */
208
+ readonly command?: "sedum" | "npx sedum";
192
209
  readonly confirmInit?: (question: string) => Promise<boolean>;
193
210
  }
194
211
  /** Parse and execute explicit argv without reading or exiting the process. */
package/dist/index.js CHANGED
@@ -2,18 +2,24 @@ import {
2
2
  renderRunSummary,
3
3
  runCli,
4
4
  runExitCode
5
- } from "./chunk-V4JF5CPE.js";
6
- import "./chunk-72CYPRWT.js";
5
+ } from "./chunk-ONJZI3ER.js";
6
+ import "./chunk-BEY4UNIW.js";
7
7
  import {
8
8
  ProjectConfigError,
9
9
  discoverConfiguredTests,
10
10
  loadProjectConfig
11
- } from "./chunk-W2BEUHUB.js";
11
+ } from "./chunk-GYFQYSYT.js";
12
+
13
+ // src/index.ts
14
+ import { test, expect, secret } from "@sedum-dev/core/script";
12
15
  export {
13
16
  ProjectConfigError,
14
17
  discoverConfiguredTests,
18
+ expect,
15
19
  loadProjectConfig,
16
20
  renderRunSummary,
17
21
  runCli,
18
- runExitCode
22
+ runExitCode,
23
+ secret,
24
+ test
19
25
  };
@@ -2,11 +2,11 @@ import {
2
2
  browserAvailable,
3
3
  keyPresent,
4
4
  supportedNode
5
- } from "./chunk-UACA6VAM.js";
5
+ } from "./chunk-NMAMFLDA.js";
6
6
  import {
7
7
  ProjectConfigError,
8
8
  loadProjectConfig
9
- } from "./chunk-W2BEUHUB.js";
9
+ } from "./chunk-GYFQYSYT.js";
10
10
 
11
11
  // src/init-command.ts
12
12
  import { constants } from "fs";
@@ -19,16 +19,20 @@ browser: chromium
19
19
  outputDir: .sedum/runs
20
20
  reporterDir: .sedum/reports
21
21
  `;
22
- var EXAMPLE = `description: Sign in to the SauceDemo sample store
23
- url: https://www.saucedemo.com/
24
- data:
25
- user: standard_user
26
- password: $SAUCE_PASSWORD
27
- steps:
28
- - type {{user}} in the username field
29
- - type {{password}} in the password field
30
- - click the login button
31
- - verify a list of products with prices is shown
22
+ var EXAMPLE = `import { test, secret } from "sedum-cli";
23
+
24
+ test(
25
+ "a customer signs in to the SauceDemo sample store",
26
+ { url: "https://www.saucedemo.com/" },
27
+ async ({ ai, env }) => {
28
+ await ai("type {{user}} in the username field", { user: "standard_user" });
29
+ await ai("type {{password}} in the password field", {
30
+ password: secret(env.SAUCE_PASSWORD ?? ""),
31
+ });
32
+ await ai("click the login button");
33
+ await ai("verify a list of products with prices is shown");
34
+ },
35
+ );
32
36
  `;
33
37
  var ENV_EXAMPLE = `# Get a TypeSafe key and put it in .env, or set it in your shell.
34
38
  # For a compatible provider, also set TYPESAFE_BASE_URL and optionally TYPESAFE_DEFAULT_MODEL.
@@ -36,7 +40,12 @@ TYPESAFE_API_KEY=
36
40
  # Public SauceDemo sample account; no Sauce Labs account is required.
37
41
  SAUCE_PASSWORD=secret_sauce
38
42
  `;
39
- var IGNORE = [".env", ".sedum/runs/", ".sedum/reports/"];
43
+ var IGNORE = [
44
+ "node_modules/",
45
+ ".env",
46
+ ".sedum/runs/",
47
+ ".sedum/reports/"
48
+ ];
40
49
  var WORDMARK = [
41
50
  " \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588 \u2588 \u2588 \u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588 \u2588",
42
51
  "\u2588 \u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2591\u2588 \u2588\u2591 \u2588\u2591\u2588\u2588 \u2588\u2588\u2591 \u2588\u2591\u2591\u2591\u2588 \u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2591 \u2588\u2591",
@@ -153,12 +162,12 @@ async function executeInitCommand(options) {
153
162
  await regularDirectory(path.join(root, "tests"));
154
163
  for (const [name, contents] of [
155
164
  ["sedum.config.yaml", CONFIG],
156
- ["tests/example.test.yaml", EXAMPLE],
165
+ ["tests/example.test.ts", EXAMPLE],
157
166
  [".env.example", ENV_EXAMPLE]
158
167
  ]) {
159
168
  const result = await createOrKeep(path.join(root, name), contents);
160
169
  if (name === ".env.example" && result === "kept") keptEnvExample = true;
161
- if (name === "tests/example.test.yaml" && result === "created")
170
+ if (name === "tests/example.test.ts" && result === "created")
162
171
  createdExample = true;
163
172
  say(`${result} ${name}
164
173
  `);
@@ -166,7 +175,7 @@ async function executeInitCommand(options) {
166
175
  say(await updateIgnore(root, options));
167
176
  say("\nSedum runs plain-language tests in a browser.\n");
168
177
  if (createdExample) {
169
- const title = "\u2500\u2500 tests/example.test.yaml ";
178
+ const title = "\u2500\u2500 tests/example.test.ts ";
170
179
  const divider = "\u2500".repeat(54);
171
180
  say(`
172
181
  ${title}${divider.slice(title.length)}
@@ -219,7 +228,7 @@ ${++step}. ${title}
219
228
  ]);
220
229
  }
221
230
  next("Run the example", [
222
- "sedum run tests/example.test.yaml --headed",
231
+ "sedum run tests/example.test.ts --headed",
223
232
  "This calls the TypeSafe API and may incur a charge."
224
233
  ]);
225
234
  return { stdout: output.join(""), stderr: "", exitCode: 0 };
@@ -5,15 +5,16 @@ import {
5
5
  outputDiagnostic,
6
6
  planLanes,
7
7
  runPool,
8
- setupDiagnostic
9
- } from "./chunk-72CYPRWT.js";
8
+ setupDiagnostic,
9
+ stopsRun
10
+ } from "./chunk-BEY4UNIW.js";
10
11
  import {
11
12
  discoverRunTests
12
- } from "./chunk-UVCFRFDV.js";
13
+ } from "./chunk-DRCPO7W3.js";
13
14
  import {
14
15
  ProjectConfigError,
15
16
  loadProjectConfig
16
- } from "./chunk-W2BEUHUB.js";
17
+ } from "./chunk-GYFQYSYT.js";
17
18
 
18
19
  // src/run-command.ts
19
20
  import {
@@ -22,9 +23,13 @@ import {
22
23
  ReusableBrowserDriver,
23
24
  RunRecorder,
24
25
  OpenRouterVisionResolver,
26
+ isScriptTestFile,
27
+ probeOpenRouterKey,
25
28
  runFlow,
29
+ runScriptTest,
26
30
  safeText,
27
- validateRunResult as validateRunResult2
31
+ validateRunResult as validateRunResult2,
32
+ RejectionRouter
28
33
  } from "@sedum-dev/core";
29
34
  import {
30
35
  DEFAULT_PROVIDER_CONCURRENCY,
@@ -65,6 +70,8 @@ var ProgressWriter = class _ProgressWriter {
65
70
  draining = null;
66
71
  attemptFolders = /* @__PURE__ */ new Map();
67
72
  files;
73
+ /** How to invoke sedum in report rerun hints. */
74
+ command = "sedum";
68
75
  static async create(root, runId, outputDirectory = path.join(root, ".sedum", "runs"), files = {}) {
69
76
  if (!/^[a-zA-Z0-9-]+$/.test(runId)) throw new Error("Invalid run ID");
70
77
  const resolvedRoot = path.resolve(root);
@@ -199,7 +206,10 @@ var ProgressWriter = class _ProgressWriter {
199
206
  const frames = await this.loadReplayFrames(snapshot);
200
207
  await this.atomicWrite(
201
208
  "report.html",
202
- renderHtml(snapshot, frames ? { replayFrames: frames } : {})
209
+ renderHtml(snapshot, {
210
+ ...frames ? { replayFrames: frames } : {},
211
+ command: this.command
212
+ })
203
213
  );
204
214
  } catch (cause) {
205
215
  throw new ProgressWriterError(this.htmlPath, { cause });
@@ -207,7 +217,10 @@ var ProgressWriter = class _ProgressWriter {
207
217
  }
208
218
  if (this.files.markdown) {
209
219
  try {
210
- await this.atomicWrite("report.md", renderMarkdown(snapshot));
220
+ await this.atomicWrite(
221
+ "report.md",
222
+ renderMarkdown(snapshot, { command: this.command })
223
+ );
211
224
  } catch (cause) {
212
225
  throw new ProgressWriterError(this.markdownPath, { cause });
213
226
  }
@@ -215,7 +228,10 @@ var ProgressWriter = class _ProgressWriter {
215
228
  const junit = this.files.junit;
216
229
  if (junit) {
217
230
  try {
218
- await this.atomicWrite("junit.xml", renderJunit(snapshot, junit));
231
+ await this.atomicWrite(
232
+ "junit.xml",
233
+ renderJunit(snapshot, { ...junit, command: this.command })
234
+ );
219
235
  } catch (cause) {
220
236
  throw new ProgressWriterError(this.junitPath, { cause });
221
237
  }
@@ -405,6 +421,29 @@ var SUPPORTED_REPORTERS = [
405
421
  "markdown",
406
422
  "junit"
407
423
  ];
424
+ function strayRejectionDiagnostic(strays, config) {
425
+ const stray = strays[0];
426
+ const where = stray.source ? `${path3.relative(config.projectRoot, stray.source.file).split(path3.sep).join("/")}:${stray.source.line}: ` : "";
427
+ const message = safeDiscoveryText(stray.message, config);
428
+ const more = strays.length > 1 ? ` (${strays.length - 1} more rejected outside their tests; see the terminal.)` : "";
429
+ if (stray.reason === "internal")
430
+ return {
431
+ code: "internal_rejection",
432
+ message: `Sedum hit an unexpected error during the run: ${message}${more}`,
433
+ fix: "Rerun the command; if it repeats, report it at https://github.com/sedum-dev/sedum/issues with the run's progress.json."
434
+ };
435
+ const what = {
436
+ finished: `a promise ${stray.test ? `\`${safeDiscoveryText(stray.test, config)}\`` : "a test"} did not await rejected after that test finished`,
437
+ shared: "a promise nobody awaited rejected in lines several tests share, such as tests declared in a loop, so no test is blamed",
438
+ outside: "a promise nobody awaited rejected outside any running test, so no test is blamed",
439
+ unknown: "a promise nobody awaited rejected with a value that has no stack"
440
+ }[stray.reason];
441
+ return {
442
+ code: "stray_rejection",
443
+ message: `${where}${what}: ${message}${more}`,
444
+ fix: "Add `await` before the page, expect, API, and ai calls the test starts."
445
+ };
446
+ }
408
447
  function safeDiscoveryText(value, config) {
409
448
  const withoutUrls = value.replace(/https?:\/\/[^\s`"'<>]+/giu, "[URL]");
410
449
  return safeText(
@@ -452,11 +491,13 @@ async function openReportCopy(root, runId, canonical, outputDir, reporterDir, se
452
491
  return void 0;
453
492
  }
454
493
  if (!selection.json && !junit) return void 0;
455
- return ProgressWriter.create(root, runId, reporterDir, {
494
+ const writer = await ProgressWriter.create(root, runId, reporterDir, {
456
495
  json: selection.json,
457
496
  html: false,
458
497
  junit
459
498
  });
499
+ writer.command = canonical.command;
500
+ return writer;
460
501
  }
461
502
  function reportFormat(target) {
462
503
  const name = path3.basename(target);
@@ -596,6 +637,9 @@ async function preExecutionFailure(root, runId, outputDir, reporterDir, selectio
596
637
  }
597
638
  async function executeRunCommand(options) {
598
639
  const invocationRoot = process.cwd();
640
+ let rejections;
641
+ let strayConfig;
642
+ let reportedStrays = 0;
599
643
  const reportFiles = reportSelection(options);
600
644
  const runId = randomUUID();
601
645
  let committed = false;
@@ -716,6 +760,7 @@ async function executeRunCommand(options) {
716
760
  config.outputDir,
717
761
  { markdown: reportFiles.markdown }
718
762
  );
763
+ writer.command = options.command ?? "sedum";
719
764
  } catch {
720
765
  commit();
721
766
  const intended = path3.join(config.outputDir, runId);
@@ -880,6 +925,9 @@ async function executeRunCommand(options) {
880
925
  let files;
881
926
  let globalSelectedTests = 0;
882
927
  let discoveryProblems = [];
928
+ strayConfig = config;
929
+ rejections = new RejectionRouter(config.projectRoot);
930
+ rejections.install();
883
931
  try {
884
932
  const selection = await discoverRunTests(
885
933
  config,
@@ -888,7 +936,10 @@ async function executeRunCommand(options) {
888
936
  );
889
937
  globalSelectedTests = selection.tests.length;
890
938
  const selected = options.shard ? shardTests(selection.tests, options.shard) : selection.tests;
891
- files = selected.map((test) => path3.join(config.projectRoot, test.file));
939
+ files = selected.map((test) => ({
940
+ file: path3.join(config.projectRoot, test.file),
941
+ id: test.id
942
+ }));
892
943
  discoveryProblems = [
893
944
  ...selection.problems,
894
945
  ...selection.invalid.flatMap(
@@ -953,6 +1004,18 @@ async function executeRunCommand(options) {
953
1004
  await recorder.finish(canonicalDiagnosticError(diagnostic));
954
1005
  return terminalExecution(diagnostic);
955
1006
  }
1007
+ if (files.length === 0 && discoveryProblems.length) {
1008
+ const [first] = discoveryProblems;
1009
+ const diagnostic = {
1010
+ code: "discovery_error",
1011
+ message: discoveryProblems.length === 1 ? `${first.file}: ${first.message}` : `${discoveryProblems.length} test file or path problem(s) were found; the first: ${first.file}: ${first.message}`,
1012
+ fix: first.fix
1013
+ };
1014
+ await recorder.addDiscoveryProblems(discoveryProblems);
1015
+ commit();
1016
+ await recorder.finish(canonicalDiagnosticError(diagnostic));
1017
+ return terminalExecution(diagnostic);
1018
+ }
956
1019
  if (files.length === 0) {
957
1020
  const error = new ProjectConfigError([
958
1021
  {
@@ -962,7 +1025,7 @@ async function executeRunCommand(options) {
962
1025
  col: 1,
963
1026
  key: "tests.include",
964
1027
  message: "The selection matched no valid test files.",
965
- fix: "Add a matching *.test.yaml file or correct paths and filters."
1028
+ fix: "Add a matching *.test.ts or *.test.yaml file, or correct paths and filters."
966
1029
  }
967
1030
  ]);
968
1031
  const diagnostic = setupDiagnostic(error);
@@ -979,10 +1042,14 @@ async function executeRunCommand(options) {
979
1042
  files.length
980
1043
  );
981
1044
  const providerConcurrency = options.providerConcurrency ?? Math.min(DEFAULT_PROVIDER_CONCURRENCY, lanes * 2);
1045
+ const visionKey = config.vision.enabled ? await (options.probeVisionKey ?? probeOpenRouterKey)(
1046
+ config.visionApiKey
1047
+ ).catch(() => "unreachable") : null;
982
1048
  await recorder.selectTests(files.length, {
983
1049
  parallel: { requested: options.parallel ?? 1, lanes },
984
1050
  shard: options.shard ? { ...options.shard, globalSelectedTests } : null,
985
- providerConcurrency
1051
+ providerConcurrency,
1052
+ ...visionKey ? { vision: { model: config.vision.model, key: visionKey } } : {}
986
1053
  });
987
1054
  if (discoveryProblems.length)
988
1055
  await recorder.addDiscoveryProblems(discoveryProblems);
@@ -1009,22 +1076,25 @@ async function executeRunCommand(options) {
1009
1076
  timeoutMs: config.vision.timeoutMs
1010
1077
  }) : void 0;
1011
1078
  let operational = null;
1079
+ let erroredTests = 0;
1012
1080
  const driver = new PlaywrightBrowserDriver();
1013
1081
  const browsers = Array.from(
1014
1082
  { length: lanes },
1015
1083
  () => new ReusableBrowserDriver(driver)
1016
1084
  );
1085
+ const router = rejections;
1017
1086
  try {
1018
1087
  await runPool({
1019
1088
  items: files,
1020
1089
  lanes,
1021
1090
  signal,
1022
- run: async (file, lane, ordinal) => {
1091
+ run: async ({ file, id }, lane, ordinal) => {
1023
1092
  const browser = browsers[lane];
1093
+ const execute = (dependencies) => isScriptTestFile(file) ? runScriptTest(file, id, dependencies) : runFlow(file, dependencies);
1024
1094
  for (let attempt = 0; attempt <= (options.retries ?? 0); attempt++) {
1025
1095
  if (attempt > 0)
1026
1096
  await recorder.testAt(ordinal)?.startAttempt(lane);
1027
- const result = await runFlow(file, {
1097
+ const result = await execute({
1028
1098
  repoRoot: config.projectRoot,
1029
1099
  browser,
1030
1100
  provider,
@@ -1049,6 +1119,7 @@ async function executeRunCommand(options) {
1049
1119
  ...options.headed ? { headedOverlay: true } : {},
1050
1120
  ...options.slowMoMs !== void 0 ? { slowMoMs: options.slowMoMs } : {},
1051
1121
  signal,
1122
+ rejections: router,
1052
1123
  report: {
1053
1124
  recorder,
1054
1125
  slot: { ordinal, lane },
@@ -1065,8 +1136,12 @@ async function executeRunCommand(options) {
1065
1136
  if (signal.aborted) return "stop";
1066
1137
  if (result.status === "could_not_run") {
1067
1138
  await browser.recycle();
1068
- operational ??= flowDiagnostic(result);
1069
- return "stop";
1139
+ const diagnostic = flowDiagnostic(result);
1140
+ operational ??= diagnostic;
1141
+ if (stopsRun(result.code)) return "stop";
1142
+ erroredTests += 1;
1143
+ await recorder.testAt(ordinal)?.errorTest(canonicalDiagnosticError(diagnostic));
1144
+ break;
1070
1145
  }
1071
1146
  if (result.status === "passed" || result.retryable === false)
1072
1147
  break;
@@ -1078,6 +1153,10 @@ async function executeRunCommand(options) {
1078
1153
  gate.close();
1079
1154
  await Promise.all(browsers.map((browser) => browser.recycle()));
1080
1155
  }
1156
+ if (router.unattributed.length && !operational) {
1157
+ reportedStrays = router.unattributed.length;
1158
+ operational = strayRejectionDiagnostic(router.unattributed, config);
1159
+ }
1081
1160
  if (signal.aborted) {
1082
1161
  const diagnostic = timedOut ? {
1083
1162
  code: "run_timeout",
@@ -1096,7 +1175,12 @@ async function executeRunCommand(options) {
1096
1175
  return terminalExecution(diagnostic);
1097
1176
  }
1098
1177
  if (operational) {
1099
- const diagnostic = operational;
1178
+ const first = operational;
1179
+ const diagnostic = erroredTests > 1 ? {
1180
+ code: "test_errors",
1181
+ message: `${erroredTests} tests could not run. First: ${first.message}`,
1182
+ fix: "Fix the tests named under needs attention, then rerun them."
1183
+ } : first;
1100
1184
  commit();
1101
1185
  await recorder.finish(canonicalDiagnosticError(diagnostic));
1102
1186
  return terminalExecution(diagnostic);
@@ -1163,8 +1247,14 @@ async function executeRunCommand(options) {
1163
1247
  } finally {
1164
1248
  if (timeout) clearTimeout(timeout);
1165
1249
  options.signal?.removeEventListener("abort", onExternalAbort);
1250
+ rejections?.dispose();
1251
+ for (const late of rejections?.unattributed.slice(reportedStrays) ?? [])
1252
+ options.onStrayRejection?.(
1253
+ strayRejectionDiagnostic([late], strayConfig).message
1254
+ );
1166
1255
  }
1167
1256
  }
1168
1257
  export {
1169
- executeRunCommand
1258
+ executeRunCommand,
1259
+ strayRejectionDiagnostic
1170
1260
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sedum-cli",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.0-alpha.6",
4
4
  "repository": "https://github.com/sedum-dev/sedum",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -25,9 +25,9 @@
25
25
  "commander": "14.0.2",
26
26
  "minimatch": "10.2.6",
27
27
  "yaml": "2.9.1",
28
- "@sedum-dev/core": "0.1.0-alpha.4",
29
- "@sedum-dev/provider-typesafe": "0.1.0-alpha.4",
30
- "@sedum-dev/reporters": "0.1.0-alpha.4"
28
+ "@sedum-dev/core": "0.1.0-alpha.6",
29
+ "@sedum-dev/reporters": "0.1.0-alpha.6",
30
+ "@sedum-dev/provider-typesafe": "0.1.0-alpha.6"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsup src/index.ts src/cli.ts --format esm --dts --clean --out-dir dist",