cypress-annotate 0.4.0 → 1.1.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.
Files changed (63) hide show
  1. package/AGENTS.md +40 -28
  2. package/CHANGELOG.md +174 -0
  3. package/DOCS/images/crop.png +0 -0
  4. package/DOCS/images/failure-hook.png +0 -0
  5. package/DOCS/internals.md +151 -0
  6. package/README.md +104 -352
  7. package/dist/annotate-image.d.ts +19 -2
  8. package/dist/annotate-image.d.ts.map +1 -1
  9. package/dist/annotate-image.js +55 -12
  10. package/dist/cypress/commands.d.ts +6 -1
  11. package/dist/cypress/commands.d.ts.map +1 -1
  12. package/dist/cypress/commands.js +20 -6
  13. package/dist/cypress/config.d.ts +42 -0
  14. package/dist/cypress/config.d.ts.map +1 -0
  15. package/dist/cypress/config.js +102 -0
  16. package/dist/cypress/failure-hook.d.ts.map +1 -1
  17. package/dist/cypress/failure-hook.js +17 -3
  18. package/dist/cypress/failure-report.d.ts +6 -0
  19. package/dist/cypress/failure-report.d.ts.map +1 -1
  20. package/dist/cypress/failure-report.js +14 -4
  21. package/dist/cypress/task.d.ts +39 -3
  22. package/dist/cypress/task.d.ts.map +1 -1
  23. package/dist/cypress/task.js +61 -5
  24. package/dist/draw.d.ts +4 -0
  25. package/dist/draw.d.ts.map +1 -1
  26. package/dist/draw.js +7 -4
  27. package/dist/index.d.ts +9 -20
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +7 -57
  30. package/dist/types.d.ts +13 -69
  31. package/dist/types.d.ts.map +1 -1
  32. package/package.json +11 -43
  33. package/skills/cypress-annotate/SKILL.md +62 -9
  34. package/DOCS/pipeline.md +0 -308
  35. package/dist/annotate.d.ts +0 -9
  36. package/dist/annotate.d.ts.map +0 -1
  37. package/dist/annotate.js +0 -82
  38. package/dist/browser/collect-elements.js +0 -158
  39. package/dist/browser/measure-target.js +0 -69
  40. package/dist/claude-reasoner.d.ts +0 -17
  41. package/dist/claude-reasoner.d.ts.map +0 -1
  42. package/dist/claude-reasoner.js +0 -192
  43. package/dist/cli.d.ts +0 -3
  44. package/dist/cli.d.ts.map +0 -1
  45. package/dist/cli.js +0 -84
  46. package/dist/cypress/failure-explainer.d.ts +0 -45
  47. package/dist/cypress/failure-explainer.d.ts.map +0 -1
  48. package/dist/cypress/failure-explainer.js +0 -123
  49. package/dist/finder.d.ts +0 -68
  50. package/dist/finder.d.ts.map +0 -1
  51. package/dist/finder.js +0 -64
  52. package/dist/inventory.d.ts +0 -33
  53. package/dist/inventory.d.ts.map +0 -1
  54. package/dist/inventory.js +0 -88
  55. package/dist/measure.d.ts +0 -11
  56. package/dist/measure.d.ts.map +0 -1
  57. package/dist/measure.js +0 -145
  58. package/dist/pipeline.d.ts +0 -60
  59. package/dist/pipeline.d.ts.map +0 -1
  60. package/dist/pipeline.js +0 -115
  61. package/skills/annotate-bug/SKILL.md +0 -121
  62. package/src/browser/collect-elements.js +0 -158
  63. package/src/browser/measure-target.js +0 -69
@@ -1,5 +1,5 @@
1
1
  import sharp from 'sharp';
