@cappa/core 0.6.3 → 0.7.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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  //#region \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -7,16 +7,12 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
9
  var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
- key = keys[i];
13
- if (!__hasOwnProp.call(to, key) && key !== except) {
14
- __defProp(to, key, {
15
- get: ((k) => from[k]).bind(null, key),
16
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
- });
18
- }
19
- }
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
20
16
  }
21
17
  return to;
22
18
  };
@@ -24,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
20
  value: mod,
25
21
  enumerable: true
26
22
  }) : target, mod));
27
-
28
23
  //#endregion
29
24
  let node_fs = require("node:fs");
30
25
  node_fs = __toESM(node_fs);
@@ -32,13 +27,13 @@ let _blazediff_gmsd = require("@blazediff/gmsd");
32
27
  _blazediff_gmsd = __toESM(_blazediff_gmsd);
33
28
  let _cappa_logger = require("@cappa/logger");
34
29
  let node_fs_promises = require("node:fs/promises");
30
+ node_fs_promises = __toESM(node_fs_promises);
35
31
  let pngjs = require("pngjs");
36
32
  let _blazediff_core = require("@blazediff/core");
37
33
  _blazediff_core = __toESM(_blazediff_core);
38
34
  let node_path = require("node:path");
39
35
  node_path = __toESM(node_path);
40
36
  let playwright_core = require("playwright-core");
41
-
42
37
  //#region src/features/png/util.ts
