screw-bugs 0.1.8 → 0.1.10

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