screw-bugs 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +906 -2
  3. package/bin/screw-bugs.js +29 -0
  4. package/dist/browser-playwright/annotate.d.ts +9 -0
  5. package/dist/browser-playwright/annotate.js +86 -0
  6. package/dist/browser-playwright/capture.d.ts +232 -0
  7. package/dist/browser-playwright/capture.js +1049 -0
  8. package/dist/browser-playwright/frames.d.ts +77 -0
  9. package/dist/browser-playwright/frames.js +191 -0
  10. package/dist/browser-playwright/index.d.ts +2 -0
  11. package/dist/browser-playwright/index.js +2 -0
  12. package/dist/browser-playwright/input.d.ts +44 -0
  13. package/dist/browser-playwright/input.js +116 -0
  14. package/dist/browser-playwright/launch.d.ts +21 -0
  15. package/dist/browser-playwright/launch.js +86 -0
  16. package/dist/browser-playwright/page.d.ts +387 -0
  17. package/dist/browser-playwright/page.js +1930 -0
  18. package/dist/build-info.json +5 -0
  19. package/dist/cli/app.d.ts +19 -0
  20. package/dist/cli/app.js +70 -0
  21. package/dist/cli/build-info.d.ts +52 -0
  22. package/dist/cli/build-info.js +82 -0
  23. package/dist/cli/commands.d.ts +14 -0
  24. package/dist/cli/commands.js +308 -0
  25. package/dist/cli/config.d.ts +16 -0
  26. package/dist/cli/config.js +71 -0
  27. package/dist/cli/doctor.d.ts +19 -0
  28. package/dist/cli/doctor.js +113 -0
  29. package/dist/cli/environment.d.ts +20 -0
  30. package/dist/cli/environment.js +34 -0
  31. package/dist/cli/exit-codes.d.ts +29 -0
  32. package/dist/cli/exit-codes.js +28 -0
  33. package/dist/cli/failure.d.ts +20 -0
  34. package/dist/cli/failure.js +15 -0
  35. package/dist/cli/index.d.ts +6 -0
  36. package/dist/cli/index.js +6 -0
  37. package/dist/cli/install-method.d.ts +96 -0
  38. package/dist/cli/install-method.js +148 -0
  39. package/dist/cli/main.d.ts +1 -0
  40. package/dist/cli/main.js +10 -0
  41. package/dist/cli/mcp.d.ts +30 -0
  42. package/dist/cli/mcp.js +309 -0
  43. package/dist/cli/node-version.d.ts +3 -0
  44. package/dist/cli/node-version.js +22 -0
  45. package/dist/cli/operations.d.ts +127 -0
  46. package/dist/cli/operations.js +337 -0
  47. package/dist/cli/package-info.d.ts +22 -0
  48. package/dist/cli/package-info.js +25 -0
  49. package/dist/cli/report-server.d.ts +170 -0
  50. package/dist/cli/report-server.js +387 -0
  51. package/dist/cli/signals.d.ts +37 -0
  52. package/dist/cli/signals.js +61 -0
  53. package/dist/cli/stamp-build.d.ts +1 -0
  54. package/dist/cli/stamp-build.js +9 -0
  55. package/dist/cli/update-check.d.ts +140 -0
  56. package/dist/cli/update-check.js +316 -0
  57. package/dist/cli/uploads.d.ts +16 -0
  58. package/dist/cli/uploads.js +80 -0
  59. package/dist/core/css.d.ts +95 -0
  60. package/dist/core/css.js +436 -0
  61. package/dist/core/engine.d.ts +65 -0
  62. package/dist/core/engine.js +436 -0
  63. package/dist/core/errors.d.ts +66 -0
  64. package/dist/core/errors.js +30 -0
  65. package/dist/core/evidence.d.ts +14 -0
  66. package/dist/core/evidence.js +127 -0
  67. package/dist/core/index.d.ts +12 -0
  68. package/dist/core/index.js +12 -0
  69. package/dist/core/labels.d.ts +47 -0
  70. package/dist/core/labels.js +199 -0
  71. package/dist/core/liveness.d.ts +45 -0
  72. package/dist/core/liveness.js +64 -0
  73. package/dist/core/marks.d.ts +63 -0
  74. package/dist/core/marks.js +410 -0
  75. package/dist/core/services.d.ts +444 -0
  76. package/dist/core/services.js +22 -0
  77. package/dist/core/steps.d.ts +96 -0
  78. package/dist/core/steps.js +656 -0
  79. package/dist/core/uploads.d.ts +49 -0
  80. package/dist/core/uploads.js +133 -0
  81. package/dist/core/video.d.ts +16 -0
  82. package/dist/core/video.js +101 -0
  83. package/dist/core/viewport.d.ts +28 -0
  84. package/dist/core/viewport.js +50 -0
  85. package/dist/report/html.d.ts +37 -0
  86. package/dist/report/html.js +762 -0
  87. package/dist/report/index.d.ts +5 -0
  88. package/dist/report/index.js +5 -0
  89. package/dist/report/markup.d.ts +27 -0
  90. package/dist/report/markup.js +75 -0
  91. package/dist/report/pr-summary.d.ts +11 -0
  92. package/dist/report/pr-summary.js +110 -0
  93. package/dist/report/sha256.d.ts +9 -0
  94. package/dist/report/sha256.js +97 -0
  95. package/dist/report/styles.d.ts +1 -0
  96. package/dist/report/styles.js +328 -0
  97. package/dist/report/view.d.ts +141 -0
  98. package/dist/report/view.js +368 -0
  99. package/dist/report/walkthrough.d.ts +75 -0
  100. package/dist/report/walkthrough.js +458 -0
  101. package/dist/schema/config.d.ts +7 -0
  102. package/dist/schema/config.js +6 -0
  103. package/dist/schema/doctor.d.ts +46 -0
  104. package/dist/schema/doctor.js +23 -0
  105. package/dist/schema/evidence.d.ts +994 -0
  106. package/dist/schema/evidence.js +521 -0
  107. package/dist/schema/findings.d.ts +159 -0
  108. package/dist/schema/findings.js +80 -0
  109. package/dist/schema/index.d.ts +7 -0
  110. package/dist/schema/index.js +7 -0
  111. package/dist/schema/job.d.ts +1724 -0
  112. package/dist/schema/job.js +505 -0
  113. package/dist/schema/ledger.d.ts +951 -0
  114. package/dist/schema/ledger.js +193 -0
  115. package/dist/schema/status.d.ts +7 -0
  116. package/dist/schema/status.js +11 -0
  117. package/dist/store-local/accounts.d.ts +7 -0
  118. package/dist/store-local/accounts.js +9 -0
  119. package/dist/store-local/index.d.ts +3 -0
  120. package/dist/store-local/index.js +3 -0
  121. package/dist/store-local/paths.d.ts +10 -0
  122. package/dist/store-local/paths.js +17 -0
  123. package/dist/store-local/storage.d.ts +20 -0
  124. package/dist/store-local/storage.js +170 -0
  125. package/package.json +73 -4
