@cappa/core 0.1.1 → 0.1.2

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,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { getLogger, type Logger } from "@cappa/logger";
3
4
  import {
4
5
  type Browser,
5
6
  type BrowserContext,
@@ -15,7 +16,7 @@ import {
15
16
  type CompareResult,
16
17
  compareImages,
17
18
  } from "./compare";
18
- import type { DiffConfig } from "./types";
19
+ import type { DiffConfig, ScreenshotOptions } from "./types";
19
20
 
20
21
  const defaultDiffConfig: DiffConfig = {
21
22
  threshold: 0.1,
@@ -26,39 +27,42 @@ const defaultDiffConfig: DiffConfig = {
26
27
  };
27
28
 
28
29
  class ScreenshotTool {
29
- browserType: string;
30
+ browserType: "chromium" | "firefox" | "webkit";
30
31
  headless: boolean;
31
32
  viewport: { width: number; height: number };
32
33
  outputDir: string;
33
34
  actualDir: string;
34
35
  diffDir: string;
35
36
  expectedDir: string;
36
- fullPage: boolean;
37
37
  browser: Browser | null = null;
38
38
  context: BrowserContext | null = null;
39
39
  page: Page | null = null;
40
40
  diff: DiffConfig;
41
+ logger: Logger;
41
42
 
42
43
  constructor(options: {
43
- browserType?: string;
44
+ browserType?: "chromium" | "firefox" | "webkit";
44
45
  headless?: boolean;
45
46
  viewport?: { width: number; height: number };
46
47
  outputDir?: string;
47
- fullPage?: boolean;
48
48
  diff?: DiffConfig;
49
49
  }) {
50
50
  this.browserType = options.browserType || "chromium";
51
51
  this.headless = options.headless !== false; // Default to headless
52
52
  this.viewport = options.viewport || { width: 1920, height: 1080 };
53
53
  this.outputDir = options.outputDir || "./screenshots";
54
- this.fullPage = options.fullPage !== false; // Default to full page
55
54
  this.diff = { ...defaultDiffConfig, ...options.diff };
56
55
  // Set up subdirectories
57
56
  this.actualDir = path.join(this.outputDir, "actual");
58
57
  this.diffDir = path.join(this.outputDir, "diff");
59
58
  this.expectedDir = path.join(this.outputDir, "expected");
59
+
60
+ this.logger = getLogger();
60
61
  }
61
62
 
63
+ /**
64
+ * Initialize playwright and page
65
+ */
62
66
  async init() {
63
67
  // Create output directories if they don't exist
64
68
  this.createDirectories();
@@ -70,8 +74,7 @@ class ScreenshotTool {
70
74
  webkit,
71
75
  };
72
76
 
73
- const browserClass =
74
- browserMap[this.browserType as keyof typeof browserMap];
77
+ const browserClass = browserMap[this.browserType];
75
78
  if (!browserClass) {
76
79
  throw new Error(`Unsupported browser type: ${this.browserType}`);
77
80
  }
@@ -88,12 +91,16 @@ class ScreenshotTool {
88
91
  reducedMotion: "reduce",
89
92
  deviceScaleFactor: 2,
90
93
  userAgent: `${await defaultUserAgent} CappaStorybook`,
94
+ viewport: this.viewport,
91
95
  });
92
96
 
93
97
  this.page = await this.context?.newPage();
94
- this.page?.setViewportSize(this.viewport);
95
98
  }
96
99
 
100
+ /**
101
+ * Closes browser
102
+ * If not closed, the process will not exit
103
+ */
97
104
  async close() {
98
105
  if (this.context) {
99
106
  await this.context.close();
@@ -103,6 +110,9 @@ class ScreenshotTool {
103
110
  }
104
111
  }
105
112
 
113
+ /**
114
+ * Navigates to a URL with "domcontentloaded" waitUntil
115
+ */
106
116
  async goTo(page: Page, url: string) {
107
117
  if (!this.context) {
108
118
  throw new Error("Browser not initialized");
@@ -110,6 +120,9 @@ class ScreenshotTool {
110
120
  await page.goto(url, { waitUntil: "domcontentloaded" });
111
121
  }
112
122
 
123
+ /**
124
+ * Creates directories for screenshots and other files
125
+ */
113
126
  private createDirectories() {
114
127
  // Create main output directory and subdirectories
115
128
  const directories = [
@@ -122,41 +135,48 @@ class ScreenshotTool {
122
135
  for (const dir of directories) {
123
136
  if (!fs.existsSync(dir)) {
124
137
  fs.mkdirSync(dir, { recursive: true });
125
- console.log(`Created directory: ${dir}`);
138
+ this.logger.debug(`Initialized directory: ${dir}`);
126
139
  }
127
140
  }
128
141
  }
129
142
 
143
+ /**
144
+ * Gets the path to the actual screenshot file
145
+ */
130
146
  getActualFilePath(filename: string): string {
131
147
  return path.join(this.actualDir, filename);
132
148
  }
133
149
 
150
+ /**
151
+ * Gets the path to the diff screenshot file
152
+ */
134
153
  getDiffFilePath(filename: string): string {
135
154
  return path.join(this.diffDir, filename);
136
155
  }
137
156
 
157
+ /**
158
+ * Gets the path to the expected screenshot file
159
+ */
138
160
  getExpectedFilePath(filename: string): string {
139
161
  return path.join(this.expectedDir, filename);
140
162
  }
141
163
 
142
- // Keep original method for backward compatibility
143
- getFilePath(filename: string) {
144
- return this.getActualFilePath(filename);
145
- }
146
-
164
+ /**
165
+ * Takes a screenshot of the page
166
+ */
147
167
  async takeScreenshot(
148
168
  page: Page,
149
169
  filename: string,
150
- options: {
151
- fullPage?: boolean;
152
- mask?: Locator[];
153
- omitBackground?: boolean;
154
- } = {},
170
+ options: ScreenshotOptions,
155
171
  ) {
156
172
  if (!this.browser) {
157
173
  throw new Error("Browser not initialized");
158
174
  }
159
175
 
176
+ if (options.skip) {
177
+ return;
178
+ }
179
+
160
180
  try {
161
181
  // Generate filename - save to actual directory
162
182
  const filepath = this.getActualFilePath(filename);
@@ -164,74 +184,28 @@ class ScreenshotTool {
164
184
  // Take screenshot
165
185
  const screenshotOptions = {
166
186
  path: filepath,
167
- fullPage:
168
- (options.fullPage as boolean) !== undefined
169
- ? options.fullPage
170
- : this.fullPage,
171
- type: "png",
187
+ fullPage: options.fullPage,
188
+ type: "png" as const,
172
189
  timeout: 60000,
173
190
  mask: options.mask,
174
191
  omitBackground: options.omitBackground,
175
192
  scale: "css" as const,
176
193
  } satisfies PageScreenshotOptions;
177
194
 
178
- await page.screenshot(screenshotOptions);
179
-
180
- console.log(`Screenshot saved: ${filepath}`);
181
- return filepath;
182
- } catch (error) {
183
- console.error(
184
- `Error taking screenshot of ${page.url()}:`,
185
- (error as Error).message,
186
- );
187
- throw error;
188
- }
189
- }
190
-
191
- async takeElementScreenshot(
192
- page: Page,
193
- selector: string,
194
- options: {
195
- filename?: string;
196
- fullPage?: boolean;
197
- } = {},
198
- ) {
199
- if (!this.browser) {
200
- throw new Error("Browser not initialized");
201
- }
202
-
203
- try {
204
- // Wait for element to be visible
205
- await page.waitForSelector(selector, { timeout: 10000 });
206
-
207
- const element = await page.$(selector);
208
- if (!element) {
209
- throw new Error(`Element not found: ${selector}`);
195
+ if (options.delay) {
196
+ await page.waitForTimeout(options.delay);
210
197
  }
211
198
 
212
- const filename =
213
- (options.filename as string | undefined) ||
214
- `${selector.replace(/[^a-zA-Z0-9]/g, "_")}.png`;
215
- // Save to actual directory
216
- const filepath = this.getActualFilePath(filename);
217
-
218
- const elementScreenshotOptions = {
219
- path: filepath,
220
- type: "png",
221
- } satisfies PageScreenshotOptions;
222
-
223
- await element.screenshot(elementScreenshotOptions);
199
+ await page.screenshot(screenshotOptions);
224
200
 
225
- console.log(`Element screenshot saved: ${filepath}`);
201
+ this.logger.success(`Screenshot saved: ${filepath}`);
226
202
  return filepath;
227
203
  } catch (error) {
228
- console.error(
229
- `Error taking element screenshot of ${page.url()}:`,
204
+ this.logger.error(
205
+ `Error taking screenshot of ${page.url()}:`,
230
206
  (error as Error).message,
231
207
  );
232
208
  throw error;
233
- } finally {
234
- await page.close();
235
209
  }
236
210
  }
237
211
 
@@ -265,10 +239,7 @@ class ScreenshotTool {
265
239
 
266
240
  // Take screenshot and get buffer
267
241
  const screenshotOptions = {
268
- fullPage:
269
- (options.fullPage as boolean) !== undefined
270
- ? options.fullPage
271
- : this.fullPage,
242
+ fullPage: options.fullPage,
272
243
  type: "png" as const,
273
244
  timeout: 60000,
274
245
  mask: options.mask,
@@ -282,7 +253,7 @@ class ScreenshotTool {
282
253
  // Save screenshot to actual directory
283
254
  fs.writeFileSync(filepath, screenshotBuffer);
284
255
 
285
- console.log(`Screenshot saved: ${filepath}`);
256
+ this.logger.success(`Screenshot saved: ${filepath}`);
286
257
 
287
258
  // Perform comparison
288
259
  const comparisonResult = await compareImages(
@@ -292,12 +263,16 @@ class ScreenshotTool {
292
263
  { ...this.diff, ...options.compareOptions },
293
264
  );
294
265
 
295
- console.log(
296
- `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${
297
- comparisonResult.passed ? "PASSED" : "FAILED"
298
- })`,
266
+ this.logger.debug(
267
+ `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,
299
268
  );
300
269
 
270
+ if (comparisonResult.passed) {
271
+ this.logger.success(`Screenshot passed visual comparison`);
272
+ } else {
273
+ this.logger.error(`Screenshot failed visual comparison`);
274
+ }
275
+
301
276
  let diffImagePath: string | undefined;
302
277
 
303
278
  // Save diff image if requested and there are differences
@@ -312,6 +287,8 @@ class ScreenshotTool {
312
287
 
313
288
  fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });
314
289
  fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
290
+
291
+ this.logger.debug(`Diff image saved: ${diffImagePath}`);
315
292
  }
316
293
 
317
294
  return {
@@ -320,7 +297,7 @@ class ScreenshotTool {
320
297
  diffImagePath,
321
298
  };
322
299
  } catch (error) {
323
- console.error(
300
+ this.logger.error(
324
301
  `Error taking screenshot with comparison of ${page.url()}:`,
325
302
  (error as Error).message,
326
303
  );
@@ -328,102 +305,6 @@ class ScreenshotTool {
328
305
  }
329
306
  }
330
307
 
331
- async batchScreenshots(urls: string[], options = {}) {
332
- const results: {
333
- url: string;
334
- success: boolean;
335
- filepath: string;
336
- error?: string;
337
- }[] = [];
338
-
339
- for (const url of urls) {
340
- try {
341
- const page = this.page;
342
- if (!page) {
343
- throw new Error("Page not initialized");
344
- }
345
- await this.goTo(page, url);
346
- const filepath = await this.takeScreenshot(page, url, options);
347
- results.push({ url, success: true, filepath });
348
- } catch (error) {
349
- results.push({
350
- url,
351
- success: false,
352
- error: (error as Error).message,
353
- filepath: "",
354
- });
355
- }
356
- }
357
-
358
- return results;
359
- }
360
-
361
- async takeResponsiveScreenshots(
362
- url: string,
363
- viewports: { width: number; height: number; name: string }[] = [
364
- { width: 1920, height: 1080, name: "desktop" },
365
- { width: 768, height: 1024, name: "tablet" },
366
- { width: 375, height: 667, name: "mobile" },
367
- ],
368
- options: {
369
- fullPage?: boolean;
370
- } = {},
371
- ) {
372
- if (!this.context) {
373
- throw new Error("Browser not initialized");
374
- }
375
-
376
- const results: {
377
- viewport: string;
378
- success: boolean;
379
- filepath: string;
380
- error?: string;
381
- }[] = [];
382
-
383
- for (const viewport of viewports) {
384
- try {
385
- const page = await this.context?.newPage();
386
- await page.setViewportSize(viewport);
387
-
388
- await page.goto(url, { waitUntil: "domcontentloaded" });
389
- await page.waitForTimeout(2000);
390
-
391
- const filename = `${viewport.name}.png`;
392
- // Save to actual directory
393
- const filepath = this.getActualFilePath(filename);
394
-
395
- const responsiveScreenshotOptions = {
396
- path: filepath,
397
- fullPage:
398
- (options.fullPage as boolean) !== undefined
399
- ? options.fullPage
400
- : this.fullPage,
401
- type: "png" as const,
402
- };
403
-
404
- await page.screenshot(responsiveScreenshotOptions);
405
-
406
- await page.close();
407
-
408
- console.log(`Responsive screenshot saved: ${filepath}`);
409
- results.push({ viewport: viewport.name, success: true, filepath });
410
- } catch (error) {
411
- console.error(
412
- `Error taking responsive screenshot for ${viewport.name}:`,
413
- (error as Error).message,
414
- );
415
- results.push({
416
- viewport: viewport.name,
417
- success: false,
418
- error: (error as Error).message,
419
- filepath: "",
420
- });
421
- }
422
- }
423
-
424
- return results;
425
- }
426
-
427
308
  // Utility method to check if expected image exists
428
309
  hasExpectedImage(filename: string): boolean {
429
310
  const expectedPath = this.getExpectedFilePath(filename);
package/src/types.ts CHANGED
@@ -1,13 +1,17 @@
1
+ import type { Locator } from "playwright-core";
1
2
  import type { Plugin, PluginDef } from "./plugin";
2
3
 
3
4
  export type PossiblePromise<T> = Promise<T> | T;
4
5
 
6
+ /**
7
+ * Configuration for the comparison of images
8
+ */
5
9
  export interface DiffConfig {
6
10
  /**
7
11
  * Matching threshold (0-1). Lower = more sensitive
8
12
  * Default = 0.1
9
13
  *
10
- * This affects how similar a pixel needs to be to the reference image to be considered the same.
14
+ * This affects how similar a pixel needs to be in the reference image to be considered the same.
11
15
  */
12
16
  threshold?: number;
13
17
  /**
@@ -55,34 +59,28 @@ export interface DiffConfig {
55
59
  */
56
60
  export type UserConfig = {
57
61
  /**
58
- * The project root directory, which can be either an absolute path or a path relative to the location of your `cappa.config.ts` file.
59
- * @default process.cwd()
62
+ * The directory to save screenshots and other files in
60
63
  */
61
- root?: string;
62
64
  outputDir?: string;
65
+ /**
66
+ * Configuration for the comparison of images
67
+ */
63
68
  diff?: DiffConfig;
64
69
  /**
65
- * An array of Cappa plugins used for generation. Each plugin may have additional configurable options (defined within the plugin itself). If a plugin relies on another plugin, an error will occur if the required dependency is missing. Refer to "pre" for more details.
70
+ * An array of Cappa plugins used for generation.
71
+ * Each plugin may have additional configurable options (defined within the plugin itself).
66
72
  */
67
73
  plugins?: Array<Plugin | PluginDef>;
68
74
  };
69
75
 
70
76
  export type ScreenshotOptions = {
71
77
  fullPage?: boolean;
72
- waitForSelector?: string;
73
- waitForTimeout?: number;
74
78
  delay?: number;
75
79
  skip?: boolean;
76
- mask?: string[];
80
+ mask?: Locator[];
77
81
  omitBackground?: boolean;
78
82
  };
79
83
 
80
- export interface Exposed {
81
- emitCapture(opt: ScreenshotOptions): void;
82
- getBaseScreenshotOptions(): ScreenshotOptions;
83
- waitBrowserMetricsStable(): Promise<void>;
84
- }
85
-
86
84
  export interface Screenshot {
87
85
  id: string;
88
86
  name: string;