@cappa/core 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,22 @@ 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
+ } from "./types";
20
24
 
21
25
  const defaultDiffConfig: DiffConfig = {
22
26
  threshold: 0.1,
@@ -26,20 +30,52 @@ const defaultDiffConfig: DiffConfig = {
26
30
  maxDiffPercentage: 0,
27
31
  };
28
32
 
33
+ export interface ScreenshotCaptureDetails {
34
+ filename: string;
35
+ filepath?: string;
36
+ comparisonResult?: CompareResult;
37
+ diffImagePath?: string;
38
+ skipped?: boolean;
39
+ }
40
+
41
+ export interface ScreenshotVariantCaptureDetails
42
+ extends ScreenshotCaptureDetails {
43
+ id: string;
44
+ label?: string;
45
+ }
46
+
47
+ export interface ScreenshotCaptureResult {
48
+ base: ScreenshotCaptureDetails;
49
+ variants: ScreenshotVariantCaptureDetails[];
50
+ }
51
+
52
+ export interface ScreenshotCaptureExtras {
53
+ saveDiffImage?: boolean;
54
+ diffImageFilename?: string;
55
+ variants?: Record<
56
+ string,
57
+ {
58
+ saveDiffImage?: boolean;
59
+ diffImageFilename?: string;
60
+ }
61
+ >;
62
+ }
63
+
29
64
  class ScreenshotTool {
30
65
  browserType: "chromium" | "firefox" | "webkit";
31
66
  headless: boolean;
32
67
  viewport: { width: number; height: number };
33
68
  outputDir: string;
34
- actualDir: string;
35
- diffDir: string;
36
- expectedDir: string;
37
69
  browser: Browser | null = null;
38
70
  context: BrowserContext | null = null;
39
71
  page: Page | null = null;
72
+ concurrency: number;
73
+ contexts: BrowserContext[] = [];
74
+ pages: Page[] = [];
40
75
  diff: DiffConfig;
41
76
  logger: Logger;
42
77
  retries: number;
78
+ filesystem: ScreenshotFileSystem;
43
79
 
44
80
  constructor(options: {
45
81
  browserType?: "chromium" | "firefox" | "webkit";
@@ -48,28 +84,24 @@ class ScreenshotTool {
48
84
  outputDir?: string;
49
85
  diff?: DiffConfig;
50
86
  retries?: number;
87
+ concurrency?: number;
51
88
  }) {
52
89
  this.browserType = options.browserType || "chromium";
53
90
  this.headless = options.headless !== false; // Default to headless
54
91
  this.viewport = options.viewport || { width: 1920, height: 1080 };
55
92
  this.outputDir = options.outputDir || "./screenshots";
56
93
  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");
94
+ this.concurrency = Math.max(1, options.concurrency || 1);
61
95
 
62
96
  this.logger = getLogger();
63
97
  this.retries = options.retries || 2;
98
+ this.filesystem = new ScreenshotFileSystem(this.outputDir);
64
99
  }
65
100
 
66
101
  /**
67
102
  * Initialize playwright and page
68
103
  */
69
104
  async init() {
70
- // Create output directories if they don't exist
71
- this.createDirectories();
72
-
73
105
  // Launch browser based on type
74
106
  const browserMap = {
75
107
  chromium,
@@ -90,14 +122,26 @@ class ScreenshotTool {
90
122
  .newPage()
91
123
  .then((page) => page.evaluate(() => navigator.userAgent));
92
124
 
93
- this.context = await this.browser.newContext({
94
- reducedMotion: "reduce",
95
- deviceScaleFactor: 2,
96
- userAgent: `${await defaultUserAgent} CappaStorybook`,
97
- viewport: this.viewport,
98
- });
125
+ // Create N contexts and pages
126
+ this.contexts = [];
127
+ this.pages = [];
128
+
129
+ for (let i = 0; i < this.concurrency; i++) {
130
+ const context = await this.browser.newContext({
131
+ reducedMotion: "reduce",
132
+ deviceScaleFactor: 2,
133
+ userAgent: `${await defaultUserAgent} CappaStorybook`,
134
+ viewport: this.viewport,
135
+ });
136
+ const page = await context.newPage();
137
+
138
+ this.contexts.push(context);
139
+ this.pages.push(page);
140
+ }
99
141
 
100
- this.page = await this.context?.newPage();
142
+ // Backward compatibility
143
+ this.context = this.contexts[0] ?? null;
144
+ this.page = this.pages[0] ?? null;
101
145
  }
102
146
 
103
147
  /**
@@ -105,8 +149,8 @@ class ScreenshotTool {
105
149
  * If not closed, the process will not exit
106
150
  */
107
151
  async close() {
108
- if (this.context) {
109
- await this.context.close();
152
+ for (const context of this.contexts) {
153
+ await context.close();
110
154
  }
111
155
  if (this.browser) {
112
156
  await this.browser.close();
@@ -123,54 +167,13 @@ class ScreenshotTool {
123
167
  await page.goto(url, { waitUntil: "domcontentloaded" });
124
168
  }
125
169
 
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
170
  /**
168
171
  * Takes a screenshot of the page
169
172
  */
170
173
  async takeScreenshot(
171
174
  page: Page,
172
175
  filename: string,
173
- options: ScreenshotOptions,
176
+ options: ScreenshotSettings,
174
177
  ) {
175
178
  if (!this.browser) {
176
179
  throw new Error("Browser not initialized");
@@ -182,7 +185,7 @@ class ScreenshotTool {
182
185
 
183
186
  try {
184
187
  // Generate filename - save to actual directory
185
- const filepath = this.getActualFilePath(filename);
188
+ const filepath = this.filesystem.getActualFilePath(filename);
186
189
 
187
190
  // Take screenshot
188
191
  const screenshotOptions = {
@@ -193,13 +196,17 @@ class ScreenshotTool {
193
196
  mask: options.mask,
194
197
  omitBackground: options.omitBackground,
195
198
  scale: "css" as const,
199
+ animations: "disabled",
200
+ caret: "hide",
196
201
  } satisfies PageScreenshotOptions;
197
202
 
198
- if (options.delay) {
199
- await page.waitForTimeout(options.delay);
200
- }
203
+ await this.withViewport(page, options.viewport, async () => {
204
+ if (options.delay) {
205
+ await page.waitForTimeout(options.delay);
206
+ }
201
207
 
202
- await page.screenshot(screenshotOptions);
208
+ await page.screenshot(screenshotOptions);
209
+ });
203
210
 
204
211
  return filepath;
205
212
  } catch (error) {
@@ -211,11 +218,97 @@ class ScreenshotTool {
211
218
  }
212
219
  }
213
220
 
221
+ /**
222
+ * Sets the viewport size and executes the action, ensuring the original viewport is restored
223
+ * even if the action throws an error.
224
+ */
225
+ private async withViewport<T>(
226
+ page: Page,
227
+ viewport: ScreenshotSettings["viewport"],
228
+ action: () => Promise<T>,
229
+ ): Promise<T> {
230
+ if (!viewport) {
231
+ return action();
232
+ }
233
+
234
+ const previousViewport = page.viewportSize();
235
+
236
+ // Check if the new viewport is the same as the current one
237
+ if (
238
+ previousViewport &&
239
+ previousViewport.width === viewport.width &&
240
+ previousViewport.height === viewport.height
241
+ ) {
242
+ return action();
243
+ }
244
+
245
+ await page.setViewportSize(viewport);
246
+
247
+ try {
248
+ return await action();
249
+ } finally {
250
+ // Always restore the original viewport, even if the action throws an error
251
+ if (previousViewport) {
252
+ await page.setViewportSize(previousViewport);
253
+ }
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Takes a screenshot and returns the buffer (for comparison purposes)
259
+ */
260
+ async takeScreenshotBuffer(
261
+ page: Page,
262
+ options: ScreenshotSettings,
263
+ ): Promise<Buffer> {
264
+ if (!this.browser) {
265
+ throw new Error("Browser not initialized");
266
+ }
267
+
268
+ if (options.skip) {
269
+ throw new Error("Screenshot skipped");
270
+ }
271
+
272
+ try {
273
+ // Take screenshot without saving to file
274
+ const screenshotOptions = {
275
+ fullPage: options.fullPage,
276
+ type: "png" as const,
277
+ timeout: 60000,
278
+ mask: options.mask,
279
+ omitBackground: options.omitBackground,
280
+ scale: "css" as const,
281
+ animations: "disabled",
282
+ caret: "hide",
283
+ } satisfies PageScreenshotOptions;
284
+
285
+ const buffer = await this.withViewport(
286
+ page,
287
+ options.viewport,
288
+ async () => {
289
+ if (options.delay) {
290
+ await page.waitForTimeout(options.delay);
291
+ }
292
+
293
+ return page.screenshot(screenshotOptions);
294
+ },
295
+ );
296
+
297
+ return buffer;
298
+ } catch (error) {
299
+ this.logger.error(
300
+ `Error taking screenshot of ${page.url()}:`,
301
+ (error as Error).message,
302
+ );
303
+ throw error;
304
+ }
305
+ }
306
+
214
307
  async takeScreenshotWithComparison(
215
308
  page: Page,
216
309
  filename: string,
217
310
  referenceImage: Buffer,
218
- options: ScreenshotOptions & {
311
+ options: ScreenshotSettings & {
219
312
  saveDiffImage?: boolean;
220
313
  diffImageFilename?: string;
221
314
  },
@@ -230,24 +323,20 @@ class ScreenshotTool {
230
323
 
231
324
  try {
232
325
  // Generate filename and take screenshot - save to actual directory
233
- const filepath = this.getActualFilePath(filename);
234
- fs.mkdirSync(path.dirname(filepath), { recursive: true });
326
+ const filepath = this.filesystem.getActualFilePath(filename);
235
327
 
236
- // Take screenshot and get buffer
237
- const screenshotOptions = {
328
+ const screenshotSettings: ScreenshotSettings = {
238
329
  fullPage: options.fullPage,
239
- type: "png" as const,
240
- timeout: 60000,
241
330
  mask: options.mask,
242
331
  omitBackground: options.omitBackground,
243
- scale: "css" as const,
244
- } satisfies PageScreenshotOptions;
332
+ delay: options.delay,
333
+ viewport: options.viewport,
334
+ };
245
335
 
246
336
  const retryScreenshot = await this.retryScreenshot(
247
337
  page,
248
- filename,
249
338
  referenceImage,
250
- screenshotOptions,
339
+ screenshotSettings,
251
340
  );
252
341
 
253
342
  if (!retryScreenshot.screenshotPath) {
@@ -255,7 +344,7 @@ class ScreenshotTool {
255
344
  }
256
345
 
257
346
  // Save screenshot to actual directory
258
- fs.writeFileSync(filepath, retryScreenshot.screenshotPath);
347
+ this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
259
348
  this.logger.success(`Screenshot saved: ${filepath}`);
260
349
 
261
350
  if (retryScreenshot.passed) {
@@ -274,17 +363,29 @@ class ScreenshotTool {
274
363
  ) {
275
364
  const diffFilename = options.diffImageFilename || filename;
276
365
  // Save to diff directory
277
- diffImagePath = this.getDiffFilePath(diffFilename);
366
+ diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
278
367
 
279
- fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
280
- fs.writeFileSync(
281
- diffImagePath,
368
+ this.filesystem.writeDiffFile(
369
+ diffFilename,
282
370
  retryScreenshot.comparisonResult.diffBuffer,
283
371
  );
284
372
 
285
373
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
286
374
  }
287
375
 
376
+ // different sizes diff image
377
+ if (retryScreenshot.comparisonResult.differentSizes) {
378
+ this.logger.warn(`Screenshot has different sizes than reference image`);
379
+
380
+ const diffFilename = options.diffImageFilename || filename;
381
+ diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
382
+ const diffBuffer = createDiffSizePngImage(200, 200);
383
+
384
+ this.filesystem.writeDiffFile(diffFilename, diffBuffer);
385
+
386
+ this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
387
+ }
388
+
288
389
  return {
289
390
  screenshotPath: filepath,
290
391
  comparisonResult: retryScreenshot.comparisonResult,
@@ -301,16 +402,12 @@ class ScreenshotTool {
301
402
 
302
403
  async retryScreenshot(
303
404
  page: Page,
304
- filename: string,
305
405
  referenceImage: Buffer,
306
- options: ScreenshotOptions & {
307
- saveDiffImage?: boolean;
308
- diffImageFilename?: string;
309
- },
406
+ options: ScreenshotSettings,
310
407
  ) {
311
408
  for (let i = 0; i < this.retries; i++) {
312
409
  try {
313
- const screenshotBuffer = await this.takeScreenshot(page, filename, {
410
+ const screenshotBuffer = await this.takeScreenshotBuffer(page, {
314
411
  ...options,
315
412
  delay: this.getIncBackoffDelay(i, options.delay || 0),
316
413
  });
@@ -323,9 +420,18 @@ class ScreenshotTool {
323
420
  screenshotBuffer,
324
421
  referenceImage,
325
422
  true,
326
- { ...this.diff, ...options },
423
+ this.diff,
327
424
  );
328
425
 
426
+ // bail early if the images are different sizes
427
+ if (comparisonResult.differentSizes) {
428
+ return {
429
+ screenshotPath: screenshotBuffer,
430
+ comparisonResult,
431
+ passed: false,
432
+ };
433
+ }
434
+
329
435
  // last retry
330
436
  if (i === this.retries - 1 && !comparisonResult.passed) {
331
437
  this.logger.error(
@@ -364,6 +470,134 @@ class ScreenshotTool {
364
470
  };
365
471
  }
366
472
 
473
+ getVariantFilename(filename: string, variant: ScreenshotVariant): string {
474
+ if (variant.filename) {
475
+ return variant.filename;
476
+ }
477
+
478
+ const parsed = path.parse(filename);
479
+ const sanitizedId = variant.id
480
+ .trim()
481
+ .replace(/[^a-zA-Z0-9_-]+/g, "-")
482
+ .replace(/-+/g, "-")
483
+ .replace(/^-|-$/g, "");
484
+ const suffix = sanitizedId || "variant";
485
+ const ext = parsed.ext || ".png";
486
+ const variantName = `${parsed.name}--${suffix}${ext}`;
487
+
488
+ return parsed.dir ? path.join(parsed.dir, variantName) : variantName;
489
+ }
490
+
491
+ async capture(
492
+ page: Page,
493
+ filename: string,
494
+ options: ScreenshotOptions,
495
+ extras: ScreenshotCaptureExtras = {},
496
+ ): Promise<ScreenshotCaptureResult> {
497
+ if (!this.browser) {
498
+ throw new Error("Browser not initialized");
499
+ }
500
+
501
+ const { variants = [], ...baseOptions } = options;
502
+ const baseResult: ScreenshotCaptureDetails = { filename };
503
+ const variantResults: ScreenshotVariantCaptureDetails[] = [];
504
+
505
+ const baseSaveDiff = extras.saveDiffImage ?? false;
506
+ const baseDiffFilename = extras.diffImageFilename ?? filename;
507
+
508
+ if (baseOptions.skip) {
509
+ return {
510
+ base: { ...baseResult, skipped: true },
511
+ variants: variants.map((variant) => ({
512
+ id: variant.id,
513
+ label: variant.label,
514
+ filename: this.getVariantFilename(filename, variant),
515
+ skipped: true,
516
+ })),
517
+ };
518
+ }
519
+
520
+ if (this.filesystem.hasExpectedFile(filename)) {
521
+ const { screenshotPath, comparisonResult, diffImagePath } =
522
+ await this.takeScreenshotWithComparison(
523
+ page,
524
+ filename,
525
+ this.filesystem.readExpectedFile(filename),
526
+ {
527
+ ...baseOptions,
528
+ saveDiffImage: baseSaveDiff,
529
+ diffImageFilename: baseDiffFilename,
530
+ },
531
+ );
532
+
533
+ baseResult.filepath = screenshotPath;
534
+ baseResult.comparisonResult = comparisonResult;
535
+ baseResult.diffImagePath = diffImagePath;
536
+ } else {
537
+ baseResult.filepath = await this.takeScreenshot(
538
+ page,
539
+ filename,
540
+ baseOptions,
541
+ );
542
+ }
543
+
544
+ for (const variant of variants) {
545
+ const variantFilename = this.getVariantFilename(filename, variant);
546
+ const variantOptions: ScreenshotSettings = {
547
+ ...baseOptions,
548
+ ...variant.options,
549
+ };
550
+
551
+ const variantResult: ScreenshotVariantCaptureDetails = {
552
+ id: variant.id,
553
+ label: variant.label,
554
+ filename: variantFilename,
555
+ };
556
+
557
+ if (variantOptions.skip) {
558
+ variantResult.skipped = true;
559
+ variantResults.push(variantResult);
560
+ continue;
561
+ }
562
+
563
+ const variantExtra = extras.variants?.[variant.id];
564
+ const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
565
+ const variantDiffFilename =
566
+ variantExtra?.diffImageFilename ?? variantFilename;
567
+
568
+ if (this.filesystem.hasExpectedFile(variantFilename)) {
569
+ const { screenshotPath, comparisonResult, diffImagePath } =
570
+ await this.takeScreenshotWithComparison(
571
+ page,
572
+ variantFilename,
573
+ this.filesystem.readExpectedFile(variantFilename),
574
+ {
575
+ ...variantOptions,
576
+ saveDiffImage: variantSaveDiff,
577
+ diffImageFilename: variantDiffFilename,
578
+ },
579
+ );
580
+
581
+ variantResult.filepath = screenshotPath;
582
+ variantResult.comparisonResult = comparisonResult;
583
+ variantResult.diffImagePath = diffImagePath;
584
+ } else {
585
+ variantResult.filepath = await this.takeScreenshot(
586
+ page,
587
+ variantFilename,
588
+ variantOptions,
589
+ );
590
+ }
591
+
592
+ variantResults.push(variantResult);
593
+ }
594
+
595
+ return {
596
+ base: baseResult,
597
+ variants: variantResults,
598
+ };
599
+ }
600
+
367
601
  /**
368
602
  * Gets the exponential backoff delay
369
603
  */
@@ -371,19 +605,25 @@ class ScreenshotTool {
371
605
  return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
372
606
  }
373
607
 
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
- }
608
+ /**
609
+ * Get a page from the pool by index
610
+ */
611
+ getPageFromPool(index: number): Page {
612
+ if (index < 0) {
613
+ throw new Error(`Page index ${index} must be non-negative`);
614
+ }
379
615
 
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}`);
616
+ if (index >= this.pages.length) {
617
+ throw new Error(
618
+ `Page index ${index} exceeds pool size ${this.pages.length}`,
619
+ );
620
+ }
621
+
622
+ if (!this.pages[index]) {
623
+ throw new Error(`Page index ${index} is undefined`);
385
624
  }
386
- return fs.readFileSync(expectedPath);
625
+
626
+ return this.pages[index];
387
627
  }
388
628
  }
389
629
 
package/src/types.ts CHANGED
@@ -70,6 +70,10 @@ export type UserConfig = {
70
70
  * The number of times to retry a screenshot if it fails
71
71
  */
72
72
  retries?: number;
73
+ /**
74
+ * The number of parallel browser contexts to use for taking screenshots
75
+ */
76
+ concurrency?: number;
73
77
  /**
74
78
  * An array of Cappa plugins used for generation.
75
79
  * Each plugin may have additional configurable options (defined within the plugin itself).
@@ -77,12 +81,26 @@ export type UserConfig = {
77
81
  plugins?: Array<Plugin | PluginDef>;
78
82
  };
79
83
 
80
- export type ScreenshotOptions = {
84
+ export type Viewport = { width: number; height: number };
85
+
86
+ export type ScreenshotSettings = {
81
87
  fullPage?: boolean;
82
88
  delay?: number;
83
89
  skip?: boolean;
84
90
  mask?: Locator[];
85
91
  omitBackground?: boolean;
92
+ viewport?: Viewport;
93
+ };
94
+
95
+ export type ScreenshotVariant = {
96
+ id: string;
97
+ label?: string;
98
+ filename?: string;
99
+ options?: ScreenshotSettings;
100
+ };
101
+
102
+ export type ScreenshotOptions = ScreenshotSettings & {
103
+ variants?: ScreenshotVariant[];
86
104
  };
87
105
 
88
106
  export interface Screenshot {