sedum-cli 0.1.0-alpha.12 → 0.1.0-alpha.18

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,538 @@
1
+ import {
2
+ ProjectConfigError,
3
+ configDiagnostic,
4
+ loadProjectConfig,
5
+ readProjectEnvironment
6
+ } from "./chunk-KZF4NZ6M.js";
7
+
8
+ // src/explore-command.ts
9
+ import { randomInt } from "crypto";
10
+ import { mkdir as mkdir2, readFile, writeFile as writeFile3 } from "fs/promises";
11
+ import path3 from "path";
12
+ import { InvalidArgumentError } from "commander";
13
+
14
+ // src/explore-frames.ts
15
+ import { mkdir, writeFile } from "fs/promises";
16
+ import path from "path";
17
+ var FrameRecorder = class _FrameRecorder {
18
+ constructor(directory, page, sensitive) {
19
+ this.directory = directory;
20
+ this.page = page;
21
+ this.sensitive = sensitive;
22
+ }
23
+ directory;
24
+ page;
25
+ sensitive;
26
+ #steps = /* @__PURE__ */ new Map();
27
+ /** Frame bytes by their path in the run directory, for the HTML report. */
28
+ bytes = /* @__PURE__ */ new Map();
29
+ static async create(directory, page, sensitiveOrigins) {
30
+ await mkdir(path.join(directory, "frames"), { recursive: true });
31
+ return new _FrameRecorder(directory, page, new Set(sensitiveOrigins));
32
+ }
33
+ get frames() {
34
+ return this.#steps;
35
+ }
36
+ async before(step, box) {
37
+ const file = await this.#capture(`frames/step-${step}-before.jpg`);
38
+ if (!file) return;
39
+ this.#frames(step).before = file;
40
+ if (box) this.#frames(step).box = box;
41
+ }
42
+ async after(step) {
43
+ const file = await this.#capture(`frames/step-${step}.jpg`);
44
+ if (file) this.#frames(step).after = file;
45
+ }
46
+ #frames(step) {
47
+ let frames = this.#steps.get(step);
48
+ if (!frames) this.#steps.set(step, frames = {});
49
+ return frames;
50
+ }
51
+ /** The frame's path in the run directory, or null when none was taken. */
52
+ async #capture(file) {
53
+ if (!this.page.captureFrame || this.#isSensitive()) return null;
54
+ const bytes = await this.page.captureFrame().catch(() => null);
55
+ if (!bytes) return null;
56
+ await writeFile(path.join(this.directory, file), bytes);
57
+ this.bytes.set(file, bytes);
58
+ return file;
59
+ }
60
+ #isSensitive() {
61
+ try {
62
+ return this.sensitive.has(new URL(this.page.url).origin);
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+ };
68
+
69
+ // src/explore-output.ts
70
+ import { writeFile as writeFile2 } from "fs/promises";
71
+ import path2 from "path";
72
+ async function writeExploreReports(directory, result, meta, frames) {
73
+ const { buildExploreRunResult } = await import("@sedum-dev/core");
74
+ const { renderExploreHtml, renderExploreMarkdown } = await import("@sedum-dev/reporters");
75
+ const run2 = buildExploreRunResult(result, meta);
76
+ const files = {
77
+ result: path2.join(directory, "result.json"),
78
+ markdown: path2.join(directory, "report.md"),
79
+ html: path2.join(directory, "report.html")
80
+ };
81
+ await writeFile2(files.result, `${JSON.stringify(run2, null, 2)}
82
+ `);
83
+ await writeFile2(files.markdown, renderExploreMarkdown(run2));
84
+ await writeFile2(files.html, renderExploreHtml(run2, { frames }));
85
+ return { run: run2, files };
86
+ }
87
+
88
+ // src/explore-command.ts
89
+ var EXPLORE_MODES = [
90
+ "guided",
91
+ "heuristic",
92
+ "random"
93
+ ];
94
+ function exploreMode(value) {
95
+ if (!EXPLORE_MODES.includes(value))
96
+ throw new InvalidArgumentError(
97
+ `Expected one of ${EXPLORE_MODES.join(", ")}.`
98
+ );
99
+ return value;
100
+ }
101
+ function seedValue(value) {
102
+ const seed = /^\d{1,10}$/u.test(value) ? Number(value) : NaN;
103
+ if (!(seed <= 2147483647))
104
+ throw new InvalidArgumentError("Expected an integer from 0 to 2147483647.");
105
+ return seed;
106
+ }
107
+ function watched(options) {
108
+ const origins = options.watchOrigins ?? [];
109
+ const ignore = options.ignoreConsole ?? [];
110
+ const allow = options.detectAllow ?? [];
111
+ const oracles = {
112
+ ...origins.length ? { watchOrigins: origins } : {},
113
+ ...options.rejectedSubmits ? { rejectedSubmits: true } : {},
114
+ ...ignore.length ? { ignoreConsole: ignore } : {},
115
+ ...allow.length ? { allow } : {}
116
+ };
117
+ return Object.keys(oracles).length ? { oracles } : {};
118
+ }
119
+ function tuning(options) {
120
+ return { tuning: { safety: options.safety } };
121
+ }
122
+ function restoreLocalStorage(origin, items) {
123
+ return `(() => {
124
+ if (location.origin !== ${JSON.stringify(origin)}) return;
125
+ for (const { name, value } of ${JSON.stringify(items)})
126
+ if (localStorage.getItem(name) === null) localStorage.setItem(name, value);
127
+ })()`;
128
+ }
129
+ async function openPage(browser, cookies) {
130
+ const context = await browser.newContext({
131
+ viewport: { width: 1280, height: 720 }
132
+ });
133
+ const page = await context.newPage();
134
+ if (cookies) {
135
+ const state = JSON.parse(await readFile(cookies, "utf8"));
136
+ const native = page.playwright?.();
137
+ if (!native) throw new Error("Cookies need a Playwright browser.");
138
+ await native.context.addCookies(state.cookies ?? []);
139
+ for (const { origin, localStorage } of state.origins ?? [])
140
+ await native.context.addInitScript(
141
+ restoreLocalStorage(origin, localStorage)
142
+ );
143
+ }
144
+ return { page, close: () => context.close() };
145
+ }
146
+ function collectText(value, previous = []) {
147
+ return [...previous, value];
148
+ }
149
+ function watchOrigin(value, previous = []) {
150
+ return [...previous, new URL(startUrl(value)).origin];
151
+ }
152
+ function startUrl(value) {
153
+ try {
154
+ const url = new URL(value);
155
+ if (url.protocol === "http:" || url.protocol === "https:") return url.href;
156
+ } catch {
157
+ }
158
+ throw new InvalidArgumentError("Expected an absolute http or https URL.");
159
+ }
160
+ function describe(action) {
161
+ if (action.kind === "click")
162
+ return `click ${action.target.role} "${action.target.name}"`;
163
+ if (action.kind === "type")
164
+ return `type ${action.source.kind === "faker" ? action.source.generator : action.source.kind} into "${action.target.name}"`;
165
+ return action.kind;
166
+ }
167
+ function progressLine(entry) {
168
+ const kind = entry.pageKind ? ` [${entry.pageKind}]` : "";
169
+ const events = entry.events.length ? ` ! ${entry.events.map((e) => e.signature).join("; ")}` : "";
170
+ const outcome = entry.outcome === "acted" ? "" : ` (${entry.outcome})`;
171
+ return `${String(entry.step).padStart(4)} ${entry.route}${kind} ${describe(entry.action)}${outcome}${events}
172
+ `;
173
+ }
174
+ function cost(calls) {
175
+ const tokens = calls.reduce((sum, call) => sum + call.usage.inputTokens, 0);
176
+ const usd = calls.reduce((sum, call) => sum + (call.totalCostUsd ?? 0), 0);
177
+ return `${calls.length} calls, ${tokens} input tokens, $${usd.toFixed(5)}`;
178
+ }
179
+ async function launch(headed) {
180
+ const { PlaywrightBrowserDriver } = await import("@sedum-dev/core");
181
+ return new PlaywrightBrowserDriver().launch({
182
+ browser: "chromium",
183
+ headless: !headed
184
+ });
185
+ }
186
+ async function advisor(mode, needed, provider = {}) {
187
+ if (mode !== "guided" && !needed) return void 0;
188
+ const { TypeSafeAdapter } = await import("@sedum-dev/provider-typesafe");
189
+ return new TypeSafeAdapter(provider);
190
+ }
191
+ async function exploreProvider(cwd, environment = process.env) {
192
+ const config = await loadProjectConfig(cwd, environment);
193
+ const file = await readProjectEnvironment(config.projectRoot);
194
+ const value = (name) => environment[name]?.trim() || file[name]?.trim() || void 0;
195
+ const keyName = config.providerName === "typesafe" ? config.apiKeyEnv ?? "TYPESAFE_API_KEY" : "TYPESAFE_API_KEY";
196
+ const apiKey = value(keyName) ?? "";
197
+ const baseURL = value("TYPESAFE_BASE_URL");
198
+ const model = value("TYPESAFE_DEFAULT_MODEL");
199
+ return {
200
+ provider: {
201
+ apiKey,
202
+ ...baseURL ? { baseURL } : {},
203
+ ...model ? { model } : {}
204
+ },
205
+ keyName
206
+ };
207
+ }
208
+ function traceEnd(result, step) {
209
+ let end = 0;
210
+ result.trace.forEach((entry, index) => {
211
+ if (entry.step <= step) end = index + 1;
212
+ });
213
+ return end;
214
+ }
215
+ async function shrinkFailures(browser, result, options, directory) {
216
+ const context = {
217
+ result,
218
+ options,
219
+ directory,
220
+ resolver: await advisor("guided", true, options.provider),
221
+ freshPage: () => openPage(browser, options.cookies),
222
+ calls: []
223
+ };
224
+ const tests = /* @__PURE__ */ new Map();
225
+ await mkdir2(path3.join(directory, "tests"), { recursive: true });
226
+ for (const [index, failure] of result.failures.entries())
227
+ tests.set(failure.signature, await shrinkOne(failure, index, context));
228
+ return { calls: context.calls, tests };
229
+ }
230
+ async function shrinkOne(failure, index, context) {
231
+ const { result, options } = context;
232
+ if (failure.kind === "semantic") {
233
+ options.write(` ${failure.signature}: page check, not shrunk
234
+ `);
235
+ return { notShrunk: "a page check needs Jev on every replay" };
236
+ }
237
+ const { shrink } = await import("@sedum-dev/core");
238
+ const actions = result.trace.map((entry) => entry.action);
239
+ const prefix = actions.slice(0, traceEnd(result, failure.step));
240
+ const shrunk = await shrink({
241
+ startUrl: result.startUrl,
242
+ actions: prefix,
243
+ signature: failure.signature,
244
+ freshPage: context.freshPage,
245
+ ...watched(options)
246
+ });
247
+ if (!shrunk.reproduced) {
248
+ options.write(` ${failure.signature}: did not reproduce on replay
249
+ `);
250
+ return { notShrunk: "did not reproduce on replay" };
251
+ }
252
+ const test = await emitOne(
253
+ { failure, index, actions: shrunk.actions, originalLength: prefix.length },
254
+ context
255
+ );
256
+ options.write(
257
+ ` ${failure.signature}
258
+ ${prefix.length} -> ${shrunk.actions.length} actions in ${shrunk.replays} replays; ${test.sentences.matched}/${test.sentences.located} sentences round-tripped; ${test.reproduced ? "reproduced" : "NOT reproduced"} by sentences
259
+ ${path3.join(context.directory, test.path)}
260
+ `
261
+ );
262
+ return test;
263
+ }
264
+ async function emitOne(shrunk, context) {
265
+ const { failure, index, actions, originalLength } = shrunk;
266
+ const { emitTest } = await import("@sedum-dev/core");
267
+ const fresh = await context.freshPage();
268
+ try {
269
+ const emitted = await emitTest(fresh.page, context.resolver, {
270
+ startUrl: context.result.startUrl,
271
+ actions,
272
+ failure,
273
+ originalLength,
274
+ ...watched(context.options)
275
+ });
276
+ context.calls.push(...emitted.calls);
277
+ const relative = `tests/finding-F${index + 1}.test.yaml`;
278
+ await writeFile3(path3.join(context.directory, relative), emitted.yaml);
279
+ const located = emitted.steps.filter((s) => s.roundTrip !== "n/a");
280
+ return {
281
+ path: relative,
282
+ yaml: emitted.yaml,
283
+ actionsBefore: originalLength,
284
+ actionsAfter: actions.length,
285
+ reproduced: emitted.reproduced,
286
+ sentences: {
287
+ matched: located.filter((s) => s.roundTrip === "matched").length,
288
+ located: located.length
289
+ }
290
+ };
291
+ } finally {
292
+ await fresh.close();
293
+ }
294
+ }
295
+ function summary(result) {
296
+ const kinds = Object.entries(result.kinds).map(([kind, n]) => `${kind} ${n}`).join(", ");
297
+ const lines = [
298
+ `
299
+ Explored ${result.trace.length} actions in ${(result.elapsedMs / 1e3).toFixed(1)}s (seed ${result.seed}, ${result.mode}).`,
300
+ `States: ${result.states} distinct, ${result.routes.length} routes.${kinds ? ` Page kinds: ${kinds}.` : ""}`,
301
+ result.skippedDestructive.length ? `Not clicked (destructive or session-ending): ${result.skippedDestructive.join(", ")}.` : "",
302
+ result.calls.length ? `Jev: ${cost(result.calls)}.` : "",
303
+ Object.keys(result.writes).length ? `Writes (successful non-GET requests): ${Object.entries(result.writes).map(([key, n]) => `${key} \xD7${n}`).join(", ")}.` : "No writes observed.",
304
+ result.stopReason ? `Stopped early: ${result.stopReason}` : "",
305
+ result.failures.length ? `Failures (${result.failures.length}):
306
+ ${result.failures.map((f) => ` step ${f.step}: ${f.signature}`).join("\n")}` : "No failures observed."
307
+ ];
308
+ return `${lines.filter(Boolean).join("\n")}
309
+ `;
310
+ }
311
+ var SAFETY_OFF = "Safety is off: the walk may delete, send or pay, but never logs itself out.\nUse --safe on shared or production-like data.\n";
312
+ function shownPath(file) {
313
+ const relative = path3.relative(process.cwd(), file);
314
+ return !relative || relative.startsWith("..") ? file : relative;
315
+ }
316
+ function runId(seed) {
317
+ return `${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-")}-seed-${seed}`;
318
+ }
319
+ async function openRun(options) {
320
+ const seed = options.seed ?? randomInt(2147483647);
321
+ const id = runId(seed);
322
+ const directory = path3.resolve(options.out, id);
323
+ await mkdir2(directory, { recursive: true });
324
+ const trace = path3.join(directory, "trace.jsonl");
325
+ const header = {
326
+ sedumExplore: 1,
327
+ startUrl: options.url,
328
+ seed,
329
+ mode: options.mode,
330
+ steps: options.steps
331
+ };
332
+ await writeFile3(trace, `${JSON.stringify(header)}
333
+ `);
334
+ options.write(
335
+ `Exploring ${options.url} (seed ${seed}, ${options.mode}). Trace: ${trace}
336
+ `
337
+ );
338
+ if (options.safety === "off") options.write(SAFETY_OFF);
339
+ return { seed, id, directory, trace, startedAt: (/* @__PURE__ */ new Date()).toISOString() };
340
+ }
341
+ async function walk(page, place, frames, options) {
342
+ const { explore: explore2 } = await import("@sedum-dev/core");
343
+ const guide = await advisor(options.mode, false, options.provider);
344
+ return explore2(page, {
345
+ startUrl: options.url,
346
+ steps: options.steps,
347
+ seed: place.seed,
348
+ mode: options.mode,
349
+ ...guide ? { advisor: guide } : {},
350
+ ...tuning(options),
351
+ ...watched(options),
352
+ ...options.detect ? { detect: options.detect } : {},
353
+ ...options.signal ? { signal: options.signal } : {},
354
+ ...frames ? {
355
+ beforeAction: (step, _action, box) => frames.before(step, box ?? null)
356
+ } : {},
357
+ onStep: async (entry) => {
358
+ await frames?.after(entry.step);
359
+ options.write(progressLine(entry));
360
+ await writeFile3(place.trace, `${JSON.stringify(entry)}
361
+ `, { flag: "a" });
362
+ }
363
+ });
364
+ }
365
+ async function report(run2, options) {
366
+ const { browser, result, place, frames } = run2;
367
+ const shrunk = options.shrink && result.failures.length ? await shrinkReport(browser, result, options, place.directory) : null;
368
+ const { files } = await writeExploreReports(
369
+ place.directory,
370
+ result,
371
+ {
372
+ runId: place.id,
373
+ startedAt: place.startedAt,
374
+ requestedSteps: options.steps,
375
+ safety: options.safety,
376
+ detect: options.detect ?? "browser",
377
+ trace: "trace.jsonl",
378
+ directory: shownPath(place.directory),
379
+ ...frames ? { frames: frames.frames } : {},
380
+ ...shrunk ? { tests: shrunk.tests, extraCalls: shrunk.calls } : {}
381
+ },
382
+ frames?.bytes ?? /* @__PURE__ */ new Map()
383
+ );
384
+ options.write(
385
+ `result ${files.result}
386
+ markdown ${files.markdown}
387
+ report ${files.html}
388
+ `
389
+ );
390
+ }
391
+ async function executeExploreCommand(options) {
392
+ const place = await openRun(options);
393
+ const browser = await launch(options.headed);
394
+ try {
395
+ const { page, close } = await openPage(browser, options.cookies);
396
+ const frames = options.replay ? await FrameRecorder.create(
397
+ place.directory,
398
+ page,
399
+ options.sensitiveOrigins ?? []
400
+ ) : null;
401
+ const result = await walk(page, place, frames, options);
402
+ await close();
403
+ options.write(summary(result));
404
+ await report({ browser, result, place, frames }, options);
405
+ return result.failures.length ? 1 : 0;
406
+ } finally {
407
+ await browser.close();
408
+ }
409
+ }
410
+ async function shrinkReport(browser, result, options, directory) {
411
+ options.write("Shrinking failures:\n");
412
+ const shrunk = await shrinkFailures(browser, result, options, directory);
413
+ if (shrunk.calls.length)
414
+ options.write(`Locator round-trips: ${cost(shrunk.calls)}.
415
+ `);
416
+ return shrunk;
417
+ }
418
+ async function executeRerunCommand(options) {
419
+ const { replay } = await import("@sedum-dev/core");
420
+ const [first, ...rest] = (await readFile(options.trace, "utf8")).split("\n").filter(Boolean);
421
+ const header = JSON.parse(first ?? "{}");
422
+ if (!header.startUrl)
423
+ throw new InvalidArgumentError("Not an exploration trace.");
424
+ const actions = rest.map((line) => JSON.parse(line).action);
425
+ const browser = await launch(options.headed);
426
+ try {
427
+ const context = await browser.newContext({
428
+ viewport: { width: 1280, height: 720 }
429
+ });
430
+ const result = await replay(
431
+ await context.newPage(),
432
+ header.startUrl,
433
+ actions
434
+ );
435
+ const signatures = [...new Set(result.events.map((e) => e.signature))];
436
+ options.write(
437
+ `Reran ${result.divergedAt ?? actions.length} of ${actions.length} actions${result.divergedAt === void 0 ? "" : ` (diverged at action ${result.divergedAt})`}.
438
+ ${signatures.length ? signatures.map((s) => ` ${s}`).join("\n") : "No failures observed."}
439
+ `
440
+ );
441
+ return signatures.length ? 1 : 0;
442
+ } finally {
443
+ await browser.close();
444
+ }
445
+ }
446
+ function safetyOf(safe) {
447
+ if (safe === void 0) return "off";
448
+ return safe === true ? "on" : safe;
449
+ }
450
+ async function run(url, flags, io, provider) {
451
+ return executeExploreCommand({
452
+ url,
453
+ steps: flags.steps,
454
+ ...flags.seed === void 0 ? {} : { seed: flags.seed },
455
+ mode: flags.mode,
456
+ out: path3.resolve(io.cwd, flags.out),
457
+ shrink: flags.shrink,
458
+ headed: flags.headed,
459
+ safety: safetyOf(flags.safe),
460
+ replay: flags.replay,
461
+ sensitiveOrigins: flags.sensitiveOrigin,
462
+ watchOrigins: flags.watchOrigin,
463
+ rejectedSubmits: flags.rejectedSubmits,
464
+ ignoreConsole: flags.ignoreConsole,
465
+ detect: flags.detect,
466
+ detectAllow: flags.detectAllow,
467
+ ...flags.cookies ? { cookies: path3.resolve(io.cwd, flags.cookies) } : {},
468
+ provider,
469
+ ...io.signal ? { signal: io.signal } : {},
470
+ write: io.write
471
+ });
472
+ }
473
+ function usageProblem({
474
+ url,
475
+ flags
476
+ }) {
477
+ if (flags.detect === "semantic" && flags.mode !== "guided")
478
+ return "--detect semantic asks Jev in each new page's guided call.\nFix: use it with --mode guided.\n";
479
+ return url ? null : "Missing start URL.\nFix: use `sedum explore <url>`.\n";
480
+ }
481
+ async function exploreAction(url, flags, io) {
482
+ if (flags.rerun)
483
+ return executeRerunCommand({
484
+ trace: path3.resolve(io.cwd, flags.rerun),
485
+ headed: flags.headed,
486
+ write: io.write
487
+ });
488
+ const problem = usageProblem({ url, flags });
489
+ if (problem) {
490
+ io.writeErr(problem);
491
+ return 3;
492
+ }
493
+ return explore(url, flags, io);
494
+ }
495
+ async function explore(url, flags, io) {
496
+ const credentials = await projectCredentials(io);
497
+ if (!credentials) return 3;
498
+ const { ProviderError } = await import("@sedum-dev/core");
499
+ try {
500
+ return await run(url, flags, io, credentials.provider);
501
+ } catch (error) {
502
+ if (!(error instanceof ProviderError && error.code === "configuration"))
503
+ throw error;
504
+ io.writeErr(missingKeyMessage(credentials, error.message));
505
+ }
506
+ return 3;
507
+ }
508
+ async function projectCredentials(io) {
509
+ try {
510
+ return await exploreProvider(io.cwd);
511
+ } catch (error) {
512
+ if (!(error instanceof ProjectConfigError)) throw error;
513
+ const diagnostic = configDiagnostic(error);
514
+ io.writeErr(`${diagnostic.message}
515
+ Fix: ${diagnostic.fix}
516
+ `);
517
+ return null;
518
+ }
519
+ }
520
+ function missingKeyMessage({ provider, keyName }, adapterMessage) {
521
+ const message = provider.apiKey ? adapterMessage : `Set ${keyName} to use the TypeSafe provider.`;
522
+ return `${message}
523
+ Fix: set ${keyName} in the project-root .env or your shell, or use --mode random or --mode heuristic without --shrink.
524
+ `;
525
+ }
526
+
527
+ export {
528
+ EXPLORE_MODES,
529
+ exploreMode,
530
+ seedValue,
531
+ collectText,
532
+ watchOrigin,
533
+ startUrl,
534
+ exploreProvider,
535
+ executeExploreCommand,
536
+ executeRerunCommand,
537
+ exploreAction
538
+ };