@argos-ci/playwright 7.7.1 → 7.9.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/dist/index.d.mts CHANGED
@@ -1,23 +1,18 @@
1
- import { ScreenshotMetadata } from "@argos-ci/util";
1
+ import { ElementPadding, ScreenshotMetadata } from "@argos-ci/util";
2
2
  import { StabilizationPluginOptions, ViewportOption } from "@argos-ci/browser";
3
3
  import { ElementHandle, Frame, Locator, LocatorScreenshotOptions, Page, PageScreenshotOptions } from "@playwright/test";
4
4
  import "playwright-core";
5
- //#region ../../node_modules/.pnpm/playwright@1.63.0/node_modules/playwright/types/test.d.ts
6
5
  // --- BEGINGLOBAL ---
7
6
  declare global {
8
7
  export namespace PlaywrightTest {
9
8
  export interface Matchers<R, T = unknown> {}
10
9
  }
11
10
  }
12
- //#endregion
13
- //#region src/attachment.d.ts
14
11
  type ArgosAttachment = {
15
12
  name: string;
16
13
  contentType: string;
17
14
  path: string;
18
15
  };
19
- //#endregion
20
- //#region src/aria-snapshot.d.ts
21
16
  type LocatorOptions$1 = Parameters<Page["locator"]>[1];
22
17
  type ArgosSnapshotOptions = {
23
18
  /**
@@ -61,18 +56,32 @@ name: string,
61
56
  * Options for the snapshot.
62
57
  */
63
58
  options?: ArgosSnapshotOptions): Promise<ArgosAttachment[]>;
64
- //#endregion
65
- //#region src/screenshot.d.ts
66
59
  type LocatorOptions = Parameters<Page["locator"]>[1];
