@cappa/core 0.1.1 → 0.1.3

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.js CHANGED
@@ -25,6 +25,8 @@ let node_fs = require("node:fs");
25
25
  node_fs = __toESM(node_fs);
26
26
  let node_path = require("node:path");
27
27
  node_path = __toESM(node_path);
28
+ let __cappa_logger = require("@cappa/logger");
29
+ __cappa_logger = __toESM(__cappa_logger);
28
30
  let playwright_core = require("playwright-core");
29
31
  playwright_core = __toESM(playwright_core);
30
32
  let __blazediff_core = require("@blazediff/core");
@@ -34,7 +36,7 @@ pngjs = __toESM(pngjs);
34
36
 
35
37
  //#region src/config.ts
36
38
  /**
37
- * Type helper to make it easier to use vite.config.ts accepts a direct UserConfig object, or a function that returns it. The function receives a ConfigEnv object.
39
+ * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.
38
40
  */
39
41
  function defineConfig(options) {
40
42
  return options;
@@ -51,10 +53,9 @@ const compare = (image1, image2, diff, width, height, options) => {
51
53
  * @param image2 - Second image (file path or Buffer)
52
54
  * @param withDiff - Whether to create a diff image
53
55
  * @param options - Comparison options
54
- * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)
55
56
  * @returns Comparison result
56
57
  */
57
- async function compareImages(image1, image2, withDiff = false, options) {
58
+ async function compareImages(image1, image2, withDiff = false, options = {}) {
58
59
  const png1 = await loadPNG(image1);
59
60
  const png2 = await loadPNG(image2);
60
61
  const { width, height } = png1;
@@ -65,14 +66,13 @@ async function compareImages(image1, image2, withDiff = false, options) {
65
66
  const numDiffPixels = compare(png1.data, png2.data, diff?.data, width, height, options);
66
67
  const totalPixels = width * height;
67
68
  const percentDifference = numDiffPixels / totalPixels * 100;
68
- const passed = percentDifference <= (options.maxDiffPercentage || 0);
69
69
  const diffBuffer = diff ? pngjs.PNG.sync.write(diff) : void 0;
70
70
  return {
71
71
  numDiffPixels,
72
72
  totalPixels,
73
73
  percentDifference,
74
74
  diffBuffer,
75
- passed
75
+ passed: isPassed(percentDifference, numDiffPixels, options)
76
76
  };
77
77
  }
78
78
  /**
@@ -85,6 +85,12 @@ async function loadPNG(source) {
85
85
  return pngjs.PNG.sync.read(buffer);
86
86
  }
87
87
  }
88
+ const isPassed = (percentDifference, numDiffPixels, options) => {
89
+ if (options.maxDiffPercentage && options.maxDiffPixels) return percentDifference <= options.maxDiffPercentage && numDiffPixels <= options.maxDiffPixels;
90
+ if (options.maxDiffPercentage) return percentDifference <= options.maxDiffPercentage;
91
+ if (options.maxDiffPixels) return numDiffPixels <= options.maxDiffPixels;
92
+ return numDiffPixels === 0;
93
+ };
88
94
 
89
95
  //#endregion
90
96
  //#region src/screenshot.ts
@@ -103,11 +109,12 @@ var ScreenshotTool = class {
103
109
  actualDir;
104
110
  diffDir;
105
111
  expectedDir;
106
- fullPage;
107
112
  browser = null;
108
113
  context = null;
109
114
  page = null;
110
115
  diff;
116
+ logger;
117
+ retries;
111
118
  constructor(options) {
112
119
  this.browserType = options.browserType || "chromium";
113
120
  this.headless = options.headless !== false;
@@ -116,7 +123,6 @@ var ScreenshotTool = class {
116
123
  height: 1080
117
124
  };
118
125
  this.outputDir = options.outputDir || "./screenshots";
119
- this.fullPage = options.fullPage !== false;
120
126
  this.diff = {
121
127
  ...defaultDiffConfig,
122
128
  ...options.diff
@@ -124,7 +130,12 @@ var ScreenshotTool = class {
124
130
  this.actualDir = node_path.default.join(this.outputDir, "actual");
125
131
  this.diffDir = node_path.default.join(this.outputDir, "diff");
126
132
  this.expectedDir = node_path.default.join(this.outputDir, "expected");
133
+ this.logger = (0, __cappa_logger.getLogger)();
134
+ this.retries = options.retries || 2;
127
135
  }
136
+ /**
137
+ * Initialize playwright and page
138
+ */
128
139
  async init() {
129
140
  this.createDirectories();
130
141
  const browserClass = {
@@ -138,19 +149,29 @@ var ScreenshotTool = class {
138
149
  this.context = await this.browser.newContext({
139
150
  reducedMotion: "reduce",
140
151
  deviceScaleFactor: 2,
141
- userAgent: `${await defaultUserAgent} CappaStorybook`
152
+ userAgent: `${await defaultUserAgent} CappaStorybook`,
153
+ viewport: this.viewport
142
154
  });
143
155
  this.page = await this.context?.newPage();
144
- this.page?.setViewportSize(this.viewport);
145
156
  }
157
+ /**
158
+ * Closes browser
159
+ * If not closed, the process will not exit
160
+ */
146
161
  async close() {
147
162
  if (this.context) await this.context.close();
148
163
  if (this.browser) await this.browser.close();
149
164
  }
165
+ /**
166
+ * Navigates to a URL with "domcontentloaded" waitUntil
167
+ */
150
168
  async goTo(page, url) {
151
169
  if (!this.context) throw new Error("Browser not initialized");
152
170
  await page.goto(url, { waitUntil: "domcontentloaded" });
153
171
  }
172
+ /**
173
+ * Creates directories for screenshots and other files
174
+ */
154
175
  createDirectories() {
155
176
  const directories = [
156
177
  this.outputDir,
@@ -160,173 +181,128 @@ var ScreenshotTool = class {
160
181
  ];
161
182
  for (const dir of directories) if (!node_fs.default.existsSync(dir)) {
162
183
  node_fs.default.mkdirSync(dir, { recursive: true });
163
- console.log(`Created directory: ${dir}`);
184
+ this.logger.debug(`Initialized directory: ${dir}`);
164
185
  }
165
186
  }
187
+ /**
188
+ * Gets the path to the actual screenshot file
189
+ */
166
190
  getActualFilePath(filename) {
167
191
  return node_path.default.join(this.actualDir, filename);
168
192
  }
193
+ /**
194
+ * Gets the path to the diff screenshot file
195
+ */
169
196
  getDiffFilePath(filename) {
170
197
  return node_path.default.join(this.diffDir, filename);
171
198
  }
199
+ /**
200
+ * Gets the path to the expected screenshot file
201
+ */
172
202
  getExpectedFilePath(filename) {
173
203
  return node_path.default.join(this.expectedDir, filename);
174
204
  }
175
- getFilePath(filename) {
176
- return this.getActualFilePath(filename);
177
- }
178
- async takeScreenshot(page, filename, options = {}) {
205
+ /**
206
+ * Takes a screenshot of the page
207
+ */
208
+ async takeScreenshot(page, filename, options) {
179
209
  if (!this.browser) throw new Error("Browser not initialized");
210
+ if (options.skip) return;
180
211
  try {
181
212
  const filepath = this.getActualFilePath(filename);
182
213
  const screenshotOptions = {
183
214
  path: filepath,
184
- fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
215
+ fullPage: options.fullPage,
185
216
  type: "png",
186
217
  timeout: 6e4,
187
218
  mask: options.mask,
188
219
  omitBackground: options.omitBackground,
189
220
  scale: "css"
190
221
  };
222
+ if (options.delay) await page.waitForTimeout(options.delay);
191
223
  await page.screenshot(screenshotOptions);
192
- console.log(`Screenshot saved: ${filepath}`);
193
- return filepath;
194
- } catch (error) {
195
- console.error(`Error taking screenshot of ${page.url()}:`, error.message);
196
- throw error;
197
- }
198
- }
199
- async takeElementScreenshot(page, selector, options = {}) {
200
- if (!this.browser) throw new Error("Browser not initialized");
201
- try {
202
- await page.waitForSelector(selector, { timeout: 1e4 });
203
- const element = await page.$(selector);
204
- if (!element) throw new Error(`Element not found: ${selector}`);
205
- const filename = options.filename || `${selector.replace(/[^a-zA-Z0-9]/g, "_")}.png`;
206
- const filepath = this.getActualFilePath(filename);
207
- const elementScreenshotOptions = {
208
- path: filepath,
209
- type: "png"
210
- };
211
- await element.screenshot(elementScreenshotOptions);
212
- console.log(`Element screenshot saved: ${filepath}`);
213
224
  return filepath;
214
225
  } catch (error) {
215
- console.error(`Error taking element screenshot of ${page.url()}:`, error.message);
226
+ this.logger.error(`Error taking screenshot of ${page.url()}:`, error.message);
216
227
  throw error;
217
- } finally {
218
- await page.close();
219
228
  }
220
229
  }
221
- async takeScreenshotWithComparison(page, filename, referenceImage, options = {}) {
230
+ async takeScreenshotWithComparison(page, filename, referenceImage, options) {
222
231
  if (!this.browser) throw new Error("Browser not initialized");
223
232
  try {
224
233
  const filepath = this.getActualFilePath(filename);
225
234
  node_fs.default.mkdirSync(node_path.default.dirname(filepath), { recursive: true });
226
235
  const screenshotOptions = {
227
- fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
236
+ fullPage: options.fullPage,
228
237
  type: "png",
229
238
  timeout: 6e4,
230
239
  mask: options.mask,
231
240
  omitBackground: options.omitBackground,
232
241
  scale: "css"
233
242
  };
234
- const screenshotBuffer = await page.screenshot(screenshotOptions);
235
- node_fs.default.writeFileSync(filepath, screenshotBuffer);
236
- console.log(`Screenshot saved: ${filepath}`);
237
- const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
238
- ...this.diff,
239
- ...options.compareOptions
240
- });
241
- console.log(`Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${comparisonResult.passed ? "PASSED" : "FAILED"})`);
243
+ const retryScreenshot = await this.retryScreenshot(page, filename, referenceImage, screenshotOptions);
244
+ if (!retryScreenshot.screenshotPath) throw new Error("Screenshot buffer is undefined");
245
+ node_fs.default.writeFileSync(filepath, retryScreenshot.screenshotPath);
246
+ this.logger.success(`Screenshot saved: ${filepath}`);
247
+ if (retryScreenshot.passed) this.logger.success(`Screenshot passed visual comparison`);
248
+ else this.logger.error(`Screenshot failed visual comparison`);
242
249
  let diffImagePath;
243
- if (options.saveDiffImage && comparisonResult.diffBuffer && !comparisonResult.passed) {
250
+ if (options.saveDiffImage && retryScreenshot.comparisonResult.diffBuffer && !retryScreenshot.passed) {
244
251
  const diffFilename = options.diffImageFilename || filename;
245
252
  diffImagePath = this.getDiffFilePath(diffFilename);
246
253
  node_fs.default.mkdirSync(node_path.default.dirname(diffImagePath), { recursive: true });
247
- node_fs.default.writeFileSync(diffImagePath, comparisonResult.diffBuffer);
254
+ node_fs.default.writeFileSync(diffImagePath, retryScreenshot.comparisonResult.diffBuffer);
255
+ this.logger.debug(`Diff image saved: ${diffImagePath}`);
248
256
  }
249
257
  return {
250
258
  screenshotPath: filepath,
251
- comparisonResult,
259
+ comparisonResult: retryScreenshot.comparisonResult,
252
260
  diffImagePath
253
261
  };
254
262
  } catch (error) {
255
- console.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
263
+ this.logger.error(`Error taking screenshot with comparison of ${page.url()}:`, error.message);
256
264
  throw error;
257
265
  }
258
266
  }
259
- async batchScreenshots(urls, options = {}) {
260
- const results = [];
261
- for (const url of urls) try {
262
- const page = this.page;
263
- if (!page) throw new Error("Page not initialized");
264
- await this.goTo(page, url);
265
- const filepath = await this.takeScreenshot(page, url, options);
266
- results.push({
267
- url,
268
- success: true,
269
- filepath
267
+ async retryScreenshot(page, filename, referenceImage, options) {
268
+ for (let i = 0; i < this.retries; i++) try {
269
+ const screenshotBuffer = await this.takeScreenshot(page, filename, {
270
+ ...options,
271
+ delay: this.getIncBackoffDelay(i, options.delay || 0)
270
272
  });
271
- } catch (error) {
272
- results.push({
273
- url,
274
- success: false,
275
- error: error.message,
276
- filepath: ""
273
+ if (!screenshotBuffer) throw new Error("Screenshot buffer is undefined");
274
+ const comparisonResult = await compareImages(screenshotBuffer, referenceImage, true, {
275
+ ...this.diff,
276
+ ...options
277
277
  });
278
- }
279
- return results;
280
- }
281
- async takeResponsiveScreenshots(url, viewports = [
282
- {
283
- width: 1920,
284
- height: 1080,
285
- name: "desktop"
286
- },
287
- {
288
- width: 768,
289
- height: 1024,
290
- name: "tablet"
291
- },
292
- {
293
- width: 375,
294
- height: 667,
295
- name: "mobile"
296
- }
297
- ], options = {}) {
298
- if (!this.context) throw new Error("Browser not initialized");
299
- const results = [];
300
- for (const viewport of viewports) try {
301
- const page = await this.context?.newPage();
302
- await page.setViewportSize(viewport);
303
- await page.goto(url, { waitUntil: "domcontentloaded" });
304
- await page.waitForTimeout(2e3);
305
- const filename = `${viewport.name}.png`;
306
- const filepath = this.getActualFilePath(filename);
307
- const responsiveScreenshotOptions = {
308
- path: filepath,
309
- fullPage: options.fullPage !== void 0 ? options.fullPage : this.fullPage,
310
- type: "png"
278
+ if (i === this.retries - 1 && !comparisonResult.passed) {
279
+ this.logger.error(`Failed to match screenshot after ${this.retries} retries`);
280
+ return {
281
+ screenshotPath: screenshotBuffer,
282
+ comparisonResult,
283
+ passed: false
284
+ };
285
+ }
286
+ if (comparisonResult.passed) return {
287
+ screenshotPath: screenshotBuffer,
288
+ comparisonResult,
289
+ passed: true
311
290
  };
312
- await page.screenshot(responsiveScreenshotOptions);
313
- await page.close();
314
- console.log(`Responsive screenshot saved: ${filepath}`);
315
- results.push({
316
- viewport: viewport.name,
317
- success: true,
318
- filepath
319
- });
291
+ else this.logger.warn(`Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`);
320
292
  } catch (error) {
321
- console.error(`Error taking responsive screenshot for ${viewport.name}:`, error.message);
322
- results.push({
323
- viewport: viewport.name,
324
- success: false,
325
- error: error.message,
326
- filepath: ""
327
- });
293
+ this.logger.error(`Error taking screenshot after ${i + 1} retries:`, error.message);
328
294
  }
329
- return results;
295
+ return {
296
+ screenshotPath: null,
297
+ comparisonResult: null,
298
+ passed: false
299
+ };
300
+ }
301
+ /**
302
+ * Gets the exponential backoff delay
303
+ */
304
+ getIncBackoffDelay(i, delay) {
305
+ return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;
330
306
  }
331
307
  hasExpectedImage(filename) {
332
308
  const expectedPath = this.getExpectedFilePath(filename);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["PNG","fs","defaultDiffConfig: DiffConfig","path","fs","diffImagePath: string | undefined","results: {\n url: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[]","results: {\n viewport: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[]"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use vite.config.ts accepts a direct UserConfig object, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig,\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n // Create diff image\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n // Compare images using pixelmatch\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n const passed = percentDifference <= (options.maxDiffPercentage || 0);\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed,\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\n }\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param maxDifferencePercent - Maximum allowed difference percentage (0-100)\n * @param options - Comparison options\n * @returns Whether the images are similar enough\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig,\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n return result.passed;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: string;\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n fullPage: boolean;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n\n constructor(options: {\n browserType?: string;\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n fullPage?: boolean;\n diff?: DiffConfig;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.outputDir = options.outputDir || \"./screenshots\";\n this.fullPage = options.fullPage !== false; // Default to full page\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n }\n\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass =\n browserMap[this.browserType as keyof typeof browserMap];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n });\n\n this.page = await this.context?.newPage();\n this.page?.setViewportSize(this.viewport);\n }\n\n async close() {\n if (this.context) {\n await this.context.close();\n }\n if (this.browser) {\n await this.browser.close();\n }\n }\n\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, { waitUntil: \"domcontentloaded\" });\n }\n\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n console.log(`Created directory: ${dir}`);\n }\n }\n }\n\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n // Keep original method for backward compatibility\n getFilePath(filename: string) {\n return this.getActualFilePath(filename);\n }\n\n async takeScreenshot(\n page: Page,\n filename: string,\n options: {\n fullPage?: boolean;\n mask?: Locator[];\n omitBackground?: boolean;\n } = {},\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage:\n (options.fullPage as boolean) !== undefined\n ? options.fullPage\n : this.fullPage,\n type: \"png\",\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n await page.screenshot(screenshotOptions);\n\n console.log(`Screenshot saved: ${filepath}`);\n return filepath;\n } catch (error) {\n console.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeElementScreenshot(\n page: Page,\n selector: string,\n options: {\n filename?: string;\n fullPage?: boolean;\n } = {},\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Wait for element to be visible\n await page.waitForSelector(selector, { timeout: 10000 });\n\n const element = await page.$(selector);\n if (!element) {\n throw new Error(`Element not found: ${selector}`);\n }\n\n const filename =\n (options.filename as string | undefined) ||\n `${selector.replace(/[^a-zA-Z0-9]/g, \"_\")}.png`;\n // Save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n const elementScreenshotOptions = {\n path: filepath,\n type: \"png\",\n } satisfies PageScreenshotOptions;\n\n await element.screenshot(elementScreenshotOptions);\n\n console.log(`Element screenshot saved: ${filepath}`);\n return filepath;\n } catch (error) {\n console.error(\n `Error taking element screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n } finally {\n await page.close();\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: {\n fullPage?: boolean;\n mask?: Locator[];\n omitBackground?: boolean;\n // Comparison options\n compareOptions?: CompareOptions;\n maxDifferencePercent?: number;\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n } = {},\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage:\n (options.fullPage as boolean) !== undefined\n ? options.fullPage\n : this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n // Get screenshot as buffer for comparison\n const screenshotBuffer = await page.screenshot(screenshotOptions);\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, screenshotBuffer);\n\n console.log(`Screenshot saved: ${filepath}`);\n\n // Perform comparison\n const comparisonResult = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options.compareOptions },\n );\n\n console.log(\n `Comparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%) (${\n comparisonResult.passed ? \"PASSED\" : \"FAILED\"\n })`,\n );\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n comparisonResult.diffBuffer &&\n !comparisonResult.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(diffImagePath, comparisonResult.diffBuffer);\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n console.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async batchScreenshots(urls: string[], options = {}) {\n const results: {\n url: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[] = [];\n\n for (const url of urls) {\n try {\n const page = this.page;\n if (!page) {\n throw new Error(\"Page not initialized\");\n }\n await this.goTo(page, url);\n const filepath = await this.takeScreenshot(page, url, options);\n results.push({ url, success: true, filepath });\n } catch (error) {\n results.push({\n url,\n success: false,\n error: (error as Error).message,\n filepath: \"\",\n });\n }\n }\n\n return results;\n }\n\n async takeResponsiveScreenshots(\n url: string,\n viewports: { width: number; height: number; name: string }[] = [\n { width: 1920, height: 1080, name: \"desktop\" },\n { width: 768, height: 1024, name: \"tablet\" },\n { width: 375, height: 667, name: \"mobile\" },\n ],\n options: {\n fullPage?: boolean;\n } = {},\n ) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n\n const results: {\n viewport: string;\n success: boolean;\n filepath: string;\n error?: string;\n }[] = [];\n\n for (const viewport of viewports) {\n try {\n const page = await this.context?.newPage();\n await page.setViewportSize(viewport);\n\n await page.goto(url, { waitUntil: \"domcontentloaded\" });\n await page.waitForTimeout(2000);\n\n const filename = `${viewport.name}.png`;\n // Save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n const responsiveScreenshotOptions = {\n path: filepath,\n fullPage:\n (options.fullPage as boolean) !== undefined\n ? options.fullPage\n : this.fullPage,\n type: \"png\" as const,\n };\n\n await page.screenshot(responsiveScreenshotOptions);\n\n await page.close();\n\n console.log(`Responsive screenshot saved: ${filepath}`);\n results.push({ viewport: viewport.name, success: true, filepath });\n } catch (error) {\n console.error(\n `Error taking responsive screenshot for ${viewport.name}:`,\n (error as Error).message,\n );\n results.push({\n viewport: viewport.name,\n success: false,\n error: (error as Error).message,\n filepath: \"\",\n });\n }\n }\n\n return results;\n }\n\n // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAgB,aACd,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AM;IAAU,CAAC;WAC3D,OAAO;AACd,WAAQ,MACN,0CAA0C,SAAS,KAAK,IACvD,MAAgB,QAClB;AACD,WAAQ,KAAK;IACX,UAAU,SAAS;IACnB,SAAS;IACT,OAAQ,MAAgB;IACxB,UAAU;IACX,CAAC;;AAIN,SAAO;;CAIT,iBAAiB,UAA2B;EAC1C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,SAAOH,gBAAG,WAAW,aAAa;;CAIpC,uBAAuB,UAA0B;EAC/C,MAAM,eAAe,KAAK,oBAAoB,SAAS;AACvD,MAAI,CAACA,gBAAG,WAAW,aAAa,CAC9B,OAAM,IAAI,MAAM,6BAA6B,eAAe;AAE9D,SAAOA,gBAAG,aAAa,aAAa;;;AAIxC,yBAAe"}
1
+ {"version":3,"file":"index.js","names":["PNG","fs","defaultDiffConfig: DiffConfig","path","fs","diffImagePath: string | undefined"],"sources":["../src/config.ts","../src/compare.ts","../src/screenshot.ts"],"sourcesContent":["import type { PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig | Array<UserConfig>>\n | (() => PossiblePromise<UserConfig | Array<UserConfig>>),\n): typeof options {\n return options;\n}\n","import fs from \"node:fs\";\nimport blazediff from \"@blazediff/core\";\nimport type { BlazeDiffOptions } from \"@blazediff/types\";\nimport { PNG } from \"pngjs\";\nimport type { DiffConfig } from \"./types\";\n\nexport type CompareOptions = BlazeDiffOptions;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: BlazeDiffOptions,\n) => {\n return blazediff(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n // Load images as PNG objects\n const png1 = await loadPNG(image1);\n const png2 = await loadPNG(image2);\n\n const { width, height } = png1;\n\n const diff = withDiff ? new PNG({ width, height }) : undefined;\n\n const numDiffPixels = compare(\n png1.data,\n png2.data,\n diff?.data,\n width,\n height,\n options,\n );\n\n const totalPixels = width * height;\n const percentDifference = (numDiffPixels / totalPixels) * 100;\n\n // Convert diff image to buffer\n const diffBuffer = diff ? PNG.sync.write(diff) : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n };\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n if (Buffer.isBuffer(source)) {\n return PNG.sync.read(source);\n } else {\n const buffer = fs.readFileSync(source);\n return PNG.sync.read(buffer);\n }\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - First image (file path or Buffer)\n * @param image2 - Second image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig = {},\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n\n return result.passed;\n}\n\nconst isPassed = (\n percentDifference: number,\n numDiffPixels: number,\n options: DiffConfig,\n) => {\n if (options.maxDiffPercentage && options.maxDiffPixels) {\n return (\n percentDifference <= options.maxDiffPercentage &&\n numDiffPixels <= options.maxDiffPixels\n );\n }\n\n if (options.maxDiffPercentage) {\n return percentDifference <= options.maxDiffPercentage;\n }\n\n if (options.maxDiffPixels) {\n return numDiffPixels <= options.maxDiffPixels;\n }\n\n // fallback to 0 pixels\n return numDiffPixels === 0;\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Locator,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n type CompareOptions,\n type CompareResult,\n compareImages,\n} from \"./compare\";\nimport type { DiffConfig, ScreenshotOptions } from \"./types\";\n\nconst defaultDiffConfig: DiffConfig = {\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n outputDir: string;\n actualDir: string;\n diffDir: string;\n expectedDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n diff: DiffConfig;\n logger: Logger;\n retries: number;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n outputDir?: string;\n diff?: DiffConfig;\n retries?: number;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.outputDir = options.outputDir || \"./screenshots\";\n this.diff = { ...defaultDiffConfig, ...options.diff };\n // Set up subdirectories\n this.actualDir = path.join(this.outputDir, \"actual\");\n this.diffDir = path.join(this.outputDir, \"diff\");\n this.expectedDir = path.join(this.outputDir, \"expected\");\n\n this.logger = getLogger();\n this.retries = options.retries || 2;\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Create output directories if they don't exist\n this.createDirectories();\n\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass = browserMap[this.browserType];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n this.browser = await browserClass.launch({\n headless: this.headless,\n });\n\n const defaultUserAgent = (await this.browser.newContext())\n .newPage()\n .then((page) => page.evaluate(() => navigator.userAgent));\n\n this.context = await this.browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${await defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n\n this.page = await this.context?.newPage();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n */\n async close() {\n if (this.context) {\n await this.context.close();\n }\n if (this.browser) {\n await this.browser.close();\n }\n }\n\n /**\n * Navigates to a URL with \"domcontentloaded\" waitUntil\n */\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, { waitUntil: \"domcontentloaded\" });\n }\n\n /**\n * Creates directories for screenshots and other files\n */\n private createDirectories() {\n // Create main output directory and subdirectories\n const directories = [\n this.outputDir,\n this.actualDir,\n this.diffDir,\n this.expectedDir,\n ];\n\n for (const dir of directories) {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n this.logger.debug(`Initialized directory: ${dir}`);\n }\n }\n }\n\n /**\n * Gets the path to the actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return path.join(this.actualDir, filename);\n }\n\n /**\n * Gets the path to the diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return path.join(this.diffDir, filename);\n }\n\n /**\n * Gets the path to the expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return path.join(this.expectedDir, filename);\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n return;\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.getActualFilePath(filename);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n if (options.delay) {\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n\n return filepath;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: ScreenshotOptions & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n ): Promise<{\n screenshotPath: string;\n comparisonResult: CompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.getActualFilePath(filename);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // Take screenshot and get buffer\n const screenshotOptions = {\n fullPage: options.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n } satisfies PageScreenshotOptions;\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n filename,\n referenceImage,\n screenshotOptions,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n fs.writeFileSync(filepath, retryScreenshot.screenshotPath);\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n if (retryScreenshot.passed) {\n this.logger.success(`Screenshot passed visual comparison`);\n } else {\n this.logger.error(`Screenshot failed visual comparison`);\n }\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n retryScreenshot.comparisonResult.diffBuffer &&\n !retryScreenshot.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.getDiffFilePath(diffFilename);\n\n fs.mkdirSync(path.dirname(diffImagePath), { recursive: true });\n fs.writeFileSync(\n diffImagePath,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult: retryScreenshot.comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n this.logger.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async retryScreenshot(\n page: Page,\n filename: string,\n referenceImage: Buffer,\n options: ScreenshotOptions & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n ) {\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshot(page, filename, {\n ...options,\n delay: this.getIncBackoffDelay(i, options.delay || 0),\n });\n\n if (!screenshotBuffer) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n const comparisonResult = await compareImages(\n screenshotBuffer,\n referenceImage,\n true,\n { ...this.diff, ...options },\n );\n\n // last retry\n if (i === this.retries - 1 && !comparisonResult.passed) {\n this.logger.error(\n `Failed to match screenshot after ${this.retries} retries`,\n );\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\n }\n\n if (comparisonResult.passed) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: true,\n };\n } else {\n this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`,\n );\n }\n } catch (error) {\n this.logger.error(\n `Error taking screenshot after ${i + 1} retries:`,\n (error as Error).message,\n );\n }\n }\n\n return {\n screenshotPath: null,\n comparisonResult: null,\n passed: false,\n };\n }\n\n /**\n * Gets the exponential backoff delay\n */\n getIncBackoffDelay(i: number, delay: number): number {\n return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;\n }\n\n // Utility method to check if expected image exists\n hasExpectedImage(filename: string): boolean {\n const expectedPath = this.getExpectedFilePath(filename);\n return fs.existsSync(expectedPath);\n }\n\n // Utility method to get expected image as buffer (for future approval process)\n getExpectedImageBuffer(filename: string): Buffer {\n const expectedPath = this.getExpectedFilePath(filename);\n if (!fs.existsSync(expectedPath)) {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n return fs.readFileSync(expectedPath);\n }\n}\n\nexport default ScreenshotTool;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAgB,aACd,SAGgB;AAChB,QAAO;;;;;ACMT,MAAM,WACJ,QACA,QACA,MACA,OACA,QACA,YACG;AACH,sCAAiB,QAAQ,QAAQ,MAAM,OAAO,QAAQ,QAAQ;;;;;;;;;;AAWhE,eAAsB,cACpB,QACA,QACA,WAAoB,OACpB,UAAsB,EAAE,EACA;CAExB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,MAAM,OAAO,MAAM,QAAQ,OAAO;CAElC,MAAM,EAAE,OAAO,WAAW;CAE1B,MAAM,OAAO,WAAW,IAAIA,UAAI;EAAE;EAAO;EAAQ,CAAC,GAAG;CAErD,MAAM,gBAAgB,QACpB,KAAK,MACL,KAAK,MACL,MAAM,MACN,OACA,QACA,QACD;CAED,MAAM,cAAc,QAAQ;CAC5B,MAAM,oBAAqB,gBAAgB,cAAe;CAG1D,MAAM,aAAa,OAAOA,UAAI,KAAK,MAAM,KAAK,GAAG;AAEjD,QAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,SAAS,mBAAmB,eAAe,QAAQ;EAC5D;;;;;AAMH,eAAe,QAAQ,QAAuC;AAC5D,KAAI,OAAO,SAAS,OAAO,CACzB,QAAOA,UAAI,KAAK,KAAK,OAAO;MACvB;EACL,MAAM,SAASC,gBA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