43
38
  const pngSignature = Buffer.from([
44
39
  137,
@@ -151,7 +146,6 @@ function extractTextMetadata(buffer) {
151
146
  }
152
147
  return metadata;
153
148
  }
154
-
155
149
  //#endregion
156
150
  //#region src/features/png/png.ts
157
151
  /**
@@ -218,7 +212,6 @@ var PNG = class PNG {
218
212
  await (0, node_fs_promises.writeFile)(targetPath, this.toBuffer(options));
219
213
  }
220
214
  };
221
-
222
215
  //#endregion
223
216
  //#region src/compare/gmsd.ts
224
217
  const compare$1 = (image1, image2, diff, width, height, options) => {
@@ -233,8 +226,7 @@ const compare$1 = (image1, image2, diff, width, height, options) => {
233
226
  * @returns Comparison result
234
227
  */
235
228
  async function compareImagesGMSD(image1, image2, withDiff = false, options = {}) {
236
- const png1 = await loadPNG$1(image1);
237
- const png2 = await loadPNG$1(image2);
229
+ const [png1, png2] = await Promise.all([loadPNG$1(image1), loadPNG$1(image2)]);
238
230
  const { width, height } = png1;
239
231
  if (width !== png2.width || height !== png2.height) return {
240
232
  gmsd: Infinity,
@@ -284,7 +276,6 @@ function annotateDiffImage$1(image, options) {
284
276
  async function imagesMatchGMSD(image1, image2, options = {}) {
285
277
  return (await compareImagesGMSD(image1, image2, false, options)).passed;
286
278
  }
287
-
288
279
  //#endregion
289
280
  //#region src/compare/pixel.ts
290
281
  const compare = (image1, image2, diff, width, height, options) => {
@@ -299,8 +290,7 @@ const compare = (image1, image2, diff, width, height, options) => {
299
290
  * @returns Comparison result
300
291
  */
301
292
  async function compareImages(image1, image2, withDiff = false, options = {}) {
302
- const png1 = await loadPNG(image1);
303
- const png2 = await loadPNG(image2);
293
+ const [png1, png2] = await Promise.all([loadPNG(image1), loadPNG(image2)]);
304
294
  const { width, height } = png1;
305
295
  if (width !== png2.width || height !== png2.height) return {
306
296
  numDiffPixels: 0,
@@ -386,7 +376,6 @@ function createDiffSizePngImage(width, height) {
386
376
  }
387
377
  return png.toBuffer();
388
378
  }
389
-
390
379
  //#endregion
391
380
  //#region src/config.ts
392
381
  /**
@@ -395,7 +384,6 @@ function createDiffSizePngImage(width, height) {
395
384
  function defineConfig(options) {
396
385
  return options;
397
386
  }
398
-
399
387
  //#endregion
400
388
  //#region src/filesystem.ts
401
389
  /**
@@ -409,9 +397,9 @@ var ScreenshotFileSystem = class {
409
397
  this.actual = node_path.default.resolve(outputDir, "actual");
410
398
  this.expected = node_path.default.resolve(outputDir, "expected");
411
399
  this.diff = node_path.default.resolve(outputDir, "diff");
412
- this.ensureParentDir(this.actual);
413
- this.ensureParentDir(this.expected);
414
- this.ensureParentDir(this.diff);
400
+ this.ensureParentDirSync(this.actual);
401
+ this.ensureParentDirSync(this.expected);
402
+ this.ensureParentDirSync(this.diff);
415
403
  }
416
404
  clearActual() {
417
405
  this.removeDir(this.actual);
@@ -461,7 +449,7 @@ var ScreenshotFileSystem = class {
461
449
  const actualPath = node_path.default.resolve(this.actual, relativePath);
462
450
  const expectedPath = node_path.default.resolve(this.expected, relativePath);
463
451
  const diffPath = node_path.default.resolve(this.diff, relativePath);
464
- this.ensureParentDir(expectedPath);
452
+ this.ensureParentDirSync(expectedPath);
465
453
  node_fs.default.copyFileSync(actualPath, expectedPath);
466
454
  if (node_fs.default.existsSync(diffPath)) {
467
455
  this.copyDiffMetadataToExpected(diffPath, expectedPath);
@@ -492,7 +480,14 @@ var ScreenshotFileSystem = class {
492
480
  * Ensure the parent directory of a file exists. If not, it creates it.
493
481
  * @param filePath - The path to the file.
494
482
  */
495
- ensureParentDir(filePath) {
483
+ async ensureParentDir(filePath) {
484
+ const dir = node_path.default.dirname(filePath);
485
+ await node_fs_promises.default.mkdir(dir, { recursive: true });
486
+ }
487
+ /**
488
+ * Synchronous version used only during constructor initialization.
489
+ */
490
+ ensureParentDirSync(filePath) {
496
491
  const dir = node_path.default.dirname(filePath);
497
492
  if (!node_fs.default.existsSync(dir)) node_fs.default.mkdirSync(dir, { recursive: true });
498
493
  }
@@ -545,33 +540,41 @@ var ScreenshotFileSystem = class {
545
540
  /**
546
541
  * Write a file to the actual directory
547
542
  */
548
- writeActualFile(filename, data) {
543
+ async writeActualFile(filename, data) {
549
544
  const filepath = this.getActualFilePath(filename);
550
- this.ensureParentDir(filepath);
551
- node_fs.default.writeFileSync(filepath, data);
545
+ await this.ensureParentDir(filepath);
546
+ await node_fs_promises.default.writeFile(filepath, data);
552
547
  }
553
548
  /**
554
549
  * Write a file to the diff directory
555
550
  */
556
- writeDiffFile(filename, data) {
551
+ async writeDiffFile(filename, data) {
557
552
  const filepath = this.getDiffFilePath(filename);
558
- this.ensureParentDir(filepath);
559
- node_fs.default.writeFileSync(filepath, data);
553
+ await this.ensureParentDir(filepath);
554
+ await node_fs_promises.default.writeFile(filepath, data);
560
555
  }
561
556
  /**
562
557
  * Check if an expected file exists
563
558
  */
564
- hasExpectedFile(filename) {
559
+ async hasExpectedFile(filename) {
565
560
  const expectedPath = this.getExpectedFilePath(filename);
566
- return node_fs.default.existsSync(expectedPath);
561
+ try {
562
+ await node_fs_promises.default.access(expectedPath);
563
+ return true;
564
+ } catch {
565
+ return false;
566
+ }
567
567
  }
568
568
  /**
569
569
  * Read an expected file
570
570
  */
571
- readExpectedFile(filename) {
571
+ async readExpectedFile(filename) {
572
572
  const expectedPath = this.getExpectedFilePath(filename);
573
- if (!node_fs.default.existsSync(expectedPath)) throw new Error(`Expected image not found: ${expectedPath}`);
574
- return node_fs.default.readFileSync(expectedPath);
573
+ try {
574
+ return await node_fs_promises.default.readFile(expectedPath);
575
+ } catch {
576
+ throw new Error(`Expected image not found: ${expectedPath}`);
577
+ }
575
578
  }
576
579
  /**
577
580
  * Resolve the actual path of a screenshot file.
@@ -588,7 +591,6 @@ var ScreenshotFileSystem = class {
588
591
  return relativePath;
589
592
  }
590
593
  };
591
-
592
594
  //#endregion
593
595
  //#region src/screenshot.ts
594
596
  const defaultPixelDiffConfig = {
@@ -674,20 +676,23 @@ var ScreenshotTool = class {
674
676
  }[this.browserType];
675
677
  if (!browserClass) throw new Error(`Unsupported browser type: ${this.browserType}`);
676
678
  this.browser = await browserClass.launch({ headless: this.headless });
677
- const defaultUserAgent = (await this.browser.newContext()).newPage().then((page) => page.evaluate(() => navigator.userAgent));
678
- this.contexts = [];
679
- this.pages = [];
680
- for (let i = 0; i < this.concurrency; i++) {
679
+ const tempCtx = await this.browser.newContext();
680
+ const defaultUserAgent = await (await tempCtx.newPage()).evaluate(() => navigator.userAgent);
681
+ await tempCtx.close();
682
+ const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
681
683
  const context = await this.browser.newContext({
682
684
  reducedMotion: "reduce",
683
685
  deviceScaleFactor: 2,
684
- userAgent: `${await defaultUserAgent} CappaStorybook`,
686
+ userAgent: `${defaultUserAgent} CappaStorybook`,
685
687
  viewport: this.viewport
686
688
  });
687
- const page = await context.newPage();
688
- this.contexts.push(context);
689
- this.pages.push(page);
690
- }
689
+ return {
690
+ context,
691
+ page: await context.newPage()
692
+ };
693
+ }));
694
+ this.contexts = results.map((r) => r.context);
695
+ this.pages = results.map((r) => r.page);
691
696
  this.context = this.contexts[0] ?? null;
692
697
  this.page = this.pages[0] ?? null;
693
698
  }
@@ -714,7 +719,7 @@ var ScreenshotTool = class {
714
719
  if (options.skip) return;
715
720
  try {
716
721
  const filepath = this.filesystem.getActualFilePath(filename);
717
- this.filesystem.ensureParentDir(filepath);
722
+ await this.filesystem.ensureParentDir(filepath);
718
723
  const screenshotOptions = {
719
724
  path: filepath,
720
725
  fullPage: options.fullPage ?? this.fullPage,
@@ -797,23 +802,23 @@ var ScreenshotTool = class {
797
802
  };
798
803
  const retryScreenshot = await this.retryScreenshot(page, referenceImage, screenshotSettings, diffOverride);
799
804
  if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
800
- this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
805
+ await this.filesystem.writeActualFile(filename, retryScreenshot.screenshotPath);
801
806
  this.logger.debug(`Actual screenshot saved: ${filepath}`);
802
807
  if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
803
808
  else this.logger.error(`Screenshot failed visual comparison`);
804
809
  let diffImagePath;
805
- if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
810
+ if (options.saveDiffImage && retryScreenshot.comparisonResult?.diffBuffer && !retryScreenshot.passed) {
806
811
  const diffFilename = options.diffImageFilename || filename;
807
812
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
808
- this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
813
+ await this.filesystem.writeDiffFile(diffFilename, retryScreenshot.comparisonResult.diffBuffer);
809
814
  this.logger.debug(`Diff image saved: ${diffImagePath}`);
810
815
  }
811
- if (typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
816
+ if (retryScreenshot.comparisonResult !== null && typeof retryScreenshot.comparisonResult === "object" && "differentSizes" in retryScreenshot.comparisonResult && retryScreenshot.comparisonResult.differentSizes) {
812
817
  this.logger.warn(`Screenshot has different sizes than reference image`);
813
818
  const diffFilename = options.diffImageFilename || filename;
814
819
  diffImagePath = this.filesystem.getDiffFilePath(diffFilename);
815
820
  const diffBuffer = createDiffSizePngImage(200, 200);
816
- this.filesystem.writeDiffFile(diffFilename, diffBuffer);
821
+ await this.filesystem.writeDiffFile(diffFilename, diffBuffer);
817
822
  this.logger.debug(`Diff Size image saved: ${diffImagePath}`);
818
823
  }
819
824
  return {
@@ -878,14 +883,15 @@ var ScreenshotTool = class {
878
883
  result.skipped = true;
879
884
  return result;
880
885
  }
886
+ const start = extras.captureStart ?? performance.now();
881
887
  const saveDiff = extras.saveDiffImage ?? false;
882
888
  const diffFilename = extras.diffImageFilename ?? filename;
883
889
  const diffOverride = extras.diff;
884
- if (!this.filesystem.hasExpectedFile(filename)) {
890
+ if (!await this.filesystem.hasExpectedFile(filename)) {
885
891
  this.logger.debug(`Expected image not found for ${filename}, taking screenshot`);
886
892
  result.filepath = await this.takeScreenshot(page, filename, options);
887
893
  } else {
888
- const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, this.filesystem.readExpectedFile(filename), {
894
+ const { screenshotPath, comparisonResult, diffImagePath } = await this.takeScreenshotWithComparison(page, filename, await this.filesystem.readExpectedFile(filename), {
889
895
  ...options,
890
896
  saveDiffImage: saveDiff,
891
897
  diffImageFilename: diffFilename
@@ -894,6 +900,8 @@ var ScreenshotTool = class {
894
900
  result.comparisonResult = comparisonResult;
895
901
  result.diffImagePath = diffImagePath;
896
902
  }
903
+ const duration = Math.round(performance.now() - start);
904
+ this.logger.debug(`${filename} captured in ${duration}ms`);
897
905
  return result;
898
906
  }
899
907
  async capture(page, filename, options, extras = {}) {
@@ -919,7 +927,8 @@ var ScreenshotTool = class {
919
927
  const baseCaptureResult = await this.captureSingleScreenshot(page, filename, baseOptions, {
920
928
  saveDiffImage: baseSaveDiff,
921
929
  diffImageFilename: baseDiffFilename,
922
- diff: baseDiffOverride
930
+ diff: baseDiffOverride,
931
+ captureStart: extras.captureStart
923
932
  });
924
933
  baseResult.filepath = baseCaptureResult.filepath;
925
934
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -997,13 +1006,19 @@ var ScreenshotTool = class {
997
1006
  const baseSaveDiff = extras.saveDiffImage ?? false;
998
1007
  const baseDiffFilename = extras.diffImageFilename ?? baseFilename;
999
1008
  const baseDiffOverride = extras.diff;
1000
- (0, _cappa_logger.getLogger)().debug(`Going to base URL: ${baseUrl}`);
1001
- await page.goto(baseUrl);
1002
- await this.applyScreenshotOptimizations(page);
1009
+ let baseStart;
1010
+ if (!extras.skipBaseNavigation) {
1011
+ baseStart = performance.now();
1012
+ (0, _cappa_logger.getLogger)().debug(`Going to base URL: ${baseUrl}`);
1013
+ await page.goto(baseUrl);
1014
+ await this.applyScreenshotOptimizations(page);
1015
+ await extras.waitForStability?.(page);
1016
+ }
1003
1017
  const baseCaptureResult = await this.captureSingleScreenshot(page, baseFilename, baseOptions, {
1004
1018
  saveDiffImage: baseSaveDiff,
1005
1019
  diffImageFilename: baseDiffFilename,
1006
- diff: baseDiffOverride
1020
+ diff: baseDiffOverride,
1021
+ captureStart: extras.captureStart ?? baseStart
1007
1022
  });
1008
1023
  baseResult.filepath = baseCaptureResult.filepath;
1009
1024
  baseResult.comparisonResult = baseCaptureResult.comparisonResult;
@@ -1025,9 +1040,11 @@ var ScreenshotTool = class {
1025
1040
  variantResults.push(variantResult);
1026
1041
  continue;
1027
1042
  }
1043
+ const variantStart = performance.now();
1028
1044
  (0, _cappa_logger.getLogger)().debug(`Going to variant URL: ${variant.url}`);
1029
1045
  await page.goto(variant.url);
1030
1046
  await this.applyScreenshotOptimizations(page);
1047
+ await extras.waitForStability?.(page);
1031
1048
  const variantExtra = extras.variants?.[variant.id];
1032
1049
  const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;
1033
1050
  const variantDiffFilename = variantExtra?.diffImageFilename ?? variantFilename;
@@ -1035,7 +1052,8 @@ var ScreenshotTool = class {
1035
1052
  const variantCaptureResult = await this.captureSingleScreenshot(page, variantFilename, variantOptions, {
1036
1053
  saveDiffImage: variantSaveDiff,
1037
1054
  diffImageFilename: variantDiffFilename,
1038
- diff: variantDiffOverride
1055
+ diff: variantDiffOverride,
1056
+ captureStart: variantStart
1039
1057
  });
1040
1058
  variantResult.filepath = variantCaptureResult.filepath;
1041
1059
  variantResult.comparisonResult = variantCaptureResult.comparisonResult;
@@ -1064,7 +1082,6 @@ var ScreenshotTool = class {
1064
1082
  return this.pages[index];
1065
1083
  }
1066
1084
  };
1067
-
1068
1085
  //#endregion
1069
1086
  exports.ScreenshotFileSystem = ScreenshotFileSystem;
1070
1087
  exports.ScreenshotTool = ScreenshotTool;
@@ -1073,4 +1090,5 @@ exports.compareImagesGMSD = compareImagesGMSD;
1073
1090
  exports.defineConfig = defineConfig;
1074
1091
  exports.imagesMatch = imagesMatch;
1075
1092
  exports.imagesMatchGMSD = imagesMatchGMSD;
1093
+
1076
1094
  //# sourceMappingURL=index.cjs.map