@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/dist/index.mjs CHANGED
@@ -13,6 +13,167 @@ function defineConfig(options) {
13
13
  return options;
14
14
  }
15
15
 
16
+ //#endregion
17
+ //#region src/filesystem.ts
18
+ /**
19
+ * Class for interacting with the local file system to store the screenshots.
20
+ */
21
+ var ScreenshotFileSystem = class {
22
+ actualDir;
23
+ expectedDir;
24
+ diffDir;
25
+ constructor(outputDir) {
26
+ this.actualDir = path.resolve(outputDir, "actual");
27
+ this.expectedDir = path.resolve(outputDir, "expected");
28
+ this.diffDir = path.resolve(outputDir, "diff");
29
+ this.ensureParentDir(this.actualDir);
30
+ this.ensureParentDir(this.expectedDir);
31
+ this.ensureParentDir(this.diffDir);
32
+ }
33
+ clearActual() {
34
+ this.removeDir(this.actualDir);
35
+ }
36
+ clearDiff() {
37
+ this.removeDir(this.diffDir);
38
+ }
39
+ clearActualAndDiff() {
40
+ this.clearActual();
41
+ this.clearDiff();
42
+ }
43
+ /**
44
+ * Approve a screenshot based on its actual file path.
45
+ * @param actualFilePath - The path to the actual screenshot file.
46
+ * @returns The paths to the actual, expected, and diff screenshot files.
47
+ */
48
+ approveFromActualPath(actualFilePath) {
49
+ const actualAbsolute = this.resolveActualPath(actualFilePath);
50
+ const relativePath = path.relative(this.actualDir, actualAbsolute);
51
+ if (relativePath.startsWith("..")) throw new Error(`Cannot approve screenshot outside of actual directory: ${actualFilePath}`);
52
+ return this.approveRelative(relativePath);
53
+ }
54
+ /**
55
+ * Approve a screenshot based on its name.
56
+ * @param name - The name of the screenshot. Can include '.png' extension.
57
+ * @returns The paths to the actual, expected, and diff screenshot files.
58
+ */
59
+ approveByName(name) {
60
+ const relativeWithExtension = name.endsWith(".png") ? name : `${name}.png`;
61
+ return this.approveRelative(relativeWithExtension);
62
+ }
63
+ /**
64
+ * Approve a screenshot based on a relative path.
65
+ * @param relativePath - The relative path to the screenshot.
66
+ * @returns The paths to the actual, expected, and diff screenshot files.
67
+ */
68
+ approveRelative(relativePath) {
69
+ const actualPath = path.resolve(this.actualDir, relativePath);
70
+ const expectedPath = path.resolve(this.expectedDir, relativePath);
71
+ const diffPath = path.resolve(this.diffDir, relativePath);
72
+ this.ensureParentDir(expectedPath);
73
+ fs.copyFileSync(actualPath, expectedPath);
74
+ if (fs.existsSync(diffPath)) fs.unlinkSync(diffPath);
75
+ return {
76
+ actualPath,
77
+ expectedPath,
78
+ diffPath
79
+ };
80
+ }
81
+ /**
82
+ * Ensure the parent directory of a file exists. If not, it creates it.
83
+ * @param filePath - The path to the file.
84
+ */
85
+ ensureParentDir(filePath) {
86
+ const dir = path.dirname(filePath);
87
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
88
+ }
89
+ /**
90
+ * Remove a directory and all its contents.
91
+ * @param dir - The path to the directory.
92
+ */
93
+ removeDir(dir) {
94
+ if (fs.existsSync(dir)) fs.rmSync(dir, {
95
+ recursive: true,
96
+ force: true
97
+ });
98
+ }
99
+ /**
100
+ * Get the actual directory path
101
+ */
102
+ getActualDir() {
103
+ return this.actualDir;
104
+ }
105
+ /**
106
+ * Get the expected directory path
107
+ */
108
+ getExpectedDir() {
109
+ return this.expectedDir;
110
+ }
111
+ /**
112
+ * Get the diff directory path
113
+ */
114
+ getDiffDir() {
115
+ return this.diffDir;
116
+ }
117
+ /**
118
+ * Get the path to an actual screenshot file
119
+ */
120
+ getActualFilePath(filename) {
121
+ return path.resolve(this.actualDir, filename);
122
+ }
123
+ /**
124
+ * Get the path to an expected screenshot file
125
+ */
126
+ getExpectedFilePath(filename) {
127
+ return path.resolve(this.expectedDir, filename);
128
+ }
129
+ /**
130
+ * Get the path to a diff screenshot file
131
+ */
132
+ getDiffFilePath(filename) {
133
+ return path.resolve(this.diffDir, filename);
134
+ }
135
+ /**
136
+ * Write a file to the actual directory
137
+ */
138
+ writeActualFile(filename, data) {
139
+ const filepath = this.getActualFilePath(filename);
140
+ this.ensureParentDir(filepath);
141
+ fs.writeFileSync(filepath, data);
142
+ }
143
+ /**
144
+ * Write a file to the diff directory
145
+ */
146
+ writeDiffFile(filename, data) {
147
+ const filepath = this.getDiffFilePath(filename);
148
+ this.ensureParentDir(filepath);
149
+ fs.writeFileSync(filepath, data);
150
+ }
151
+ /**
152
+ * Check if an expected file exists
153
+ */
154
+ hasExpectedFile(filename) {
155
+ const expectedPath = this.getExpectedFilePath(filename);
156
+ return fs.existsSync(expectedPath);
157
+ }
158
+ /**
159
+ * Read an expected file
160
+ */
161
+ readExpectedFile(filename) {
162
+ const expectedPath = this.getExpectedFilePath(filename);
163
+ if (!fs.existsSync(expectedPath)) throw new Error(`Expected image not found: ${expectedPath}`);
164
+ return fs.readFileSync(expectedPath);
165
+ }
166
+ /**
167
+ * Resolve the actual path of a screenshot file.
168
+ * @param filePath - The path to the screenshot file.
169
+ * @returns The actual path of the screenshot file.
170
+ */
171
+ resolveActualPath(filePath) {
172
+ if (path.isAbsolute(filePath)) return filePath;
173
+ return path.resolve(this.actualDir, filePath);
174
+ }
175
+ };
176
+
16
177
  //#endregion
