@circi/cypress 0.0.0-stage → 0.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.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # @circi/cypress
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [CirCI](https://circi.dev) plugin for Cypress. Your tests keep Cypress's own `cy.screenshot('name')`; the plugin copies each named screenshot to `.circi/screenshots/cypress/<spec path>/<name>.png` and `cypress run` uploads them to your CirCI server when it ends. CirCI compares and reviews them.
4
+
5
+ ```ts
6
+ // cypress.config.ts
7
+ import { circi } from '@circi/cypress'
8
+ import { defineConfig } from 'cypress'
9
+
10
+ export default defineConfig({
11
+ e2e: {
12
+ setupNodeEvents: circi({ name: 'cypress-chrome' }),
13
+ },
14
+ })
15
+ ```
16
+
17
+ ```ts
18
+ // cypress/support/e2e.ts (and component.ts)
19
+ import '@circi/cypress/support'
20
+ ```
21
+
22
+ ```ts
23
+ cy.visit('/')
24
+ cy.screenshot('home')
25
+ cy.get('header').screenshot('header')
26
+ ```
27
+
28
+ The screenshots are named `<spec path from the project root>/<name>`, like `@circi/vitest` names its own: `cypress/e2e/home.cy.ts/home`, `cypress/e2e/home.cy.ts/header`. The whole path is in the name, so `admin/home.cy.ts` and `public/home.cy.ts` never share a screenshot. Always pass a name: one with nothing usable in it (`'!!'`) is skipped with a `[circi] skipped screenshot` notice, and the test is unaffected. Renaming or moving a spec file starts new baselines.
29
+
30
+ If you already have a `setupNodeEvents`, call the plugin inside it:
31
+
32
+ ```ts
33
+ setupNodeEvents(on, config) {
34
+ circi({ name: 'cypress-chrome' })(on, config)
35
+ // your own setup
36
+ return config
37
+ }
38
+ ```
39
+
40
+ Cypress keeps one handler per event (`before:run`, `after:screenshot`, `after:run`), so a handler of your own for one of them replaces the plugin's or the other way round: use a helper such as `cypress-on-fix` if you need both.
41
+
42
+ ## What is uploaded
43
+
44
+ Every screenshot a run takes with a name. Cypress's automatic screenshot of a failing test, and a `cy.screenshot()` without a name, are not. Each file gets a `.png.json` next to it with the spec, the browser and the viewport, which CirCI keeps with the screenshot. The upload happens in `cypress run` only (not in `cypress open`). Each tool keeps its own folder under `dir`, and the plugin writes, empties (when a run starts, so a build holds only that run's screenshots) and uploads only `<dir>/cypress`: another tool's folder, like `@circi/vitest`'s, is never touched.
45
+
46
+ The upload is the same code as `circi upload`: `CIRCI_API_URL` and `CIRCI_TOKEN` say where and who, and the commit, branch and pull request come from your CI. Without them the plugin prints `[circi] skipped: set CIRCI_API_URL and CIRCI_TOKEN to upload screenshots` and the run is unaffected, as with `@circi/vitest`.
47
+
48
+ ## What a screenshot shows
49
+
50
+ The support file keeps `cy.screenshot()`'s signature and what it yields, and changes what it captures so that a screenshot holds the thing and nothing around it:
51
+
52
+ - **An element** (`cy.get(sel).screenshot('x')`): its own box, cropped tight.
53
+ - **The page** (`cy.screenshot('x')`): the content of the page, as tall as the content is. A short page isn't padded to the viewport's height, and Cypress's own interface isn't in it.
54
+ - **Component testing**: the mounted component's box (the one element inside `[data-cy-root]`), not the viewport.
55
+ - An element with no size, or one that is hidden, is an error (`nothing to capture`), not a blank image.
56
+ - `padding` adds space on purpose: `cy.get(sel).screenshot('x', { padding: 10 })`. On a page it adds space below the content, up to the end of the document.
57
+ - An explicit `capture` or `clip` is left as you wrote it.
58
+
59
+ Before it captures, it also waits for fonts, and stops animations and the caret. It sets `Cypress.Screenshot.defaults` to `capture: 'fullPage'` and `disableTimersAndAnimations: true`.
60
+
61
+ ## Options
62
+
63
+ The same options, names and defaults as the `@circi/vitest` reporter:
64
+
65
+ | Option | Default | Meaning |
66
+ | --------- | ----------------------- | -------------------------------------------------------------------------- |
67
+ | `apiUrl` | `CIRCI_API_URL` | CirCI address. |
68
+ | `token` | `CIRCI_TOKEN` | Project CI token. |
69
+ | `name` | `cypress` | Build name; give each browser or suite its own (`cypress-chrome`). |
70
+ | `dir` | `.circi/screenshots` | The folder shared by the tools; this plugin uses `<dir>/cypress`, relative to the project root. |
71
+ | `clean` | `true` | Empty `<dir>/cypress` (only that folder) when the run starts. |
72
+ | `root` | Cypress's `projectRoot` | Project root to look in. |
73
+ | `wait` | `false` | Wait for the result and fail the run while changes need review. |
74
+ | `strict` | `false` | Also fail the run if the upload fails. By default tests pass or fail alone. |
75
+ | `shard` | `CIRCI_SHARD` (`2/4`) | This machine's shard (`{ index, total }`, `index` from 0) of a parallel run. |
76
+
77
+ With `wait`, the run fails (a non-zero exit code) while changes need review. With machines running one run in parallel, give each its shard (the same `name` on every machine): they become one CirCI build, processed once all of them have uploaded.
78
+
79
+ Tested with Cypress 16.3 (Electron, end-to-end and component testing); needs Node 22 or later. `peerDependencies` allows Cypress 13 or later, which hasn't been tried.
80
+
81
+ - [Changelog](https://github.com/cir-ci/repo/blob/main/packages/cypress/CHANGELOG.md)
82
+
83
+ Licensed under the GNU GPL v3.
@@ -0,0 +1,332 @@
1
+ /** Thin client for the CirCI `/v1` API, using the built-in fetch. */
2
+ declare namespace ApiClient {
3
+ interface Options {
4
+ baseUrl: string;
5
+ token: string;
6
+ fetch?: typeof fetch | undefined;
7
+ /** Per request, in milliseconds (default 30 s; file and site uploads get four times that). */
8
+ timeoutMs?: number;
9
+ /** Tries per call for transient failures (default 4). */
10
+ attempts?: number;
11
+ /** First backoff in milliseconds; each retry doubles it, with jitter (default 500). */
12
+ retryDelayMs?: number | undefined;
13
+ }
14
+ interface Project {
15
+ workspace: string;
16
+ slug: string;
17
+ name: string;
18
+ defaultBranch: string;
19
+ dashboardUrl: string;
20
+ }
21
+ interface Build {
22
+ id: string;
23
+ number: number;
24
+ name: string;
25
+ status: string;
26
+ conclusion: string | null;
27
+ reviewStatus: string;
28
+ url: string;
29
+ }
30
+ interface UploadInstruction {
31
+ sha256: string;
32
+ url: string;
33
+ method: 'PUT';
34
+ headers: Record<string, string>;
35
+ /** `token`: send the project token too (uploads through the API, local-disk storage). */
36
+ auth: 'token' | 'none';
37
+ }
38
+ interface Status {
39
+ build: ApiClient.Build;
40
+ counts: {
41
+ added: number;
42
+ removed: number;
43
+ changed: number;
44
+ unchanged: number;
45
+ failed: number;
46
+ total: number;
47
+ };
48
+ /** Screenshots the server couldn't read, with why. */
49
+ unreadable: {
50
+ name: string;
51
+ reason: string;
52
+ }[];
53
+ outcome: {
54
+ state: 'pending' | 'pass' | 'fail';
55
+ summary: string;
56
+ warning?: string;
57
+ };
58
+ gate: 'exit-code' | 'status';
59
+ errorMessage: string | null;
60
+ }
61
+ interface SiteUpload {
62
+ site: {
63
+ name: string;
64
+ kind: string;
65
+ slug: string;
66
+ };
67
+ version: {
68
+ commitSha: string;
69
+ fileCount: number;
70
+ totalBytes: number;
71
+ };
72
+ addresses: {
73
+ commit: string;
74
+ branch?: string;
75
+ };
76
+ branchMoved: boolean;
77
+ replaced: boolean;
78
+ }
79
+ }
80
+ declare class ApiClient {
81
+ readonly baseUrl: string;
82
+ private readonly token;
83
+ private readonly fetchImpl;
84
+ private readonly timeoutMs;
85
+ private readonly attempts;
86
+ private readonly retryDelayMs;
87
+ constructor(options: ApiClient.Options);
88
+ project(): Promise<ApiClient.Project>;
89
+ createBuild(body: Record<string, unknown>): Promise<{
90
+ build: ApiClient.Build;
91
+ uploads: ApiClient.UploadInstruction[];
92
+ }>;
93
+ finalize(buildId: string, body: Record<string, unknown>): Promise<{
94
+ build: ApiClient.Build;
95
+ complete: boolean;
96
+ shardsReceived: number;
97
+ shardsTotal: number;
98
+ }>;
99
+ status(buildId: string, gate?: 'status' | 'exit-code'): Promise<ApiClient.Status>;
100
+ /** Uploads a site (a `.tar.gz`); the query says what and where it is. */
101
+ uploadSite(query: Record<string, string>, archive: Uint8Array): Promise<ApiClient.SiteUpload>;
102
+ /** The commit a branch's address serves now, or null when the server says it has none yet. */
103
+ servedCommit(name: string, branch: string): Promise<string | null>;
104
+ /** Sends one file as instructed by the server, retrying transient failures. */
105
+ upload(instruction: ApiClient.UploadInstruction, bytes: Uint8Array): Promise<void>;
106
+ /** One request with a timeout; a failure to get an answer becomes a `NetworkError`. */
107
+ private send;
108
+ /** Reads the answer; a non-2xx one throws an `ApiError` carrying the server's `error` text. */
109
+ private parse;
110
+ private json;
111
+ }
112
+ declare namespace detectCi {
113
+ interface Context {
114
+ provider: 'github' | 'gitea' | 'gitlab' | 'bitbucket' | 'circleci' | 'buildkite' | 'jenkins' | 'azure' | 'local';
115
+ /** The commit that was built. For PRs this is the PR's head, never a synthetic merge commit. */
116
+ commitSha?: string;
117
+ branch?: string;
118
+ prNumber?: number;
119
+ /** Branch the PR targets. */
120
+ baseBranch?: string;
121
+ /** The PR comes from a fork (PLAN §7.6: forks never move branch links). */
122
+ fromFork?: boolean;
123
+ /** Link to the CI job, for "re-run to unblock" messages. */
124
+ jobUrl?: string;
125
+ /** Who triggered the run, as the CI names them. The server may replace it with the PR's author. */
126
+ author?: detectCi.Author;
127
+ }
128
+ interface Author {
129
+ login: string;
130
+ email?: string;
131
+ /** Sign-in provider the id belongs to, so the server can match a linked account. */
132
+ provider?: string;
133
+ providerId?: string;
134
+ }
135
+ }
136
+ type Env = Record<string, string | undefined>;
137
+ type ReadJson = (path: string) => unknown;
138
+ declare function detectCi(env: Env, readJson: ReadJson): detectCi.Context;
139
+ declare namespace CirciOptions {
140
+ /** One shard of a parallel build; the build is processed once all `total` shards arrive. */
141
+ interface Shard {
142
+ /** 0-based. */
143
+ index: number;
144
+ total: number;
145
+ /** Ties the shards together. Default: the CI run's ID. */
146
+ nonce?: string;
147
+ }
148
+ /**
149
+ * The options every CirCI integration that writes screenshots and uploads them when it is done
150
+ * shares (`@circi/vitest`'s reporter, `@circi/storybook`'s addon): same names, same meanings,
151
+ * same defaults.
152
+ */
153
+ interface Common {
154
+ /** CirCI address. Default: `CIRCI_API_URL`. */
155
+ apiUrl?: string;
156
+ /** Project CI token. Default: `CIRCI_TOKEN`. */
157
+ token?: string;
158
+ /** Build name; give each kind of build its own. Each integration has its own default. */
159
+ name?: string;
160
+ /**
161
+ * The folder that holds the captures, relative to the project root. Default `.circi/screenshots`.
162
+ * Each tool writes, cleans and uploads only its own folder inside it: `<dir>/vitest`,
163
+ * `<dir>/storybook`, `<dir>/cypress`.
164
+ */
165
+ dir?: string;
166
+ /** Empty this tool's folder in `dir` when the run starts, so a build holds only this run's captures. Default false. */
167
+ clean?: boolean;
168
+ /** Project root to look in. Default: the working directory (Vitest: the root of the run). */
169
+ root?: string;
170
+ /** Wait for the result and fail the run when changes need review. Default false. */
171
+ wait?: boolean;
172
+ /** Fail the run if the upload fails. Default false. */
173
+ strict?: boolean;
174
+ /** This process's shard, if not given on the command line. */
175
+ shard?: Shard;
176
+ log?: (line: string) => void;
177
+ }
178
+ }
179
+ declare namespace gitRunner {
180
+ interface Runner {
181
+ /** Runs git and returns trimmed stdout; throws on a non-zero exit. */
182
+ run(args: string[]): Promise<string>;
183
+ }
184
+ }
185
+ declare function gitRunner(cwd: string): gitRunner.Runner;
186
+ declare namespace collectAncestry {
187
+ interface Options {
188
+ /** The commit being uploaded: the PR head, never a synthetic merge commit (PLAN §7.1). */
189
+ headSha: string;
190
+ /** Branch whose history holds the baselines: the PR's base, or the project's default branch. */
191
+ baseBranch: string;
192
+ /** True for builds on the default branch itself: history starts at the head's parent. */
193
+ isBaseBranchBuild: boolean;
194
+ remote?: string;
195
+ /** Fetch missing history from the remote (default true). */
196
+ fetch?: boolean;
197
+ /** How many commits to send. */
198
+ limit?: number;
199
+ /** Stop deepening a shallow clone after this many commits. */
200
+ maxDepth?: number;
201
+ }
202
+ interface Result {
203
+ status: 'ok' | 'missing' | 'truncated';
204
+ mergeBaseSha?: string;
205
+ /** Nearest first. */
206
+ ancestorShas: string[];
207
+ /** Why history is missing or truncated, for the CLI to print. */
208
+ warning?: string;
209
+ }
210
+ }
211
+ /**
212
+ * Collects the history the server uses to pick a baseline (PLAN §7.1 step 3, §7.2), so baseline
213
+ * selection never depends on a git host's API.
214
+ */
215
+ declare function collectAncestry(git: gitRunner.Runner, options: collectAncestry.Options): Promise<collectAncestry.Result>;
216
+ declare namespace upload {
217
+ interface Options {
218
+ dir: string;
219
+ apiUrl: string;
220
+ token: string;
221
+ /** Build name, for several kinds of builds per commit (e.g. `chromium`, `mobile`). */
222
+ name?: string;
223
+ wait?: boolean;
224
+ /**
225
+ * This job uploads one shard of a parallel build: `index` is 0-based. Shards of one build
226
+ * share a nonce (default: the CI run's id), and the build is processed once all `total` arrive.
227
+ */
228
+ shard?: {
229
+ index: number;
230
+ total: number;
231
+ nonce?: string;
232
+ };
233
+ /** Who blocks the merge: the git host's check (`status`) or this job (`exit-code`). Default: the server decides. */
234
+ gate?: 'status' | 'exit-code';
235
+ /** Who made the change (`--author`); replaces what the CI environment says. */
236
+ author?: string;
237
+ waitTimeoutMs?: number;
238
+ pollIntervalMs?: number;
239
+ /** First backoff between retries of a failed API call, in milliseconds (default 500). */
240
+ retryDelayMs?: number;
241
+ /** Allow `git fetch` to complete shallow history (default true). */
242
+ fetch?: boolean;
243
+ cwd?: string;
244
+ env?: Record<string, string | undefined>;
245
+ fetchImpl?: typeof fetch;
246
+ log?: (line: string) => void;
247
+ }
248
+ interface Result {
249
+ /**
250
+ * 0 pass, 1 the result should block the merge, 2 something went wrong (including a build the
251
+ * server couldn't process).
252
+ */
253
+ exitCode: 0 | 1 | 2;
254
+ build: ApiClient.Build;
255
+ ci: detectCi.Context;
256
+ ancestry: collectAncestry.Result;
257
+ uploaded: number;
258
+ deduplicated: number;
259
+ status?: ApiClient.Status;
260
+ }
261
+ }
262
+ declare function upload(options: upload.Options): Promise<upload.Result>;
263
+ export declare namespace circi {
264
+ /** `name` defaults to `cypress`; give each browser project its own (`cypress-chrome`). */
265
+ interface Options extends CirciOptions.Common {
266
+ /**
267
+ * Empty this plugin's own folder, `<dir>/cypress`, when a run starts, so a build holds only
268
+ * this run's screenshots. Other tools' folders under `dir` are never touched. Default true.
269
+ */
270
+ clean?: boolean;
271
+ /** For tests. */
272
+ uploadImpl?: (options: upload.Options) => Promise<Pick<upload.Result, 'exitCode'>>;
273
+ env?: Record<string, string | undefined>;
274
+ }
275
+ }
276
+ /** The parts of Cypress's Node-side events and config this plugin reads (the real ones fit). */
277
+ declare namespace CypressNode {
278
+ /** `after:screenshot`'s details. */
279
+ interface ScreenshotDetails {
280
+ name?: string | null;
281
+ /** Only the spec's base name, and so not unique: the spec's path comes from `before:spec`. */
282
+ specName?: string;
283
+ path: string;
284
+ testFailure?: boolean;
285
+ /** Not in Cypress's types; read when a version sends it. */
286
+ viewport?: {
287
+ width: number;
288
+ height: number;
289
+ };
290
+ }
291
+ interface RunDetails {
292
+ browser?: {
293
+ name?: string;
294
+ };
295
+ }
296
+ interface RunResults {
297
+ /** `failed` when Cypress could not run at all (a failed run result has no `runs`). */
298
+ status?: string;
299
+ runs?: unknown;
300
+ }
301
+ interface Spec {
302
+ /** The spec's path from the project root, as Cypress lists it. */
303
+ relative?: string;
304
+ name?: string;
305
+ }
306
+ /** Cypress's `on`, only the events used here (the real one accepts these handlers). */
307
+ interface Events {
308
+ (event: 'before:run', handler: (details: RunDetails) => void | Promise<void>): void;
309
+ (event: 'before:spec', handler: (spec: Spec) => void | Promise<void>): void;
310
+ (event: 'after:screenshot', handler: (details: ScreenshotDetails) => Promise<{
311
+ path?: string;
312
+ }>): void;
313
+ (event: 'after:run', handler: (results: RunResults) => void | Promise<void>): void;
314
+ }
315
+ interface Config {
316
+ projectRoot: string;
317
+ viewportWidth?: number;
318
+ viewportHeight?: number;
319
+ }
320
+ }
321
+ /**
322
+ * The Cypress plugin: `setupNodeEvents: circi({ name: 'cypress-chrome' })` in `cypress.config.ts`.
323
+ *
324
+ * Tests keep `cy.screenshot('name')`. Every named screenshot a run takes (not the automatic
325
+ * screenshot of a failing test) is copied to
326
+ * `.circi/screenshots/cypress/<spec path>/<name>.png`, with a `.png.json` sidecar naming the spec,
327
+ * browser and viewport, and `cypress run` uploads them to CirCI when it ends. To also do your own
328
+ * setup, call it inside yours:
329
+ * `setupNodeEvents(on, config) { circi(options)(on, config); return config }`.
330
+ */
331
+ export declare function circi(options?: circi.Options): <C extends CypressNode.Config>(on: CypressNode.Events, config: C) => C;
332
+ export {};