@@ -0,0 +1,656 @@
1
+ import { Effect } from 'effect';
2
+ import { baseName, ABSENCE_WATCH_MS, DEFAULT_WAIT_MS, elementOf, framesOf, isWebUrl, loadTimeoutOf, REASON_MAX, schemeOf, uploadFileOf, } from '../schema/index.js';
3
+ const SLUG_MAX = 40;
4
+ /**
5
+ * A screenshot name as a decorative part of a file name: lowercase letters, digits and dashes,
6
+ * at most `SLUG_MAX` characters. It never makes a file name unique on its own; see
7
+ * {@link evidenceFileName}.
8
+ */
9
+ export const fileSlug = (name) => name
10
+ .toLowerCase()
11
+ .replace(/[^a-z0-9]+/g, '-')
12
+ .slice(0, SLUG_MAX)
13
+ .replace(/^-+|-+$/g, '') || 'shot';
14
+ const pad = (n) => String(n).padStart(2, '0');
15
+ /**
16
+ * Where the `shot`th screenshot of the `caseNumber`th case is stored, relative to the evidence
17
+ * folder, such as `01/03-after-login.png`. Both numbers are 1-based. The numbers alone make a name
18
+ * unique, so it does not depend on how a file system compares names: `A` and `a`, or `shot` and
19
+ * `SHOT`, never land on the same file on Windows or macOS. The name starts with digits and holds
20
+ * only lowercase letters, digits and dashes, so it is never a reserved Windows name (`CON`,
21
+ * `LPT1`) and never ends in a dot or space.
22
+ */
23
+ export const evidenceFileName = (caseNumber, shot, name) => `${pad(caseNumber)}/${pad(shot)}-${fileSlug(name)}.png`;
24
+ const ok = { _tag: 'ok' };
25
+ const describeElement = (target) => {
26
+ if (target.role !== undefined)
27
+ return target.name === undefined ? target.role : `${target.role} "${target.name}"`;
28
+ if (target.text !== undefined)
29
+ return `text "${target.text}"`;
30
+ if (target.label !== undefined)
31
+ return `label "${target.label}"`;
32
+ if (target.alt !== undefined)
33
+ return `alt "${target.alt}"`;
34
+ return `css "${target.css ?? ''}"`;
35
+ };
36
+ /** Where something is, innermost frame first, such as ` in iframe css "iframe.preview"`. */
37
+ export const describeFrames = (frames) => frames
38
+ .toReversed()
39
+ .map((frame) => ` in iframe ${describeElement(frame)}`)
40
+ .join('');
41
+ /** Such as `text "Save" in iframe css "iframe.preview"`. */
42
+ export const describeTarget = (target) => describeElement(target) + describeFrames(framesOf(target.frame));
43
+ export const describeStep = (step) => {
44
+ switch (step.action) {
45
+ case 'goto':
46
+ return `goto ${step.url}`;
47
+ case 'reload':
48
+ return 'reload';
49
+ case 'click':
50
+ return `click ${describeTarget(step.target)}`;
51
+ case 'fill':
52
+ return `fill ${describeTarget(step.target)}`;
53
+ case 'upload':
54
+ return `upload ${step.files.map((f) => baseName(uploadFileOf(f).path)).join(', ')} to ${describeTarget(step.target)}`;
55
+ case 'press':
56
+ return `press ${step.key}`;
57
+ case 'expectText':
58
+ return `expectText "${step.text}"${describeFrames(framesOf(step.frame))}`;
59
+ case 'expectNoText':
60
+ return `expectNoText "${step.text}"${step.target !== undefined
61
+ ? ` in ${describeTarget(step.target)}`
62
+ : describeFrames(framesOf(step.frame))}`;
63
+ case 'waitFor':
64
+ return `waitFor ${describeTarget(step.target)} to be ${step.state ?? 'visible'}`;
65
+ case 'scroll':
66
+ return step.target !== undefined
67
+ ? `scroll to ${describeTarget(step.target)}`
68
+ : step.to !== undefined
69
+ ? `scroll to ${step.to}${describeFrames(framesOf(step.frame))}`
70
+ : `scroll by ${step.by ?? 0} px${describeFrames(framesOf(step.frame))}`;
71
+ case 'expectUrl':
72
+ return `expectUrl "${step.includes}"`;
73
+ case 'expectLink':
74
+ return `expectLink ${describeTarget(step.target)} ${step.match === 'exact' ? 'is' : 'contains'} "${step.href}"`;
75
+ case 'screenshot':
76
+ return `screenshot ${step.name}`;
77
+ }
78
+ };
79
+ /** Relative URLs (`/login`) are resolved against the job URL. */
80
+ export const resolveUrl = (url, base) => URL.canParse(url, base) ? new URL(url, base).href : url;
81
+ /**
82
+ * The scheme of a URL screw-bugs must not open or capture, such as `file:`; undefined for http
83
+ * and https (see `WEB_SCHEMES`). `about:blank` holds nothing, so it passes too: it is where a
84
+ * page starts, and where it stays when a load fails.
85
+ */
86
+ export const refusedScheme = (url) => url === 'about:blank' || isWebUrl(url) ? undefined : (schemeOf(url) ?? 'non-web');
87
+ const ONLY_WEB = 'only http and https pages are tested';
88
+ const wentOff = {
89
+ page: 'The page went to',
90
+ frame: 'A frame in the page went to',
91
+ window: 'A new tab or window went to',
92
+ };
93
+ /**
94
+ * The first step of every case is a navigation, so each case starts from a known page: a case
95
+ * that does not begin with goto starts at the job URL. A case that continues (`CaseSpec.continue`)
96
+ * starts where the case before it ended instead, with its own steps only.
97
+ */
98
+ export const withStartPage = (spec, jobUrl) => spec.continue === true || spec.steps[0]?.action === 'goto'
99
+ ? spec.steps
100
+ : [{ action: 'goto', url: jobUrl }, ...spec.steps];
101
+ /** A step that could not run; `missing` counts only when what it looked for was not there. */
102
+ const blocked = (error, missing) => ({
103
+ _tag: 'blocked',
104
+ message: error.message,
105
+ ...(error.notFound === true && missing !== undefined ? { missing } : {}),
106
+ });
107
+ /** Where `frame` goes in a hint, as a step gives it: one frame, or a list outermost first. */
108
+ const frameJson = (frames) => `"frame":${JSON.stringify(frames.length === 1 ? frames[0] : frames)}`;
109
+ /**
110
+ * What to change when a step did not find its text or element where it looked (`given`, the
111
+ * page itself when empty) but it is somewhere else (`found`): the `frame` to add, to use instead,
112
+ * or to remove. Up to `named` frames are named, and how many hold it. `inTarget` says that `frame`
113
+ * goes on the step's target. Undefined when there is nothing to say.
114
+ */
115
+ export const frameHint = (found, given, inTarget, named = 2) => {
116
+ if (given.length > 0 && found.inPage)
117
+ return `it is not in that iframe but in the page itself: remove "frame"${inTarget ? ' from the target' : ''}`;
118
+ if (found.frames.length === 0)
119
+ return undefined;
120
+ const [intro, verb, where] = given.length === 0
121
+ ? [
122
+ found.count === 1 ? 'it is in an iframe' : `it is in ${found.count} iframes`,
123
+ 'add',
124
+ ' to the target',
125
+ ]
126
+ : [
127
+ found.count === 1
128
+ ? 'it is not in that iframe but in another'
129
+ : `it is not in that iframe but in ${found.count} others`,
130
+ 'use',
131
+ ' in the target',
132
+ ];
133
+ const shown = found.frames.slice(0, Math.max(1, named));
134
+ const rest = found.count - shown.length;
135
+ return (`${intro}: ${verb} ${shown.map(frameJson).join(' or ')}${inTarget ? where : ''}` +
136
+ (rest > 0 ? ` (${rest} more not named)` : ''));
137
+ };
138
+ /**
139
+ * A reason with a hint after it (see `frameHint`), kept within `REASON_MAX` so the hint shows
140
+ * whole where reasons are cut. `hints` says the same in fewer words each, most first; the first
141
+ * that fits is used, with the step's own message, else with `short`. When none fits, the
142
+ * shortest is used, with `label` cut at a word (or only its step number).
143
+ */
144
+ export const withHint = (label, message, short, hints) => {
145
+ const join = (head, said, hint) => `${head}: ${said.replace(/\.$/, '')}; ${hint}.`;
146
+ for (const hint of hints)
147
+ for (const said of [message, short]) {
148
+ const reason = join(label, said, hint);
149
+ if (reason.length <= REASON_MAX)
150
+ return reason;
151
+ }
152
+ // Still too long: the shortest hint, and the label cut at a word, such as `Step 2 (click text…)`.
153
+ const hint = hints.at(-1) ?? '';
154
+ const brief = join(label, short, hint);
155
+ const room = REASON_MAX - (brief.length - label.length);
156
+ const step = label.split(' (')[0];
157
+ const sliced = label.slice(0, Math.max(0, room - 2));
158
+ const cut = /\s/.test(label.charAt(room - 2)) ? sliced.trimEnd() : sliced.replace(/\s*\S*$/, '');
159
+ return cut.length > step.length + 2
160
+ ? join(`${cut}…)`, short, hint)
161
+ : step.length <= room
162
+ ? join(step, short, hint)
163
+ : brief;
164
+ };
165
+ /** An element a step looked for, with `short` for when a hint needs the room. */
166
+ const lookedFor = (target, short) => ({
167
+ sought: { _tag: 'element', target: elementOf(target) },
168
+ frames: framesOf(target.frame),
169
+ inTarget: true,
170
+ short,
171
+ });
172
+ /** Steps that act on the page, so a page load during one is taken to be theirs. */
173
+ const ACTIONS = [
174
+ 'goto',
175
+ 'reload',
176
+ 'click',
177
+ 'fill',
178
+ 'upload',
179
+ 'press',
180
+ ];
181
+ /**
182
+ * What a page load that went wrong means for the step during which it started: an HTTP error
183
+ * fails it; a load that failed or did not finish blocks it. Every page load is counted against
184
+ * the step that was running when it started (`BrowserPage.settle`). An action (goto, reload,
185
+ * click, fill, upload, press) is taken to have caused it; during an expectation or a screenshot, which cause nothing,
186
+ * the page did it on its own, so the reason says only when it started.
187
+ */
188
+ const loadOutcome = (problem, step) => {
189
+ const tab = problem.inNewTab ? ' in a new tab or window' : '';
190
+ const subject = (step.action === 'goto' || step.action === 'reload') && !problem.inNewTab
191
+ ? 'The page'
192
+ : ACTIONS.includes(step.action)
193
+ ? `The page it opened${tab}`
194
+ : `A page load${tab} that started during this step`;
195
+ switch (problem._tag) {
196
+ case 'HttpError':
197
+ return { _tag: 'failed', message: `${subject} returned HTTP ${problem.status}.` };
198
+ case 'LoadFailed':
199
+ return { _tag: 'blocked', message: `${subject} could not be loaded: ${problem.error}.` };
200
+ case 'Unfinished':
201
+ return {
202
+ _tag: 'blocked',
203
+ message: `${subject} did not finish loading within ${problem.timeoutMs / 1000} s.`,
204
+ };
205
+ }
206
+ };
207
+ const seconds = (ms) => `${(ms ?? DEFAULT_WAIT_MS) / 1000} s`;
208
+ /** Why `waitFor` failed: the target did not reach `state` within `ms`. */
209
+ const notReached = (target, state, ms) => {
210
+ const what = describeTarget(target);
211
+ switch (state) {
212
+ case 'visible':
213
+ return `No element matching ${what} became visible within ${seconds(ms)}.`;
214
+ case 'hidden':
215
+ return `An element matching ${what} was still visible after ${seconds(ms)}.`;
216
+ case 'attached':
217
+ return `No element matching ${what} appeared in the page within ${seconds(ms)}.`;
218
+ case 'detached':
219
+ return `An element matching ${what} was still in the page after ${seconds(ms)}.`;
220
+ }
221
+ };
222
+ /**
223
+ * Whether a link's address `href` (absolute) is what an `expectLink` step expects: contains its
224
+ * `href`, or with `exact` is it, resolved against the page's URL `pageUrl` when it is a path.
225
+ */
226
+ export const linkMatches = (href, expected, match, pageUrl) => match === 'exact'
227
+ ? href === expected || href === resolveUrl(expected, pageUrl)
228
+ : href.includes(expected);
229
+ /** How text that should not show did, such as `image alt "Acme logo" in .clients`. */
230
+ export const seenText = (seen) => `${seen.as === 'text' ? 'text' : seen.as === 'alt' ? 'image alt' : 'ARIA label'} "${seen.value}"` +
231
+ (seen.near !== undefined ? ` in ${seen.near}` : '');
232
+ /** What a scroll step scrolls, as `BrowserPage.scroll` takes it. */
233
+ const scrollOf = (step) => step.target !== undefined
234
+ ? { _tag: 'target', target: step.target }
235
+ : step.to !== undefined
236
+ ? { _tag: 'end', to: step.to, frames: framesOf(step.frame) }
237
+ : { _tag: 'by', by: step.by ?? 0, frames: framesOf(step.frame) };
238
+ const runStep = (page, step, jobUrl, capture, stepShot, uploads) => {
239
+ /**
240
+ * An action is blocked when it cannot be performed; what it loads is judged later. `missing`
241
+ * is what it acted on, for when that was not there.
242
+ */
243
+ const action = (effect, missing) => effect.pipe(Effect.as(ok), Effect.catchTag('PageActionFailed', (e) => Effect.succeed(blocked(e, missing))));
244
+ const noMatch = `Not found within ${seconds('timeoutMs' in step ? step.timeoutMs : undefined)}`;
245
+ switch (step.action) {
246
+ case 'goto': {
247
+ const url = resolveUrl(step.url, jobUrl);
248
+ const scheme = refusedScheme(url);
249
+ return scheme === undefined
250
+ ? action(page.goto(url, { timeoutMs: step.timeoutMs }))
251
+ : Effect.succeed({
252
+ _tag: 'blocked',
253
+ message: `Refused to open a ${scheme} URL; ${ONLY_WEB}.`,
254
+ });
255
+ }
256
+ case 'reload':
257
+ return action(page.reload({ timeoutMs: step.timeoutMs }));
258
+ case 'click':
259
+ // A link is checked before it is followed, rather than after the page has gone there.
260
+ return page.linkUrl(step.target, { timeoutMs: step.timeoutMs }).pipe(Effect.map((href) => (href === undefined ? undefined : refusedScheme(href))), Effect.matchEffect({
261
+ onFailure: (e) => Effect.succeed(blocked(e, lookedFor(step.target, noMatch))),
262
+ onSuccess: (scheme) => scheme === undefined
263
+ ? stepShot(step.target).pipe(Effect.andThen(action(page.click(step.target, { timeoutMs: step.timeoutMs }), lookedFor(step.target, noMatch))))
264
+ : Effect.succeed({
265
+ _tag: 'blocked',
266
+ message: `It links to a ${scheme} URL, so it was not clicked; ${ONLY_WEB}.`,
267
+ }),
268
+ }));
269
+ case 'fill':
270
+ return action(page.fill(step.target, step.value, { timeoutMs: step.timeoutMs }), lookedFor(step.target, noMatch)).pipe(Effect.tap((outcome) => (outcome._tag === 'ok' ? stepShot(step.target) : Effect.void)));
271
+ case 'upload': {
272
+ // Every file was checked before the run started; one that was not is never sent.
273
+ const sources = step.files.map((file) => uploads(uploadFileOf(file).path));
274
+ const unchecked = step.files.find((_, i) => sources[i] === undefined);
275
+ if (unchecked !== undefined)
276
+ return Effect.succeed({
277
+ _tag: 'blocked',
278
+ message: `The file ${uploadFileOf(unchecked).path} was not checked before the run, so it was not sent.`,
279
+ });
280
+ return action(page.upload(step.target, sources.map((source) => source.absolute), { timeoutMs: step.timeoutMs }), lookedFor(step.target, `No file input or file chooser within ${seconds(step.timeoutMs)}`)).pipe(Effect.tap((outcome) => (outcome._tag === 'ok' ? stepShot(step.target) : Effect.void)));
281
+ }
282
+ case 'press':
283
+ return action(page.press(step.key));
284
+ case 'expectText': {
285
+ const frames = framesOf(step.frame);
286
+ return page.hasText(step.text, { timeoutMs: step.timeoutMs }, frames).pipe(Effect.map((found) => found
287
+ ? ok
288
+ : {
289
+ _tag: 'failed',
290
+ message: `The text "${step.text}" did not appear${describeFrames(frames)} within ${seconds(step.timeoutMs)}.`,
291
+ missing: {
292
+ sought: { _tag: 'text', text: step.text },
293
+ frames,
294
+ inTarget: false,
295
+ short: `Not found within ${seconds(step.timeoutMs)}`,
296
+ },
297
+ }), Effect.catchTag('PageActionFailed', (e) => Effect.succeed(blocked(e))), Effect.tap((outcome) => outcome._tag === 'ok'
298
+ ? stepShot({
299
+ text: step.text,
300
+ ...(step.frame !== undefined ? { frame: step.frame } : {}),
301
+ })
302
+ : Effect.void));
303
+ }
304
+ case 'expectNoText': {
305
+ const frames = step.target === undefined ? framesOf(step.frame) : [];
306
+ return page
307
+ .watchText(step.text, { frames, target: step.target }, ABSENCE_WATCH_MS, {
308
+ timeoutMs: step.timeoutMs,
309
+ })
310
+ .pipe(Effect.map((watched) => {
311
+ if (watched._tag === 'absent')
312
+ return ok;
313
+ // An absence is never told from a look that did not see everything.
314
+ if (watched._tag === 'incomplete')
315
+ return {
316
+ _tag: 'blocked',
317
+ message: `Not everything could be looked at (${watched.reason}), so it cannot be told that "${step.text}" is not there.`,
318
+ };
319
+ if (watched._tag === 'empty')
320
+ return {
321
+ _tag: 'blocked',
322
+ message: `Nothing showed ${step.target !== undefined ? 'in that element' : frames.length > 0 ? 'in that frame' : 'on the page'} within ${seconds(step.timeoutMs)}, so there was nothing to look for "${step.text}" in.`,
323
+ };
324
+ const where = step.target !== undefined
325
+ ? 'in that element'
326
+ : frames.length > 0
327
+ ? 'in that frame'
328
+ : `on the page${describeFrames(watched.seen.frames).replace(/^ in/, ', in')}`;
329
+ return {
330
+ _tag: 'failed',
331
+ message: `"${step.text}" is ${where} (${seenText(watched.seen)}).`,
332
+ };
333
+ }), Effect.catchTag('PageActionFailed', (e) => Effect.succeed(blocked(e, step.target === undefined ? undefined : lookedFor(step.target, noMatch)))),
334
+ // What was looked at, showing that the text is not there.
335
+ Effect.tap((outcome) => (outcome._tag === 'ok' ? stepShot(step.target) : Effect.void)));
336
+ }
337
+ case 'waitFor': {
338
+ const state = step.state ?? 'visible';
339
+ return page.waitFor(step.target, state, { timeoutMs: step.timeoutMs }).pipe(Effect.map((reached) => reached
340
+ ? ok
341
+ : {
342
+ _tag: 'failed',
343
+ message: notReached(step.target, state, step.timeoutMs),
344
+ // Only an element that never showed up may be somewhere else.
345
+ ...(state === 'visible' || state === 'attached'
346
+ ? {
347
+ missing: lookedFor(step.target, state === 'visible'
348
+ ? `Not visible within ${seconds(step.timeoutMs)}`
349
+ : `Not in the page within ${seconds(step.timeoutMs)}`),
350
+ }
351
+ : {}),
352
+ }), Effect.catchTag('PageActionFailed', (e) => Effect.succeed(blocked(e))),
353
+ // What the page shows once it got there; with the element when it is meant to be seen.
354
+ Effect.tap((outcome) => outcome._tag === 'ok'
355
+ ? stepShot(state === 'visible' || state === 'attached' ? step.target : undefined)
356
+ : Effect.void));
357
+ }
358
+ case 'scroll':
359
+ return action(page.scroll(scrollOf(step), { timeoutMs: step.timeoutMs }), step.target === undefined ? undefined : lookedFor(step.target, noMatch)).pipe(
360
+ // What is in view after scrolling, below the first screen or inside a frame.
361
+ Effect.tap((outcome) => (outcome._tag === 'ok' ? stepShot(step.target) : Effect.void)));
362
+ case 'expectUrl':
363
+ return page.urlIncludes(step.includes, { timeoutMs: step.timeoutMs }).pipe(Effect.flatMap((found) => found
364
+ ? Effect.succeed(ok)
365
+ : page.url.pipe(Effect.map((url) => ({
366
+ _tag: 'failed',
367
+ message: `The URL was ${url}, which does not contain "${step.includes}".`,
368
+ })))), Effect.catchTag('PageActionFailed', (e) => Effect.succeed(blocked(e))));
369
+ case 'expectLink': {
370
+ const match = step.match ?? 'contains';
371
+ const missing = lookedFor(step.target, noMatch);
372
+ return Effect.all([page.linkUrl(step.target, { timeoutMs: step.timeoutMs }), page.url]).pipe(Effect.map(([href, pageUrl]) => {
373
+ const what = describeTarget(step.target);
374
+ if (href === undefined)
375
+ return {
376
+ _tag: 'failed',
377
+ message: `The element matching ${what} is not a link: neither it nor an element around it has an address.`,
378
+ };
379
+ if (linkMatches(href, step.href, match, pageUrl))
380
+ return ok;
381
+ return {
382
+ _tag: 'failed',
383
+ message: match === 'exact'
384
+ ? `The link goes to ${href}, not ${step.href}.`
385
+ : `The link goes to ${href}, which does not contain "${step.href}".`,
386
+ };
387
+ }),
388
+ // A link that is not there fails the expectation, as an element waitFor never sees does.
389
+ Effect.catchTag('PageActionFailed', (e) => Effect.succeed(e.notFound === true ? { _tag: 'failed', message: e.message, missing } : blocked(e))), Effect.tap((outcome) => (outcome._tag === 'ok' ? stepShot(step.target) : Effect.void)));
390
+ }
391
+ case 'screenshot':
392
+ return capture(step.name).pipe(Effect.as(ok), Effect.catchTag('PageActionFailed', (e) => Effect.succeed(blocked(e))));
393
+ }
394
+ };
395
+ /** The element a step acts on, if it has one. */
396
+ const targetOf = (step) => step.action === 'click' ||
397
+ step.action === 'fill' ||
398
+ step.action === 'upload' ||
399
+ step.action === 'waitFor' ||
400
+ step.action === 'scroll' ||
401
+ step.action === 'expectLink' ||
402
+ step.action === 'expectNoText'
403
+ ? step.target
404
+ : undefined;
405
+ /** `01-03`: the ID of the 3rd screenshot of the 1st case, as agents name screenshots. */
406
+ export const shotId = (caseNumber, shot) => `${pad(caseNumber)}-${pad(shot)}`;
407
+ /**
408
+ * Runs one case's steps in order and maps the outcome to a status: `passed` when every step ran
409
+ * and every expectation held, `failed` at the first expectation that did not hold, `blocked`
410
+ * at the first step that could not run. A case that does not pass also gets a screenshot of
411
+ * the page as it was. Records when it and each step ran (`now`), every screenshot with the page
412
+ * state saved next to it, and a few facts about the page at the end.
413
+ */
414
+ export const runCase = (page, spec, options) => Effect.gen(function* () {
415
+ const evidence = [];
416
+ const evidenceNames = {};
417
+ const shots = [];
418
+ const timings = [];
419
+ let count = 0;
420
+ const steps = withStartPage(spec, options.jobUrl);
421
+ // The implicit first goto is not one of the caller's steps, so it is reported as step 0.
422
+ const offset = steps.length - spec.steps.length;
423
+ /** The step running now, numbered as the ledger numbers them. */
424
+ let current = -offset;
425
+ /** Saves a screenshot with its page state, and records it. */
426
+ const capture = (name, kind, shot) => Effect.gen(function* () {
427
+ const number = ++count;
428
+ const fileName = evidenceFileName(options.caseNumber, number, name);
429
+ const file = options.evidenceFile(fileName);
430
+ const askedAt = yield* options.now;
431
+ const captured = yield* page.screenshot(file.path, shot);
432
+ const atMs = Math.round(yield* options.now);
433
+ evidence.push(file.relative);
434
+ evidenceNames[file.relative] = name;
435
+ const pageFile = fileName.replace(/\.png$/, '.json');
436
+ const saved = yield* options
437
+ .savePage(pageFile, {
438
+ version: 1,
439
+ url: captured.url,
440
+ width: captured.width,
441
+ height: captured.height,
442
+ scale: captured.scale,
443
+ candidates: captured.candidates,
444
+ ...(captured.truncated !== undefined ? { truncated: captured.truncated } : {}),
445
+ ...(captured.frames !== undefined && captured.frames.length > 0
446
+ ? { frames: captured.frames }
447
+ : {}),
448
+ ...(captured.framesFound !== undefined ? { framesFound: captured.framesFound } : {}),
449
+ ...(captured.framesUnread !== undefined ? { framesUnread: captured.framesUnread } : {}),
450
+ ...(captured.nodes !== undefined && captured.nodes.length > 0
451
+ ? { nodes: captured.nodes }
452
+ : {}),
453
+ ...(captured.visual !== undefined ? { visual: captured.visual } : {}),
454
+ })
455
+ .pipe(Effect.as(true), Effect.orElseSucceed(() => false));
456
+ shots.push({
457
+ id: shotId(options.caseNumber, number),
458
+ path: file.relative,
459
+ name,
460
+ kind,
461
+ step: current,
462
+ fullPage: shot.fullPage,
463
+ width: captured.width,
464
+ height: captured.height,
465
+ ...(captured.target !== undefined ? { target: captured.target } : {}),
466
+ ...(captured.target !== undefined && captured.targetContent !== undefined
467
+ ? { targetContent: captured.targetContent }
468
+ : {}),
469
+ ...(captured.targetProblem !== undefined
470
+ ? { targetProblem: captured.targetProblem }
471
+ : {}),
472
+ ...(saved ? { page: options.evidenceFile(pageFile).relative } : {}),
473
+ atMs,
474
+ ...(captured.target !== undefined && captured.targetAfterMs !== undefined
475
+ ? { targetAtMs: Math.round(askedAt + captured.targetAfterMs) }
476
+ : {}),
477
+ ...(captured.visual !== undefined ? { visual: captured.visual } : {}),
478
+ });
479
+ });
480
+ const base = {
481
+ id: spec.id,
482
+ title: spec.title,
483
+ ...(options.continuedFrom !== undefined ? { continuedFrom: options.continuedFrom } : {}),
484
+ };
485
+ const done = (entry) => ({
486
+ ...entry,
487
+ evidence,
488
+ ...(evidence.length > 0 ? { evidenceNames } : {}),
489
+ });
490
+ /**
491
+ * Set once the case's browser went somewhere it must not be captured, such as a `file:` page
492
+ * or a `data:` frame. The adapter watches every navigation; the page's URL is checked too.
493
+ */
494
+ const offWeb = Effect.gen(function* () {
495
+ const refused = yield* page.refused;
496
+ if (refused !== undefined)
497
+ return refused;
498
+ const scheme = refusedScheme(yield* page.url);
499
+ return scheme === undefined ? undefined : { scheme, where: 'page' };
500
+ });
501
+ const stepShot = (target) => Effect.gen(function* () {
502
+ // Nothing is captured from a page off the web; the step's own check reports it.
503
+ if ((yield* offWeb) !== undefined)
504
+ return;
505
+ const step = steps[current - 1 + offset];
506
+ yield* capture(`step${current}-${step?.action ?? 'step'}`, 'step', {
507
+ fullPage: false,
508
+ target,
509
+ });
510
+ }).pipe(Effect.ignore);
511
+ /**
512
+ * Ends the case at step `index` with `outcome`, or blocked if it went off the web. `hints`
513
+ * say where else what the step did not find is (see `withHint`).
514
+ */
515
+ const end = (index, outcome, hints = []) => Effect.gen(function* () {
516
+ const label = `Step ${index + 1 - offset} (${describeStep(steps[index])})`;
517
+ const refused = yield* offWeb;
518
+ if (refused !== undefined)
519
+ return done({
520
+ ...base,
521
+ status: 'blocked',
522
+ reason: `${label}: ${wentOff[refused.where]} a ${refused.scheme} URL; ` +
523
+ `${ONLY_WEB}, so nothing from it was saved.`,
524
+ step: index + 1 - offset,
525
+ });
526
+ if (outcome === undefined)
527
+ return undefined;
528
+ // A screenshot of how the page was when the case stopped, with the step's element.
529
+ current = index + 1 - offset;
530
+ yield* capture(`step${index + 1 - offset}-${outcome._tag}`, 'failure', {
531
+ fullPage: true,
532
+ target: targetOf(steps[index]),
533
+ }).pipe(Effect.ignore);
534
+ return done({
535
+ ...base,
536
+ status: outcome._tag,
537
+ reason: hints.length > 0 && outcome.missing !== undefined
538
+ ? withHint(label, outcome.message, outcome.missing.short, hints)
539
+ : `${label}: ${outcome.message}`,
540
+ step: index + 1 - offset,
541
+ });
542
+ });
543
+ /**
544
+ * Page loads are waited for and judged before step `next` runs, and before the case is
545
+ * judged (`next` past the last step); one that went wrong ends the case at its step.
546
+ */
547
+ const settle = (next) => page
548
+ .settle(next, loadTimeoutOf(steps[next]))
549
+ .pipe(Effect.flatMap((problem) => problem === undefined
550
+ ? Effect.succeed(undefined)
551
+ : end(problem.step, loadOutcome(problem, steps[problem.step]))));
552
+ /** What the step running now did to the page, once it acted (see `StepAction`). */
553
+ let acted;
554
+ /** Records an action as it happened, on the video's clock. */
555
+ const traced = (kind, act) => Effect.gen(function* () {
556
+ const askedAt = yield* options.now;
557
+ const trace = yield* act;
558
+ acted = {
559
+ kind,
560
+ ...(trace.afterMs !== undefined ? { atMs: Math.round(askedAt + trace.afterMs) } : {}),
561
+ ...(trace.point !== undefined ? { point: trace.point } : {}),
562
+ ...(trace.target !== undefined ? { target: trace.target } : {}),
563
+ ...(trace.target !== undefined && trace.scale !== undefined
564
+ ? { scale: trace.scale }
565
+ : {}),
566
+ ...(trace.viewport !== undefined ? { viewport: trace.viewport } : {}),
567
+ };
568
+ return trace;
569
+ });
570
+ /** The page the steps act on, recording what each action did. */
571
+ const acting = {
572
+ ...page,
573
+ goto: (url, wait) => traced('goto', page.goto(url, wait)),
574
+ reload: (wait) => traced('reload', page.reload(wait)),
575
+ click: (target, wait) => traced('click', page.click(target, wait)),
576
+ fill: (target, value, wait) => traced('fill', page.fill(target, value, wait)),
577
+ upload: (target, files, wait) => traced('upload', page.upload(target, files, wait)),
578
+ press: (key) => traced('press', page.press(key)),
579
+ scroll: (to, wait) => traced('scroll', page.scroll(to, wait)),
580
+ };
581
+ const startMs = Math.round(yield* options.now);
582
+ const uploads = options.uploads ?? (() => undefined);
583
+ /** Records when step `index` ran, from `from` until now, and the files an upload sent. */
584
+ const timed = (index, from) => options.now.pipe(Effect.map((to) => {
585
+ const step = steps[index];
586
+ const files = step?.action === 'upload'
587
+ ? step.files.flatMap((file) => {
588
+ const { path } = uploadFileOf(file);
589
+ const source = uploads(path);
590
+ return source === undefined ? [] : [{ name: baseName(path), size: source.size }];
591
+ })
592
+ : [];
593
+ timings.push({
594
+ index: index + 1 - offset,
595
+ startMs: from,
596
+ endMs: Math.round(to),
597
+ ...(files.length > 0 ? { files } : {}),
598
+ ...(acted !== undefined ? { action: acted } : {}),
599
+ });
600
+ }));
601
+ const judged = yield* Effect.gen(function* () {
602
+ for (const [index, step] of steps.entries()) {
603
+ const settled = yield* settle(index);
604
+ if (settled !== undefined)
605
+ return settled;
606
+ current = index + 1 - offset;
607
+ acted = undefined;
608
+ const from = Math.round(yield* options.now);
609
+ // A page can also navigate on its own, later; so the check runs again right before a capture.
610
+ if (step.action === 'screenshot') {
611
+ const before = yield* end(index, undefined);
612
+ if (before !== undefined) {
613
+ yield* timed(index, from);
614
+ return before;
615
+ }
616
+ }
617
+ const outcome = yield* runStep(acting, step, options.jobUrl, (name) => capture(name, 'named', { fullPage: true }), stepShot, uploads);
618
+ yield* timed(index, from);
619
+ if (outcome._tag === 'ok') {
620
+ const after = yield* end(index, undefined);
621
+ if (after !== undefined)
622
+ return after;
623
+ continue;
624
+ }
625
+ // Only now, once the step's own wait is over, so a case that passes pays nothing for it.
626
+ const { missing } = outcome;
627
+ const found = missing === undefined || (yield* offWeb) !== undefined
628
+ ? undefined
629
+ : yield* page.findElsewhere(missing.sought, missing.frames);
630
+ const hints = found === undefined || missing === undefined
631
+ ? []
632
+ : [
633
+ ...new Set([2, 1].flatMap((named) => frameHint(found, missing.frames, missing.inTarget, named) ?? [])),
634
+ ];
635
+ return (yield* end(index, outcome, hints));
636
+ }
637
+ return (yield* settle(steps.length)) ?? done({ ...base, status: 'passed' });
638
+ });
639
+ // Facts come only from a page on the web, like screenshots.
640
+ const decided = judged.step === undefined ? undefined : steps[judged.step - 1 + offset];
641
+ const facts = (yield* offWeb) === undefined
642
+ ? yield* page.facts({
643
+ target: decided === undefined ? undefined : targetOf(decided),
644
+ text: judged.status !== 'passed',
645
+ })
646
+ : undefined;
647
+ const endMs = Math.round(yield* options.now);
648
+ return {
649
+ ...judged,
650
+ startMs,
651
+ endMs,
652
+ steps: timings,
653
+ ...(shots.length > 0 ? { shots } : {}),
654
+ ...(facts !== undefined ? { facts } : {}),
655
+ };
656
+ });