17
178
  //#region src/compare.ts
18
179
  const compare = (image1, image2, diff, width, height, options) => {
@@ -30,21 +191,40 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
30
191
  const png1 = await loadPNG(image1);
31
192
  const png2 = await loadPNG(image2);
32
193
  const { width, height } = png1;
194
+ if (width !== png2.width || height !== png2.height) return {
195
+ numDiffPixels: 0,
196
+ totalPixels: 0,
197
+ percentDifference: 0,
198
+ passed: false,
199
+ differentSizes: true
200
+ };
33
201
  const diff = withDiff ? new PNG({
34
202
  width,
35
203
  height
36
204
  }) : void 0;
37
- const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
38
- const totalPixels = width * height;
39
- const percentDifference = numDiffPixels / totalPixels * 100;
40
- const diffBuffer = diff ? PNG.sync.write(diff) : void 0;
41
- return {
42
- numDiffPixels,
43
- totalPixels,
44
- percentDifference,
45
- diffBuffer,
46
- passed: isPassed(percentDifference, numDiffPixels, options)
47
- };
205
+ try {
206
+ const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
207
+ const totalPixels = width * height;
208
+ const percentDifference = numDiffPixels / totalPixels * 100;
209
+ return {
210
+ numDiffPixels,
211
+ totalPixels,
212
+ percentDifference,
213
+ diffBuffer: diff ? PNG.sync.write(diff) : void 0,
214
+ passed: isPassed(percentDifference, numDiffPixels, options),
215
+ differentSizes: false
216
+ };
217
+ } catch (error) {
218
+ getLogger().error(error.message || "Unknown error");
219
+ return {
220
+ numDiffPixels: 0,
221
+ totalPixels: 0,
222
+ percentDifference: 0,
223
+ passed: false,
224
+ differentSizes: false,
225
+ error: error.message || "Unknown error"
226
+ };
227
+ }
48
228
  }
