@softure-ai/marketing-kit 0.1.9 → 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 (67) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +83 -4
  3. package/dist/cli/main.js +42 -6
  4. package/dist/cli/main.js.map +1 -1
  5. package/dist/config/config.d.ts +2 -0
  6. package/dist/config/config.d.ts.map +1 -1
  7. package/dist/config/config.js +1 -0
  8. package/dist/config/config.js.map +1 -1
  9. package/dist/config/placeholders.d.ts +32 -0
  10. package/dist/config/placeholders.d.ts.map +1 -0
  11. package/dist/config/placeholders.js +41 -0
  12. package/dist/config/placeholders.js.map +1 -0
  13. package/dist/config/schema.d.ts +2206 -0
  14. package/dist/config/schema.d.ts.map +1 -1
  15. package/dist/config/schema.js +80 -0
  16. package/dist/config/schema.js.map +1 -1
  17. package/dist/config/shot-steps.d.ts +637 -0
  18. package/dist/config/shot-steps.d.ts.map +1 -0
  19. package/dist/config/shot-steps.js +44 -0
  20. package/dist/config/shot-steps.js.map +1 -0
  21. package/dist/record/actions.d.ts +3 -10
  22. package/dist/record/actions.d.ts.map +1 -1
  23. package/dist/record/actions.js +7 -23
  24. package/dist/record/actions.js.map +1 -1
  25. package/dist/record/locator.d.ts +10 -0
  26. package/dist/record/locator.d.ts.map +1 -0
  27. package/dist/record/locator.js +24 -0
  28. package/dist/record/locator.js.map +1 -0
  29. package/dist/screenshot/gates.d.ts +46 -5
  30. package/dist/screenshot/gates.d.ts.map +1 -1
  31. package/dist/screenshot/gates.js +41 -5
  32. package/dist/screenshot/gates.js.map +1 -1
  33. package/dist/screenshot/prepare.d.ts +18 -0
  34. package/dist/screenshot/prepare.d.ts.map +1 -0
  35. package/dist/screenshot/prepare.js +60 -0
  36. package/dist/screenshot/prepare.js.map +1 -0
  37. package/dist/screenshot/screenshot.d.ts +9 -2
  38. package/dist/screenshot/screenshot.d.ts.map +1 -1
  39. package/dist/screenshot/screenshot.js +86 -7
  40. package/dist/screenshot/screenshot.js.map +1 -1
  41. package/dist/screenshot/shot-texts.d.ts +26 -0
  42. package/dist/screenshot/shot-texts.d.ts.map +1 -0
  43. package/dist/screenshot/shot-texts.js +55 -0
  44. package/dist/screenshot/shot-texts.js.map +1 -0
  45. package/dist/screenshot/sign-in.d.ts +34 -0
  46. package/dist/screenshot/sign-in.d.ts.map +1 -0
  47. package/dist/screenshot/sign-in.js +66 -0
  48. package/dist/screenshot/sign-in.js.map +1 -0
  49. package/dist/screenshot/steps.d.ts +12 -0
  50. package/dist/screenshot/steps.d.ts.map +1 -0
  51. package/dist/screenshot/steps.js +38 -0
  52. package/dist/screenshot/steps.js.map +1 -0
  53. package/package.json +2 -2
  54. package/schema/marketing.schema.json +1842 -10
  55. package/src/cli/main.ts +40 -6
  56. package/src/config/config.ts +3 -0
  57. package/src/config/placeholders.ts +60 -0
  58. package/src/config/schema.ts +85 -0
  59. package/src/config/shot-steps.ts +58 -0
  60. package/src/record/actions.ts +5 -31
  61. package/src/record/locator.ts +37 -0
  62. package/src/screenshot/gates.ts +60 -5
  63. package/src/screenshot/prepare.ts +64 -0
  64. package/src/screenshot/screenshot.ts +89 -8
  65. package/src/screenshot/shot-texts.ts +72 -0
  66. package/src/screenshot/sign-in.ts +91 -0
  67. package/src/screenshot/steps.ts +44 -0
@@ -1,4 +1,5 @@
1
- import { mkdirSync, rmSync, statSync } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, rmSync, statSync } from "node:fs";
2
3
  import { basename, dirname, extname, join } from "node:path";
3
4
 
4
5
  import { chromium, errors, type Browser, type Page } from "playwright";