67
- type ScreenshotOptions<TBase extends PageScreenshotOptions | LocatorScreenshotOptions> = Omit<TBase, "encoding" | "type" | "omitBackground" | "path">;
60
+ type ScreenshotOptions<TBase extends PageScreenshotOptions | LocatorScreenshotOptions> = Omit<TBase, "encoding" | "type" | "omitBackground" | "path" | "mask">;
68
61
  type ArgosScreenshotOptions = {
69
62
  /**
70
63
  * `Locator` or string selector of the element to take a screenshot of.
71
64
  * Passing an `ElementHandle` is discouraged, use a `Locator` instead.
72
65
  */
73
66
  element?: string | ElementHandle | Locator;
67
+ /**
68
+ * Space to capture around the element, in CSS pixels, to include shadows,
69
+ * outlines or anything overflowing its box. Requires `element`.
70
+ * A number applies to every side. An array follows the CSS `padding`
71
+ * shorthand: `[vertical, horizontal]`, `[top, horizontal, bottom]` or
72
+ * `[top, right, bottom, left]`.
73
+ * The captured area is clamped to the page, or to the frame when taking the
74
+ * screenshot of a frame.
75
+ * @example
76
+ * argosScreenshot(page, "dialog", {
77
+ * element: page.getByRole("dialog"),
78
+ * padding: 16,
79
+ * })
80
+ */
81
+ padding?: ElementPadding;
74
82
  /**
75
83
  * Viewports to take screenshots of.
84
+ * Not supported on pages without a viewport, such as Electron windows.
76
85
  */
77
86
  viewports?: ViewportOption[];
78
87
  /**
@@ -87,6 +96,35 @@ type ArgosScreenshotOptions = {
87
96
  * Custom CSS evaluated during the screenshot process.
88
97
  */
89
98
  argosCSS?: string;
99
+ /**
100
+ * Elements to hide from the screenshot, as `Locator`s or string selectors.
101
+ * Hidden elements keep their space in the layout, like with the
102
+ * `data-visual-test="transparent"` helper.
103
+ * Selectors that match nothing are ignored.
104
+ * @example
105
+ * argosScreenshot(page, "home", {
106
+ * hide: ["#clock", page.getByTestId("avatar")],
107
+ * })
108
+ */
109
+ hide?: (string | Locator)[];
110
+ /**
111
+ * Elements to remove from the screenshot, as `Locator`s or string selectors.
112
+ * Removed elements no longer take space in the layout, like with the
113
+ * `data-visual-test="removed"` helper.
114
+ * Selectors that match nothing are ignored.
115
+ * @example
116
+ * argosScreenshot(page, "home", { remove: [".cookie-banner"] })
117
+ */
118
+ remove?: (string | Locator)[];
119
+ /**
120
+ * Elements to cover with a box when the screenshot is taken, as `Locator`s
121
+ * or string selectors, like with the `data-visual-test="blackout"` helper.
122
+ * Selectors that match nothing are ignored.
123
+ * @see https://playwright.dev/docs/api/class-page#page-screenshot-option-mask
124
+ * @example
125
+ * argosScreenshot(page, "home", { mask: ["#map", page.getByRole("img")] })
126
+ */
127
+ mask?: (string | Locator)[];
90
128
  /**
91
129
  * Disable hover effects by moving the mouse to the top-left corner of the document.
92
130
  * @default true
@@ -153,13 +191,15 @@ type ArgosScreenshotOptions = {
153
191
  *
154
192
  * @example
155
193
  * argosScreenshot(page, "my-screenshot")
194
+ * argosScreenshot(page.getByRole("dialog"), "dialog")
156
195
  * @see https://argos-ci.com/docs/reference/playwright
157
196
  */
158
197
  export declare function argosScreenshot(
159
198
  /**
160
199
  * Playwright `page` or `frame` object.
200
+ * A `Locator` takes a screenshot of its element, like the `element` option.
161
201
  */
162
- handler: Page | Frame,
202
+ handler: Page | Frame | Locator,
163
203
  /**
164
204
  * Name of the screenshot. Must be unique.
165
205
  */
@@ -168,14 +208,10 @@ name: string,
168
208
  * Options for the screenshot.
169
209
  */
170
210
  options?: ArgosScreenshotOptions): Promise<ArgosAttachment[]>;
171
- //#endregion
172
- //#region src/csp.d.ts
173
211
  /**
174
212
  * Get the CSP script hash.
175
213
  */
176
214
  export declare function getCSPScriptHash(): string;
177
- //#endregion
178
- //#region src/metadata.d.ts
179
215
  type MetadataConfig = {
180
216
  sdk: ScreenshotMetadata["sdk"];
181
217
  playwrightLibraries: string[];
@@ -200,5 +236,4 @@ type MetadataConfig = {
200
236
  * Set the metadata config.
201
237
  */
202
238
  declare function setMetadataConfig(metadata: MetadataConfig): void;
203
- //#endregion
204
239
  export { type ArgosAttachment, type ArgosScreenshotOptions, type ArgosSnapshotOptions, setMetadataConfig as DO_NOT_USE_setMetadataConfig, type MetadataConfig };
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { mkdir, writeFile } from "node:fs/promises";
3
- import { getGitRepositoryPath, getMetadataPath, getScreenshotName, getTestRunKey, nextCaptureIndex, normalizeBaseNames, readVersionFromPackage, validateThreshold, writeMetadata } from "@argos-ci/util";
3
+ import { getGitRepositoryPath, getMetadataPath, getPaddedClip, getScreenshotName, getTestRunKey, intersectRects, nextCaptureIndex, normalizeBaseNames, readVersionFromPackage, resolvePaddingOption, validateThreshold, writeMetadata } from "@argos-ci/util";
4
4
  import { dirname, relative, resolve } from "node:path";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { getGlobalScript, resolveViewport } from "@argos-ci/browser";
7
7
  import { createHash } from "node:crypto";
8
- //#region src/metadata.ts
8
+ // src/metadata.ts
9
9
  const require$1 = createRequire(import.meta.url);
10
10
  /**
11
11
  * Try to resolve a package.
@@ -122,8 +122,7 @@ async function getTestMetadata(testInfo) {
122
122
  annotations: testInfo.annotations
123
123
  };
124
124
  }
125
- //#endregion
126
- //#region src/util.ts
125
+ // src/util.ts
127
126
  const require = createRequire(import.meta.url);
128
127
  /**
129
128
  * Check if the project is using the Argos reporter.
@@ -177,10 +176,116 @@ function checkIsElementHandle(value) {
177
176
  return Boolean(value && typeof value === "object" && "asElement" in value && typeof value.asElement === "function");
178
177
  }
179
178
  /**
179
+ * Check if the value is a Locator.
180
+ */
181
+ function checkIsLocator(value) {
182
+ return Boolean(value && typeof value === "object" && "elementHandle" in value && typeof value.elementHandle === "function");
183
+ }
184
+ /**
180
185
  * Check if the handler is a Frame.
181
186
  */
182
187
  function checkIsFrame(handler) {
183
- return "page" in handler && typeof handler.page === "function";
188
+ return "parentFrame" in handler && typeof handler.parentFrame === "function";
189
+ }
190
+ /**
191
+ * Get the frame an element lives in, or `null` for the main frame.
192
+ */
193
+ async function getChildFrame(page, handle) {
194
+ const frame = await handle.ownerFrame();
195
+ return frame && frame !== page.mainFrame() ? frame : null;
196
+ }
197
+ /**
198
+ * Get the page or frame a locator lives in.
199
+ */
200
+ async function getLocatorHandler(locator) {
201
+ const page = locator.page();
202
+ const handle = await locator.elementHandle();
203
+ try {
204
+ return await getChildFrame(page, handle) ?? page;
205
+ } finally {
206
+ await handle.dispose();
207
+ }
208
+ }
209
+ /**
210
+ * Get the visible area of a frame, relative to the page viewport.
211
+ * Nested frames are clipped by their parent frames.
212
+ */
213
+ async function getFrameViewport(frame) {
214
+ let viewport = null;
215
+ for (let current = frame; current?.parentFrame(); current = current.parentFrame()) {
216
+ const frameElement = await current.frameElement();
217
+ try {
218
+ const [box, metrics] = await Promise.all([frameElement.boundingBox(), frameElement.evaluate((node) => {
219
+ const element = node;
220
+ return {
221
+ clientLeft: element.clientLeft,
222
+ clientTop: element.clientTop,
223
+ clientWidth: element.clientWidth,
224
+ clientHeight: element.clientHeight,
225
+ offsetWidth: element.offsetWidth,
226
+ offsetHeight: element.offsetHeight
227
+ };
228
+ })]);
229
+ if (!box) return null;
230
+ const scaleX = metrics.offsetWidth ? box.width / metrics.offsetWidth : 1;
231
+ const scaleY = metrics.offsetHeight ? box.height / metrics.offsetHeight : 1;
232
+ const contentBox = {
233
+ x: box.x + metrics.clientLeft * scaleX,
234
+ y: box.y + metrics.clientTop * scaleY,
235
+ width: metrics.clientWidth * scaleX,
236
+ height: metrics.clientHeight * scaleY
237
+ };
238
+ viewport = viewport ? intersectRects(viewport, contentBox) : contentBox;
239
+ } finally {
240
+ await frameElement.dispose();
241
+ }
242
+ }
243
+ return viewport;
244
+ }
245
+ /**
246
+ * Take a screenshot of an element and the space around it, clamped to the
247
+ * page, or to the frame the element lives in.
248
+ */
249
+ async function screenshotElementWithPadding(args) {
250
+ const { page, element, padding, options } = args;
251
+ const handle = checkIsElementHandle(element) ? element : await element.elementHandle({ timeout: options.timeout });
252
+ try {
253
+ await handle.scrollIntoViewIfNeeded({ timeout: options.timeout });
254
+ const [box, viewport, frameViewport] = await Promise.all([
255
+ handle.boundingBox(),
256
+ page.evaluate(() => ({
257
+ x: window.scrollX,
258
+ y: window.scrollY,
259
+ width: window.innerWidth,
260
+ height: window.innerHeight
261
+ })),
262
+ getChildFrame(page, handle).then((frame) => frame && getFrameViewport(frame))
263
+ ]);
264
+ if (!box) throw new Error("Unable to take a screenshot with `padding`: the element is not visible.");
265
+ const toDocument = (rect) => ({
266
+ ...rect,
267
+ x: rect.x + viewport.x,
268
+ y: rect.y + viewport.y
269
+ });
270
+ const clip = getPaddedClip(toDocument(box), padding, frameViewport ? toDocument(frameViewport) : {
271
+ x: 0,
272
+ y: 0,
273
+ width: 1e400,
274
+ height: 1e400
275
+ });
276
+ const fitsViewport = clip.x >= viewport.x && clip.y >= viewport.y && clip.x + clip.width <= viewport.x + viewport.width && clip.y + clip.height <= viewport.y + viewport.height;
277
+ return await page.screenshot({
278
+ ...options,
279
+ fullPage: !fitsViewport,
280
+ clip: fitsViewport ? {
281
+ ...clip,
282
+ x: clip.x - viewport.x,
283
+ y: clip.y - viewport.y
284
+ } : clip
285
+ });
286
+ } finally {
287
+ if (handle !== element) await handle.dispose();
288
+ }
184
289
  }
185
290
  /**
186
291
  * Get the Playwright `Page` from the handler.
@@ -194,10 +299,28 @@ function getPage(handler) {
194
299
  /**
195
300
  * Get the viewport size.
196
301
  */
197
- function getViewportSize(page) {
302
+ async function getViewportSize(page) {
198
303
  const viewportSize = page.viewportSize();
199
- if (!viewportSize) throw new Error("Snapshots can't be taken without a viewport.");
200
- return viewportSize;
304
+ if (viewportSize) return viewportSize;
305
+ return page.evaluate(() => ({
306
+ width: window.innerWidth,
307
+ height: window.innerHeight
308
+ }));
309
+ }
310
+ /**
311
+ * Get the browser running the page, or `undefined` if it can't be identified.
312
+ */
313
+ async function getBrowserMetadata(page) {
314
+ const browser = page.context().browser();
315
+ if (browser) return {
316
+ name: browser.browserType().name(),
317
+ version: browser.version()
318
+ };
319
+ const electronVersion = (await page.evaluate(() => navigator.userAgent)).match(/\bElectron\/(\S+)/)?.[1];
320
+ return electronVersion ? {
321
+ name: "electron",
322
+ version: electronVersion
323
+ } : void 0;
201
324
  }
202
325
  /**
203
326
  * Sets the viewport size and waits for the visual viewport to match the specified dimensions.
@@ -247,28 +370,22 @@ async function getPathAndMetadata(args) {
247
370
  const overrides = getMetadataOverrides();
248
371
  const path = useArgosReporter && testInfo ? testInfo.outputPath("argos", `${names.name}${extension}`) : resolve(root, `${names.name}${extension}`);
249
372
  const dir = dirname(path);
250
- const [colorScheme, mediaType, libMetadata, testMetadata] = await Promise.all([
373
+ const [colorScheme, mediaType, libMetadata, testMetadata, viewportSize, browser] = await Promise.all([
251
374
  handler.evaluate(() => window.__ARGOS__.getColorScheme()),
252
375
  handler.evaluate(() => window.__ARGOS__.getMediaType()),
253
376
  getLibraryMetadata(),
254
377
  getTestMetadata(testInfo),
378
+ checkIsFrame(handler) ? null : getViewportSize(handler),
379
+ getBrowserMetadata(getPage(handler)),
255
380
  dir !== root ? mkdir(dir, { recursive: true }) : null
256
381
  ]);
257
- const viewportSize = checkIsFrame(handler) ? null : getViewportSize(handler);
258
- const browser = getPage(handler).context().browser();
259
- if (!browser) throw new Error("Can't take screenshots without a browser.");
260
- const browserName = browser.browserType().name();
261
- const browserVersion = browser.version();
262
382
  const metadata = {
263
383
  url: overrides?.url ?? handler.url(),
264
384
  colorScheme,
265
385
  mediaType,
266
386
  test: testMetadata,
267
387
  story: overrides?.story,
268
- browser: {
269
- name: browserName,
270
- version: browserVersion
271
- },
388
+ browser,
272
389
  ...libMetadata
273
390
  };
274
391
  const viewport = viewportSize ?? getMetadataOverrides()?.viewport;
@@ -307,6 +424,20 @@ async function beforeEach(handler, context) {
307
424
  };
308
425
  }
309
426
  /**
427
+ * Get the `Locator` of a string selector, or the `Locator` itself.
428
+ */
429
+ function toLocator(handler, target) {
430
+ return typeof target === "string" ? handler.locator(target) : target;
431
+ }
432
+ /**
433
+ * Apply the `hide` and `remove` options until `afterEach` runs, as if the
434
+ * matched elements had the `data-visual-test` helper attribute.
435
+ */
436
+ async function applyHelpers(handler, options) {
437
+ const apply = (targets = [], helper) => targets.map((target) => toLocator(handler, target).evaluateAll((elements, helper) => window.__ARGOS__.applyHelper(elements, helper), helper));
438
+ await Promise.all([...apply(options.hide, "transparent"), ...apply(options.remove, "removed")]);
439
+ }
440
+ /**
310
441
  * Increase the timeout for the test x3.
311
442
  * Returns a function to reset the timeout.
312
443
  */
@@ -352,13 +483,11 @@ async function attachAttachments(args) {
352
483
  contentType: attachment.contentType
353
484
  })));
354
485
  }