49
229
  /**
50
230
  * Load a PNG image from file path or Buffer
@@ -56,12 +236,37 @@ async function loadPNG(source) {
56
236
  return PNG.sync.read(buffer);
57
237
  }
58
238
  }
239
+ /**
240
+ * Check if the comparison passed based on the options
241
+ * @param percentDifference - Percentage difference between the images
242
+ * @param numDiffPixels - Number of different pixels
243
+ * @param options - Comparison options
244
+ * @returns Whether the comparison passed
245
+ */
59
246
  const isPassed = (percentDifference, numDiffPixels, options) => {
60
247
  if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
61
248
  if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
62
249
  if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
63
250
  return numDiffPixels === 0;
64
251
  };
252
+ /**
253
+ * Create different size png image with all pixels red
254
+ * @returns
255
+ */
256
+ function createDiffSizePngImage(width, height) {
257
+ const png = new PNG({
258
+ width,
259
+ height
260
+ });
261
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
262
+ const idx = width * y + x << 2;
263
+ png.data[idx] = 255;
264
+ png.data[idx + 1] = 0;
265
+ png.data[idx + 2] = 0;
266
+ png.data[idx + 3] = 255;
267
+ }
268
+ return PNG.sync.write(png);
269
+ }
65
270
 
66
271
  //#endregion
67
272
  //#region src/screenshot.ts
