@cappa/core 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/screenshot.ts CHANGED
@@ -1,4 +1,3 @@
1
- import fs from "node:fs";
2
1
  import path from "node:path";
3
2
  import { getLogger, type Logger } from "@cappa/logger";
4
3
  import {
@@ -6,17 +5,23 @@ import {
6
5
  type BrowserContext,
7
6
  chromium,
8
7
  firefox,
9
- type Locator,
10
8
  type Page,
11
9
  type PageScreenshotOptions,
12
10
  webkit,
13
11
  } from "playwright-core";
14
12
  import {
15
- type CompareOptions,
16
13
  type CompareResult,
17
14
  compareImages,
15
+ createDiffSizePngImage,
18
16
  } from "./compare";
19
- import type { DiffConfig, ScreenshotOptions } from "./types";
17
+ import { ScreenshotFileSystem } from "./filesystem";
18
+ import type {
19
+ DiffConfig,
20
+ ScreenshotOptions,
21
+ ScreenshotSettings,
22
+ ScreenshotVariant,
23
+ ScreenshotVariantWithUrl,
24
+ } from "./types";
20
25
 
21
26
  const defaultDiffConfig: DiffConfig = {
22
27
  threshold: 0.1,
@@ -26,20 +31,52 @@ const defaultDiffConfig: DiffConfig = {
26
31
  maxDiffPercentage: 0,
27
32
  };
28
33
 
34
+ export interface ScreenshotCaptureDetails {
35
+ filename: string;
36
+ filepath?: string;
37
+ comparisonResult?: CompareResult;
38
+ diffImagePath?: string;
39
+ skipped?: boolean;
40
+ }
41
+
42
+ export interface ScreenshotVariantCaptureDetails
43
+ extends ScreenshotCaptureDetails {
44
+ id: string;
45
+ label?: string;
46
+ }
47
+
48
+ export interface ScreenshotCaptureResult {
49
+ base: ScreenshotCaptureDetails;
50
+ variants: ScreenshotVariantCaptureDetails[];
51
+ }
52
+
53
+ export interface ScreenshotCaptureExtras {
54
+ saveDiffImage?: boolean;
55
+ diffImageFilename?: string;
56
+ variants?: Record<
57
+ string,
58
+ {
59
+ saveDiffImage?: boolean;
60
+ diffImageFilename?: string;
61
+ }
62
+ >;
63
+ }
64
+
29
65
  class ScreenshotTool {
30
66
  browserType: "chromium" | "firefox" | "webkit";
31
67
  headless: boolean;
32
68
  viewport: { width: number; height: number };
33
69
  outputDir: string;
34
- actualDir: string;
35
- diffDir: string;
36
- expectedDir: string;
37
70
  browser: Browser | null = null;
38
71
  context: BrowserContext | null = null;
39
72
  page: Page | null = null;
73
+ concurrency: number;
74
+ contexts: BrowserContext[] = [];
75
+ pages: Page[] = [];
40
76
  diff: DiffConfig;
41
77
  logger: Logger;
42
78
  retries: number;
79
+ filesystem: ScreenshotFileSystem;
43
80
 
44
81
  constructor(options: {
45
82
  browserType?: "chromium" | "firefox" | "webkit";
@@ -48,28 +85,24 @@ class ScreenshotTool {
48
85
  outputDir?: string;
49
86
  diff?: DiffConfig;
50
87
  retries?: number;
88
+ concurrency?: number;
51
89
  }) {
52
90
  this.browserType = options.browserType || "chromium";
53
91
  this.headless = options.headless !== false; // Default to headless
54
92
  this.viewport = options.viewport || { width: 1920, height: 1080 };
55
93
  this.outputDir = options.outputDir || "./screenshots";
56
94
  this.diff = { ...defaultDiffConfig, ...options.diff };
57
- // Set up subdirectories
58
- this.actualDir = path.join(this.outputDir, "actual");
59
- this.diffDir = path.join(this.outputDir, "diff");
60
- this.expectedDir = path.join(this.outputDir, "expected");
95
+ this.concurrency = Math.max(1, options.concurrency || 1);
61
96
 
62
97
  this.logger = getLogger();
63
98
  this.retries = options.retries || 2;
99
+ this.filesystem = new ScreenshotFileSystem(this.outputDir);
64
100
  }
65
101
 
66
102
  /**
67
103
  * Initialize playwright and page
68
104
  */
69
105
  async init() {
70
- // Create output directories if they don't exist
71
- this.createDirectories();
72
-
73
106
  // Launch browser based on type
74
107
  const browserMap = {
75
108
  chromium,
@@ -90,14 +123,26 @@ class ScreenshotTool {
90
123
  .newPage()
91
124
  .then((page) => page.evaluate(() => navigator.userAgent));
92
125
 
93
- this.context = await this.browser.newContext({
94
- reducedMotion: "reduce",
95
- deviceScaleFactor: 2,
96
- userAgent: `${await defaultUserAgent} CappaStorybook`,
97
- viewport: this.viewport,
98
- });
126
+ // Create N contexts and pages
127
+ this.contexts = [];
128
+ this.pages = [];
129
+
130
+ for (let i = 0; i < this.concurrency; i++) {
131
+ const context = await this.browser.newContext({
132
+ reducedMotion: "reduce",
133
+ deviceScaleFactor: 2,
134
+ userAgent: `${await defaultUserAgent} CappaStorybook`,
135
+ viewport: this.viewport,
136
+ });
137
+ const page = await context.newPage();
138
+
139
+ this.contexts.push(context);
140
+ this.pages.push(page);
141
+ }
99
142
 
100
- this.page = await this.context?.newPage();
143
+ // Backward compatibility
144
+ this.context = this.contexts[0] ?? null;
145
+ this.page = this.pages[0] ?? null;
101
146
  }
102
147
 
103
148
  /**
@@ -105,8 +150,8 @@ class ScreenshotTool {
105
150
  * If not closed, the process will not exit
106
151
  */
107
152
  async close() {
108
- if (this.context) {
109
- await this.context.close();
153
+ for (const context of this.contexts) {
154
+ await context.close();
110
155
  }
111
156
  if (this.browser) {
112
157
  await this.browser.close();
@@ -123,54 +168,13 @@ class ScreenshotTool {
123
168
  await page.goto(url, { waitUntil: "domcontentloaded" });
124
169
  }
125
170
 
126
- /**
127
- * Creates directories for screenshots and other files
128
- */
129
- private createDirectories() {
130
- // Create main output directory and subdirectories
131
- const directories = [
132
- this.outputDir,
133
- this.actualDir,
134
- this.diffDir,
135
- this.expectedDir,
136
- ];
137
-
138
- for (const dir of directories) {
139
- if (!fs.existsSync(dir)) {
140
- fs.mkdirSync(dir, { recursive: true });
141
- this.logger.debug(`Initialized directory: ${dir}`);
142
- }
143
- }
144
- }
145
-
146
- /**
147
- * Gets the path to the actual screenshot file
148
- */
149
- getActualFilePath(filename: string): string {
150
- return path.join(this.actualDir, filename);
151
- }
152
-
153
- /**
154
- * Gets the path to the diff screenshot file
155
- */
156
- getDiffFilePath(filename: string): string {
157
- return path.join(this.diffDir, filename);
158
- }
159
-
160
- /**
161
- * Gets the path to the expected screenshot file
162
- */
163
- getExpectedFilePath(filename: string): string {
164
- return path.join(this.expectedDir, filename);
165
- }
166
-
167
171
  /**
168
172
  * Takes a screenshot of the page
169
173
  */
170
174
  async takeScreenshot(
171
175
  page: Page,
172
176
  filename: string,
173
- options: ScreenshotOptions,
177
+ options: ScreenshotSettings,
174
178
  ) {
175
179
  if (!this.browser) {
176
180
  throw new Error("Browser not initialized");
@@ -182,7 +186,7 @@ class ScreenshotTool {
182
186
 
183
187
  try {
184
188
  // Generate filename - save to actual directory
185
- const filepath = this.getActualFilePath(filename);
189
+ const filepath = this.filesystem.getActualFilePath(filename);
186
190
 
187
191
  // Take screenshot
188
192
  const screenshotOptions = {
@@ -193,13 +197,17 @@ class ScreenshotTool {
193
197
  mask: options.mask,
194
198
  omitBackground: options.omitBackground,
195
199
  scale: "css" as const,
200
+ animations: "disabled",
201
+ caret: "hide",
196
202
  } satisfies PageScreenshotOptions;
197
203
 
198
- if (options.delay) {
199
- await page.waitForTimeout(options.delay);
200
- }
204
+ await this.withViewport(page, options.viewport, async () => {
205
+ if (options.delay) {
206
+ await page.waitForTimeout(options.delay);
207
+ }
201
208
 
202
- await page.screenshot(screenshotOptions);
209
+ await page.screenshot(screenshotOptions);
210
+ });
203
211
 
204
212
  return filepath;
205
213
  } catch (error) {
@@ -211,11 +219,97 @@ class ScreenshotTool {
211
219
  }
212
220
  }
213
221
 
222
+ /**
223
+ * Sets the viewport size and executes the action, ensuring the original viewport is restored
224
+ * even if the action throws an error.
225
+ */
226
+ private async withViewport<T>(
227
+ page: Page,
228
+ viewport: ScreenshotSettings["viewport"],
229
+ action: () => Promise<T>,
230
+ ): Promise<T> {
231
+ if (!viewport) {
232
+ return action();
233
+ }
234
+
235
+ const previousViewport = page.viewportSize();
236
+
237
+ // Check if the new viewport is the same as the current one
238
+ if (
239
+ previousViewport &&
240
+ previousViewport.width === viewport.width &&
241
+ previousViewport.height === viewport.height
242
+ ) {
243
+ return action();
244
+ }
245
+
246
+ await page.setViewportSize(viewport);
247
+
248
+ try {
249
+ return await action();
250
+ } finally {
251
+ // Always restore the original viewport, even if the action throws an error
252
+ if (previousViewport) {
253
+ await page.setViewportSize(previousViewport);
254
+ }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Takes a screenshot and returns the buffer (for comparison purposes)
260
+ */
261
+ async takeScreenshotBuffer(
262
+ page: Page,
263
+ options: ScreenshotSettings,
264
+ ): Promise<Buffer> {
265
+ if (!this.browser) {
266
+ throw new Error("Browser not initialized");
267
+ }
268
+
269
+ if (options.skip) {
270
+ throw new Error("Screenshot skipped");
271
+ }
272
+
273
+ try {
274
+ // Take screenshot without saving to file
275
+ const screenshotOptions = {
276
+ fullPage: options.fullPage,
277
+ type: "png" as const,
278
+ timeout: 60000,
279
+ mask: options.mask,
280
+ omitBackground: options.omitBackground,
281
+ scale: "css" as const,
282
+ animations: "disabled",
283
+ caret: "hide",
284
+ } satisfies PageScreenshotOptions;
285
+
286
+ const buffer = await this.withViewport(
287
+ page,
288
+ options.viewport,
289
+ async () => {
290
+ if (options.delay) {
291
+ await page.waitForTimeout(options.delay);
292
+ }
293
+
294
+ return page.screenshot(screenshotOptions);
295
+ },
296
+ );
297
+
298
+ return buffer;
299
+ } catch (error) {
300
+ this.logger.error(
301
+ `Error taking screenshot of ${page.url()}:`,
302
+ (error as Error).message,
303
+ );
304
+ throw error;
305
+ }
306
+ }
307
+
214
308
  async takeScreenshotWithComparison(
215
309
  page: Page,
216
310
  filename: string,
217
311
  referenceImage: Buffer,
218
- options: ScreenshotOptions & {
312
+ options: ScreenshotSettings & {
219
313
  saveDiffImage?: boolean;
220
314
  diffImageFilename?: string;
221
315
  },
@@ -230,24 +324,20 @@ class ScreenshotTool {
230
324
 
231
325
  try {
232
326
  // Generate filename and take screenshot - save to actual directory
233
- const filepath = this.getActualFilePath(filename);
234
- fs.mkdirSync(path.dirname(filepath), { recursive: true });
327
+ const filepath = this.filesystem.getActualFilePath(filename);
235
328
 
236
- // Take screenshot and get buffer
237
- const screenshotOptions = {
329
+ const screenshotSettings: ScreenshotSettings = {
238
330
  fullPage: options.fullPage,
239
- type: "png" as const,
240
- timeout: 60000,
241
331
  mask: options.mask,
242
332
  omitBackground: options.omitBackground,
243
- scale: "css" as const,
244
- } satisfies PageScreenshotOptions;
333
+ delay: options.delay,
334
+ viewport: options.viewport,
335
+ };
245
336
 
246
337
  const retryScreenshot = await this.retryScreenshot(
247
338
  page,
248
- filename,
249
339
  referenceImage,
250
- screenshotOptions,
340
+ screenshotSettings,
251
341
  );
252
342
 
253
343
  if (!retryScreenshot.screenshotPath) {
@@ -255,7 +345,7 @@ class ScreenshotTool {
255
345
  }
256
346
 
257
347
  // Save screenshot to actual directory
258
- fs.writeFileSync(filepath, retryScreenshot.screenshotPath);
348
+ this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
259
349
  this.logger.success(`Screenshot saved: ${filepath}`);
260
350
 
261
351
  if (retryScreenshot.passed) {
@@ -274,17 +364,29 @@ class ScreenshotTool {
274
364
  ) {
275
365
  const diffFilename = options.diffImageFilename || filename;
276
366
  // Save to diff directory
277
- diffImagePath = this.getDiffFilePath(diffFilename);
367
+ diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
278
368
 
279
- fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
280
- fs.writeFileSync(
281
- diffImagePath,
369
+ this.filesystem.writeDiffFile(
370
+ diffFilename,
282
371
  retryScreenshot.comparisonResult.diffBuffer,
283
372
  );
284
373
 
285
374
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
286
375
  }
287
376
 
377
+ // different sizes diff image
378
+ if (retryScreenshot.comparisonResult.differentSizes) {
379
+ this.logger.warn(`Screenshot has different sizes than reference image`);
380
+
381
+ const diffFilename = options.diffImageFilename || filename;
382
+ diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
383
+ const diffBuffer = createDiffSizePngImage(200, 200);
384
+
385
+ this.filesystem.writeDiffFile(diffFilename, diffBuffer);
386
+
387
+ this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
388
+ }
389
+
288
390
  return {
289
391
  screenshotPath: filepath,
290
392
  comparisonResult: retryScreenshot.comparisonResult,
@@ -301,16 +403,12 @@ class ScreenshotTool {
301
403
 
302
404
  async retryScreenshot(
303
405
  page: Page,
304
- filename: string,
305
406
  referenceImage: Buffer,
306
- options: ScreenshotOptions & {
307
- saveDiffImage?: boolean;
308
- diffImageFilename?: string;
309
- },
407
+ options: ScreenshotSettings,
310
408
  ) {
311
409
  for (let i = 0; i < this.retries; i++) {
312
410
  try {
313
- const screenshotBuffer = await this.takeScreenshot(page, filename, {
411
+ const screenshotBuffer = await this.takeScreenshotBuffer(page, {
314
412
  ...options,
315
413
  delay: this.getIncBackoffDelay(i, options.delay || 0),
316
414
  });
@@ -323,9 +421,18 @@ class ScreenshotTool {
323
421
  screenshotBuffer,
324
422
  referenceImage,
325
423
  true,
326
- { ...this.diff, ...options },
424
+ this.diff,
327
425
  );
328
426
 
427
+ // bail early if the images are different sizes
428
+ if (comparisonResult.differentSizes) {
429
+ return {
430
+ screenshotPath: screenshotBuffer,
431
+ comparisonResult,
432
+ passed: false,
433
+ };
434
+ }
435
+
329
436
  // last retry
330
437
  if (i === this.retries - 1 && !comparisonResult.passed) {
331
438
  this.logger.error(
@@ -364,6 +471,286 @@ class ScreenshotTool {
364
471
  };
365
472
  }
366
473
 
474
+ getVariantFilename(filename: string, variant: ScreenshotVariant): string {
475
+ if (variant.filename) {
476
+ return variant.filename;
477
+ }
478
+
479
+ const parsed = path.parse(filename);
480
+ const sanitizedId = variant.id
481
+ .trim()
482
+ .replace(/[^a-zA-Z0-9_-]+/g, "-")
483
+ .replace(/-+/g, "-")
484
+ .replace(/^-|-$/g, "");
485
+ const suffix = sanitizedId || "variant";
486
+ const ext = parsed.ext || ".png";
487
+ const variantName = `${parsed.name}--${suffix}${ext}`;
488
+
489
+ return parsed.dir ? path.join(parsed.dir, variantName) : variantName;
490
+ }
491
+
492
+ /**
493
+ * Captures a single screenshot with the given options
494
+ */
495
+ private async captureSingleScreenshot(
496
+ page: Page,
497
+ filename: string,
498
+ options: ScreenshotSettings,
499
+ extras: {
500
+ saveDiffImage?: boolean;
501
+ diffImageFilename?: string;
502
+ } = {},
503
+ ): Promise<ScreenshotCaptureDetails> {
504
+ const result: ScreenshotCaptureDetails = { filename };
505
+
506
+ if (options.skip) {
507
+ result.skipped = true;
508
+ return result;
509
+ }
510
+
511
+ const saveDiff = extras.saveDiffImage ?? false;
512
+ const diffFilename = extras.diffImageFilename ?? filename;
513
+
514
+ if (this.filesystem.hasExpectedFile(filename)) {
515
+ const { screenshotPath, comparisonResult, diffImagePath } =
516
+ await this.takeScreenshotWithComparison(
517
+ page,
518
+ filename,
519
+ this.filesystem.readExpectedFile(filename),
520
+ {
521
+ ...options,
522
+ saveDiffImage: saveDiff,
523
+ diffImageFilename: diffFilename,
524
+ },
525
+ );
526
+
527
+ result.filepath = screenshotPath;
528
+ result.comparisonResult = comparisonResult;
529
+ result.diffImagePath = diffImagePath;
530
+ } else {
531
+ result.filepath = await this.takeScreenshot(page, filename, options);
532
+ }
533
+
534
+ return result;
535
+ }
536
+
537
+ async capture(
538
+ page: Page,
539
+ filename: string,
540
+ options: ScreenshotOptions,
541
+ extras: ScreenshotCaptureExtras = {},
542
+ ): Promise<ScreenshotCaptureResult> {
543
+ if (!this.browser) {
544
+ throw new Error("Browser not initialized");
545
+ }
546
+
547
+ const { variants = [], ...baseOptions } = options;
548
+ const baseResult: ScreenshotCaptureDetails = { filename };
549
+ const variantResults: ScreenshotVariantCaptureDetails[] = [];
550
+
551
+ const baseSaveDiff = extras.saveDiffImage ?? false;
552
+ const baseDiffFilename = extras.diffImageFilename ?? filename;
553
+
554
+ if (baseOptions.skip) {
555
+ return {
556
+ base: { ...baseResult, skipped: true },
557
+ variants: variants.map((variant) => ({
558
+ id: variant.id,
559
+ label: variant.label,
560
+ filename: this.getVariantFilename(filename, variant),
561
+ skipped: true,
562
+ })),
563
+ };
564
+ }
565
+
566
+ // Capture base screenshot
567
+ const baseCaptureResult = await this.captureSingleScreenshot(
568
+ page,
569
+ filename,
570
+ baseOptions,
571
+ {
572
+ saveDiffImage: baseSaveDiff,
573
+ diffImageFilename: baseDiffFilename,
574
+ },
575
+ );
576
+
577
+ baseResult.filepath = baseCaptureResult.filepath;
578
+ baseResult.comparisonResult = baseCaptureResult.comparisonResult;
579
+ baseResult.diffImagePath = baseCaptureResult.diffImagePath;
580
+ baseResult.skipped = baseCaptureResult.skipped;
581
+
582
+ for (const variant of variants) {
583
+ const variantFilename = this.getVariantFilename(filename, variant);
584
+ const variantOptions: ScreenshotSettings = {
585
+ ...baseOptions,
586
+ ...variant.options,
587
+ };
588
+
589
+ const variantResult: ScreenshotVariantCaptureDetails = {
590
+ id: variant.id,
591
+ label: variant.label,
592
+ filename: variantFilename,
593
+ };
594
+
595
+ if (variantOptions.skip) {
596
+ variantResult.skipped = true;
597
+ variantResults.push(variantResult);
598
+ continue;
599
+ }
600
+
601
+ const variantExtra = extras.variants?.[variant.id];
602
+ const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
603
+ const variantDiffFilename =
604
+ variantExtra?.diffImageFilename ?? variantFilename;
605
+
606
+ const variantCaptureResult = await this.captureSingleScreenshot(
607
+ page,
608
+ variantFilename,
609
+ variantOptions,
610
+ {
611
+ saveDiffImage: variantSaveDiff,
612
+ diffImageFilename: variantDiffFilename,
613
+ },
614
+ );
615
+
616
+ variantResult.filepath = variantCaptureResult.filepath;
617
+ variantResult.comparisonResult = variantCaptureResult.comparisonResult;
618
+ variantResult.diffImagePath = variantCaptureResult.diffImagePath;
619
+ variantResult.skipped = variantCaptureResult.skipped;
620
+
621
+ variantResults.push(variantResult);
622
+ }
623
+
624
+ return {
625
+ base: baseResult,
626
+ variants: variantResults,
627
+ };
628
+ }
629
+
630
+ /**
631
+ * Applies SVG and UI optimizations for screenshots
632
+ */
633
+ private async applyScreenshotOptimizations(page: Page) {
634
+ await page.addStyleTag({
635
+ content: `
636
+ *, *::before, *::after {
637
+ -moz-animation: none !important;
638
+ -moz-transition: none !important;
639
+ transition: none !important;
640
+ animation: none !important;
641
+ }
642
+ *, input, textarea { caret-color: transparent !important }
643
+ *:focus { outline: none !important }
644
+ *:focus-visible { outline: none !important }
645
+ *:focus-within { outline: none !important }
646
+ * { text-rendering: optimizeLegibility !important }
647
+ ::-webkit-scrollbar { display: none !important }
648
+ html { scroll-behavior: auto !important }
649
+ svg, svg * {
650
+ shape-rendering: crispEdges !important;
651
+ text-rendering: geometricPrecision !important;
652
+ vector-effect: non-scaling-stroke !important;
653
+ }
654
+ img { image-rendering: crisp-edges !important }
655
+ `,
656
+ });
657
+ }
658
+
659
+ /**
660
+ * Captures screenshots for multiple variants, each with their own URL
661
+ */
662
+ async captureWithVariants(
663
+ page: Page,
664
+ baseFilename: string,
665
+ baseUrl: string,
666
+ baseOptions: ScreenshotSettings,
667
+ variants: ScreenshotVariantWithUrl[],
668
+ extras: ScreenshotCaptureExtras = {},
669
+ ): Promise<ScreenshotCaptureResult> {
670
+ if (!this.browser) {
671
+ throw new Error("Browser not initialized");
672
+ }
673
+
674
+ const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };
675
+ const variantResults: ScreenshotVariantCaptureDetails[] = [];
676
+
677
+ const baseSaveDiff = extras.saveDiffImage ?? false;
678
+ const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
679
+
680
+ // Capture base screenshot
681
+ getLogger().debug(`Going to base URL: ${baseUrl}`);
682
+ await page.goto(baseUrl);
683
+ await this.applyScreenshotOptimizations(page);
684
+ const baseCaptureResult = await this.captureSingleScreenshot(
685
+ page,
686
+ baseFilename,
687
+ baseOptions,
688
+ {
689
+ saveDiffImage: baseSaveDiff,
690
+ diffImageFilename: baseDiffFilename,
691
+ },
692
+ );
693
+
694
+ baseResult.filepath = baseCaptureResult.filepath;
695
+ baseResult.comparisonResult = baseCaptureResult.comparisonResult;
696
+ baseResult.diffImagePath = baseCaptureResult.diffImagePath;
697
+ baseResult.skipped = baseCaptureResult.skipped;
698
+
699
+ // Capture variant screenshots
700
+ for (const variant of variants) {
701
+ const variantFilename =
702
+ variant.filename || this.getVariantFilename(baseFilename, variant);
703
+ const variantOptions: ScreenshotSettings = {
704
+ ...baseOptions,
705
+ ...variant.options,
706
+ };
707
+
708
+ const variantResult: ScreenshotVariantCaptureDetails = {
709
+ id: variant.id,
710
+ label: variant.label,
711
+ filename: variantFilename,
712
+ };
713
+
714
+ if (variantOptions.skip) {
715
+ variantResult.skipped = true;
716
+ variantResults.push(variantResult);
717
+ continue;
718
+ }
719
+
720
+ // Navigate to variant URL and apply optimizations
721
+ getLogger().debug(`Going to variant URL: ${variant.url}`);
722
+ await page.goto(variant.url);
723
+ await this.applyScreenshotOptimizations(page);
724
+
725
+ const variantExtra = extras.variants?.[variant.id];
726
+ const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
727
+ const variantDiffFilename =
728
+ variantExtra?.diffImageFilename ?? variantFilename;
729
+
730
+ const variantCaptureResult = await this.captureSingleScreenshot(
731
+ page,
732
+ variantFilename,
733
+ variantOptions,
734
+ {
735
+ saveDiffImage: variantSaveDiff,
736
+ diffImageFilename: variantDiffFilename,
737
+ },
738
+ );
739
+
740
+ variantResult.filepath = variantCaptureResult.filepath;
741
+ variantResult.comparisonResult = variantCaptureResult.comparisonResult;
742
+ variantResult.diffImagePath = variantCaptureResult.diffImagePath;
743
+ variantResult.skipped = variantCaptureResult.skipped;
744
+
745
+ variantResults.push(variantResult);
746
+ }
747
+
748
+ return {
749
+ base: baseResult,
750
+ variants: variantResults,
751
+ };
752
+ }
753
+
367
754
  /**
368
755
  * Gets the exponential backoff delay
369
756
  */
@@ -371,19 +758,25 @@ class ScreenshotTool {
371
758
  return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
372
759
  }
373
760
 
374
- // Utility method to check if expected image exists
375
- hasExpectedImage(filename: string): boolean {
376
- const expectedPath = this.getExpectedFilePath(filename);
377
- return fs.existsSync(expectedPath);
378
- }
761
+ /**
762
+ * Get a page from the pool by index
763
+ */
764
+ getPageFromPool(index: number): Page {
765
+ if (index < 0) {
766
+ throw new Error(`Page index ${index} must be non-negative`);
767
+ }
768
+
769
+ if (index >= this.pages.length) {
770
+ throw new Error(
771
+ `Page index ${index} exceeds pool size ${this.pages.length}`,
772
+ );
773
+ }
379
774
 
380
- // Utility method to get expected image as buffer (for future approval process)
381
- getExpectedImageBuffer(filename: string): Buffer {
382
- const expectedPath = this.getExpectedFilePath(filename);
383
- if (!fs.existsSync(expectedPath)) {
384
- throw new Error(`Expected image not found: ${expectedPath}`);
775
+ if (!this.pages[index]) {
776
+ throw new Error(`Page index ${index} is undefined`);
385
777
  }
386
- return fs.readFileSync(expectedPath);
778
+
779
+ return this.pages[index];
387
780
  }
388
781
  }
389
782