355
- //#endregion
356
- //#region src/attachment.ts
486
+ // src/attachment.ts
357
487
  function getAttachmentName(name, type) {
358
488
  return `argos/${type}___${name}`;
359
489
  }
360
- //#endregion
361
- //#region src/aria-snapshot.ts
490
+ // src/aria-snapshot.ts
362
491
  const DEFAULT_SNAPSHOTS_ROOT = "./screenshots";
363
492
  /**
364
493
  * Stabilize the UI and takes a snapshot of the application under test.
@@ -431,27 +560,44 @@ function getStabilizationContext$1(options) {
431
560
  options: stabilize
432
561
  };
433
562
  }
434
- //#endregion
435
- //#region src/screenshot.ts
563
+ // src/screenshot.ts
436
564
  const DEFAULT_SCREENSHOT_ROOT = "./screenshots";
437
565
  /**
438
566
  * Stabilize the UI and take a screenshot of the application under test.
439
567
  *
440
568
  * @example
441
569
  * argosScreenshot(page, "my-screenshot")
570
+ * argosScreenshot(page.getByRole("dialog"), "dialog")
442
571
  * @see https://argos-ci.com/docs/reference/playwright
443
572
  */
444
573
  async function argosScreenshot(handler, name, options = {}) {
445
- const { element, has, hasText, hasNot, hasNotText, viewports, argosCSS: _argosCSS, root = DEFAULT_SCREENSHOT_ROOT, ariaSnapshot, disableHover = true, baseName, ...playwrightOptions } = options;
446
- const baseNames = normalizeBaseNames(baseName);
447
574
  if (!handler) throw new Error("A Playwright `handler` object is required.");
575
+ if (checkIsLocator(handler)) {
576
+ if (options.element !== void 0) throw new Error("The `element` option can't be used when the handler is a `Locator`. Pass the page instead.");
577
+ return argosScreenshot(await getLocatorHandler(handler), name, {
578
+ ...options,
579
+ element: handler
580
+ });
581
+ }
582
+ const { element, padding, has, hasText, hasNot, hasNotText, viewports, argosCSS: _argosCSS, root = DEFAULT_SCREENSHOT_ROOT, ariaSnapshot, disableHover = true, baseName, hide, remove, mask = [], ...playwrightOptions } = options;
583
+ const baseNames = normalizeBaseNames(baseName);
448
584
  if (!name) throw new Error("The `name` argument is required.");
449
- const screenshotTarget = typeof element === "string" ? handler.locator(element, {
585
+ const paddingSides = resolvePaddingOption({
586
+ padding,
587
+ element,
588
+ clip: playwrightOptions.clip
589
+ });
590
+ if (viewports) {
591
+ if (checkIsFrame(handler)) throw new Error(`viewports option is not supported with an iframe`);
592
+ if (!handler.viewportSize()) throw new Error(`viewports option is not supported on a page without a viewport, such as an Electron window`);
593
+ }
594
+ const elementTarget = typeof element === "string" ? handler.locator(element, {
450
595
  has,
451
596
  hasText,
452
597
  hasNot,
453
598
  hasNotText
454
- }) : element ?? (checkIsFrame(handler) ? handler.locator("body") : handler);
599
+ }) : element;
600
+ const screenshotTarget = elementTarget ?? (checkIsFrame(handler) ? handler.locator("body") : handler);
455
601
  const testInfo = await getTestInfo();
456
602
  const captureIndex = takeCaptureIndex(testInfo);
457
603
  const useArgosReporter = checkIsUsingArgosReporter(testInfo);
@@ -460,7 +606,6 @@ async function argosScreenshot(handler, name, options = {}) {
460
606
  useArgosReporter,
461
607
  root
462
608
  });