@@ -77,15 +282,16 @@ var ScreenshotTool = class {
77
282
  headless;
78
283
  viewport;
79
284
  outputDir;
80
- actualDir;
81
- diffDir;
82
- expectedDir;
83
285
  browser = null;
84
286
  context = null;
85
287
  page = null;
288
+ concurrency;
289
+ contexts = [];
290
+ pages = [];
86
291
  diff;
87
292
  logger;
88
293
  retries;
294
+ filesystem;
89
295
  constructor(options) {
90
296
  this.browserType = options.browserType || "chromium";
91
297
  this.headless = options.headless !== false;
@@ -98,17 +304,15 @@ var ScreenshotTool = class {
98
304
  ...defaultDiffConfig,
99
305
  ...options.diff
100
306
  };
101
- this.actualDir = path.join(this.outputDir, "actual");
102
- this.diffDir = path.join(this.outputDir, "diff");
103
- this.expectedDir = path.join(this.outputDir, "expected");
307
+ this.concurrency = Math.max(1, options.concurrency || 1);
104
308
  this.logger = getLogger();
105
309
  this.retries = options.retries || 2;
310
+ this.filesystem = new ScreenshotFileSystem(this.outputDir);
106
311
  }
107
312
  /**
108
313
  * Initialize playwright and page
109
314
  */
110
315
  async init() {
111
- this.createDirectories();
112
316
  const browserClass = {
113
317
  chromium,
114
318
  firefox,
@@ -117,20 +321,28 @@ var ScreenshotTool = class {
117
321
  if (!browserClass) throw new Error(`Unsupported browser type: ${this.browserType}`);
118
322
  this.browser = await browserClass.launch({ headless: this.headless });
119
323
  const defaultUserAgent = (await this.browser.newContext()).newPage().then((page) => page.evaluate(() => navigator.userAgent));
120
- this.context = await this.browser.newContext({
121
- reducedMotion: "reduce",
122
- deviceScaleFactor: 2,
123
- userAgent: `${await defaultUserAgent} CappaStorybook`,
124
- viewport: this.viewport
125
- });
126
- this.page = await this.context?.newPage();
324
+ this.contexts = [];
325
+ this.pages = [];
326
+ for (let i = 0; i < this.concurrency; i++) {
327
+ const context = await this.browser.newContext({
328
+ reducedMotion: "reduce",
329
+ deviceScaleFactor: 2,
330
+ userAgent: `${await defaultUserAgent} CappaStorybook`,
331
+ viewport: this.viewport
332
+ });
333
+ const page = await context.newPage();
334
+ this.contexts.push(context);
335
+ this.pages.push(page);
336
+ }
337
+ this.context = this.contexts[0] ?? null;
338
+ this.page = this.pages[0] ?? null;
127
339
  }
128
340
  /**
129
341
  * Closes browser
130
342
  * If not closed, the process will not exit
131
343
  */
132
344
  async close() {
133
- if (this.context) await this.context.close();
345
+ for (const context of this.contexts) await context.close();
134
346
  if (this.browser) await this.browser.close();
135
347
  }
136
348
  /**
@@ -141,46 +353,13 @@ var ScreenshotTool = class {
141
353
  await page.goto(url, { waitUntil: "domcontentloaded" });
142
354
  }
143
355
  /**
144
- * Creates directories for screenshots and other files
145
- */
146
- createDirectories() {
147
- const directories = [
148
- this.outputDir,
149
- this.actualDir,
150
- this.diffDir,
151
- this.expectedDir
152
- ];
153
- for (const dir of directories) if (!fs.existsSync(dir)) {
154
- fs.mkdirSync(dir, { recursive: true });
155
- this.logger.debug(`Initialized directory: ${dir}`);
156
- }
157
- }
158
- /**
159
- * Gets the path to the actual screenshot file
160
- */
161
- getActualFilePath(filename) {
162
- return path.join(this.actualDir, filename);
163
- }
164
- /**
165
- * Gets the path to the diff screenshot file
166
- */
167
- getDiffFilePath(filename) {
168
- return path.join(this.diffDir, filename);
169
- }
170
- /**
171
- * Gets the path to the expected screenshot file
172
- */
173
- getExpectedFilePath(filename) {
174
- return path.join(this.expectedDir, filename);
175
- }
176
- /**
177
356
  * Takes a screenshot of the page
178
357
  */
179
358
  async takeScreenshot(page, filename, options) {
180
359
  if (!this.browser) throw new Error("Browser not initialized");
181
360
  if (options.skip) return;
182
361
  try {
183
- const filepath = this.getActualFilePath(filename);
362
+ const filepath = this.filesystem.getActualFilePath(filename);
184
363
  const screenshotOptions = {
185
364
  path: filepath,
186
365
  fullPage: options.fullPage,
@@ -188,43 +367,93 @@ var ScreenshotTool = class {
188
367
  timeout: 6e4,
189
368
  mask: options.mask,
190
369
  omitBackground: options.omitBackground,
191
- scale: "css"
370
+ scale: "css",
371
+ animations: "disabled",
372
+ caret: "hide"
192
373
  };
193
- if (options.delay) await page.waitForTimeout(options.delay);
194
- await page.screenshot(screenshotOptions);
374
+ await this.withViewport(page, options.viewport, async () => {
375
+ if (options.delay) await page.waitForTimeout(options.delay);
376
+ await page.screenshot(screenshotOptions);
377
+ });
195
378
  return filepath;
196
379
  } catch (error) {
197
380
  this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
198
381
  throw error;
199
382
  }
200
383
  }
201
- async takeScreenshotWithComparison(page, filename, referenceImage, options) {
384
+ /**
385
+ * Sets the viewport size and executes the action, ensuring the original viewport is restored
386
+ * even if the action throws an error.
387
+ */
388
+ async withViewport(page, viewport, action) {
389
+ if (!viewport) return action();
390
+ const previousViewport = page.viewportSize();
391
+ if (previousViewport && previousViewport.width === viewport.width && previousViewport.height === viewport.height) return action();
392
+ await page.setViewportSize(viewport);
393
+ try {
394
+ return await action();
395
+ } finally {
396
+ if (previousViewport) await page.setViewportSize(previousViewport);
397
+ }
398
+ }
399
+ /**
400
+ * Takes a screenshot and returns the buffer (for comparison purposes)
401
+ */
402
+ async takeScreenshotBuffer(page, options) {
202
403
  if (!this.browser) throw new Error("Browser not initialized");
404
+ if (options.skip) throw new Error("Screenshot skipped");
203
405
  try {
204
- const filepath = this.getActualFilePath(filename);
205
- fs.mkdirSync(path.dirname(filepath), { recursive: true });
206
406
  const screenshotOptions = {
207
407
  fullPage: options.fullPage,
208
408
  type: "png",
209
409
  timeout: 6e4,
210
410
  mask: options.mask,
211
411
  omitBackground: options.omitBackground,
212
- scale: "css"
412
+ scale: "css",
413
+ animations: "disabled",
414
+ caret: "hide"
415
+ };
416
+ return await this.withViewport(page, options.viewport, async () => {
417
+ if (options.delay) await page.waitForTimeout(options.delay);
418
+ return page.screenshot(screenshotOptions);
419
+ });
420
+ } catch (error) {
421
+ this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
422
+ throw error;
423
+ }
424
+ }
425
+ async takeScreenshotWithComparison(page, filename, referenceImage, options) {
426
+ if (!this.browser) throw new Error("Browser not initialized");
427
+ try {
428
+ const filepath = this.filesystem.getActualFilePath(filename);
429
+ const screenshotSettings = {
430
+ fullPage: options.fullPage,
431
+ mask: options.mask,
432
+ omitBackground: options.omitBackground,
433
+ delay: options.delay,
434
+ viewport: options.viewport
213
435
  };
214
- const retryScreenshot = await this.retryScreenshot(page, filename, referenceImage, screenshotOptions);
436
+ const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings);
215
437
  if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
216
- fs.writeFileSync(filepath, retryScreenshot.screenshotPath);
438
+ this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
217
439
  this.logger.success(`Screenshot saved: ${filepath}`);
218
440
  if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
219
441
  else this.logger.error(`Screenshot failed visual comparison`);
220
442
  let diffImagePath;
221
443
  if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
222
444
  const diffFilename = options.diffImageFilename || filename;
223
- diffImagePath = this.getDiffFilePath(diffFilename);
224
- fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
225
- fs.writeFileSync(diffImagePath, retryScreenshot.comparisonResult.diffBuffer);
445
+ diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
446
+ this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
226
447
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
227
448
  }
449
+ if (retryScreenshot.comparisonResult.differentSizes) {
450
+ this.logger.warn(`Screenshot has different sizes than reference image`);
451
+ const diffFilename = options.diffImageFilename || filename;
452
+ diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
453
+ const diffBuffer = createDiffSizePngImage(200, 200);
454
+ this.filesystem.writeDiffFile(diffFilename, diffBuffer);
455
+ this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
456
+ }
228
457
  return {
229
458
  screenshotPath: filepath,
230
459
  comparisonResult: retryScreenshot.comparisonResult,
@@ -235,17 +464,19 @@ var ScreenshotTool = class {
235
464
  throw error;
236
465
  }
237
466
  }
238
- async retryScreenshot(page, filename, referenceImage, options) {
467
+ async retryScreenshot(page, referenceImage, options) {
239
468
  for (let i = 0; i < this.retries; i++) try {
240
- const screenshotBuffer = await this.takeScreenshot(page, filename, {
469
+ const screenshotBuffer = await this.takeScreenshotBuffer(page, {
241
470
  ...options,
242
471
  delay: this.getIncBackoffDelay(i, options.delay || 0)
243
472
  });
244
473
  if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
245
- const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
246
- ...this.diff,
247
- ...options
248
- });
474
+ const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, this.diff);
475
+ if (comparisonResult.differentSizes) return {
476
+ screenshotPath: screenshotBuffer,
477
+ comparisonResult,
478
+ passed: false
479
+ };
249
480
  if (i === this.retries - 1 && !comparisonResult.passed) {
250
481
  this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
251
482
  return {
@@ -269,24 +500,199 @@ var ScreenshotTool = class {
269
500
  passed: false
270
501
  };
271
502
  }
503
+ getVariantFilename(filename, variant) {
504
+ if (variant.filename) return variant.filename;
505
+ const parsed = path.parse(filename);
506
+ const suffix = variant.id.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "variant";
507
+ const ext = parsed.ext || ".png";
508
+ const variantName = `${parsed.name}--${suffix}${ext}`;
509
+ return parsed.dir ? path.join(parsed.dir, variantName) : variantName;
510
+ }
511
+ /**
512
+ * Captures a single screenshot with the given options
513
+ */
514
+ async captureSingleScreenshot(page, filename, options, extras = {}) {
515
+ const result = { filename };
516
+ if (options.skip) {
517
+ result.skipped = true;
518
+ return result;
519
+ }
520
+ const saveDiff = extras.saveDiffImage ?? false;
521
+ const diffFilename = extras.diffImageFilename ?? filename;
522
+ if (this.filesystem.hasExpectedFile(filename)) {
523
+ const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, this.filesystem.readExpectedFile(filename), {
524
+ ...options,
525
+ saveDiffImage: saveDiff,
526
+ diffImageFilename: diffFilename
527
+ });
528
+ result.filepath = screenshotPath;
529
+ result.comparisonResult = comparisonResult;
530
+ result.diffImagePath = diffImagePath;
531
+ } else result.filepath = await this.takeScreenshot(page, filename, options);
532
+ return result;
533
+ }
534
+ async capture(page, filename, options, extras = {}) {
535
+ if (!this.browser) throw new Error("Browser not initialized");
536
+ const { variants = [],...baseOptions } = options;
537
+ const baseResult = { filename };
538
+ const variantResults = [];
539
+ const baseSaveDiff = extras.saveDiffImage ?? false;
540
+ const baseDiffFilename = extras.diffImageFilename ?? filename;
541
+ if (baseOptions.skip) return {
542
+ base: {
543
+ ...baseResult,
544
+ skipped: true
545
+ },
546
+ variants: variants.map((variant) => ({
547
+ id: variant.id,
548
+ label: variant.label,
549
+ filename: this.getVariantFilename(filename, variant),
550
+ skipped: true
551
+ }))
552
+ };
553
+ const baseCaptureResult = await this.captureSingleScreenshot(page, filename, baseOptions, {
554
+ saveDiffImage: baseSaveDiff,
555
+ diffImageFilename: baseDiffFilename
556
+ });
557
+ baseResult.filepath = baseCaptureResult.filepath;
558
+ baseResult.comparisonResult = baseCaptureResult.comparisonResult;
559
+ baseResult.diffImagePath = baseCaptureResult.diffImagePath;
560
+ baseResult.skipped = baseCaptureResult.skipped;
561
+ for (const variant of variants) {
562
+ const variantFilename = this.getVariantFilename(filename, variant);
563
+ const variantOptions = {
564
+ ...baseOptions,
565
+ ...variant.options
566
+ };
567
+ const variantResult = {
568
+ id: variant.id,
569
+ label: variant.label,
570
+ filename: variantFilename
571
+ };
572
+ if (variantOptions.skip) {
573
+ variantResult.skipped = true;
574
+ variantResults.push(variantResult);
575
+ continue;
576
+ }
577
+ const variantExtra = extras.variants?.[variant.id];
578
+ const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
579
+ const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
580
+ const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
581
+ saveDiffImage: variantSaveDiff,
582
+ diffImageFilename: variantDiffFilename
583
+ });
584
+ variantResult.filepath = variantCaptureResult.filepath;
585
+ variantResult.comparisonResult = variantCaptureResult.comparisonResult;
586
+ variantResult.diffImagePath = variantCaptureResult.diffImagePath;
587
+ variantResult.skipped = variantCaptureResult.skipped;
588
+ variantResults.push(variantResult);
589
+ }
590
+ return {
591
+ base: baseResult,
592
+ variants: variantResults
593
+ };
594
+ }
595
+ /**
596
+ * Applies SVG and UI optimizations for screenshots
597
+ */
598
+ async applyScreenshotOptimizations(page) {
599
+ await page.addStyleTag({ content: `
600
+ *, *::before, *::after {
601
+ -moz-animation: none !important;
602
+ -moz-transition: none !important;
603
+ transition: none !important;
604
+ animation: none !important;
605
+ }
606
+ *, input, textarea { caret-color: transparent !important }
607
+ *:focus { outline: none !important }
608
+ *:focus-visible { outline: none !important }
609
+ *:focus-within { outline: none !important }
610
+ * { text-rendering: optimizeLegibility !important }
611
+ ::-webkit-scrollbar { display: none !important }
612
+ html { scroll-behavior: auto !important }
613
+ svg, svg * {
614
+ shape-rendering: crispEdges !important;
615
+ text-rendering: geometricPrecision !important;
616
+ vector-effect: non-scaling-stroke !important;
617
+ }
618
+ img { image-rendering: crisp-edges !important }
619
+ ` });
620
+ }
621
+ /**
622
+ * Captures screenshots for multiple variants, each with their own URL
623
+ */
624
+ async captureWithVariants(page, baseFilename, baseUrl, baseOptions, variants, extras = {}) {
625
+ if (!this.browser) throw new Error("Browser not initialized");
626
+ const baseResult = { filename: baseFilename };
627
+ const variantResults = [];
628
+ const baseSaveDiff = extras.saveDiffImage ?? false;
629
+ const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
630
+ getLogger().debug(`Going to base URL: ${baseUrl}`);
631
+ await page.goto(baseUrl);
632
+ await this.applyScreenshotOptimizations(page);
633
+ const baseCaptureResult = await this.captureSingleScreenshot(page, baseFilename, baseOptions, {
634
+ saveDiffImage: baseSaveDiff,
635
+ diffImageFilename: baseDiffFilename
636
+ });
637
+ baseResult.filepath = baseCaptureResult.filepath;
638
+ baseResult.comparisonResult = baseCaptureResult.comparisonResult;
639
+ baseResult.diffImagePath = baseCaptureResult.diffImagePath;
640
+ baseResult.skipped = baseCaptureResult.skipped;
641
+ for (const variant of variants) {
642
+ const variantFilename = variant.filename || this.getVariantFilename(baseFilename, variant);
643
+ const variantOptions = {
644
+ ...baseOptions,
645
+ ...variant.options
646
+ };
647
+ const variantResult = {
648
+ id: variant.id,
649
+ label: variant.label,
650
+ filename: variantFilename
651
+ };
652
+ if (variantOptions.skip) {
653
+ variantResult.skipped = true;
654
+ variantResults.push(variantResult);
655
+ continue;
656
+ }
657
+ getLogger().debug(`Going to variant URL: ${variant.url}`);
658
+ await page.goto(variant.url);
659
+ await this.applyScreenshotOptimizations(page);
660
+ const variantExtra = extras.variants?.[variant.id];
661
+ const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
662
+ const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
663
+ const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
664
+ saveDiffImage: variantSaveDiff,
665
+ diffImageFilename: variantDiffFilename
666
+ });
667
+ variantResult.filepath = variantCaptureResult.filepath;
668
+ variantResult.comparisonResult = variantCaptureResult.comparisonResult;
669
+ variantResult.diffImagePath = variantCaptureResult.diffImagePath;
670
+ variantResult.skipped = variantCaptureResult.skipped;
671
+ variantResults.push(variantResult);
672
+ }
673
+ return {
674
+ base: baseResult,
675
+ variants: variantResults
676
+ };
677
+ }
272
678
  /**
273
679
  * Gets the exponential backoff delay
274
680
  */
275
681
  getIncBackoffDelay(i, delay) {
276
682
  return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
277
683
  }
278
- hasExpectedImage(filename) {
279
- const expectedPath = this.getExpectedFilePath(filename);
280
- return fs.existsSync(expectedPath);
281
- }
282
- getExpectedImageBuffer(filename) {
283
- const expectedPath = this.getExpectedFilePath(filename);
284
- if (!fs.existsSync(expectedPath)) throw new Error(`Expected image not found: ${expectedPath}`);
285
- return fs.readFileSync(expectedPath);
684
+ /**
685
+ * Get a page from the pool by index
686
+ */
687
+ getPageFromPool(index) {
688
+ if (index < 0) throw new Error(`Page index ${index} must be non-negative`);
689
+ if (index >= this.pages.length) throw new Error(`Page index ${index} exceeds pool size ${this.pages.length}`);
690
+ if (!this.pages[index]) throw new Error(`Page index ${index} is undefined`);
691
+ return this.pages[index];
286
692
  }
287
693
  };
288
694
  var screenshot_default = ScreenshotTool;
289
695
 
290
696
  //#endregion
291
- export { screenshot_default as ScreenshotTool, defineConfig };
697
+ export { ScreenshotFileSystem, screenshot_default as ScreenshotTool, defineConfig };
292
698
  //# sourceMappingURL=index.mjs.map