@@ -7,14 +8,18 @@ import type { ColorTheme } from "../config/colors.js";
7
8
  import type { MarketingJson } from "../config/schema.js";
8
9
  import { getScreenshotNames, getScreenshotShots } from "../config/screenshot-names.js";
9
10
  import { containsPhrase } from "../film.js";
10
- import { findScrollFailure, findSizeFailure, findStatusFailure, type ScreenshotGate } from "./gates.js";
11
+ import { getLocator } from "../record/locator.js";
12
+ import { findCropFrame, findDimensionFailure, findScrollFailure, findSizeFailure, findStatusFailure, type ScreenshotGate } from "./gates.js";
13
+ import { readPageText, signIn, type SessionState, type SignInPlan } from "./sign-in.js";
14
+ import { runShotSteps } from "./steps.js";
11
15
 
12
16
  /**
13
17
  * `softure-marketing shots`: the `screenshots` entries of `marketing.json`. Each shot of an entry
14
18
  * (one per colour scheme, `config/screenshot-names.ts`) gets a fresh browser context with the entry's viewport, device
15
19
  * scale and motion preference, and is kept only when it passes every gate (`gates.ts`) on its own.
16
20
  * Every file an entry could write is removed before it runs, so a failed shot leaves no file behind,
17
- * not even an older one: a stale PNG must never look like a fresh pass.
21
+ * not even an older one: a stale PNG must never look like a fresh pass. Entries with `signedIn` share one sign-in
22
+ * per run, and no two kept files of a run may have the same bytes.
18
23
  */
19
24
 
20
25
  export type ScreenshotEntry = MarketingJson["screenshots"][number];
@@ -40,6 +45,8 @@ export interface TakeScreenshotsOptions {
40
45
  browser: ScreenshotBrowser;
41
46
  /** A Chromium to use instead of Playwright's own (`PLAYWRIGHT_CHROMIUM_PATH`). */
42
47
  executablePath?: string;
48
+ /** How `signedIn` entries sign in, placeholders resolved; without it, every `signedIn` shot is refused. */
49
+ signIn?: SignInPlan;
43
50
  }
44
51
 
45
52
  /** `id` is the entry's, `name` the file's without `.png` (`<id>` or `<id>-<scheme>`). */