463
- const originalViewportSize = checkIsFrame(handler) ? null : getViewportSize(handler);
464
609
  const fullPage = options.fullPage !== void 0 ? options.fullPage : screenshotTarget === handler;
465
610
  const context = getStabilizationContext(options);
466
611
  const afterAll = await beforeAll(handler, context, { disableHover });
@@ -485,8 +630,20 @@ async function argosScreenshot(handler, name, options = {}) {
485
630
  stabilize: stabilizationOptions ?? options.stabilize
486
631
  })) });
487
632
  await waitForReadiness(handler, context);
633
+ await applyHelpers(handler, {
634
+ hide,
635
+ remove
636
+ });
488
637
  const afterEach = await beforeEach(handler, context);
489
638
  await waitForReadiness(handler, context);
639
+ const screenshotOptions = {
640
+ path: screenshotPath,
641
+ type: "png",
642
+ fullPage,
643
+ animations: "disabled",
644
+ ...playwrightOptions,
645
+ mask: ["[data-visual-test=\"blackout\"]", ...mask].map((target) => toLocator(handler, target))
646
+ };
490
647
  const [snapshotPath] = await Promise.all([
491
648
  (async () => {
492
649
  if (!ariaSnapshot) return null;
@@ -505,14 +662,12 @@ async function argosScreenshot(handler, name, options = {}) {
505
662
  }), writeMetadata(snapshotPath, snapshotMetadata)]);
506
663
  return snapshotPath;
507
664
  })(),
