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

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.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # sedum-cli
2
+
3
+ Write browser tests in plain English, keep the full power of TypeScript, and run the whole suite on every pull request for dollars a month instead of thousands.
4
+
5
+ ![Sedum running a plain-English login test in a real browser: it passes with 0.98 confidence for under a cent](https://raw.githubusercontent.com/sedum-dev/sedum/main/docs/assets/demo.gif)
6
+
7
+ Sedum is an open-source (MIT) browser end-to-end test runner built on Playwright. Each step is a sentence such as `await ai("click the Checkout button")`. Sedum finds the element on the page with a fast decision model and your own API key. Clicking, typing, waiting, verdicts, and exit codes are deterministic Playwright.
8
+
9
+ > **Status: pre-alpha.** The test format may change before 1.0, and Windows is experimental. Linux and macOS are verified.
10
+
11
+ ## Try it
12
+
13
+ You need Node.js 20.19 or newer and credentials for TypeSafe Jev (the default) or Cloudflare Clef.
14
+
15
+ ```sh
16
+ mkdir my-sedum-tests && cd my-sedum-tests
17
+ npm init -y
18
+ git init # locator results are cached in Git metadata
19
+ npm install -D sedum-cli
20
+ npx sedum init # an example test, config, and .env.example
21
+ npx sedum browsers install chromium # if init says it is missing
22
+ cp .env.example .env # then set TYPESAFE_API_KEY in .env
23
+ npx sedum run tests/example.test.ts --headed
24
+ ```
25
+
26
+ To see a failure, change the last step to a false claim, such as `verify an error message says the password is incorrect`, and run it again. It fails with exit code 1 and says how sure it is. If anything is missing, `npx sedum doctor` says what and how to fix it.
27
+
28
+ ## A test
29
+
30
+ ```ts
31
+ import { secret, test } from "sedum-cli";
32
+
33
+ test(
34
+ "a customer logs in",
35
+ { url: "https://www.saucedemo.com/" },
36
+ async ({ ai, env }) => {
37
+ await ai("type standard_user in the username field");
38
+ await ai("type {{password}} in the password field", {
39
+ password: secret(env.SAUCE_PASSWORD!),
40
+ });
41
+ await ai("click the login button");
42
+ await ai("verify a list of products with prices is shown");
43
+ },
44
+ );
45
+ ```
46
+
47
+ Between steps you can use Playwright's `page` and `expect`, any test-data library, and API calls. Tests can also be plain YAML files with a list of sentences.
48
+
49
+ ## Why Sedum
50
+
51
+ - **Cheap enough for every PR.** In the project's own benchmark, a 20-person team's pull request suite costs $38 to $91 a month on Sedum with Jev, against $4,875 at a per-step platform's published rates. Method and caveats are on [sedum.dev](https://sedum.dev).
52
+ - **Probabilities, not guesses.** Every claim is scored against a threshold and checked for contradicting evidence, so a marginal pass is flagged instead of silently green.
53
+ - **No black box.** Prompts, scoring, and caching are in the repository.
54
+ - **Made for coding agents.** `npx sedum run --reporter markdown` writes a failure report that Claude Code or Cursor can read and fix from.
55
+
56
+ ## Documentation
57
+
58
+ - [Full README and quickstart](https://github.com/sedum-dev/sedum#readme)
59
+ - [CLI commands](https://github.com/sedum-dev/sedum/blob/main/docs/cli.md)
60
+ - [Running in CI](https://github.com/sedum-dev/sedum/blob/main/docs/ci.md)
61
+ - [Project configuration](https://github.com/sedum-dev/sedum/blob/main/docs/configuration.md)
62
+ - [Report an issue](https://github.com/sedum-dev/sedum/issues)
63
+
64
+ MIT licensed.
@@ -0,0 +1,392 @@
1
+ import {
2
+ discoverRunTests
3
+ } from "./chunk-AWBC7NOM.js";
4
+ import {
5
+ createCliProvider,
6
+ providerDiagnostic
7
+ } from "./chunk-S7OB3JEF.js";
8
+ import {
9
+ affectedPathIgnored,
10
+ loadProjectConfig,
11
+ validAffectedGlob
12
+ } from "./chunk-FAGJCNV7.js";
13
+
14
+ // src/affected-selection.ts
15
+ import { realpath } from "fs/promises";
16
+ import path2 from "path";
17
+ import {
18
+ isScriptTestFile,
19
+ loadFlowFile,
20
+ ProviderError,
21
+ resolveFlowModules
22
+ } from "@sedum-dev/core";
23
+
24
+ // src/affected-git.ts
25
+ import path from "path";
26
+
27
+ // src/affected-git-read.ts
28
+ import { spawn } from "child_process";
29
+ import { isUtf8 } from "buffer";
30
+ var MAX_DIFF_BYTES = 16 * 1024 * 1024;
31
+ var AffectedSelectionError = class extends Error {
32
+ };
33
+ function gitRead(cwd, args, signal, limit = MAX_DIFF_BYTES) {
34
+ return new Promise((resolve, reject) => {
35
+ const child = spawn("git", args, {
36
+ cwd,
37
+ stdio: ["ignore", "pipe", "ignore"],
38
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
39
+ ...signal ? { signal } : {}
40
+ });
41
+ const buffers = [];
42
+ let bytes = 0;
43
+ let exceeded = false;
44
+ child.stdout.on("data", (buffer) => {
45
+ bytes += buffer.length;
46
+ if (bytes > limit) {
47
+ exceeded = true;
48
+ child.kill();
49
+ } else buffers.push(buffer);
50
+ });
51
+ child.on("error", reject);
52
+ child.on("close", (code) => {
53
+ if (exceeded)
54
+ reject(
55
+ new AffectedSelectionError(
56
+ "Retained Git input exceeds the 16 MiB guard. Run the full suite; input was not truncated."
57
+ )
58
+ );
59
+ else if (code !== 0) reject(new Error("Git read failed"));
60
+ else resolve(Buffer.concat(buffers));
61
+ });
62
+ }).then(decodeGitOutput);
63
+ }
64
+ function decodeGitOutput(output) {
65
+ if (!isUtf8(output))
66
+ throw new AffectedSelectionError(
67
+ "Git input is not valid UTF-8. Run the full suite."
68
+ );
69
+ return output.toString("utf8");
70
+ }
71
+
72
+ // src/affected-git.ts
73
+ async function assertAffectedSnapshot({
74
+ root,
75
+ head,
76
+ signal
77
+ }) {
78
+ signal?.throwIfAborted();
79
+ await assertVisibleIndex({ root, head, signal });
80
+ const status = await gitRead(
81
+ root,
82
+ [
83
+ "status",
84
+ "--porcelain=v1",
85
+ "-z",
86
+ "--untracked-files=no",
87
+ "--ignore-submodules=none"
88
+ ],
89
+ signal
90
+ );
91
+ if (status)
92
+ throw new AffectedSelectionError(
93
+ "Tracked staged or unstaged changes (including dirty submodules) are not allowed with --affected, even on ignored paths. Commit or stash them first; no sources were sent."
94
+ );
95
+ if ((await gitRead(root, ["rev-parse", "HEAD"], signal)).trim() !== head)
96
+ throw new AffectedSelectionError(
97
+ "HEAD changed during affected selection. Retry from a clean checkout."
98
+ );
99
+ }
100
+ async function assertVisibleIndex({
101
+ root,
102
+ signal
103
+ }) {
104
+ const entries = (await gitRead(
105
+ root,
106
+ ["ls-files", "-v", "-z", "--full-name", "--", ":/"],
107
+ signal
108
+ )).split("\0");
109
+ if (entries.some((entry) => /^[a-zS] /u.test(entry)))
110
+ throw new AffectedSelectionError(
111
+ "Tracked files with assume-unchanged or skip-worktree flags are not supported with --affected, even on ignored paths. Clear those index flags or run without --affected; no sources were sent."
112
+ );
113
+ }
114
+ async function readCommittedSource({ root, head, signal }, file) {
115
+ const relative = repositoryRelativePath(root, file);
116
+ try {
117
+ return await gitRead(root, ["show", `${head}:${relative}`], signal);
118
+ } catch (error) {
119
+ rethrowGitError(
120
+ error,
121
+ signal,
122
+ "A test or module is not readable at pinned HEAD. Commit test sources before using --affected."
123
+ );
124
+ }
125
+ }
126
+ function rethrowGitError(error, signal, message) {
127
+ if (error instanceof AffectedSelectionError) throw error;
128
+ signal?.throwIfAborted();
129
+ throw new AffectedSelectionError(message);
130
+ }
131
+ function repositoryRelativePath(root, file) {
132
+ const relative = path.relative(root, file).split(path.sep).join("/");
133
+ if (relative.startsWith("../") || path.isAbsolute(relative))
134
+ throw new AffectedSelectionError(
135
+ "A test or module is outside the Git repository."
136
+ );
137
+ return relative;
138
+ }
139
+ async function findBaseRef({ root, signal }) {
140
+ for (const candidate of [
141
+ "refs/heads/main",
142
+ "refs/remotes/origin/main",
143
+ "refs/heads/master",
144
+ "refs/remotes/origin/master"
145
+ ]) {
146
+ try {
147
+ await gitRead(
148
+ root,
149
+ ["rev-parse", "--verify", "--end-of-options", `${candidate}^{commit}`],
150
+ signal
151
+ );
152
+ return candidate;
153
+ } catch {
154
+ signal?.throwIfAborted();
155
+ }
156
+ }
157
+ throw new AffectedSelectionError(
158
+ "No main or master ref found. Fetch the base branch or pass --base <ref>."
159
+ );
160
+ }
161
+ async function resolveBranchRange(snapshot, base) {
162
+ const reference = base || await findBaseRef(snapshot);
163
+ const commit = (await gitRead(
164
+ snapshot.root,
165
+ ["rev-parse", "--verify", "--end-of-options", `${reference}^{commit}`],
166
+ snapshot.signal
167
+ )).trim();
168
+ const mergeBase = (await gitRead(
169
+ snapshot.root,
170
+ ["merge-base", commit, snapshot.head],
171
+ snapshot.signal
172
+ )).trim();
173
+ return { reference, mergeBase };
174
+ }
175
+ async function assertUntrackedIgnored({ root, signal }, ignore) {
176
+ const untracked = (await gitRead(
177
+ root,
178
+ [
179
+ "ls-files",
180
+ "--others",
181
+ "--exclude-standard",
182
+ "--full-name",
183
+ "-z",
184
+ "--",
185
+ ":/"
186
+ ],
187
+ signal
188
+ )).split("\0").filter(Boolean);
189
+ if (untracked.some((file) => !affectedPathIgnored(file, ignore)))
190
+ throw new AffectedSelectionError(
191
+ "Untracked files are not represented in committed git diff. Commit intended files or ignore unrelated files before using --affected."
192
+ );
193
+ }
194
+ var DIFF_ARGS = [
195
+ "diff",
196
+ "--no-ext-diff",
197
+ "--no-textconv",
198
+ "--no-renames",
199
+ "--no-relative",
200
+ "--ignore-submodules=none"
201
+ ];
202
+ async function readRetainedPatches({ root, head, signal }, mergeBase, files) {
203
+ const patches = [];
204
+ let bytes = 0;
205
+ for (const file of files) {
206
+ const patch = await gitRead(
207
+ root,
208
+ [
209
+ ...DIFF_ARGS,
210
+ "--no-color",
211
+ "--submodule=short",
212
+ "--src-prefix=a/",
213
+ "--dst-prefix=b/",
214
+ "--unified=3",
215
+ mergeBase,
216
+ head,
217
+ "--",
218
+ `:(top,literal)${file}`
219
+ ],
220
+ signal,
221
+ MAX_DIFF_BYTES - bytes
222
+ );
223
+ if (/^Binary files .* differ$/mu.test(patch) || /^[+ -]Subproject commit /mu.test(patch))
224
+ throw new AffectedSelectionError(
225
+ "Binary or submodule changes cannot be scored reliably. Run the full suite without --affected."
226
+ );
227
+ bytes += Buffer.byteLength(patch);
228
+ patches.push(patch);
229
+ }
230
+ return patches.join("");
231
+ }
232
+ function assertValidIgnores(ignore) {
233
+ if (ignore.some((pattern) => !validAffectedGlob(pattern)))
234
+ throw new AffectedSelectionError(
235
+ "Affected ignores must be valid nonempty repository-relative POSIX globs."
236
+ );
237
+ }
238
+ async function readBranchDiff(cwd, base, signal, ignore = []) {
239
+ assertValidIgnores(ignore);
240
+ const git = (...args) => gitRead(cwd, args, signal);
241
+ try {
242
+ const root = (await git("rev-parse", "--show-toplevel")).trim();
243
+ const head = (await git("rev-parse", "--verify", "HEAD^{commit}")).trim();
244
+ const snapshot = { root, head, signal };
245
+ await assertAffectedSnapshot(snapshot);
246
+ const { reference, mergeBase } = await resolveBranchRange(snapshot, base);
247
+ await assertUntrackedIgnored(snapshot, ignore);
248
+ const changed = (await git(...DIFF_ARGS, "--name-only", "-z", mergeBase, head, "--", ":/")).split("\0").filter(Boolean);
249
+ const ignoredFiles = changed.filter(
250
+ (file) => affectedPathIgnored(file, ignore)
251
+ );
252
+ const diff = await readRetainedPatches(
253
+ snapshot,
254
+ mergeBase,
255
+ changed.filter((file) => !affectedPathIgnored(file, ignore))
256
+ );
257
+ await assertAffectedSnapshot(snapshot);
258
+ return {
259
+ root,
260
+ base: reference,
261
+ head,
262
+ mergeBase,
263
+ diff,
264
+ changed,
265
+ ignoredFiles
266
+ };
267
+ } catch (error) {
268
+ rethrowGitError(
269
+ error,
270
+ signal,
271
+ "Could not read a complete Git diff. Check the base ref and merge-base history (fetch deeper for shallow clones), or run without --affected."
272
+ );
273
+ }
274
+ }
275
+
276
+ // src/affected-selection.ts
277
+ async function selectAffectedTests(options) {
278
+ const config = await loadProjectConfig(options.cwd, process.env, {
279
+ ...options.environment ? { environment: options.environment } : {}
280
+ });
281
+ const canonicalProjectRoot = await realpath(config.projectRoot);
282
+ const branch = await readBranchDiff(
283
+ config.projectRoot,
284
+ options.base,
285
+ options.signal,
286
+ [...config.affected.ignore, ...options.ignore ?? []]
287
+ );
288
+ const snapshot = {
289
+ root: branch.root,
290
+ head: branch.head,
291
+ signal: options.signal
292
+ };
293
+ const source = async (file) => readCommittedSource(snapshot, await realpath(file));
294
+ const selection = await discoverRunTests(
295
+ config,
296
+ options.paths,
297
+ options.filters
298
+ );
299
+ if (selection.invalid.length || selection.problems.length || !selection.tests.length)
300
+ throw new AffectedSelectionError(
301
+ "Test discovery is empty or invalid. Run sedum validate and fix discovery before using --affected."
302
+ );
303
+ const changed = new Set(
304
+ branch.changed.map((file) => path2.resolve(branch.root, file))
305
+ );
306
+ for (const file of [...changed])
307
+ changed.add(await realpath(file).catch(() => file));
308
+ const tests = [];
309
+ const forced = [];
310
+ for (const test of selection.tests) {
311
+ const file = path2.join(config.projectRoot, test.file);
312
+ if (isScriptTestFile(file)) {
313
+ if (tests.some((scored) => scored.file === test.file)) continue;
314
+ forced.push(changed.has(await realpath(file)));
315
+ tests.push({
316
+ file: test.file,
317
+ source: await source(file),
318
+ modules: []
319
+ });
320
+ continue;
321
+ }
322
+ const parsed = await loadFlowFile(file, {
323
+ repoRoot: config.projectRoot,
324
+ rejectSymlinks: true
325
+ });
326
+ const resolved = await resolveFlowModules(parsed, {
327
+ repoRoot: config.projectRoot
328
+ });
329
+ if (!resolved.value || resolved.diagnostics.some((item) => item.severity === "error"))
330
+ throw new AffectedSelectionError(
331
+ "A test or module is invalid. Run sedum validate before using --affected."
332
+ );
333
+ const files = [await realpath(file), ...resolved.moduleFiles];
334
+ forced.push(files.some((source2) => changed.has(source2)));
335
+ tests.push({
336
+ file: test.file,
337
+ source: await source(file),
338
+ modules: await Promise.all(
339
+ resolved.moduleFiles.map(async (module) => ({
340
+ file: path2.relative(canonicalProjectRoot, module).split(path2.sep).join("/"),
341
+ source: await source(module)
342
+ }))
343
+ )
344
+ });
345
+ }
346
+ options.signal?.throwIfAborted();
347
+ await assertAffectedSnapshot(snapshot);
348
+ const candidates = tests.filter((_, index) => !forced[index]);
349
+ let scores;
350
+ try {
351
+ scores = branch.diff && candidates.length ? await (options.createProvider ? await options.createProvider(config) : await createCliProvider(config)).scoreRelevance(
352
+ branch.diff,
353
+ candidates,
354
+ options.signal ? { signal: options.signal } : void 0
355
+ ) : { probabilities: candidates.map(() => 0), calls: [], chunkCount: 0 };
356
+ } catch (error) {
357
+ if (error instanceof ProviderError && (error.code === "authentication" || error.code === "configuration")) {
358
+ const diagnostic = providerDiagnostic(config.providerName, error.code);
359
+ throw new AffectedSelectionError(
360
+ `${diagnostic.message}
361
+ Fix: ${diagnostic.fix}`
362
+ );
363
+ }
364
+ throw error;
365
+ }
366
+ let candidateIndex = 0;
367
+ const probabilities = tests.map(
368
+ (_, index) => forced[index] ? 1 : scores.probabilities[candidateIndex++]
369
+ );
370
+ return {
371
+ base: branch.base,
372
+ head: branch.head,
373
+ mergeBase: branch.mergeBase,
374
+ changedFiles: branch.changed,
375
+ ignoredFiles: branch.ignoredFiles,
376
+ chunkCount: scores.chunkCount ?? (scores.calls.length ? 1 : 0),
377
+ aggregation: "max",
378
+ threshold: options.threshold,
379
+ calls: scores.calls,
380
+ tests: tests.map((test, index) => ({
381
+ file: test.file,
382
+ probability: probabilities[index],
383
+ selected: forced[index] || branch.diff !== "" && probabilities[index] >= options.threshold,
384
+ reason: forced[index] ? "test-or-module-changed" : branch.diff ? "model" : branch.ignoredFiles.length ? "all-ignored" : "no-diff"
385
+ }))
386
+ };
387
+ }
388
+ export {
389
+ AffectedSelectionError,
390
+ readBranchDiff,
391
+ selectAffectedTests
392
+ };
@@ -0,0 +1,132 @@
1
+ import {
2
+ discoverConfiguredTests
3
+ } from "./chunk-FAGJCNV7.js";
4
+
5
+ // src/run-selection.ts
6
+ import { lstat, realpath } from "fs/promises";
7
+ import path from "path";
8
+ import { minimatch } from "minimatch";
9
+ import {
10
+ listTests,
11
+ loadListingEntries,
12
+ TEST_SUFFIXES,
13
+ walkSuiteFiles
14
+ } from "@sedum-dev/core";
15
+ function contained(root, target) {
16
+ const relative = path.relative(root, target);
17
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
18
+ }
19
+ function selectRunTests(tests, filters) {
20
+ const includes = filters.include ?? [];
21
+ const excludes = filters.exclude ?? [];
22
+ const labels = filters.labels ?? [];
23
+ const names = filters.names ?? [];
24
+ const ids = filters.ids ?? [];
25
+ return tests.filter(
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(
27
+ (name) => `${test.id}
28
+ ${test.description ?? ""}`.toLowerCase().includes(name.toLowerCase())
29
+ ))
30
+ );
31
+ }
32
+ async function discoverRunTests(config, paths, filters = {}) {
33
+ const problems = [];
34
+ const files = /* @__PURE__ */ new Set();
35
+ const root = await realpath(config.projectRoot);
36
+ if (paths.length === 0) {
37
+ for (const file of await discoverConfiguredTests(config)) {
38
+ const target = await realpath(file);
39
+ if (contained(root, target)) files.add(target);
40
+ else
41
+ problems.push({
42
+ file: "<outside-project>",
43
+ code: "outside_root",
44
+ message: "A configured test is outside the project root.",
45
+ fix: "Keep the test directory inside the project."
46
+ });
47
+ }
48
+ } else {
49
+ for (const requested of paths) {
50
+ const candidate = path.resolve(config.projectRoot, requested);
51
+ const namedInside = contained(config.projectRoot, candidate);
52
+ const file = namedInside ? path.relative(config.projectRoot, candidate).split(path.sep).join("/") : "<outside-project>";
53
+ if (!namedInside) {
54
+ problems.push({
55
+ file,
56
+ code: "outside_root",
57
+ message: "Path is outside the project root.",
58
+ fix: "Choose a path inside the project."
59
+ });
60
+ continue;
61
+ }
62
+ let info;
63
+ try {
64
+ info = await lstat(candidate);
65
+ } catch {
66
+ problems.push({
67
+ file,
68
+ code: "missing_path",
69
+ message: "Path does not exist.",
70
+ fix: "Check the path and rerun."
71
+ });
72
+ continue;
73
+ }
74
+ if (info.isSymbolicLink()) {
75
+ problems.push({
76
+ file,
77
+ code: "symlinked_path",
78
+ message: "Symlinked test paths are not supported.",
79
+ fix: "Name the regular file."
80
+ });
81
+ continue;
82
+ }
83
+ const target = await realpath(candidate).catch(() => candidate);
84
+ if (!contained(root, target)) {
85
+ problems.push({
86
+ file,
87
+ code: "outside_root",
88
+ message: "Path is outside the project root.",
89
+ fix: "Choose a path inside the project."
90
+ });
91
+ continue;
92
+ }
93
+ if (info.isDirectory()) {
94
+ for (const file2 of await walkSuiteFiles(
95
+ target,
96
+ TEST_SUFFIXES,
97
+ (folder) => {
98
+ problems.push({
99
+ file: path.relative(root, folder),
100
+ code: "unreadable_directory",
101
+ message: "Directory could not be read.",
102
+ fix: "Check permissions."
103
+ });
104
+ }
105
+ ))
106
+ files.add(file2);
107
+ } else if (info.isFile() && TEST_SUFFIXES.some((suffix) => candidate.endsWith(suffix)))
108
+ files.add(target);
109
+ else
110
+ problems.push({
111
+ file,
112
+ code: "unsupported_file",
113
+ message: "Expected a *.test.ts or *.test.yaml file, or a directory.",
114
+ fix: "Choose a test path."
115
+ });
116
+ }
117
+ }
118
+ const parsed = await loadListingEntries([...files].sort(), {
119
+ repoRoot: root,
120
+ rejectSymlinks: true
121
+ });
122
+ const listing = listTests(parsed, { repoRoot: root });
123
+ return {
124
+ tests: selectRunTests(listing.tests, filters),
125
+ invalid: listing.invalid,
126
+ problems
127
+ };
128
+ }
129
+
130
+ export {
131
+ discoverRunTests
132
+ };