2
- import { buildOverlaySvg, compositeOverlay } from './draw.js';
2
+ import { buildOverlaySvg, compositeOverlay, DEFAULT_FONT_STACK, } from './draw.js';
3
3
  const DEFAULT_STYLE = {
4
4
  color: '#FF3B30',
5
5
  strokeWidth: 3,
@@ -8,9 +8,20 @@ const DEFAULT_STYLE = {
8
8
  dimOutside: 0,
9
9
  labelFontSize: 14,
10
10
  labelColor: '#FFFFFF',
11
+ labelBackground: '',
12
+ labelFontFamily: DEFAULT_FONT_STACK,
13
+ labelFontWeight: 600,
11
14
  };
15
+ /**
16
+ * Merge style layers, lowest priority first. `labelBackground` defaults to
17
+ * whatever `color` resolved to, so setting one brand colour themes the outline
18
+ * and the label pill together, and setting both still works.
19
+ */
12
20
  export function resolveStyle(...layers) {
13
- return Object.assign({}, DEFAULT_STYLE, ...layers.map((l) => l ?? {}));
21
+ const merged = Object.assign({}, DEFAULT_STYLE, ...layers.map((l) => l ?? {}));
22
+ if (!merged.labelBackground)
23
+ merged.labelBackground = merged.color;
24
+ return merged;
14
25
  }
15
26
  /** Convert CSS-pixel style values into image pixels at the capture's scale. */
16
27
  function toDeviceStyle(style, scale) {
@@ -21,6 +32,9 @@ function toDeviceStyle(style, scale) {
21
32
  dimOutside: style.dimOutside,
22
33
  labelFontSize: style.labelFontSize * scale,
23
34
  labelColor: style.labelColor,
35
+ labelBackground: style.labelBackground,
36
+ labelFontFamily: style.labelFontFamily,
37
+ labelFontWeight: style.labelFontWeight,
24
38
  };
25
39
  }
26
40
  function inflate(rect, by) {
@@ -47,8 +61,15 @@ function clampRect(rect, width, height) {
47
61
  * screenshots to keep them cheap to send, and a capture that has been resized
48
62
  * behind your back is exactly what makes a box drift. So the image is measured
49
63
  * and the reported ratio is treated as a hint.
64
+ *
65
+ * A narrow image has a second explanation, though. A headless browser window
66
+ * smaller than the viewport captures only its top-left corner, at full scale,
67
+ * and width alone cannot tell that apart from a resize. So when the capturing
68
+ * tool says the image was not resized, its pixel ratio wins.
50
69
  */
51
- export function resolveScale(imageWidth, cssWidth, devicePixelRatio, warnings) {
70
+ export function resolveScale(imageWidth, cssWidth, devicePixelRatio, warnings, report) {
71
+ if (report && !report.scaled && report.pixelRatio > 0)
72
+ return report.pixelRatio;
52
73
  if (cssWidth <= 0) {
53
74
  warnings.push('Page metrics reported a zero-width viewport; falling back to devicePixelRatio.');
54
75
  return devicePixelRatio;
@@ -86,7 +107,17 @@ export async function annotateImage(screenshot, targets, options) {
86
107
  if (imageWidth === 0 || imageHeight === 0)
87
108
  throw new Error('Could not read the screenshot dimensions.');
88
109
  const cssWidth = fullPage ? metrics.documentWidth : metrics.viewportWidth;
89
- const scale = resolveScale(imageWidth, cssWidth, metrics.devicePixelRatio, warnings);
110
+ const cssHeight = fullPage ? metrics.documentHeight : metrics.viewportHeight;
111
+ const scale = resolveScale(imageWidth, cssWidth, metrics.devicePixelRatio, warnings, options.captureReport);
112
+ // The CSS area the image actually holds, from its own top-left corner.
113
+ const coveredWidth = imageWidth / scale;
114
+ const coveredHeight = imageHeight / scale;
115
+ if (coveredWidth < cssWidth - 1 || coveredHeight < cssHeight - 1) {
116
+ warnings.push(`Screenshot covers only ${Math.round(coveredWidth)}x${Math.round(coveredHeight)} CSS px of the ` +
117
+ `${Math.round(cssWidth)}x${Math.round(cssHeight)} ${fullPage ? 'page' : 'viewport'}, which usually ` +
118
+ `means the browser window is smaller than the viewport. Size the window to match in before:browser:launch.`);
119
+ }
120
+ const placed = [];
90
121
  for (const target of targets) {
91
122
  const name = target.describe ?? 'target';
92
123
  if (target.viewportRect.width === 0 || target.viewportRect.height === 0) {
@@ -96,18 +127,26 @@ export async function annotateImage(screenshot, targets, options) {
96
127
  warnings.push(`${name} is position:fixed, so it has no stable document position in a full-page capture; ` +
97
128
  `annotated where it was painted.`);
98
129
  }
99
- }
100
- const sourceRects = targets.map((target) => {
101
- const style = resolveStyle(options.style, target.style);
102
130
  const base = fullPage ? documentRectOf(target, metrics) : target.viewportRect;
103
- return scaleRect(inflate(base, style.padding), scale);
104
- });
131
+ const right = base.x + base.width;
132
+ const bottom = base.y + base.height;
133
+ if (base.x >= coveredWidth || base.y >= coveredHeight || right <= 0 || bottom <= 0) {
134
+ warnings.push(`${name} is outside the captured area, so no box was drawn for it.`);
135
+ continue;
136
+ }
137
+ if (base.x < 0 || base.y < 0 || right > coveredWidth || bottom > coveredHeight) {
138
+ warnings.push(`${name} runs past the edge of the captured area; its box is clipped.`);
139
+ }
140
+ const style = resolveStyle(options.style, target.style);
141
+ placed.push({ target, rect: scaleRect(inflate(base, style.padding), scale) });
142
+ }
143
+ const sourceRects = placed.map((p) => p.rect);
105
144
  let finalImage = screenshot;
106
145
  let finalWidth = imageWidth;
107
146
  let finalHeight = imageHeight;
108
147
  let originX = 0;
109
148
  let originY = 0;
110
- if (options.crop) {
149
+ if (options.crop && sourceRects.length > 0) {
111
150
  const pad = (options.cropPadding ?? 40) * scale;
112
151
  const union = sourceRects.reduce((acc, r) => {
113
152
  const x = Math.min(acc.x, r.x);
@@ -138,7 +177,7 @@ export async function annotateImage(screenshot, targets, options) {
138
177
  }
139
178
  const drawnRects = sourceRects.map((r) => ({ ...r, x: r.x - originX, y: r.y - originY }));
140
179
  const specs = drawnRects.map((rect, i) => {
141
- const target = targets[i];
180
+ const target = placed[i]?.target;
142
181
  const style = resolveStyle(options.style, target?.style);
143
182
  return {
144
183
  rect,
@@ -147,7 +186,11 @@ export async function annotateImage(screenshot, targets, options) {
147
186
  style: toDeviceStyle(style, scale),
148
187
  };
149
188
  });
150
- const image = await compositeOverlay(finalImage, buildOverlaySvg(finalWidth, finalHeight, specs));
189
+ // Nothing landed in the image, so leave it untouched. Dimming everything
190
+ // outside zero boxes would only darken the whole screenshot.
191
+ const image = specs.length > 0
192
+ ? await compositeOverlay(finalImage, buildOverlaySvg(finalWidth, finalHeight, specs))
193
+ : finalImage;
151
194
  return {
152
195
  image,
153
196
  rawImage: finalImage,
@@ -10,12 +10,17 @@ import type { AnnotationStyle, ShapeKind } from '../types.js';
10
10
  * hand: scroll, then measure, then screenshot, with nothing in between. Every
11
11
  * rectangle is only valid for the scroll position it was measured at.
12
12
  */
13
+ /**
14
+ * Every field here can also be set once for the whole project, under
15
+ * `env.annotate` in cypress.config. A value passed to a single call wins over
16
+ * the project default, which wins over the built-in one.
17
+ */
13
18
  export interface AnnotateCommandOptions {
14
19
  /** One per selector, in order. */
15
20
  label?: string | string[];
16
21
  /** Screenshot name; defaults to a slug of the first selector. */
17
22
  name?: string;
18
- /** Crop to the element with the surroundings dimmed. Good for a ticket. */
23
+ /** Crop to the element, keeping `cropPadding` of context. Good for a ticket. */
19
24
  crop?: boolean;
20
25
  cropPadding?: number;
21
26
  shape?: ShapeKind;
@@ -1 +1 @@
1
- {"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../src/cypress/commands.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,kBAAkB,EAExB,MAAM,kBAAkB,CAAC;AAE1B,OA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H,MAAM,WAAW,sBAAsB;IACrC,kCAAkC;IAClC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC1B,iEAAiE;IACjE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gFAAgF;IAChF,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,2EAA2E;IAC3E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6DAA6D;IAC7D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,YAAY,EAAE,kBAAkB,EAAE,CAAC;AAgGnC,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,SAAS;YACjB;;;;;;;;;;;eAWG;YACH,QAAQ,CACN,MAAM,EAAE,kBAAkB,GAAG,kBAAkB,EAAE,EACjD,OAAO,CAAC,EAAE,sBAAsB,GAC/B,SAAS,CAAC,kBAAkB,CAAC,CAAC;SAClC;KACF;CACF"}
@@ -1,10 +1,14 @@
1
1
  /// <reference types="cypress" />
2
2
  import { measureTargets, describeTarget, } from './measure-dom.js';
3
3
  import { isFullyVisible, scrollIntoViewIfNeeded } from './scroll-into-view.js';
4
+ import { readAnnotateConfig } from './config.js';
4
5
  function slugify(text) {
5
6
  return text.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'annotated';
6
7
  }
7
8
  Cypress.Commands.add('annotate', (target, options = {}) => {
9
+ // Project defaults from env.annotate in cypress.config, so a team sets its
10
+ // colour once. Anything passed here wins over them.
11
+ const defaults = readAnnotateConfig();
8
12
  const specs = Array.isArray(target) ? target : [target];
9
13
  const labels = options.label === undefined
10
14
  ? []
@@ -34,12 +38,13 @@ Cypress.Commands.add('annotate', (target, options = {}) => {
34
38
  const firstSpec = specs[0];
35
39
  if (typeof firstSpec !== 'string')
36
40
  return cy.wrap(initial, { log: false });
37
- return scrollIntoViewIfNeeded(firstSpec, options.scrollOffset ?? 120)
41
+ return scrollIntoViewIfNeeded(firstSpec, options.scrollOffset ?? defaults.scrollOffset ?? 120)
38
42
  // Re-measure: the rects from before the scroll are now meaningless.
39
43
  .then(() => cy.window({ log: false }).then((w) => measureTargets(w, specs)));
40
44
  })
41
45
  .then((measurement) => {
42
46
  let screenshotPath;
47
+ let captureReport;
43
48
  return cy
44
49
  .screenshot(name, {
45
50
  capture,
@@ -47,6 +52,11 @@ Cypress.Commands.add('annotate', (target, options = {}) => {
47
52
  log: false,
48
53
  onAfterScreenshot(_el, props) {
49
54
  screenshotPath = props.path;
55
+ // Cypress sets `scaled` at runtime but leaves it out of its types.
56
+ // Without it, send nothing and let the scale be inferred as before.
57
+ const scaled = props.scaled;
58
+ if (typeof scaled === 'boolean')
59
+ captureReport = { pixelRatio: props.pixelRatio, scaled };
50
60
  },
51
61
  })
52
62
  .then(() => {
@@ -56,13 +66,17 @@ Cypress.Commands.add('annotate', (target, options = {}) => {
56
66
  return cy.task('annotateScreenshot', {
57
67
  screenshotPath,
58
68
  measurement,
69
+ captureReport,
59
70
  labels,
60
71
  capture,
61
- crop: options.crop,
62
- cropPadding: options.cropPadding,
63
- shape: options.shape,
64
- style: options.style,
65
- keepRaw: options.keepRaw,
72
+ crop: options.crop ?? defaults.crop,
73
+ cropPadding: options.cropPadding ?? defaults.cropPadding,
74
+ shape: options.shape ?? defaults.shape,
75
+ style: { ...defaults.style, ...options.style },
76
+ keepRaw: options.keepRaw ?? defaults.keepRaw,
77
+ manifestPath: defaults.manifestPath,
78
+ spec: Cypress.spec.relative,
79
+ test: Cypress.currentTest?.titlePath?.join(' > ') ?? name,
66
80
  });
67
81
  })
68
82
  .then((result) => {
@@ -0,0 +1,42 @@
1
+ import type { AnnotationStyle, ShapeKind } from '../types.js';
2
+ /**
3
+ * Project-wide defaults, read from `env.annotate` in cypress.config.
4
+ *
5
+ * export default defineConfig({
6
+ * env: {
7
+ * annotate: {
8
+ * style: { color: '#7C3AED', strokeWidth: 4 },
9
+ * },
10
+ * },
11
+ * });
12
+ *
13
+ * Cypress serialises `env` into the browser, so one block reaches cy.annotate()
14
+ * and the failure hook alike, and `CYPRESS_annotate='{"style":{...}}'` overrides
15
+ * it for a single CI job without a second mechanism to learn.
16
+ *
17
+ * Everything here is also settable per call, and the per-call value wins.
18
+ */
19
+ export interface AnnotateEnvConfig {
20
+ style?: AnnotationStyle;
21
+ shape?: ShapeKind;
22
+ /** Crop to the annotated element rather than keeping the whole viewport. */
23
+ crop?: boolean;
24
+ cropPadding?: number;
25
+ /** Write `<name>.raw.png` beside every annotated shot, for diffing. */
26
+ keepRaw?: boolean;
27
+ /** Leave this many CSS px above an element that had to be scrolled to. */
28
+ scrollOffset?: number;
29
+ /** One JSON record per annotated screenshot. Default out/cypress/annotations.json. */
30
+ manifestPath?: string;
31
+ /** Where failure records accumulate. Default out/cypress/failures.json. */
32
+ reportPath?: string;
33
+ }
34
+ export declare const DEFAULT_MANIFEST_PATH = "out/cypress/annotations.json";
35
+ export declare const DEFAULT_REPORT_PATH = "out/cypress/failures.json";
36
+ /**
37
+ * Reads and validates `Cypress.env('annotate')`. A typo is reported rather than
38
+ * silently dropped, because a theme that quietly does nothing is worse than one
39
+ * that says why.
40
+ */
41
+ export declare function readAnnotateConfig(): AnnotateEnvConfig;
42
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/cypress/config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE9D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,iBAAiB;IAChC,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,4EAA4E;IAC5E,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,uEAAuE;IACvE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,2EAA2E;IAC3E,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,qBAAqB,iCAAiC,CAAC;AACpE,eAAO,MAAM,mBAAmB,8BAA8B,CAAC;AAwE/D;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,iBAAiB,CA8BtD"}
@@ -0,0 +1,102 @@
1
+ export const DEFAULT_MANIFEST_PATH = 'out/cypress/annotations.json';
2
+ export const DEFAULT_REPORT_PATH = 'out/cypress/failures.json';
3
+ const STYLE_KEYS = {
4
+ color: 'string',
5
+ strokeWidth: 'number',
6
+ padding: 'number',
7
+ radius: 'number',
8
+ dimOutside: 'number',
9
+ labelFontSize: 'number',
10
+ labelColor: 'string',
11
+ labelBackground: 'string',
12
+ labelFontFamily: 'string',
13
+ labelFontWeight: 'string|number',
14
+ };
15
+ const TOP_LEVEL_KEYS = {
16
+ style: 'object',
17
+ shape: 'string',
18
+ crop: 'boolean',
19
+ cropPadding: 'number',
20
+ keepRaw: 'boolean',
21
+ scrollOffset: 'number',
22
+ manifestPath: 'string',
23
+ reportPath: 'string',
24
+ };
25
+ const SHAPES = ['box', 'circle', 'arrow'];
26
+ // One warning per distinct problem per run. An afterEach hook would otherwise
27
+ // repeat the same typo once per test, which buries the run's real output.
28
+ const warned = new Set();
29
+ function warn(message) {
30
+ if (warned.has(message))
31
+ return;
32
+ warned.add(message);
33
+ // Cypress.log is unavailable outside a test body, so console is the floor.
34
+ if (typeof Cypress !== 'undefined' && typeof Cypress.log === 'function') {
35
+ Cypress.log({ name: 'annotate', message: `! ${message}` });
36
+ }
37
+ console.warn(`cypress-annotate: ${message}`);
38
+ }
39
+ function typeOf(value) {
40
+ return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;
41
+ }
42
+ function validateStyle(raw) {
43
+ const style = {};
44
+ for (const [key, value] of Object.entries(raw)) {
45
+ const expected = STYLE_KEYS[key];
46
+ if (!expected) {
47
+ warn(`env.annotate.style.${key} is not a style option and was ignored. Valid: ${Object.keys(STYLE_KEYS).join(', ')}.`);
48
+ continue;
49
+ }
50
+ const actual = typeOf(value);
51
+ if (expected === 'string|number' ? actual !== 'string' && actual !== 'number' : actual !== expected) {
52
+ warn(`env.annotate.style.${key} should be a ${expected} but was a ${actual}; ignored.`);
53
+ continue;
54
+ }
55
+ if (key === 'dimOutside' && (value < 0 || value > 1)) {
56
+ warn(`env.annotate.style.dimOutside should be between 0 and 1 but was ${String(value)}; ignored.`);
57
+ continue;
58
+ }
59
+ if (expected === 'number' && value < 0) {
60
+ warn(`env.annotate.style.${key} should not be negative but was ${String(value)}; ignored.`);
61
+ continue;
62
+ }
63
+ style[key] = value;
64
+ }
65
+ return style;
66
+ }
67
+ /**
68
+ * Reads and validates `Cypress.env('annotate')`. A typo is reported rather than
69
+ * silently dropped, because a theme that quietly does nothing is worse than one
70
+ * that says why.
71
+ */
72
+ export function readAnnotateConfig() {
73
+ const raw = typeof Cypress === 'undefined' ? undefined : Cypress.env('annotate');
74
+ if (raw === undefined || raw === null)
75
+ return {};
76
+ if (typeOf(raw) !== 'object') {
77
+ warn(`env.annotate should be an object but was a ${typeOf(raw)}; ignored.`);
78
+ return {};
79
+ }
80
+ const config = {};
81
+ for (const [key, value] of Object.entries(raw)) {
82
+ const expected = TOP_LEVEL_KEYS[key];
83
+ if (!expected) {
84
+ warn(`env.annotate.${key} is not an option and was ignored. Valid: ${Object.keys(TOP_LEVEL_KEYS).join(', ')}.`);
85
+ continue;
86
+ }
87
+ if (typeOf(value) !== expected) {
88
+ warn(`env.annotate.${key} should be a ${expected} but was a ${typeOf(value)}; ignored.`);
89
+ continue;
90
+ }
91
+ if (key === 'style') {
92
+ config.style = validateStyle(value);
93
+ continue;
94
+ }
95
+ if (key === 'shape' && !SHAPES.includes(value)) {
96
+ warn(`env.annotate.shape should be one of ${SHAPES.join(', ')} but was "${String(value)}"; ignored.`);
97
+ continue;
98
+ }
99
+ config[key] = value;
100
+ }
101
+ return config;
102
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"failure-hook.d.ts","sourceRoot":"","sources":["../../src/cypress/failure-hook.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAe,MAAM,aAAa,CAAC;AAGhE,MAAM,WAAW,qBAAqB;IACpC,6DAA6D;IAC7D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,eAAe,CAAC;CACzB;AAQD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,qBAA0B,GAAG,IAAI,CA4IhF"}
1
+ {"version":3,"file":"failure-hook.d.ts","sourceRoot":"","sources":["../../src/cypress/failure-hook.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,aAAa,CAAC;AAG/E,MAAM,WAAW,qBAAqB;IACpC,6DAA6D;IAC7D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,eAAe,CAAC;CACzB;AAMD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,qBAA0B,GAAG,IAAI,CAyJhF"}
@@ -2,7 +2,7 @@
2
2
  import { describeFailure, recoverFailure } from './failure-selector.js';
3
3
  import { collectInventory, measureTargets, readMetrics } from './measure-dom.js';
4
4
  import { isFullyVisible, scrollIntoViewIfNeeded } from './scroll-into-view.js';
5
- const DEFAULT_REPORT_PATH = 'out/cypress/failures.json';
5
+ import { readAnnotateConfig, DEFAULT_REPORT_PATH } from './config.js';
6
6
  function slugify(text) {
7
7
  return text.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase().slice(0, 60) || 'failure';
8
8
  }
@@ -29,10 +29,13 @@ function slugify(text) {
29
29
  * and it becomes ambiguous which one the DOM measurement actually matches.
30
30
  */
31
31
  export function registerFailureCapture(options = {}) {
32
- const reportPath = options.reportPath ?? DEFAULT_REPORT_PATH;
33
32
  afterEach(function () {
34
33
  if (this.currentTest?.state !== 'failed')
35
34
  return;
35
+ // Read inside the hook rather than at registration: the support file is
36
+ // evaluated before Cypress has finished setting up env for the spec.
37
+ const defaults = readAnnotateConfig();
38
+ const reportPath = options.reportPath ?? defaults.reportPath ?? DEFAULT_REPORT_PATH;
36
39
  // Read failure state before issuing any cy.* command below - those mutate
37
40
  // cy.state('current'), so this has to happen first and synchronously.
38
41
  const err = this.currentTest.err;
@@ -88,6 +91,7 @@ export function registerFailureCapture(options = {}) {
88
91
  .then((win) => prepare(win))
89
92
  .then(({ target, resolved, inventory, metrics }) => {
90
93
  let screenshotPath;
94
+ let captureReport;
91
95
  return cy
92
96
  .screenshot(name, {
93
97
  capture: 'viewport',
@@ -95,6 +99,11 @@ export function registerFailureCapture(options = {}) {
95
99
  log: false,
96
100
  onAfterScreenshot(_el, props) {
97
101
  screenshotPath = props.path;
102
+ // Cypress sets `scaled` at runtime but leaves it out of its types.
103
+ // Without it, send nothing and let the scale be inferred as before.
104
+ const scaled = props.scaled;
105
+ if (typeof scaled === 'boolean')
106
+ captureReport = { pixelRatio: props.pixelRatio, scaled };
98
107
  },
99
108
  })
100
109
  .then(() => {
@@ -107,9 +116,14 @@ export function registerFailureCapture(options = {}) {
107
116
  return cy.task('annotateScreenshot', {
108
117
  screenshotPath,
109
118
  measurement: { metrics, targets: [target] },
119
+ captureReport,
110
120
  labels: [label],
111
121
  capture: 'viewport',
112
- style: options.style,
122
+ style: { ...defaults.style, ...options.style },
123
+ keepRaw: defaults.keepRaw,
124
+ manifestPath: defaults.manifestPath,
125
+ spec: Cypress.spec.relative,
126
+ test: testTitle,
113
127
  });
114
128
  })
115
129
  .then((annotateResult) => {
@@ -37,5 +37,11 @@ export interface AppendFailureArgs {
37
37
  reportPath: string;
38
38
  record: FailureRecord;
39
39
  }
40
+ /**
41
+ * Append one record to a JSON array on disk, creating the file and its parent
42
+ * directory if neither exists. Read-modify-write is safe here because Cypress
43
+ * runs tasks one at a time, in the single Node process behind the run.
44
+ */
45
+ export declare function appendRecord<T>(path: string, record: T): Promise<void>;
40
46
  export declare function appendFailureRecord({ reportPath, record }: AppendFailureArgs): Promise<null>;
41
47
  //# sourceMappingURL=failure-report.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"failure-report.d.ts","sourceRoot":"","sources":["../../src/cypress/failure-report.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,eAAe,EAAE,OAAO,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,uEAAuE;IACvE,QAAQ,EAAE,OAAO,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,SAAS,EAAE,SAAS,GAAG,IAAI,CAAC;IAC5B,iFAAiF;IACjF,OAAO,EAAE,WAAW,CAAC;I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C,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,aAAa,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAU5E;AAED,wBAAsB,mBAAmB,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAGlG"}
@@ -1,14 +1,24 @@
1
- import { readFile, writeFile } from 'node:fs/promises';
2
- export async function appendFailureRecord({ reportPath, record }) {
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ /**
4
+ * Append one record to a JSON array on disk, creating the file and its parent
5
+ * directory if neither exists. Read-modify-write is safe here because Cypress
6
+ * runs tasks one at a time, in the single Node process behind the run.
7
+ */
8
+ export async function appendRecord(path, record) {
3
9
  let existing = [];
4
10
  try {
5
- existing = JSON.parse(await readFile(reportPath, 'utf8'));
11
+ existing = JSON.parse(await readFile(path, 'utf8'));
6
12
  }
7
13
  catch (error) {
8
14
  if (error.code !== 'ENOENT')
9
15
  throw error;
16
+ await mkdir(dirname(path), { recursive: true });
10
17
  }
11
18
  existing.push(record);
12
- await writeFile(reportPath, JSON.stringify(existing, null, 2));
19
+ await writeFile(path, JSON.stringify(existing, null, 2));
20
+ }
21
+ export async function appendFailureRecord({ reportPath, record }) {
22
+ await appendRecord(reportPath, record);
13
23
  return null;
14
24
  }
@@ -1,4 +1,4 @@
1
- import type { AnnotationStyle, PixelRect, ShapeKind } from '../types.js';
1
+ import type { AnnotationStyle, CaptureReport, PixelRect, ShapeKind } from '../types.js';
2
2
  import type { DomMeasurement } from './measure-dom.js';
3
3
  /**
4
4
  * The Node half of the Cypress plugin.
@@ -10,6 +10,8 @@ import type { DomMeasurement } from './measure-dom.js';
10
10
  export interface AnnotateTaskArgs {
11
11
  screenshotPath: string;
12
12
  measurement: DomMeasurement;
13
+ /** `pixelRatio` and `scaled` from Cypress's `onAfterScreenshot` props. */
14
+ captureReport?: CaptureReport;
13
15
  labels?: (string | undefined)[];
14
16
  capture?: 'viewport' | 'fullPage';
15
17
  crop?: boolean;
@@ -20,6 +22,28 @@ export interface AnnotateTaskArgs {
20
22
  outPath?: string;
21
23
  /** Also keep the un-annotated pixels, at `<out>.raw.png`. */
22
24
  keepRaw?: boolean;
25
+ /** Where to record what was annotated. Defaults to out/cypress/annotations.json. */
26
+ manifestPath?: string;
27
+ /** Spec and test the annotation came from. Only used for the manifest. */
28
+ spec?: string;
29
+ test?: string;
30
+ }
31
+ /**
32
+ * One line of the run's manifest. CI wants a list of what was produced without
33
+ * having to walk the screenshots folder and guess which files are ours, and a
34
+ * ticket wants to know which test a given image came from.
35
+ */
36
+ export interface AnnotationRecord {
37
+ spec: string | null;
38
+ test: string | null;
39
+ labels: string[];
40
+ outPath: string;
41
+ rawPath: string | null;
42
+ width: number;
43
+ height: number;
44
+ drawnRects: PixelRect[];
45
+ warnings: string[];
46
+ timestamp: string;
23
47
  }
24
48
  export interface AnnotateTaskResult {
25
49
  outPath: string;
@@ -38,10 +62,22 @@ export declare function annotateScreenshot(args: AnnotateTaskArgs): Promise<Anno
38
62
  * any of those overloads; the narrowing cast is contained below.
39
63
  */
40
64
  export type CypressPluginOn = (...args: never[]) => unknown;
65
+ /** The `config` half of setupNodeEvents. Accepted for forwards compatibility. */
66
+ export interface AnnotateSetupConfig {
67
+ env?: Record<string, unknown>;
68
+ }
41
69
  /**
42
70
  * Register in cypress.config setupNodeEvents:
43
71
  *
44
- * setupNodeEvents(on) { registerAnnotateTasks(on); }
72
+ * setupNodeEvents(on, config) { registerAnnotateTasks(on, config); }
73
+ *
74
+ * Deliberately registers nothing but tasks. Cypress allows one handler per run
75
+ * event and silently keeps the last one registered, so taking `before:run` or
76
+ * `after:run` here would quietly stop a project's own handler from firing. The
77
+ * manifest and the job summary are driven from the task instead, which can be
78
+ * registered alongside anything.
79
+ *
80
+ * `config` is optional and currently unused.
45
81
  */
46
- export declare function registerAnnotateTasks(on: CypressPluginOn): void;
82
+ export declare function registerAnnotateTasks(on: CypressPluginOn, _config?: AnnotateSetupConfig): void;
47
83
  //# sourceMappingURL=task.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"task.d.ts","sourceRoot":"","sources":["../../src/cypress/task.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGvD;;;;;;GAMG;AAEH,MAAM,WAAW,gBAAgB;IAC/B,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,cAAc,CAAC;IAC5B,MAAM,CAAC,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,CAAC;IAChC,OAAO,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAClC,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6DAA6D;IAC7D,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,w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