508
- screenshotTarget.screenshot({
509
- path: screenshotPath,
510
- type: "png",
511
- fullPage,
512
- mask: [handler.locator("[data-visual-test=\"blackout\"]")],
513
- animations: "disabled",
514
- ...playwrightOptions
515
- }),
665
+ elementTarget && paddingSides ? screenshotElementWithPadding({
666
+ page: getPage(handler),
667
+ element: elementTarget,
668
+ padding: paddingSides,
669
+ options: screenshotOptions
670
+ }) : screenshotTarget.screenshot(screenshotOptions),
516
671
  writeMetadata(screenshotPath, metadata)
517
672
  ]);
518
673
  const attachments = [{
@@ -544,15 +699,15 @@ async function argosScreenshot(handler, name, options = {}) {
544
699
  };
545
700
  const allAttachments = [];
546
701
  if (viewports) {
547
- if (checkIsFrame(handler)) throw new Error(`viewports option is not supported with an iframe`);
702
+ const page = getPage(handler);
703
+ const originalViewportSize = page.viewportSize();
548
704
  for (const viewport of viewports) {
549
705
  const viewportSize = resolveViewport(viewport);
550
- await setViewportSize(handler, viewportSize);
706
+ await setViewportSize(page, viewportSize);
551
707
  const attachments = await stabilizeAndScreenshot(getScreenshotName(name, { viewportWidth: viewportSize.width }), baseNames?.map((baseName) => getScreenshotName(baseName, { viewportWidth: viewportSize.width })) ?? null);
552
708
  allAttachments.push(...attachments);
553
709
  }
554
- if (!originalViewportSize) throw new Error(`Invariant: viewport size must be saved`);
555
- await setViewportSize(handler, originalViewportSize);
710
+ if (originalViewportSize) await setViewportSize(page, originalViewportSize);
556
711
  } else {
557
712
  const attachments = await stabilizeAndScreenshot(name, baseNames);
558
713
  allAttachments.push(...attachments);
@@ -572,13 +727,11 @@ function getStabilizationContext(options) {
572
727
  options: stabilize
573
728
  };
574
729
  }
575
- //#endregion
576
- //#region src/csp.ts
730
+ // src/csp.ts
577
731
  /**
578
732
  * Get the CSP script hash.
579
733
  */
580
734
  function getCSPScriptHash() {
581
735
  return `'sha256-${createHash("sha256").update(getGlobalScript()).digest("base64")}'`;
582
736
  }
583
- //#endregion
584
737
  export { setMetadataConfig as DO_NOT_USE_setMetadataConfig, argosAriaSnapshot, argosScreenshot, getCSPScriptHash };
@@ -1,6 +1,5 @@
1
1
  import { UploadParameters } from "@argos-ci/core";
2
2
  import { BrowserContextOptions, Geolocation, HTTPCredentials, LaunchOptions, PageScreenshotOptions, ViewportSize } from "playwright-core";
3
- //#region ../../node_modules/.pnpm/playwright@1.63.0/node_modules/playwright/types/test.d.ts
4
3
  type BlobReporterOptions = {
5
4
  outputDir?: string;
6
5
  fileName?: string;
@@ -8,6 +7,9 @@ type BlobReporterOptions = {
8
7
  type DotReporterOptions = {
9
8
  omitTags?: boolean;
10
9
  };
10
+ type FailuresReporterOptions = {
11
+ omitTags?: boolean;
12
+ };
11
13
  type LineReporterOptions = {
12
14
  omitTags?: boolean;
13
15
  };
@@ -25,14 +27,17 @@ type JUnitReporterOptions = {
25
27
  includeProjectInTestName?: boolean;
26
28
  includeRetries?: boolean;
27
29
  omitTags?: boolean;
30
+ onlyFailures?: boolean;
28
31
  };
29
32
  type JsonReporterOptions = {
30
33
  outputFile?: string;
34
+ onlyFailures?: boolean;
31
35
  };
32
36
  type PerfettoReporterOptions = {
33
37
  outputFile?: string;
34
38
  };
35
39
  type HtmlReporterOptions = {
40
+ onlyFailures?: boolean;
36
41
  outputFolder?: string;
37
42
  open?: 'always' | 'never' | 'on-failure';
38
43
  host?: string;
@@ -44,7 +49,7 @@ type HtmlReporterOptions = {
44
49
  doNotInlineAssets?: boolean;
45
50
  mergeFiles?: boolean;
46
51
  };
47
- type ReporterDescription = Readonly<['blob'] | ['blob', BlobReporterOptions] | ['dot'] | ['dot', DotReporterOptions] | ['line'] | ['line', LineReporterOptions] | ['list'] | ['list', ListReporterOptions] | ['github'] | ['github', GitHubReporterOptions] | ['junit'] | ['junit', JUnitReporterOptions] | ['json'] | ['json', JsonReporterOptions] | ['perfetto'] | ['perfetto', PerfettoReporterOptions] | ['html'] | ['html', HtmlReporterOptions] | ['null'] | [string] | [string, any]>;
52
+ type ReporterDescription = Readonly<['blob'] | ['blob', BlobReporterOptions] | ['dot'] | ['dot', DotReporterOptions] | ['failures'] | ['failures', FailuresReporterOptions] | ['line'] | ['line', LineReporterOptions] | ['list'] | ['list', ListReporterOptions] | ['github'] | ['github', GitHubReporterOptions] | ['junit'] | ['junit', JUnitReporterOptions] | ['json'] | ['json', JsonReporterOptions] | ['perfetto'] | ['perfetto', PerfettoReporterOptions] | ['html'] | ['html', HtmlReporterOptions] | ['null'] | [string] | [string, any]>;
48
53
  type UseOptions<TestArgs, WorkerArgs> = Partial<WorkerArgs> & Partial<TestArgs>;
49
54
  /**
50
55
  * Runtime representation of the test project configuration. It is accessible in the tests via
@@ -157,6 +162,12 @@ interface FullConfig<TestArgs = {}, WorkerArgs = {}> {
157
162
  * [testConfig.failOnFlakyTests](https://playwright.dev/docs/api/class-testconfig#test-config-fail-on-flaky-tests).
158
163
  */
159
164
  failOnFlakyTests: boolean;
165
+ /**
166
+ * List of projects that were selected to run, after applying the `--project` command line filter. When no filter is
167
+ * specified, this is the same as
168
+ * [fullConfig.projects](https://playwright.dev/docs/api/class-fullconfig#full-config-projects).
169
+ */
170
+ filteredProjects: Array<FullProject>;
160
171
  /**
161
172
  * See [testConfig.forbidOnly](https://playwright.dev/docs/api/class-testconfig#test-config-forbid-only).
162
173
  */
@@ -238,7 +249,7 @@ interface FullConfig<TestArgs = {}, WorkerArgs = {}> {
238
249
  /**
239
250
  * See [testConfig.updateSnapshots](https://playwright.dev/docs/api/class-testconfig#test-config-update-snapshots).
240
251
  */
241
- updateSnapshots: "all" | "changed" | "missing" | "none";
252
+ updateSnapshots: "all" | "changed" | "missing" | "none" | "default";
242
253
  /**
243
254
  * See
244
255
  * [testConfig.updateSourceMethod](https://playwright.dev/docs/api/class-testconfig#test-config-update-source-method).
@@ -283,6 +294,7 @@ type ConnectOptions = {
283
294
  * - Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
284
295
  * - IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
285
296
  * - `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
297
+
286
298
  * Some common examples:
287
299
  * - `"*"` to expose all network.
288
300
  * - `"<loopback>"` to expose localhost network.
@@ -454,9 +466,7 @@ interface PlaywrightWorkerOptions {
454
466
  * [fixtures.browser](https://playwright.dev/docs/api/class-fixtures#fixtures-browser),
455
467
  * [fixtures.context](https://playwright.dev/docs/api/class-fixtures#fixtures-context) and
456
468
  * [fixtures.page](https://playwright.dev/docs/api/class-fixtures#fixtures-page) use the remote browser instead of
457
- * launching a browser locally, and any launch options like
458
- * [testOptions.headless](https://playwright.dev/docs/api/class-testoptions#test-options-headless) or
459
- * [testOptions.channel](https://playwright.dev/docs/api/class-testoptions#test-options-channel) are ignored.
469
+ * launching a browser locally.
460
470
  */
461
471
  connectOptions: ConnectOptions | undefined;
462
472
  /**
@@ -606,9 +616,13 @@ interface PlaywrightWorkerOptions {
606
616
  * down to fit into 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual
607
617
  * picture of each page will be scaled down if necessary to fit the specified size.
608
618
  *
609
- * To annotate actions in the video, pass `show` with `action` and/or `test` sub-options. The `action` option controls
610
- * visual highlights on interacted elements with an optional `delay` in milliseconds (defaults to `500`). The `test`
611
- * option controls which test information is displayed as a status overlay.
619
+ * To record smoother video of animations and scrolling, pass `fps`, for example `{ mode: 'on', size: { width: 1920,
620
+ * height: 1080 }, fps: 60 }`. Higher frame rates and sizes use more CPU for encoding. Firefox and WebKit currently
621
+ * capture up to 25 frames per second.
622
+ *
623
+ * To annotate actions in the video, pass `show` with `actions` and/or `test` sub-options. The `actions` option
624
+ * controls visual highlights on interacted elements, each shown for an optional `duration` in milliseconds (defaults
625
+ * to `500`). The `test` option controls which test information is displayed as a status overlay.
612
626
  *
613
627
  * **Usage**
614
628
  *
@@ -628,12 +642,18 @@ interface PlaywrightWorkerOptions {
628
642
  video: VideoMode | /** deprecated */ 'retry-with-video' | {
629
643
  mode: VideoMode;
630
644
  size?: ViewportSize;
645
+ fps?: number;
631
646
  show?: {
632
647
  actions?: {
633
648
  duration?: number;
634
649
  position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right';
635
- fontSize?: number;
650
+ /** @deprecated Use `style.title` instead. */ fontSize?: number;
636
651
  cursor?: 'none' | 'pointer';
652
+ style?: {
653
+ point?: string;
654
+ highlight?: string;
655
+ title?: string;
656
+ };
637
657
  };
638
658
  test?: {
639
659
  level?: 'file' | 'title' | 'step';
@@ -918,6 +938,19 @@ interface PlaywrightTestOptions {
918
938
  * });
919
939
  * ```
920
940
  *
941
+ * When passing an array of credentials to [test.use(options)](https://playwright.dev/docs/api/class-test#test-use),
942
+ * wrap it into an extra array, see [fixture options](https://playwright.dev/docs/test-fixtures#fixtures-options).
943
+ *
944
+ * ```js
945
+ * // example.spec.ts
946
+ * test.use({
947
+ * httpCredentials: [[
948
+ * { username: 'alice', password: 'alice-pass', origin: 'https://a.example.com' },
949
+ * { username: 'bob', password: 'bob-pass', origin: 'https://b.example.com' },
950
+ * ], { scope: 'test' }],
951
+ * });
952
+ * ```
953
+ *
921
954
  */
922
955
  httpCredentials: HTTPCredentials | HTTPCredentials[] | undefined;
923
956
  /**
@@ -940,8 +973,8 @@ interface PlaywrightTestOptions {
940
973
  ignoreHTTPSErrors: boolean;
941
974
  /**
942
975
  * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
943
- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
944
- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
976
+ * so you don't actually need to set it manually. Defaults to `false`. Learn more about
977
+ * [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
945
978
  *
946
979
  * **Usage**
947
980
  *
@@ -1077,6 +1110,26 @@ interface PlaywrightTestOptions {
1077
1110
  *
1078
1111
  */
1079
1112
  reducedMotion: ReducedMotion;
1113
+ /**
1114
+ * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
1115
+ * [testOptions.viewport](https://playwright.dev/docs/api/class-testoptions#test-options-viewport) is set.
1116
+ *
1117
+ * **Usage**
1118
+ *
1119
+ * ```js
1120
+ * // playwright.config.ts
1121
+ * import { defineConfig } from '@playwright/test';
1122
+ *
1123
+ * export default defineConfig({
1124
+ * use: {
1125
+ * viewport: { width: 390, height: 664 },
1126
+ * screen: { width: 390, height: 844 },
1127
+ * },
1128
+ * });
1129
+ * ```
1130
+ *
1131
+ */
1132
+ screen: ViewportSize | undefined;
1080
1133
  /**
1081
1134
  * Learn more about [storage state and auth](https://playwright.dev/docs/auth).
1082
1135
  *
@@ -1466,8 +1519,6 @@ interface TestConfigWebServer {
1466
1519
  */
1467
1520
  url?: string;
1468
1521
  }
1469
- //#endregion
1470
- //#region ../../node_modules/.pnpm/playwright@1.63.0/node_modules/playwright/types/testReporter.d.ts
1471
1522
  /**
1472
1523
  * Result of the full test run.
1473
1524
  */
@@ -2036,8 +2087,8 @@ interface TestResult {
2036
2087
  workerIndex: number;
2037
2088
  }
2038
2089
  /**
2039
- * Controls which tests will run and their expected status. A [TestRun](https://playwright.dev/docs/api/class-testrun)
2040
- * is available during
2090
+ * Controls which tests will run and their expected status, and provides information about suite execution modes. A
2091
+ * [TestRun](https://playwright.dev/docs/api/class-testrun) is available during
2041
2092
  * [reporter.preprocess(params)](https://playwright.dev/docs/api/class-reporter#reporter-preprocess). Setup and
2042
2093
  * teardown projects cannot be changed.
2043
2094
  */
@@ -2062,6 +2113,25 @@ interface TestRun {
2062
2113
  * @param reason Optional explanation surfaced as the annotation description.
2063
2114
  */
2064
2115
  fixme(test: TestCase | Suite, reason?: string): void;
2116
+ /**
2117
+ * Returns the execution mode configured for a suite with
2118
+ * [test.describe.configure([options])](https://playwright.dev/docs/api/class-test#test-describe-configure),
2119
+ * [test.describe.serial([title, details, callback])](https://playwright.dev/docs/api/class-test#test-describe-serial)
2120
+ * or
2121
+ * [test.describe.parallel([title, details, callback])](https://playwright.dev/docs/api/class-test#test-describe-parallel).
2122
+ * If the suite does not configure a mode, it inherits its parent's mode. Project suites use `"parallel"` when
2123
+ * [testProject.fullyParallel](https://playwright.dev/docs/api/class-testproject#test-project-fully-parallel) is
2124
+ * enabled, and `"default"` otherwise. The root suite uses `"default"`.
2125
+ *
2126
+ * An explicit `"default"` suite does not inherit `"parallel"` from its parent: its tests run in order in the same
2127
+ * worker. The mode alone does not describe complete test groups, which also depend on worker fixtures and hooks.
2128
+ *
2129
+ * This method can only be called during
2130
+ * [reporter.preprocess(params)](https://playwright.dev/docs/api/class-reporter#reporter-preprocess), and can also
2131
+ * inspect setup and teardown projects.
2132
+ * @param suite Suite to inspect.
2133
+ */
2134
+ mode(suite: Suite): "serial" | "parallel" | "default";
2065
2135
  /**
2066
2136
  * Skips a test or every test in a suite. The test bodies are not executed and the tests are reported as skipped.
2067
2137
  * @param test Test or suite to skip.
@@ -2212,8 +2282,6 @@ interface TestStep {
2212
2282
  */
2213
2283
  title: string;
2214
2284
  }
2215
- //#endregion
2216
- //#region src/reporter.d.ts
2217
2285
  /**
2218
2286
  * Dynamic build name.
2219
2287
  * We require all values in order to ensure it works correctly in parallel mode.
@@ -2279,5 +2347,4 @@ declare class ArgosReporter implements Reporter {
2279
2347
  } | undefined>;
2280
2348
  printsToStdio(): boolean;
2281
2349
  }
2282
- //#endregion
2283
2350
  export { ArgosReporter as default };
package/dist/reporter.mjs CHANGED
@@ -7,7 +7,7 @@ import { createDirectory, createTemporaryDirectory, getGitRepositoryPath, readVe
7
7
  import { AsyncLocalStorage } from "node:async_hooks";
8
8
  import "@argos-ci/browser";
9
9
  import createDebug from "debug";
10
- //#region src/metadata.ts
10
+ // src/metadata.ts
11
11
  const require$1 = createRequire(import.meta.url);
12
12
  /**
13
13
  * Try to resolve a package.
@@ -124,8 +124,7 @@ function getAutomaticScreenshotName(test, result) {
124
124
  if (name.length > maxNameLength) return `${truncate(`${test.id} - ${test.title}`, maxNameLength)}${suffix}`;
125
125
  return `${name}${suffix}`;
126
126
  }
127
- //#endregion
128
- //#region src/attachment.ts
127
+ // src/attachment.ts
129
128
  function parseAttachmentName(name) {
130
129
  const match = name.match(/^argos\/(screenshot|aria)(\/metadata)?___(.*)$/);
131
130
  if (!match) return null;
@@ -164,8 +163,7 @@ function checkIsAutomaticScreenshot(attachment) {
164
163
  return attachment.name === "screenshot" && attachment.contentType === "image/png" && Boolean(attachment.path);
165
164
  }
166
165
  const debug = createDebug("@argos-ci/playwright");
167
- //#endregion
168
- //#region src/reporter.ts
166
+ // src/reporter.ts
169
167
  /**
170
168
  * Check if the build name is dynamic.
171
169
  */
@@ -183,7 +181,7 @@ const RECOMMENDED_CHROMIUM_ARGS = ["--disable-lcd-text", "--font-render-hinting=
183
181
  */
184
182
  function checkLaunchOptions(config) {
185
183
  for (const project of config.projects) {
186
- if ((project.use.browserName ?? "chromium") !== "chromium") continue;
184
+ if ((project.use.browserName ?? project.use.defaultBrowserType ?? "chromium") !== "chromium") continue;
187
185
  const args = project.use.launchOptions?.args ?? [];
188
186
  const missing = RECOMMENDED_CHROMIUM_ARGS.filter((arg) => !args.includes(arg));
189
187
  if (missing.length > 0) {
@@ -344,5 +342,4 @@ var ArgosReporter = class {
344
342
  return false;
345
343
  }
346
344
  };
347
- //#endregion
348
345
  export { createArgosReporterOptions, ArgosReporter as default };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@argos-ci/playwright",
3
3
  "description": "Playwright SDK for visual testing with Argos.",
4
- "version": "7.7.1",
4
+ "version": "7.9.0",
5
5
  "author": "Smooth Code",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -14,15 +14,20 @@
14
14
  "url": "https://github.com/argos-ci/argos-javascript/issues"
15
15
  },
16
16
  "keywords": [
17
+ "argos",
18
+ "argos-ci",
17
19
  "playwright",
18
20
  "playwright-reporter",
19
- "reporter",
20
21
  "playwright-plugin",
21
- "argos",
22
+ "reporter",
22
23
  "testing",
23
- "visual testing",
24
- "regression",
25
- "visual regression"
24
+ "e2e-testing",
25
+ "visual-testing",
26
+ "visual-regression",
27
+ "visual-regression-testing",
28
+ "screenshot-testing",
29
+ "snapshot-testing",
30
+ "aria-snapshot"
26
31
  ],
27
32
  "publishConfig": {
28
33
  "access": "public"
@@ -47,14 +52,14 @@
47
52
  "node": ">=22.0.0"
48
53
  },
49
54
  "dependencies": {
50
- "@argos-ci/browser": "6.5.0",
51
- "@argos-ci/core": "6.8.7",
52
- "@argos-ci/util": "4.2.2",
55
+ "@argos-ci/browser": "6.6.1",
56
+ "@argos-ci/core": "6.9.0",
57
+ "@argos-ci/util": "4.3.0",
53
58
  "chalk": "^6.0.1",
54
59
  "debug": "^4.4.3"
55
60
  },
56
61
  "devDependencies": {
57
- "@playwright/test": "^1.63.0",
62
+ "@playwright/test": "^1.65.1",
58
63
  "@types/debug": "^4.1.13",
59
64
  "@types/node": "catalog:",
60
65
  "vitest": "catalog:"
@@ -69,5 +74,5 @@
69
74
  "lint": "eslint .",
70
75
  "test": "vitest src"
71
76
  },
72
- "gitHead": "e9d0b2fb39001683230eff86f9c39e0016b5cf27"
77
+ "gitHead": "96ca00234edc12d322416295a4abebbc8471b696"
73
78
  }