@@ -76,7 +83,9 @@ async function scrollThroughPage(page: Page): Promise<void> {
76
83
  async function waitForPhrase(page: Page, phrase: string): Promise<boolean> {
77
84
  const deadline = Date.now() + PHRASE_TIMEOUT_MS;
78
85
  for (;;) {
79
- if (containsPhrase(await page.locator("body").innerText(), phrase)) return true;
86
+ // A step may have started a navigation; its page is read on the next poll.
87
+ const text = await readPageText(page);
88
+ if (text !== null && containsPhrase(text, phrase)) return true;
80
89
  if (Date.now() >= deadline) return false;
81
90
  await page.waitForTimeout(PHRASE_POLL_MS);
82
91
  }
@@ -94,6 +103,26 @@ interface ShotTarget {
94
103
  file: string;
95
104
  }
96
105
 
106
+ /** Width and height of a PNG from its IHDR chunk. */
107
+ function readPngSize(file: string): { width: number; height: number } {
108
+ const bytes = readFileSync(file);
109
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
110
+ }
111
+
112
+ /** The element's rectangle in document coordinates and the page's scrollable size. */
113
+ async function measureCrop(page: Page, entry: ScreenshotEntry & { crop: NonNullable<ScreenshotEntry["crop"]> }): Promise<{ ok: true; frame: { x: number; y: number; width: number; height: number } } | { ok: false; message: string }> {
114
+ const locator = getLocator(page, entry.crop.target);
115
+ const count = await locator.count();
116
+ if (count === 0) return { ok: false, message: "no element matches crop.target" };
117
+ if (count > 1) return { ok: false, message: `crop.target matches ${count} elements; add nth to pick one` };
118
+ const element = await locator.evaluate((node) => {
119
+ const rect = node.getBoundingClientRect();
120
+ return { x: rect.left + window.scrollX, y: rect.top + window.scrollY, width: rect.width, height: rect.height };
121
+ });
122
+ const size = await page.evaluate(() => ({ width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight }));
123
+ return findCropFrame({ element, page: size, aspect: entry.crop.aspect, padding: entry.crop.padding });
124
+ }
125
+
97
126
  async function takeOne(page: Page, target: ShotTarget): Promise<ScreenshotResult> {
98
127
  const { entry, name, url } = target;
99
128
  const refuse = (gate: ScreenshotGate, message: string): ScreenshotResult => ({ ok: false, id: entry.id, name, gate, message });
@@ -120,6 +149,8 @@ async function takeOne(page: Page, target: ShotTarget): Promise<ScreenshotResult
120
149
  async function captureLoadedPage(page: Page, target: ShotTarget): Promise<ScreenshotResult> {
121
150
  const { entry, name, url, file } = target;
122
151
  await page.evaluate(() => document.fonts.ready);
152
+ const stepFailure = await runShotSteps(page, entry.steps, "steps");
153
+ if (stepFailure !== null) return { ok: false, id: entry.id, name, gate: "steps", message: stepFailure };
123
154
  if (entry.full) await scrollThroughPage(page);
124
155
  if (entry.scrollTo !== undefined) {
125
156
  const reached = await page.evaluate((top) => {
@@ -133,7 +164,23 @@ async function captureLoadedPage(page: Page, target: ShotTarget): Promise<Screen
133
164
  if (!(await waitForPhrase(page, entry.expect))) {
134
165
  return { ok: false, id: entry.id, name, gate: "phrase", message: `${url} does not show "${entry.expect}"` };
135
166
  }
136
- await page.screenshot({ path: file, fullPage: entry.full });
167
+ let frame: { width: number; height: number } | null = null;
168
+ if (entry.crop === undefined) {
169
+ await page.screenshot({ path: file, fullPage: entry.full });
170
+ } else {
171
+ const crop = await measureCrop(page, { ...entry, crop: entry.crop });
172
+ if (!crop.ok) return { ok: false, id: entry.id, name, gate: "crop", message: crop.message };
173
+ // Document coordinates with fullPage: a sticky header stays at the page's top instead of over the element.
174
+ await page.screenshot({ path: file, fullPage: true, clip: crop.frame });
175
+ frame = crop.frame;
176
+ }
177
+ if (frame !== null) {
178
+ const dimensionFailure = findDimensionFailure(readPngSize(file), frame, entry.scale);
179
+ if (dimensionFailure !== null) {
180
+ rmSync(file, { force: true });
181
+ return { ok: false, id: entry.id, name, gate: "crop", message: dimensionFailure };
182
+ }
183
+ }
137
184
  const bytes = statSync(file).size;
138
185
  const sizeFailure = findSizeFailure(bytes, entry.minBytes);
139
186
  if (sizeFailure !== null) {
@@ -153,10 +200,12 @@ interface TakeShotOptions {
153
200
  settings: ScreenshotBrowser;
154
201
  target: ShotTarget;
155
202
  scheme: ColorTheme;
203
+ /** The run's sign-in session, for a `signedIn` entry. */
204
+ session?: SessionState;
156
205
  }
157
206
 
158
207
  async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
159
- const { browser, settings, target, scheme } = options;
208
+ const { browser, settings, target, scheme, session } = options;
160
209
  const { entry } = target;
161
210
  const context = await browser.newContext({
162
211
  viewport: { width: entry.width, height: entry.height },
@@ -167,6 +216,7 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
167
216
  reducedMotion: entry.motion,
168
217
  // Resolved to an absolute path by the caller (the CLI resolves it against the folder of marketing.json).
169
218
  ...(entry.storageState === undefined ? {} : { storageState: entry.storageState }),
219
+ ...(session === undefined ? {} : { storageState: session }),
170
220
  });
171
221
  try {
172
222
  const page = await context.newPage();
@@ -189,18 +239,49 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
189
239
  }
190
240
  }
191
241
 
192
- /** Takes every shot of every entry in order; one failing shot does not stop the others. */
242
+ /**
243
+ * Refuses a kept file whose bytes an earlier kept file of the run already has (the page did not change between the
244
+ * two shots, or two entries frame the same thing), and deletes it; remembers the others.
245
+ */
246
+ function refuseDuplicate(result: ScreenshotResult, seen: Map<string, string>): ScreenshotResult {
247
+ if (!result.ok) return result;
248
+ const hash = createHash("sha256").update(readFileSync(result.file)).digest("hex");
249
+ const earlier = seen.get(hash);
250
+ if (earlier === undefined) {
251
+ seen.set(hash, result.name);
252
+ return result;
253
+ }
254
+ rmSync(result.file, { force: true });
255
+ const message = `the file has the same bytes as ${earlier}.png: the page did not change between the two shots; deleted`;
256
+ return { ok: false, id: result.id, name: result.name, gate: "duplicate", message };
257
+ }
258
+
259
+ /**
260
+ * Takes every shot of every entry in order; one failing shot does not stop the others. The sign-in runs once,
261
+ * before the first `signedIn` entry; when it fails, every `signedIn` shot is refused with its reason.
262
+ */
193
263
  export async function takeScreenshots(options: TakeScreenshotsOptions): Promise<ScreenshotResult[]> {
194
264
  const { entries, baseUrl, outDir, browser: settings } = options;
195
265
  mkdirSync(outDir, { recursive: true });
196
266
  const browser = await chromium.launch(options.executablePath === undefined ? {} : { executablePath: options.executablePath });
197
267
  const results: ScreenshotResult[] = [];
268
+ const seen = new Map<string, string>();
269
+ let signedIn: Awaited<ReturnType<typeof signIn>> | null = null;
198
270
  try {
199
271
  for (const entry of entries) {
200
272
  removeEntryFiles(outDir, entry);
273
+ if (entry.signedIn && signedIn === null) {
274
+ signedIn = options.signIn === undefined ? { ok: false, message: "no signIn block says how to sign in" } : await signIn({ browser, baseUrl, settings, plan: options.signIn });
275
+ }
201
276
  for (const shot of getScreenshotShots(entry, settings.colorScheme)) {
277
+ if (entry.signedIn && signedIn?.ok === false) {
278
+ results.push({ ok: false, id: entry.id, name: shot.name, gate: "sign-in", message: signedIn.message });
279
+ continue;
280
+ }
202
281
  const target = { entry, name: shot.name, url: new URL(entry.path, baseUrl).href, file: getScreenshotFile(outDir, shot.name) };
203
- results.push(await takeShot({ browser, settings, target, scheme: shot.scheme }));
282
+ const session = entry.signedIn && signedIn?.ok === true ? signedIn.session : undefined;
283
+ const result = await takeShot({ browser, settings, target, scheme: shot.scheme, ...(session === undefined ? {} : { session }) });
284
+ results.push(refuseDuplicate(result, seen));
204
285
  }
205
286
  }
206
287
  } finally {
@@ -0,0 +1,72 @@
1
+ import type { ShotStep } from "../config/shot-steps.js";
2
+ import { findPlaceholders, resolvePlaceholders, type PlaceholderSources } from "../config/placeholders.js";
3
+ import type { ScreenshotEntry } from "./screenshot.js";
4
+ import type { SignInPlan } from "./sign-in.js";
5
+
6
+ /**
7
+ * Every text of a `shots` run that may hold `{env:NAME}` or `{data:key}` (the sign-in's step values and phrase, each
8
+ * entry's path, phrase and step values), resolved in one place with the place it came from, so an error names the
9
+ * key to fix and never a value.
10
+ */
11
+
12
+ export interface ShotTexts {
13
+ entries: ScreenshotEntry[];
14
+ signIn: SignInPlan | null;
15
+ }
16
+
17
+ export type ResolveShotTextsResult = { ok: true; texts: ShotTexts } | { ok: false; error: string };
18
+
19
+ class UnresolvedText extends Error {}
20
+
21
+ function resolveSteps(steps: readonly ShotStep[], where: string, resolve: (text: string, where: string) => string): ShotStep[] {
22
+ return steps.map((step, index) => (step.do === "fill" ? { ...step, value: resolve(step.value, `${where}[${index}].value`) } : step));
23
+ }
24
+
25
+ /** The texts with their placeholders replaced; a page path gets its inserted values URL-encoded. */
26
+ export function resolveShotTexts(texts: ShotTexts, sources: PlaceholderSources): ResolveShotTextsResult {
27
+ const resolve = (text: string, where: string, encode?: (value: string) => string): string => {
28
+ const result = resolvePlaceholders(text, sources, encode);
29
+ if (!result.ok) throw new UnresolvedText(`${where}: ${result.error}`);
30
+ return result.value;
31
+ };
32
+ try {
33
+ const signIn =
34
+ texts.signIn === null
35
+ ? null
36
+ : { path: texts.signIn.path, steps: resolveSteps(texts.signIn.steps, "signIn.steps", resolve), expect: resolve(texts.signIn.expect, "signIn.expect") };
37
+ const entries = texts.entries.map((entry) => {
38
+ const where = `screenshot "${entry.id}"`;
39
+ return {
40
+ ...entry,
41
+ path: resolve(entry.path, `${where} path`, encodeURIComponent),
42
+ expect: resolve(entry.expect, `${where} expect`),
43
+ steps: resolveSteps(entry.steps, `${where} steps`, resolve),
44
+ };
45
+ });
46
+ return { ok: true, texts: { entries, signIn } };
47
+ } catch (error) {
48
+ if (error instanceof UnresolvedText) return { ok: false, error: error.message };
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ function listTexts(texts: ShotTexts): string[] {
54
+ const stepValues = (steps: readonly ShotStep[]) => steps.flatMap((step) => (step.do === "fill" ? [step.value] : []));
55
+ const signIn = texts.signIn === null ? [] : [...stepValues(texts.signIn.steps), texts.signIn.expect];
56
+ return [...signIn, ...texts.entries.flatMap((entry) => [entry.path, entry.expect, ...stepValues(entry.steps)])];
57
+ }
58
+
59
+ /** Whether any text reads what `signIn.prepare` prints. */
60
+ export function usesData(texts: ShotTexts): boolean {
61
+ return listTexts(texts).some((text) => findPlaceholders(text).some((placeholder) => placeholder.kind === "data"));
62
+ }
63
+
64
+ /** The first `{env:NAME}` the environment does not set, checked before the app starts or the preparation runs. */
65
+ export function findUnsetVariable(texts: ShotTexts, env: Readonly<Record<string, string | undefined>>): string | null {
66
+ for (const text of listTexts(texts)) {
67
+ for (const { kind, key } of findPlaceholders(text)) {
68
+ if (kind === "env" && (env[key] === undefined || env[key] === "")) return key;
69
+ }
70
+ }
71
+ return null;
72
+ }
@@ -0,0 +1,91 @@
1
+ import type { Browser, BrowserContext, Page } from "playwright";
2
+
3
+ import type { ShotStep } from "../config/shot-steps.js";
4
+ import { containsPhrase } from "../film.js";
5
+ import { findStatusFailure } from "./gates.js";
6
+ import type { ScreenshotBrowser } from "./screenshot.js";
7
+ import { runShotSteps } from "./steps.js";
8
+
9
+ /**
10
+ * `signIn` of marketing.json, done once per `shots` run: the sign-in page, its steps, then a phrase only a
11
+ * signed-in page shows. The session (cookies and localStorage) stays in memory and opens every `signedIn: true`
12
+ * screenshot; it is never written to disk. Values are resolved before they get here and never printed.
13
+ */
14
+
15
+ /** The sign-in with its placeholders resolved. */
16
+ export interface SignInPlan {
17
+ path: string;
18
+ steps: ShotStep[];
19
+ expect: string;
20
+ }
21
+
22
+ export type SessionState = Awaited<ReturnType<BrowserContext["storageState"]>>;
23
+
24
+ export type SignInResult = { ok: true; session: SessionState } | { ok: false; message: string };
25
+
26
+ const NAVIGATION_TIMEOUT_MS = 30_000;
27
+ /** The submit usually navigates and the next page loads its data: more time than a screenshot's 5 s. */
28
+ export const SIGN_IN_PHRASE_TIMEOUT_MS = 15_000;
29
+ const PHRASE_POLL_MS = 250;
30
+
31
+ function describeError(error: unknown): string {
32
+ return error instanceof Error ? (error.message.split("\n")[0] ?? error.name) : String(error);
33
+ }
34
+
35
+ /** The page's visible text, or null while a navigation replaces the document (its context is destroyed). */
36
+ export async function readPageText(page: Page): Promise<string | null> {
37
+ try {
38
+ return await page.locator("body").innerText({ timeout: PHRASE_POLL_MS * 4 });
39
+ } catch {
40
+ // A navigation in flight or a body not there yet: the next poll reads the new page.
41
+ return null;
42
+ }
43
+ }
44
+
45
+ async function waitForSignedIn(page: Page, phrase: string): Promise<boolean> {
46
+ const deadline = Date.now() + SIGN_IN_PHRASE_TIMEOUT_MS;
47
+ for (;;) {
48
+ const text = await readPageText(page);
49
+ if (text !== null && containsPhrase(text, phrase)) return true;
50
+ if (Date.now() >= deadline) return false;
51
+ await page.waitForTimeout(PHRASE_POLL_MS);
52
+ }
53
+ }
54
+
55
+ export interface SignInOptions {
56
+ browser: Browser;
57
+ baseUrl: string;
58
+ settings: ScreenshotBrowser;
59
+ plan: SignInPlan;
60
+ }
61
+
62
+ export async function signIn(options: SignInOptions): Promise<SignInResult> {
63
+ const { browser, baseUrl, settings, plan } = options;
64
+ const url = new URL(plan.path, baseUrl).href;
65
+ const context = await browser.newContext({ colorScheme: settings.colorScheme, locale: settings.locale, timezoneId: settings.timezone });
66
+ try {
67
+ const page = await context.newPage();
68
+ let status: number | null;
69
+ try {
70
+ const response = await page.goto(url, { waitUntil: "load", timeout: NAVIGATION_TIMEOUT_MS });
71
+ status = response?.status() ?? null;
72
+ } catch (error) {
73
+ // Any navigation failure (refused connection, DNS, timeout) is the app's, not a bug of ours.
74
+ return { ok: false, message: `loading the sign-in page ${url}: ${describeError(error)}` };
75
+ }
76
+ const statusFailure = findStatusFailure(status, url);
77
+ if (statusFailure !== null) return { ok: false, message: `the sign-in page: ${statusFailure}` };
78
+ const stepFailure = await runShotSteps(page, plan.steps, "signIn.steps");
79
+ if (stepFailure !== null) return { ok: false, message: stepFailure };
80
+ if (!(await waitForSignedIn(page, plan.expect))) {
81
+ return { ok: false, message: `after the sign-in steps, ${new URL(page.url()).pathname} does not show "${plan.expect}" within ${SIGN_IN_PHRASE_TIMEOUT_MS / 1000} s` };
82
+ }
83
+ const session = await context.storageState();
84
+ if (session.cookies.length === 0 && session.origins.length === 0) {
85
+ return { ok: false, message: `the page shows "${plan.expect}", but the browser holds no session (no cookie, no localStorage); pick a phrase only a signed-in page shows` };
86
+ }
87
+ return { ok: true, session };
88
+ } finally {
89
+ await context.close();
90
+ }
91
+ }
@@ -0,0 +1,44 @@
1
+ import type { Page } from "playwright";
2
+
3
+ import type { ShotStep } from "../config/shot-steps.js";
4
+ import { getLocator } from "../record/locator.js";
5
+
6
+ /**
7
+ * Steps of the sign-in and of a screenshot entry, done in order on the page. A step that cannot be done (its
8
+ * element never appears, matches several, is not an input) is the page's or the config's fault, so it comes back as
9
+ * a message naming the step; the message never carries a `fill` value, which may be a password.
10
+ */
11
+
12
+ /** Long enough for a client-side page to render the element, short enough that a typo does not hang the run. */
13
+ export const STEP_TIMEOUT_MS = 10_000;
14
+
15
+ function describeError(error: unknown): string {
16
+ return error instanceof Error ? (error.message.split("\n")[0] ?? error.name) : String(error);
17
+ }
18
+
19
+ async function runStep(page: Page, step: ShotStep): Promise<void> {
20
+ const timeout = STEP_TIMEOUT_MS;
21
+ switch (step.do) {
22
+ case "fill":
23
+ return getLocator(page, step.target).fill(step.value, { timeout });
24
+ case "click":
25
+ return getLocator(page, step.target).click({ timeout });
26
+ case "check":
27
+ return getLocator(page, step.target).check({ timeout });
28
+ case "press":
29
+ return page.keyboard.press(step.key);
30
+ }
31
+ }
32
+
33
+ /** Null when every step was done; otherwise which one failed (`<where>[<index>] (<do>)`) and why. */
34
+ export async function runShotSteps(page: Page, steps: readonly ShotStep[], where: string): Promise<string | null> {
35
+ for (const [index, step] of steps.entries()) {
36
+ try {
37
+ await runStep(page, step);
38
+ } catch (error) {
39
+ // Every Playwright failure of a step (timeout, strict mode, not an input) is the page's or the config's.
40
+ return `${where}[${index}] (${step.do}): ${describeError(error)}`;
41
+ }
42
+ }
43
+ return null;
44
+ }