cypress-annotate 0.4.0 → 1.0.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 +142 -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 +5 -0
  8. package/dist/annotate-image.d.ts.map +1 -1
  9. package/dist/annotate-image.js +16 -2
  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 +13 -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 +10 -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 +36 -2
  22. package/dist/cypress/task.d.ts.map +1 -1
  23. package/dist/cypress/task.js +60 -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 +6 -72
  31. package/dist/types.d.ts.map +1 -1
  32. package/package.json +10 -42
  33. package/skills/cypress-annotate/SKILL.md +51 -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
package/README.md CHANGED
@@ -1,409 +1,161 @@
1
1
  # cypress-annotate
2
2
 
3
- A Cypress plugin that draws a pixel-accurate box on exactly what's wrong in a
4
- screenshot. Call `cy.annotate()` where you already know what broke, or register
5
- the failure hook and get a box on every failed test, labelled from the
6
- assertion's own expected and actual values, with no AI involved.
3
+ When a Cypress test fails in CI, the screenshot shows you the whole page. This
4
+ draws a box on the element that actually failed, labelled with the assertion's
5
+ own expected and actual values.
7
6
 
8
- `sharp` is the only thing that installs with it. No browser download, nothing
9
- else to configure.
7
+ ![A failed assertion's target boxed in red, labelled with the expected and actual values](DOCS/images/failure-hook.png)
10
8
 
11
- ## Getting started
9
+ That label came from `err.expected` and `err.actual`, with no model call and no
10
+ network. `sharp` is the only thing that installs with the package.
12
11
 
13
- ### 1. Install
12
+ It overwrites the screenshot Cypress just took, so the annotated version is what
13
+ lands in your reports, your CI artifacts and Cypress Cloud. No second file to
14
+ collect, no reporter to configure.
15
+
16
+ ## Install
14
17
 
15
18
  ```bash
16
19
  npm install --save-dev cypress-annotate
17
20
  ```
18
21
 
19
- Needs Node 20.19+ or 22.12+. The package is ESM, and those are the versions that
20
- can `require()` an ES module, which is what Cypress's default webpack and Babel
21
- preprocessor ends up doing with the import in step 3.
22
-
23
- ### 2. Register the Node task
24
-
25
- The measuring happens in the browser, the image compositing happens in Node. This
26
- is the Node half.
22
+ Needs Node 20.19+ or 22.12+, the versions that can `require()` an ES module,
23
+ which is what Cypress's default preprocessor does with the import below.
27
24
 
28
25
  ```ts
29
26
  // cypress.config.ts
30
- import { defineConfig } from 'cypress';
31
27
  import { registerAnnotateTasks } from 'cypress-annotate/cypress/task';
32
28
 
33
29
  export default defineConfig({
30
+ // Required: Cypress's automatic screenshot would otherwise race the hook's,
31
+ // and it becomes ambiguous which one the DOM measurement matches.
32
+ screenshotOnRunFailure: false,
34
33
  e2e: {
35
- setupNodeEvents(on) {
36
- registerAnnotateTasks(on);
34
+ setupNodeEvents(on, config) {
35
+ registerAnnotateTasks(on, config);
37
36
  },
38
37
  },
39
38
  });
40
39
  ```
41
40
 
42
- ### 3. Register the command
43
-
44
41
  ```ts
45
42
  // cypress/support/e2e.ts
46
43
  import 'cypress-annotate/cypress/commands';
47
- ```
48
-
49
- That adds `cy.annotate()` and its TypeScript types. Nothing else to import in
50
- your specs.
51
-
52
- ### 4. Annotate something
53
-
54
- ```ts
55
- it('flags the broken promo button', () => {
56
- cy.visit('/checkout');
57
- cy.annotate('#promo-apply', { label: 'Apply button escapes its card' });
58
- });
59
- ```
60
-
61
- ### 5. Find the image
62
-
63
- It overwrites the screenshot Cypress just recorded, so the annotated version is
64
- what lands in `cypress/screenshots/`, in your reports, and in CI artifacts. There
65
- is no second file to collect and no reporter to configure.
66
-
67
- That's the whole setup. Everything below is optional.
68
-
69
- ## Using `cy.annotate()`
44
+ import { registerFailureCapture } from 'cypress-annotate/cypress/failure-hook';
70
45
 
71
- ```ts
72
- cy.annotate(selector, options?)
46
+ registerFailureCapture();
73
47
  ```
74
48
 
75
- `selector` is a CSS selector or an array of them. Several at once, each with its
76
- own label:
77
-
78
- ```ts
79
- cy.annotate(['#promo-apply', '#order-ref'], {
80
- label: ['Escapes its card', 'Overflows'],
81
- });
49
+ That's the whole setup. Measuring happens in the browser and compositing in
50
+ Node, which is what the task is for.
51
+
52
+ Every failed test now annotates itself and appends a record to
53
+ `out/cypress/failures.json` with the recovered selector, `expected`, `actual`,
54
+ the image paths and the drawn rect. Failures with no recoverable selector, like
55
+ an existence check, are still captured with a live inventory of candidate
56
+ elements that [annotate-agent](https://github.com/bidemiajala/annotate-agent)
57
+ can hand to Claude afterwards.
58
+
59
+ ## In CI
60
+
61
+ ```yaml
62
+ - run: npx cypress run
63
+ - uses: actions/upload-artifact@v4
64
+ if: always()
65
+ with:
66
+ name: annotated-screenshots
67
+ path: out/cypress
82
68
  ```
83
69
 
84
- Reach into an iframe with `{ frame, selector }`. The offset is the frame's
85
- content origin, so a frame with its own border and padding lands correctly, and a
86
- frame scrolled internally needs no correction:
87
-
88
- ```ts
89
- cy.annotate({ frame: 'iframe#checkout', selector: '.pay-button' }, {
90
- label: 'Pay button overflows the frame',
91
- });
70
+ **Without Cypress Cloud**, the annotated PNG is what `upload-artifact` collects,
71
+ because the annotation is written over the screenshot before the run ends.
92
72
 
93
- // nested frames, outermost first
94
- cy.annotate({ frame: ['iframe#outer', 'iframe#inner'], selector: '.total' });
73
+ **With Cypress Cloud**, it is the same file and the same code path: a
74
+ `cy.screenshot()` overwritten in place is picked up by `cypress run --record`
75
+ and uploaded as a normal `Screenshot` artifact. Confirmed against a real
76
+ recorded run. No Cloud API is involved and there is nothing to configure.
95
77
 
96
- // mix frame targets and plain ones in a single shot
97
- cy.annotate([
98
- '#order-ref',
99
- { frame: 'iframe#checkout', selector: '.pay-button' },
100
- ], { label: ['Overflows', 'Escapes its card'] });
101
- ```
78
+ A run also writes `out/cypress/annotations.json`, one record per annotated
79
+ screenshot, and on GitHub Actions appends a table of it to the job summary.
102
80
 
103
- Cross-origin frames cannot be measured from the page, so those fail loudly
104
- rather than drawing a box in the wrong place.
81
+ ## Make it yours
105
82
 
106
- Crop tight to the element with the rest of the page dimmed, which is usually what
107
- you want to paste into a ticket:
83
+ Set your defaults once, in `cypress.config.ts`:
108
84
 
109
85
  ```ts
110
- cy.annotate('#promo-apply', { label: 'Escapes its card', crop: true, cropPadding: 80 });
111
- ```
112
-
113
- Assert on where the box actually landed. The command yields the result:
114
-
115
- ```ts
116
- cy.annotate('#grand-total-value', { label: 'Wrong total' }).then((result) => {
117
- expect(result.warnings).to.be.empty;
118
- expect(result.drawnRects[0].width).to.be.greaterThan(0);
86
+ export default defineConfig({
87
+ env: {
88
+ annotate: {
89
+ style: { color: '#7C3AED', strokeWidth: 4, labelBackground: '#1F1F23' },
90
+ keepRaw: true,
91
+ },
92
+ },
119
93
  });
120
94
  ```
121
95
 
122
- ### Options
123
-
124
- | Option | Default | What it does |
125
- | --- | --- | --- |
126
- | `label` | none | Text on the box. One string, or one per selector in order. |
127
- | `name` | slug of the first selector | Screenshot filename. |
128
- | `crop` | `false` | Crop to the element and dim everything outside it. |
129
- | `cropPadding` | pipeline default | CSS px of context to keep around the crop. |
130
- | `shape` | `box` | Shape drawn around the target. |
131
- | `style` | none | Colours, stroke width, label colour, dim strength. |
132
- | `scrollIntoView` | `true` | Scroll the first target into view, but only if it isn't already. |
133
- | `scrollOffset` | `120` | CSS px left above the element when scrolling, so a fixed header doesn't cover it. |
134
- | `keepRaw` | `false` | Keep the un-annotated image alongside, for pixel assertions. |
135
- | `fullPage` | `false` | Capture the whole document. See the warning under [Things that will bite you](#things-that-will-bite-you). |
96
+ Cypress serialises `env` into the browser, so that one block reaches
97
+ `cy.annotate()` and the failure hook alike, and
98
+ `CYPRESS_annotate='{"style":{"color":"#0A9E4A"}}'` overrides it for a single CI
99
+ job. A misspelled key warns rather than being silently ignored. Layers merge
100
+ lowest first: built-in defaults, this block, the options passed to one call,
101
+ then a per-target style.
136
102
 
137
- ### What it yields
103
+ **`style`:** `color` `#FF3B30`, `strokeWidth` `3`, `padding` `4`, `radius` `6`,
104
+ `dimOutside` `0`, `labelFontSize` `14`, `labelColor` `#FFFFFF`,
105
+ `labelBackground` (defaults to `color`), `labelFontFamily`, `labelFontWeight`
106
+ `600`. Sizes are CSS px, scaled to the capture.
138
107
 
139
- | Field | Meaning |
140
- | --- | --- |
141
- | `outPath` | Where the annotated image was written. |
142
- | `rawPath` | The un-annotated image, when `keepRaw` is set. |
143
- | `width`, `height` | Image dimensions in pixels. |
144
- | `scale` | The device pixel ratio actually measured off the image. |
145
- | `drawnRects` | Final box positions, in image pixels. |
146
- | `warnings` | Anything ambiguous, such as a selector matching more than one element. |
108
+ **Everything else:** `shape` `box`, `crop` `false`, `cropPadding` `40`,
109
+ `keepRaw` `false`, `scrollOffset` `120`, `manifestPath`, `reportPath`.
147
110
 
148
- ## Annotating every failed test
111
+ ## Annotating on purpose
149
112
 
150
- For "the wrong text showed" and similar assertion failures, you can skip
151
- `cy.annotate()` entirely and have every failure annotate itself.
152
-
153
- ### 1. Turn off Cypress's own failure screenshot
113
+ When you already know what's wrong, box it yourself. Several targets at once,
114
+ each with its own label, and `{ frame, selector }` to reach inside an iframe:
154
115
 
155
116
  ```ts
156
- // cypress.config.ts
157
- export default defineConfig({
158
- screenshotOnRunFailure: false,
159
- // ...
117
+ cy.annotate(['#promo-apply', { frame: 'iframe#checkout', selector: '.pay' }], {
118
+ label: ['Escapes its card', 'Overflows the frame'],
160
119
  });
161
120
  ```
162
121
 
163
- This is required. Otherwise Cypress's automatic screenshot and this hook's
164
- screenshot race each other, and it becomes ambiguous which one the DOM
165
- measurement matches.
122
+ The frame offset used is its content origin, so a frame with its own border and
123
+ padding lands correctly, and one scrolled internally needs no correction.
124
+ Cross-origin frames fail loudly rather than drawing a box in the wrong place.
166
125
 
167
- ### 2. Register the hook
126
+ Crop tight for a ticket, and dim separately, since a crop on its own keeps the
127
+ surroundings at full brightness:
168
128
 
169
129
  ```ts
170
- // cypress/support/e2e.ts
171
- import { registerFailureCapture } from 'cypress-annotate/cypress/failure-hook';
172
-
173
- registerFailureCapture();
174
- ```
175
-
176
- Optionally, `registerFailureCapture({ reportPath: 'out/cypress/failures.json' })`
177
- to move the report, or pass `style` to change the box colours.
178
-
179
- ### 3. Run your suite as normal
180
-
181
- Every failed test now produces an annotated screenshot and one record in
182
- `out/cypress/failures.json`.
183
-
184
- ### What you get
185
-
186
- On each failure the hook recovers the selector the failing command was targeting,
187
- using `cy.state('current')`'s own args where they're available and falling back
188
- to chai-jquery's `<tag#id>` rendering in the error message. It measures that
189
- element live while the page is still in its failed state, scrolls it into view if
190
- needed, and draws a box labelled from the assertion's own values:
191
-
192
- > Expected "THIS WILL NOT MATCH" but got "£244.99"
193
-
194
- That label comes entirely from `err.expected` and `err.actual`, with **zero LLM
195
- calls**. Each record in the report carries the spec and test name, the recovered
196
- `selector` and where it came from, `expected` and `actual`, the `label`, the
197
- screenshot and annotated image paths, `drawnRect`, page `metrics`, and warnings.
198
-
199
- **When no selector can be recovered**, as with an existence check, a
200
- `cy.contains()` chain, or a generic page-state assertion, there's nothing to box
201
- deterministically. Those failures still get captured for free: a plain screenshot
202
- plus a live inventory of candidate elements, because a screenshot on its own
203
- carries no DOM information and the browser session will be gone by the time
204
- anyone looks at it. Getting Claude to explain those is a separate, explicit step,
205
- covered in [DOCS/pipeline.md](DOCS/pipeline.md).
206
-
207
- ### Cypress Cloud
208
-
209
- **Confirmed working against a real recorded run.** A `cy.screenshot()` call taken
210
- from an `afterEach` hook, overwritten in place with the annotation before the run
211
- ends, is picked up by `cypress run --record` and uploaded as a normal
212
- `Screenshot` cloud artifact, under the same category label and through the same
213
- pipeline as any other Cypress screenshot. The uploaded image showed the box.
214
-
215
- That confirmation replaced an earlier design that looked obviously safer:
216
- overwrite Cypress's own *automatic* on-failure screenshot in place, on the theory
217
- that mutating the file Cypress already tracks removes all doubt. It doesn't work.
218
- That automatic screenshot includes the full Runner UI, meaning the command log
219
- sidebar, the browser toolbar, and the app rendered at some auto-computed zoom
220
- that is never a 1:1 capture, so there's no reliable coordinate math to draw a box
221
- on it at all. The `cy.screenshot({capture: 'viewport'})` this hook takes is a
222
- clean, predictable capture, the same one every alignment test in this repo is
223
- verified against, and the `--record` result above shows that uploading it costs
224
- nothing in Cloud compatibility.
225
-
226
- Nothing in this path calls Claude, spends money, or needs `ANTHROPIC_API_KEY`
227
- available to the test job. Every CI run captures its data for free.
228
-
229
- ## Using this with an AI coding agent
230
-
231
- The package ships a skill file at `skills/cypress-annotate/SKILL.md` covering the
232
- setup, every option, and the traps worth knowing. For Claude Code, copy it into
233
- your project:
234
-
235
- ```bash
236
- cp node_modules/cypress-annotate/skills/cypress-annotate/SKILL.md \
237
- .claude/skills/cypress-annotate/SKILL.md
238
- ```
239
-
240
- Agents working inside this repo should read [AGENTS.md](AGENTS.md) instead.
241
-
242
- ## Things that will bite you
243
-
244
- **A pitfall if you write your own chai assertions against `err.expected` and
245
- `err.actual`:** they hold chai's own quoted rendering of the value rather than
246
- the raw value. `.should('have.text', 'X')` puts `'X'` into `err.expected` with
247
- the quote marks included. An early version of this feature got that wrong, and it
248
- was fixed by running a real Cypress failure and inspecting the field.
249
-
250
- **Full-page capture repeats fixed elements.** Cypress builds a full-page
251
- screenshot by scrolling and stitching, so `position: fixed` and `sticky` elements
252
- are painted several times in one image. Viewport capture is therefore the default
253
- and `fullPage` is opt-in.
254
-
255
- **`cy.scrollIntoView()` always scrolls**, whether or not the element is already
256
- on screen. Calling it unconditionally shoved a perfectly visible element up under
257
- the fixed header, where the annotation was correct but the element was hidden
258
- behind it. The command now measures first and only scrolls when the element is
259
- genuinely not fully visible, leaving `scrollOffset` px of clearance when it does.
260
-
261
- **Cypress scales the app when the window is smaller than the viewport**, and the
262
- screenshot may not be `viewport × devicePixelRatio`. `resolveScale()` measures
263
- the real ratio off the image and corrects for it.
264
-
265
- **If Cypress fails to start with "bad option: --no-sandbox"**, something in your
266
- environment has set `ELECTRON_RUN_AS_NODE=1`, which VS Code's extension host
267
- does. Cypress's binary is Electron, so it starts as plain Node and rejects
268
- Chromium flags. `npm run test:cypress` goes through
269
- [scripts/run-cypress.ts](scripts/run-cypress.ts), which strips that variable.
270
-
271
- **Worth knowing for any visual assertion in Cypress:** Electron's macOS capture
272
- applies a colour-profile shift. A fixture painted `#FF00E4` comes back as
273
- `rgb(234,51,221)`. Exact-colour assertions against your stylesheet will fail, so
274
- the test suite samples the rendered colour out of the image.
275
-
276
- ## The coordinate rules
277
-
278
- Four things have to line up, and each one is a separate opportunity to be a few
279
- pixels off. These are the rules the engine follows.
280
-
281
- **1. `getBoundingClientRect()` is viewport-relative and post-transform.**
282
- It already accounts for CSS transforms, internally scrolled ancestors, and
283
- sub-pixel layout. It does *not* account for page scroll or iframes.
284
-
285
- **2. Scroll offset applies only to a full-page capture, and only for elements
286
- that scroll.** A viewport screenshot is in the same space the rect is already in,
287
- so adding scroll there is the classic off-by-a-scroll bug. A full-page screenshot
288
- is document space, so `rect + scrollX/scrollY`. A `position: fixed` element has
289
- no document position at all, which the fixed-element note below covers.
290
-
291
- **3. Device pixel ratio scales CSS px to image px, but verify it rather than
292
- trusting it.** `resolveScale()` in [src/annotate.ts](src/annotate.ts) checks the
293
- produced image against `cssWidth × devicePixelRatio`; if they disagree by more
294
- than 2px it derives the real scale from the image and records a warning. Stroke
295
- widths, font sizes and padding are all specified in CSS px and multiplied by that
296
- same scale, so annotations look identical at dpr 1, 2 and 3.
297
-
298
- **4. Iframes add their content origin, not their border box.** The offset is
299
- `iframeRect.left + borderLeftWidth + paddingLeft`. A frame's own internal scroll
300
- needs no correction, since a rect measured inside the frame is already relative
301
- to that frame's viewport.
302
-
303
- ### The fixed-element trap
304
-
305
- Chromium's full-page capture paints `position: fixed` elements **once**, at
306
- whatever scroll offset the capture started from. So for a fixed element there is
307
- no correct "document position", and adding scroll to it puts the box thousands of
308
- pixels away from the thing it should mark.
309
-
310
- The engine detects fixed ancestry during measurement, skips the scroll correction
311
- for those elements, scrolls to the top before full-page captures by default
312
- (`scrollToTop`), and emits a warning so the caller knows why.
313
-
314
- ## How alignment is verified
315
-
316
- Eyeballing a screenshot does not prove pixel accuracy, so nothing here relies on
317
- it.
318
-
319
- Every target in [fixtures/test-page.html](fixtures/test-page.html) is painted a
320
- flat, unique colour with no radius, border or shadow, so the pixels it paints are
321
- exactly its border box. [scripts/verify.ts](scripts/verify.ts) scans the
322
- un-annotated capture for that colour, recovers the element's true pixel
323
- footprint, and compares it against the rect the engine computed.
324
-
325
- 20 cases pass: dpr 1/2/3, CSS transforms, iframe nesting with border and padding,
326
- internally scrolled containers, below-the-fold targets under both auto-scroll and
327
- manual scroll, full-page and cropped captures, fixed elements under scroll, and
328
- the percentage-region fallback in both bases.
329
-
330
- Residual drift is ≤1.13px at dpr 3, and it comes from scanner quantisation.
331
- `#target-top` sits at y=147.375 CSS px, so its top edge falls on device pixel
332
- 294.75 and the partially covered row 294 fails the colour test. Its x is an
333
- integer and the horizontal delta is exactly 0.00. The same 0.5-device-pixel
334
- signature shows up on every case, always on the axis with a fractional
335
- coordinate.
336
-
337
- ## Working on this repo
338
-
339
- ```bash
340
- npm install
341
- npm run test:cypress # cypress plugin, 7 cases, real Cypress 15
342
- npm run test:failure-selector # failed-test selector recovery, 12 cases, no browser
343
- npm run test:cypress-failures # failed-test capture end-to-end, 4 cases, real Cypress 15
344
- npm run test:svg-escaping # SVG injection regression suite, 5 cases
345
- npm run typecheck
130
+ cy.annotate('#promo-apply', {
131
+ label: 'Apply button escapes its card',
132
+ crop: true,
133
+ cropPadding: 220,
134
+ style: { dimOutside: 0.45 },
135
+ });
346
136
  ```
347
137
 
348
- The alignment suite in the section above drives a headless browser directly, so
349
- it needs a little more setup. [DOCS/pipeline.md](DOCS/pipeline.md) covers it.
350
-
351
- ### Publishing and packaging
352
-
353
- **The build runs automatically on install.** This repo ships TypeScript source
354
- and `dist/` is gitignored, so npm's `prepare` script (`tsc` plus a small
355
- asset-copy step) runs on install. Confirmed by installing the packed tarball into
356
- an empty project and importing each entry point, which is also what the
357
- `package install` CI job does on every run.
358
-
359
- Every peer dependency is marked optional, so npm installs none of them for you
360
- and stays quiet about it, as long as you only use entry points that don't need
361
- them. The three Cypress entry points need nothing beyond `cypress` itself.
138
+ ![The Apply button boxed and labelled, with the surrounding page dimmed](DOCS/images/crop.png)
362
139
 
363
- That separation was worth proving. The first attempt at the split missed a case:
364
- `ClaudeReasoner` lived in the same file as several utility functions that the
365
- root barrel re-exports, so importing anything at all from `'cypress-annotate'`,
366
- even `annotateImage`, threw `ERR_MODULE_NOT_FOUND` for `@anthropic-ai/sdk`
367
- whether or not you ever touched the reasoner. Reading the code would never have
368
- shown it, because an ES module evaluates a whole file's top-level code the moment
369
- anything is imported from it, peer-optional or otherwise. What caught it was
370
- installing the built package into an isolated scratch project with no peers
371
- present and importing each entry point for real. CI now does that on every push.
140
+ The command yields where the box landed, so you can assert on it: `drawnRects`,
141
+ `warnings`, `outPath`, `rawPath`, `width`, `height` and `scale`. Per call you
142
+ can also set `name`, a one-off `style`, `scrollIntoView`, and `fullPage`, which
143
+ Cypress builds by scrolling and stitching, so fixed elements get painted several
144
+ times into one image. Viewport capture is the default for that reason.
372
145
 
373
146
  ## Known limits
374
147
 
375
- - Label pill widths are estimated from an average glyph ratio, because librsvg
376
- gives no text measurement API. Long labels get slightly generous padding.
377
- - The Cypress plugin is exercised on Electron, Chrome and Firefox in CI, so
378
- element measurement, dpr scaling, transforms, cropping and iframe offsets are
379
- verified on Gecko as well as Chromium. The alignment suites behind
380
- [How alignment is verified](#how-alignment-is-verified) still run on Chromium
381
- only, and no suite on any browser covers the fixed-element behaviour in
382
- coordinate rule 2, which the plugin sidesteps by capturing the viewport by
383
- default.
384
-
385
- ## The CLI
386
-
387
- Installing the package puts a `cypress-annotate` binary on your path. It drives
388
- the Playwright pipeline rather than the Cypress plugin, so it needs the optional
389
- peer:
390
-
391
- ```bash
392
- npm install playwright
393
- npx playwright install chromium
394
-
395
- npx cypress-annotate --url https://example.com --selector 'a' --label 'Broken link'
396
- npx cypress-annotate --help
397
- ```
398
-
399
- Run it without playwright and it says so, along with the two commands that fix
400
- it. `--selector` and `--label` are repeatable and pair up in order, and
401
- `iframe#pay >>> .btn` reaches into a frame.
402
-
403
- ## Also in this package
404
-
405
- The same coordinate engine powers two things the Cypress plugin never touches: a
406
- general annotation pipeline you can point at any URL, and a Claude-based
407
- reasoning layer that decides *what's* wrong before drawing the box. Both are
408
- optional and neither installs by default.
409
- [DOCS/pipeline.md](DOCS/pipeline.md) covers them.
148
+ - Label widths are estimated from an average glyph ratio, because librsvg gives
149
+ no text measurement API. The ratio suits the default sans stack, so an
150
+ unusually wide or narrow `labelFontFamily` wraps a little early or late.
151
+ - CI covers Electron, Chrome and Firefox. No suite covers fixed elements under a
152
+ full-page capture, which the plugin sidesteps by capturing the viewport.
153
+ - The failure hook reads `cy.state('current')`, undocumented Cypress internals.
154
+ It is guarded, so an upgrade that renames it degrades to "no selector
155
+ recovered" rather than breaking your `afterEach`.
156
+
157
+ [DOCS/internals.md](DOCS/internals.md) has the coordinate rules, the traps worth
158
+ knowing before you hit them, and how alignment is verified against painted
159
+ pixels. `skills/cypress-annotate/SKILL.md` is the same material for a coding
160
+ agent. [CHANGELOG.md](CHANGELOG.md) covers what changed in 1.0.0 and how to
161
+ migrate. MIT.
@@ -45,6 +45,11 @@ export interface AnnotateImageResult {
45
45
  drawnRects: PixelRect[];
46
46
  warnings: string[];
47
47
  }
48
+ /**
49
+ * Merge style layers, lowest priority first. `labelBackground` defaults to
50
+ * whatever `color` resolved to, so setting one brand colour themes the outline
51
+ * and the label pill together, and setting both still works.
52
+ */
48
53
  export declare function resolveStyle(...layers: (AnnotationStyle | undefined)[]): Required<AnnotationStyle>;
49
54
  /**
50
55
  * The image-pixels-per-CSS-pixel ratio actually used for this capture.
@@ -1 +1 @@
1
- {"version":3,"file":"annotate-image.d.ts","sourceRoot":"","sources":["../src/annotate-image.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK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,CAAC;CACpB;AAeD;;;;GAIG;AAEH,wBAAgB,YAAY,CAAC,GAAG,MAAM,EAAE,CAAC,eAAe,GAAG,SAAS,CAAC,EAAE,GAAG,QAAQ,CAAC,eAAe,CAAC,CAQlG;AAoCD;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAAE,GACjB,MAAM,CAgBR;AAYD,wBAAsB,aAAa,CACjC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,cAAc,EAAE,EACzB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,mBAAmB,CAAC,CAkG9B"}
@@ -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) {
@@ -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,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE9D;;;;;;;;GAQG;AAEH,MAAM,WAAW,sBAAsB;IACrC,kCAAkC;IAClC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC1B,iEAAiE;IACjE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2EAA2E;IAC3E,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,E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,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;AA0FnC,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,7 +38,7 @@ 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
  })
@@ -58,11 +62,14 @@ Cypress.Commands.add('annotate', (target, options = {}) => {
58
62
  measurement,
59
63
  labels,
60
64
  capture,
61
- crop: options.crop,
62
- cropPadding: options.cropPadding,
63
- shape: options.shape,
64
- style: options.style,
65
- keepRaw: options.keepRaw,
65
+ crop: options.crop ?? defaults.crop,
66
+ cropPadding: options.cropPadding ?? defaults.cropPadding,
67
+ shape: options.shape ?? defaults.shape,
68
+ style: { ...defaults.style, ...options.style },
69
+ keepRaw: options.keepRaw ?? defaults.keepRaw,
70
+ manifestPath: defaults.manifestPath,
71
+ spec: Cypress.spec.relative,
72
+ test: Cypress.currentTest?.titlePath?.join(' > ') ?? name,
66
73
  });
67
74
  })
68
75
  .then((result) => {