reporting-labs 0.6.16 → 0.6.18

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.
@@ -0,0 +1,623 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CypressCollector = void 0;
37
+ exports.reportingLabs = reportingLabs;
38
+ /**
39
+ * reportingLabs for Cypress.
40
+ *
41
+ * // cypress.config.js
42
+ * const { defineConfig } = require('cypress');
43
+ * const { reportingLabs } = require('reporting-labs/cypress');
44
+ *
45
+ * module.exports = defineConfig({
46
+ * e2e: {
47
+ * setupNodeEvents(on, config) {
48
+ * reportingLabs(on, config, { title: 'Checkout regression' });
49
+ * return config;
50
+ * },
51
+ * },
52
+ * });
53
+ *
54
+ * `cypress run` then writes reporting-labs/index.html, report.json and report.pdf: the same report the Playwright
55
+ * reporter makes. It is built from what Cypress hands the Node process after every spec (`after:spec`): each test's
56
+ * title path, state, retries, duration and error, the screenshots and the spec video. Line numbers and comment meta
57
+ * come from the spec file itself. Cypress allows one handler per event, so if your config already listens to
58
+ * before:run / after:spec / after:run, call the handlers this returns from your own (see README).
59
+ *
60
+ * Cucumber (@badeball/cypress-cucumber-preprocessor): call reportingLabs() after addCucumberPreprocessorPlugin(). The
61
+ * scenarios become report rows with their Gherkin steps, tags as tags and meta, Outline rows and data tables, and the
62
+ * preprocessor's own before:run / after:spec / after:run handlers (its messages, JSON and HTML reports) still run:
63
+ * ours call them, since Cypress keeps only the handler registered last.
64
+ *
65
+ * Nothing here touches the Playwright or WebdriverIO reporters; it only reuses the shared helpers.
66
+ */
67
+ const fs = __importStar(require("fs"));
68
+ const path = __importStar(require("path"));
69
+ const crypto = __importStar(require("crypto"));
70
+ const write_report_1 = require("../write-report");
71
+ const mask_1 = require("../mask");
72
+ const explain_1 = require("../explain");
73
+ const comments_1 = require("../comments");
74
+ const reporter_1 = require("../wdio/reporter");
75
+ const reporter_2 = require("../reporter");
76
+ const DEFAULT_EMBED_LIMIT = 2 * 1024 * 1024;
77
+ const ATTEMPT_TASK = 'reportingLabs:attempt';
78
+ const ENABLED_FLAG = 'reportingLabsEnabled';
79
+ function reportingLabs(on, config = {}, options = {}) {
80
+ const opts = withRuntimeOverrides(options);
81
+ // tells the support file the task is registered; without it, cy.task would fail every test
82
+ // Cypress 16 reads it with Cypress.expose() (config.expose); 12 to 15 with Cypress.env() (config.env)
83
+ try {
84
+ if (config && typeof config === 'object') {
85
+ const major = parseInt(String(config.version ?? ''), 10);
86
+ if ('expose' in config || major >= 16)
87
+ config.expose = { ...(config.expose ?? {}), [ENABLED_FLAG]: true };
88
+ else
89
+ config.env = { ...(config.env ?? {}), [ENABLED_FLAG]: true };
90
+ }
91
+ }
92
+ catch { /* fine */ }
93
+ const collector = new CypressCollector(opts, config);
94
+ const handlers = {
95
+ beforeRun: d => safe(() => collector.beforeRun(d)),
96
+ afterSpec: (spec, results) => safe(() => collector.afterSpec(spec, results)),
97
+ afterRun: async (results) => { try {
98
+ return await collector.afterRun(results);
99
+ }
100
+ catch (e) {
101
+ console.warn('reporting-labs: report not written:', e?.message ?? e);
102
+ return undefined;
103
+ } },
104
+ };
105
+ if (typeof on === 'function') {
106
+ // what the support file collects in the browser; Cypress merges this with the project's own tasks
107
+ on('task', { [ATTEMPT_TASK]: (payload) => { safe(() => collector.addAttempt(payload)); return null; } });
108
+ // Cypress keeps the handler registered last: if the Cucumber preprocessor registered its own before ours, ours run
109
+ // its handlers too, so its reports keep working
110
+ on('before:run', async (d) => { handlers.beforeRun(d); await cucumberHandler(config, 'beforeRunHandler'); });
111
+ on('after:spec', async (spec, results) => { handlers.afterSpec(spec, results); await cucumberHandler(config, 'afterSpecHandler', spec, results); });
112
+ on('after:run', async (results) => { const out = await handlers.afterRun(results); await cucumberHandler(config, 'afterRunHandler', results); return out; });
113
+ }
114
+ return handlers;
115
+ }
116
+ const CUCUMBER = '@badeball/cypress-cucumber-preprocessor';
117
+ const CUCUMBER_FLAG = '__cypress_cucumber_preprocessor_dont_use_this_suite';
118
+ /** Runs one of the Cucumber preprocessor's run handlers, when addCucumberPreprocessorPlugin() was called for this config. */
119
+ async function cucumberHandler(config, name, ...args) {
120
+ const attached = (k) => { try {
121
+ return !!config?.[k]?.[CUCUMBER_FLAG]?.isEventHandlersAttached;
122
+ }
123
+ catch {
124
+ return false;
125
+ } };
126
+ if (!attached('expose') && !attached('env'))
127
+ return;
128
+ let fn;
129
+ try {
130
+ // the copy the project's cypress.config loaded, so the handlers share its state
131
+ const root = typeof config?.projectRoot === 'string' && config.projectRoot ? config.projectRoot : process.cwd();
132
+ fn = require(require.resolve(CUCUMBER, { paths: [root] }))[name];
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ if (typeof fn !== 'function')
138
+ return;
139
+ try {
140
+ await fn(config, ...args);
141
+ }
142
+ catch (e) {
143
+ // its handlers already run on their own (cypress-on-fix, or called from the project's handler): nothing to do
144
+ if (/^Unexpected state in \w+Handler/.test(String(e?.message ?? '')))
145
+ return;
146
+ throw e;
147
+ }
148
+ }
149
+ exports.default = reportingLabs;
150
+ function safe(fn) { try {
151
+ fn();
152
+ }
153
+ catch (e) {
154
+ console.warn('reporting-labs:', e?.message ?? e);
155
+ } }
156
+ /** REPORTING_LABS_* variables beat the options, the same contract as the Playwright, Java and Python reporters. */
157
+ function withRuntimeOverrides(options) {
158
+ const metadata = { ...(options.metadata ?? {}) };
159
+ for (const [k, v] of Object.entries(process.env)) {
160
+ const m = /^REPORTING_LABS_METADATA_([A-Z0-9_]+)$/.exec(k);
161
+ if (m && v && v.trim())
162
+ metadata[m[1].toLowerCase()] = v.trim();
163
+ }
164
+ if (!process.env.REPORTING_LABS_METADATA_ENV) {
165
+ const detected = (0, reporter_2.detectEnvName)(process.env, options.envVar);
166
+ if (detected)
167
+ metadata.env = detected;
168
+ }
169
+ const scalar = (name, current) => { const v = process.env['REPORTING_LABS_' + name]; return v && v.trim() ? v.trim() : current; };
170
+ return { ...options, metadata,
171
+ title: scalar('TITLE', options.title), theme: scalar('THEME', options.theme),
172
+ palette: scalar('PALETTE', options.palette), accent: scalar('ACCENT', options.accent),
173
+ logo: scalar('LOGO', options.logo), outputFolder: scalar('OUTPUT_FOLDER', options.outputFolder) };
174
+ }
175
+ class CypressCollector {
176
+ constructor(options, config = {}) {
177
+ this.options = options;
178
+ this.config = config;
179
+ this.tests = [];
180
+ this.startTime = 0;
181
+ this.endTime = 0;
182
+ this.browser = '';
183
+ this.cypressVersion = '';
184
+ this.assetCounter = 0;
185
+ this.assetsReady = false;
186
+ this.attempts = new Map();
187
+ this.ranBeforeRun = false;
188
+ this.warnedReplaced = false;
189
+ this.masker = (0, mask_1.makeMasker)(options.maskKeys ?? [], { knownValues: options.maskValues ?? [], fromEnv: options.maskFromEnv !== false });
190
+ this.base = typeof config.projectRoot === 'string' && config.projectRoot ? config.projectRoot : process.cwd();
191
+ this.outDir = path.resolve(this.base, options.outputFolder || 'reporting-labs');
192
+ this.assetsDir = path.join(this.outDir, 'assets');
193
+ }
194
+ addAttempt(p) {
195
+ if (!p || !Array.isArray(p.titlePath))
196
+ return;
197
+ // cypress run fires before:run first: without it, a later on('before:run') replaced ours (and so after:run too)
198
+ if (!this.ranBeforeRun && !this.warnedReplaced && this.config.isTextTerminal === true) {
199
+ this.warnedReplaced = true;
200
+ console.warn('\n reporting-labs: our before:run handler was replaced, so no report will be written. Cypress keeps one handler\n' +
201
+ ' per event: call reportingLabs() last in setupNodeEvents (after addCucumberPreprocessorPlugin() and other plugins),\n' +
202
+ ' or call its handlers from yours (see the README).\n');
203
+ }
204
+ const key = attemptKey(p.spec, p.titlePath);
205
+ const list = this.attempts.get(key) ?? [];
206
+ list[Math.max(0, Number(p.retry) || 0)] = p;
207
+ this.attempts.set(key, list);
208
+ }
209
+ beforeRun(d = {}) {
210
+ this.ranBeforeRun = true;
211
+ this.startTime = Date.now();
212
+ this.browser = browserLabel(d.browser);
213
+ this.cypressVersion = d.cypressVersion || '';
214
+ this.prepareAssets();
215
+ }
216
+ /** assets/ holds this run's copied files only: emptied once per run, before the first file lands. */
217
+ prepareAssets() {
218
+ if (this.assetsReady)
219
+ return;
220
+ this.assetsReady = true;
221
+ try {
222
+ fs.rmSync(this.assetsDir, { recursive: true, force: true });
223
+ }
224
+ catch { /* fine */ }
225
+ }
226
+ afterSpec(spec = {}, results = {}) {
227
+ this.prepareAssets();
228
+ const s = results.spec ?? spec ?? {};
229
+ const abs = s.absolute || spec.absolute || '';
230
+ const file = this.rel(abs || s.relative || spec.relative || s.name || '');
231
+ const startedAt = Date.parse(results.stats?.startedAt ?? '') || Date.now();
232
+ const endedAt = Date.parse(results.stats?.endedAt ?? '') || startedAt + (results.stats?.duration ?? 0);
233
+ if (!this.startTime || startedAt < this.startTime)
234
+ this.startTime = startedAt;
235
+ if (endedAt > this.endTime)
236
+ this.endTime = endedAt;
237
+ const cyTests = results.tests ?? [];
238
+ const out = [];
239
+ let cursor = startedAt;
240
+ const specRel = (s.relative || spec.relative || '').split(path.sep).join('/');
241
+ for (const ct of cyTests) {
242
+ const t = this.toTest(ct, abs, file, cursor);
243
+ this.enrich(t, this.attempts.get(attemptKey(specRel, ct.title ?? [])), abs);
244
+ cursor = Math.max(cursor + t.duration, ...t.results.map(r => r.startTime + r.duration));
245
+ out.push(t);
246
+ }
247
+ // The spec could not run at all (syntax error, failed import, uncaught error before the first test)
248
+ if (!out.length && results.error) {
249
+ const t = this.toTest({ title: [s.name || path.basename(file) || 'spec'], state: 'failed', duration: 0, displayError: results.error, attempts: [{ state: 'failed' }] }, abs, file, startedAt);
250
+ t.note = 'The spec failed before any test ran.';
251
+ out.push(t);
252
+ }
253
+ this.attachScreenshots(out, cyTests, results.screenshots ?? [], startedAt);
254
+ this.attachVideo(out, results.video, file);
255
+ this.tests.push(...out);
256
+ }
257
+ async afterRun(results = {}) {
258
+ if (!this.tests.length) {
259
+ if ((results.totalTests ?? 0) > 0)
260
+ console.warn('\n reporting-labs: no report: no spec results reached it. Cypress keeps one handler per event, so an after:spec\n' +
261
+ ' registered after reportingLabs() replaced ours. Call it from yours: const rl = reportingLabs(on, config, {…});\n' +
262
+ " on('after:spec', (spec, results) => { rl.afterSpec(spec, results); /* your code */ });\n");
263
+ return undefined;
264
+ }
265
+ if (!this.attempts.size && this.options.announce !== false) {
266
+ console.log("\n reporting-labs: no steps or API calls came from the browser. For them, add import 'reporting-labs/cypress/support';\n" +
267
+ " to cypress/support/e2e.js and make sure setupNodeEvents ends with return config;");
268
+ }
269
+ const project = this.browser || results.browserName || '';
270
+ for (const t of this.tests) {
271
+ t.project = project;
272
+ t.key = `${project}::${t.file}::${[...t.path, t.title].join(' › ')}`;
273
+ }
274
+ const start = Date.parse(results.startedTestsAt ?? '') || this.startTime || Date.now();
275
+ const end = Date.parse(results.endedTestsAt ?? '') || this.endTime || Date.now();
276
+ const failed = this.tests.some(t => t.outcome === 'failed' || t.outcome === 'timedOut');
277
+ const version = this.cypressVersion || results.cypressVersion || '';
278
+ const bver = results.browserVersion ? ` ${results.browserVersion}` : '';
279
+ const envRows = version ? [{ k: 'Cypress', v: version + (project ? ` · ${project}${bver}` : '') }] : [];
280
+ return (0, write_report_1.writeReport)(this.tests, { startTime: start, endTime: Math.max(end, start), runStatus: failed ? 'failed' : 'passed', workers: 1, envRows }, { ...this.options, outputFolder: this.outDir, logo: this.resolveLogo(this.options.logo), bdd: this.options.bdd });
281
+ }
282
+ /** One Cypress test → one report row. Cypress gives the attempts' states but one duration and one error (the last). */
283
+ toTest(ct, abs, file, startTime) {
284
+ const titles = (ct.title ?? []).map(x => String(x));
285
+ const title = titles[titles.length - 1] ?? '';
286
+ const suites = titles.slice(0, -1);
287
+ const attempts = ct.attempts && ct.attempts.length ? ct.attempts : [{ state: ct.state }];
288
+ const total = Math.max(0, Math.round(ct.duration ?? 0));
289
+ const each = attempts.length > 1 ? Math.round(total / attempts.length) : total;
290
+ // Line numbers and comment meta from the spec file: each describe is looked up after the one around it
291
+ const at = [];
292
+ let from = 0;
293
+ for (const st of suites) {
294
+ const ln = abs ? (0, comments_1.lineOfTitle)(abs, st, 'describe|context|suite', from) : 0;
295
+ if (ln) {
296
+ at.push(ln);
297
+ from = ln;
298
+ }
299
+ }
300
+ const line = abs ? (0, comments_1.lineOfTitle)(abs, title, 'it|test|specify', from) : 0;
301
+ const tags = [...titles.join(' ').matchAll(/@[A-Za-z][\w:.=-]*/g)].map(m => m[0]);
302
+ const fromComments = {};
303
+ if (abs && this.options.commentMeta !== false) {
304
+ try {
305
+ for (const ln of [...at, line].filter(Boolean)) {
306
+ const c = (0, comments_1.commentMetaAt)(abs, ln);
307
+ Object.assign(fromComments, c.meta);
308
+ for (const g of c.tags)
309
+ if (!tags.includes(g) && !reporter_1.META_KEYS.includes(g.slice(1).toLowerCase()))
310
+ tags.push(g);
311
+ }
312
+ }
313
+ catch { /* comments are a convenience: never fail the run over them */ }
314
+ }
315
+ const { meta, clean } = (0, reporter_1.metaFromTags)(tags, reporter_1.META_KEYS);
316
+ for (const [k, v] of Object.entries(fromComments))
317
+ meta[k] = this.masker.maskStr(v);
318
+ const results = attempts.map((a, i) => {
319
+ const status = cyStatus(a.state);
320
+ const last = i === attempts.length - 1;
321
+ const r = {
322
+ retry: i, status, duration: last ? total - each * (attempts.length - 1) : each, startTime: startTime + each * i, workerIndex: 0,
323
+ errors: [], steps: [], attachments: [], stdout: [], stderr: [], logs: [], data: [], api: [],
324
+ };
325
+ if (status === 'failed' && last && ct.displayError)
326
+ r.errors.push(this.toError(ct.displayError, abs));
327
+ return r;
328
+ });
329
+ const finalState = cyStatus(ct.state ?? attempts[attempts.length - 1].state);
330
+ let outcome = finalState === 'passed' ? 'passed' : finalState === 'skipped' ? 'skipped' : 'failed';
331
+ if (outcome === 'passed' && results.some(r => r.status === 'failed'))
332
+ outcome = 'flaky';
333
+ // a failing final state whose last attempt Cypress reports otherwise: keep the error on the last result
334
+ if (outcome === 'failed' && ct.displayError && !results[results.length - 1].errors.length)
335
+ results[results.length - 1].errors.push(this.toError(ct.displayError, abs));
336
+ const t = {
337
+ id: crypto.createHash('sha1').update(file + '\u0000' + titles.join('\u0000')).digest('hex').slice(0, 20),
338
+ key: '', title: this.masker.maskStr(title), path: suites.map(x => this.masker.maskStr(x)),
339
+ file, line, project: '', tags: clean, annotations: [], meta,
340
+ outcome, duration: total, results, retries: attempts.length - 1,
341
+ };
342
+ if (ct.state === 'skipped')
343
+ t.note = 'Not run: a before / beforeEach hook failed earlier in this spec.';
344
+ const hook = /during a `(before all|before each|after each|after all)` hook/.exec(ct.displayError ?? '');
345
+ if (hook)
346
+ t.note = `Failed in the ${hook[1]} hook${/before all|after all/.test(hook[1]) ? ', so Cypress skipped the other tests of this describe and did not retry' : ''}.`;
347
+ if (ct.state === 'pending')
348
+ t.annotations.push({ type: 'skip' });
349
+ return t;
350
+ }
351
+ /** What the support file sent for this test: real per-attempt times, steps, API calls, each attempt's error, meta(). */
352
+ enrich(t, attempts, abs) {
353
+ if (!attempts || !attempts.length)
354
+ return;
355
+ const g = [...attempts].reverse().find(a => a?.gherkin)?.gherkin;
356
+ if (g)
357
+ this.applyGherkin(t, g, attempts, abs);
358
+ t.results.forEach((r, i) => {
359
+ const a = attempts[i];
360
+ if (!a)
361
+ return;
362
+ if (typeof a.start === 'number' && a.start > 0)
363
+ r.startTime = a.start;
364
+ if (typeof a.duration === 'number')
365
+ r.duration = Math.max(0, Math.round(a.duration));
366
+ // API calls first: masking them teaches the masker the secrets they carry (a password in a body), so the
367
+ // same value typed in a step is blanked too
368
+ r.api = (a.api ?? []).map(c => this.masker.mask(trimApi(c, this.options)));
369
+ r.steps = (a.steps ?? []).map(st => this.maskStep(st));
370
+ if (r.status === 'failed' && !r.errors.length && a.err?.message)
371
+ r.errors.push(this.toError([a.err.message, a.err.stack ? a.err.stack.replace(/^[^\n]*\n?/, '') : ''].filter(Boolean).join('\n'), abs));
372
+ const cf = a.err?.codeFrame;
373
+ const e = r.errors[0];
374
+ // the file Cypress points at: the spec, or a support / step definition file it calls into (not a library's code)
375
+ const src = cf?.relativeFile ? (/(^|[\\/])node_modules[\\/]/.test(cf.relativeFile) ? '' : path.resolve(this.base, cf.relativeFile)) : abs;
376
+ if (e && cf?.line && !e.location && src && fs.existsSync(src)) {
377
+ e.location = { file: this.rel(src), line: cf.line, column: cf.column ?? 0 };
378
+ const snip = codeFrame(src, cf.line, cf.column ?? 0);
379
+ if (snip)
380
+ e.snippet = this.masker.maskStr(snip);
381
+ }
382
+ // Cucumber without a code frame: the step in the feature file
383
+ const at = a.gherkin?.stoppedAt;
384
+ if (e && !e.location && at?.line && abs) {
385
+ e.location = { file: this.rel(abs), line: at.line, column: 0 };
386
+ const snip = codeFrame(abs, at.line, 0);
387
+ if (snip)
388
+ e.snippet = this.masker.maskStr(snip);
389
+ }
390
+ });
391
+ t.duration = t.results.reduce((n, r) => n + r.duration, 0);
392
+ // meta() in the test wins over comments and tags, as in Playwright
393
+ const m = attempts[attempts.length - 1]?.meta ?? {};
394
+ for (const [k, v] of Object.entries(m)) {
395
+ if (v === undefined || v === null || typeof v === 'object' && !Array.isArray(v))
396
+ continue;
397
+ t.meta[k.toLowerCase()] = this.masker.maskStr(Array.isArray(v) ? v.join(', ') : String(v));
398
+ }
399
+ }
400
+ /** A Cucumber scenario: its feature file line, Rule, tags as tags and meta, Outline row and data tables. Runs before the
401
+ * steps are masked: a password column in Examples or a data table teaches the masker its values. */
402
+ applyGherkin(t, g, attempts, abs) {
403
+ const data = [];
404
+ const table = (name, header, rows) => {
405
+ const sens = header.map(h => this.masker.isSensitive(h));
406
+ const masked = rows.map(r => r.map((c, i) => { if (sens[i]) {
407
+ this.masker.learn(c);
408
+ return '****';
409
+ } return c; }));
410
+ data.push({ name, kind: 'table', columns: header.map(h => this.masker.maskStr(h)), rows: masked.map(r => r.map(c => c === '****' ? c : this.masker.maskStr(c))) });
411
+ };
412
+ const ex = g.example;
413
+ if (ex && Array.isArray(ex.header) && Array.isArray(ex.values))
414
+ table('Examples', ex.header.map(String), [ex.values.map(String)]);
415
+ for (const a of g.args ?? []) {
416
+ const name = this.masker.maskStr(String(a.step ?? 'Step'));
417
+ if (Array.isArray(a.table) && a.table.length) {
418
+ const [head, ...rest] = a.table.map(r => (r ?? []).map(String));
419
+ if (rest.length)
420
+ table(name, head, rest);
421
+ else
422
+ data.push({ name, kind: 'table', columns: head.map(c => this.masker.maskStr(c)), rows: [] });
423
+ }
424
+ else if (typeof a.docString === 'string')
425
+ data.push({ name, kind: 'text', text: this.masker.maskStr(a.docString) });
426
+ }
427
+ if (data.length)
428
+ for (const r of t.results)
429
+ r.data.push(...data.map(d => ({ ...d })));
430
+ if (typeof g.line === 'number' && g.line > 0)
431
+ t.line = g.line;
432
+ if (g.feature)
433
+ t.path = [this.masker.maskStr(String(g.feature)), ...(g.rule ? ['Rule: ' + this.masker.maskStr(String(g.rule))] : [])];
434
+ if (ex && Array.isArray(ex.values) && ex.values.length) {
435
+ // like the Cucumber JVM plugin: the example's values instead of Cypress's "(example #2)"
436
+ const vals = ex.values.map(String).join(', ');
437
+ const base = t.title.replace(/\s*\(example #\d+\)$/, '');
438
+ t.title = this.masker.maskStr(`${base} (${vals.length > 60 ? vals.slice(0, 60) + '…' : vals})`);
439
+ }
440
+ const { meta, clean } = (0, reporter_1.metaFromTags)((g.tags ?? []).map(String), reporter_1.META_KEYS);
441
+ for (const [k, v] of Object.entries(meta))
442
+ if (!(k in t.meta))
443
+ t.meta[k] = this.masker.maskStr(v);
444
+ for (const tag of clean)
445
+ if (!t.tags.includes(tag))
446
+ t.tags.push(tag);
447
+ const last = attempts[attempts.length - 1]?.gherkin?.stoppedAt;
448
+ if (t.outcome === 'skipped' && last?.state === 'pending' && last.step) {
449
+ t.note = `The step "${this.masker.maskStr(last.step)}" is pending: its step definition returned "pending".`;
450
+ t.annotations = t.annotations.filter(x => x.type !== 'skip');
451
+ }
452
+ void abs;
453
+ }
454
+ maskStep(st) {
455
+ return { title: this.masker.maskStr(String(st.title ?? '')), category: String(st.category ?? 'cy'), duration: Math.max(0, Math.round(Number(st.duration) || 0)),
456
+ ...(st.error ? { error: this.masker.maskStr(stripAnsi(String(st.error))) } : {}), ...(st.status === 'skipped' ? { status: 'skipped' } : {}),
457
+ steps: (st.steps ?? []).map(c => this.maskStep(c)) };
458
+ }
459
+ /** displayError is the message plus a stack (" at …"); the first frame in the spec file gives the location. */
460
+ toError(display, abs) {
461
+ const clean = stripAnsi(display);
462
+ const idx = clean.search(/\n\s+at /);
463
+ const message = this.masker.maskStr((idx >= 0 ? clean.slice(0, idx) : clean).trim());
464
+ const stack = idx >= 0 ? this.masker.maskStr(clean.slice(idx + 1)) : undefined;
465
+ const d = { message };
466
+ if (stack)
467
+ d.stack = stack;
468
+ const ex = (0, explain_1.explainError)(message);
469
+ if (ex)
470
+ d.explain = ex;
471
+ // a feature file runs as a bundle: its line numbers in the stack are the bundle's (the step comes from the support file)
472
+ if (abs && !/\.feature$/i.test(abs)) {
473
+ const base = path.basename(abs).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
474
+ const m = new RegExp(`${base}:(\\d+):(\\d+)`).exec(stack ?? clean);
475
+ if (m) {
476
+ const line = Number(m[1]), column = Number(m[2]);
477
+ d.location = { file: this.rel(abs), line, column };
478
+ const snip = codeFrame(abs, line, column);
479
+ if (snip)
480
+ d.snippet = this.masker.maskStr(snip);
481
+ }
482
+ }
483
+ return d;
484
+ }
485
+ /** Cypress names a failure screenshot "<describe> -- <it> (failed) (attempt 2).png"; a custom cy.screenshot('name')
486
+ * is matched to the test that was running when it was taken. */
487
+ attachScreenshots(tests, cyTests, shots, specStart) {
488
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '');
489
+ const byName = new Map();
490
+ cyTests.forEach((ct, i) => byName.set(norm((ct.title ?? []).join(' -- ')), i));
491
+ for (const sh of shots) {
492
+ if (!sh.path)
493
+ continue;
494
+ const base = path.basename(sh.path).replace(/\.\w+$/, '');
495
+ const attemptM = /\(attempt (\d+)\)\s*$/.exec(base);
496
+ const stem = base.replace(/\s*\(attempt \d+\)\s*$/, '').replace(/\s*\(failed\)\s*$/, '');
497
+ let ti = byName.get(norm(stem));
498
+ if (ti === undefined) {
499
+ // custom name: the test whose time window holds takenAt, else the spec's only test
500
+ const at = Date.parse(sh.takenAt ?? '');
501
+ tests.forEach((t, i) => { if (ti === undefined && at && t.results.some(r => at >= r.startTime && at <= r.startTime + r.duration + 1000))
502
+ ti = i; });
503
+ if (ti === undefined && tests.length === 1)
504
+ ti = 0;
505
+ }
506
+ if (ti === undefined || !tests[ti])
507
+ continue;
508
+ const t = tests[ti];
509
+ const at = Date.parse(sh.takenAt ?? '');
510
+ const byTime = at ? t.results.findIndex(r => at >= r.startTime && at <= r.startTime + r.duration + 1000) : -1;
511
+ const ri = attemptM ? Math.min(Number(attemptM[1]) - 1, t.results.length - 1) : (/\(failed\)/.test(base) ? firstFailed(t) : byTime >= 0 ? byTime : t.results.length - 1);
512
+ const a = this.attachment(sh.path, /\(failed\)/.test(base) ? 'screenshot' : (sh.name || stem), t.title);
513
+ if (a)
514
+ t.results[Math.max(0, ri)].attachments.push(a);
515
+ }
516
+ }
517
+ attachVideo(tests, video, file) {
518
+ if (!video || !fs.existsSync(video))
519
+ return;
520
+ const who = this.options.video === 'all' ? tests : tests.filter(t => t.outcome === 'failed' || t.outcome === 'flaky');
521
+ if (!who.length)
522
+ return;
523
+ const a = this.attachment(video, 'video', path.basename(file) || 'spec', true);
524
+ if (!a)
525
+ return;
526
+ for (const t of who)
527
+ t.results[t.results.length - 1].attachments.push({ ...a });
528
+ }
529
+ attachment(p, name, owner, isVideoFile = false) {
530
+ try {
531
+ if (!fs.existsSync(p))
532
+ return null;
533
+ const ext = path.extname(p).toLowerCase();
534
+ const contentType = ext === '.png' ? 'image/png' : ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.mp4' ? 'video/mp4' : ext === '.webm' ? 'video/webm' : 'application/octet-stream';
535
+ const size = fs.statSync(p).size;
536
+ const out = { name, contentType, size };
537
+ const isVideo = isVideoFile || contentType.startsWith('video/');
538
+ const embed = (this.options.embedAttachments ?? true) && (!isVideo || this.options.embedVideos === true);
539
+ if (embed && size <= (this.options.embedLimit ?? DEFAULT_EMBED_LIMIT)) {
540
+ out.src = `data:${contentType};base64,${fs.readFileSync(p).toString('base64')}`;
541
+ return out;
542
+ }
543
+ fs.mkdirSync(this.assetsDir, { recursive: true });
544
+ const fname = `${sanitize(owner)}-${sanitize(name)}-${this.assetCounter++}${ext}`;
545
+ fs.copyFileSync(p, path.join(this.assetsDir, fname));
546
+ out.src = `assets/${fname}`;
547
+ return out;
548
+ }
549
+ catch {
550
+ return null;
551
+ }
552
+ }
553
+ resolveLogo(logo) {
554
+ if (!logo || /^(https?:|data:)/i.test(logo))
555
+ return logo;
556
+ const file = path.resolve(this.base, logo);
557
+ const mime = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon' };
558
+ const type = mime[path.extname(file).toLowerCase()];
559
+ if (!fs.existsSync(file) || !type) {
560
+ console.warn(`reporting-labs: logo ${logo} not found or not an image`);
561
+ return undefined;
562
+ }
563
+ return `data:${type};base64,${fs.readFileSync(file).toString('base64')}`;
564
+ }
565
+ rel(file) {
566
+ if (!file)
567
+ return file;
568
+ if (!path.isAbsolute(file))
569
+ return file.split(path.sep).join('/');
570
+ try {
571
+ return path.relative(this.base, file).split(path.sep).join('/');
572
+ }
573
+ catch {
574
+ return file;
575
+ }
576
+ }
577
+ }
578
+ exports.CypressCollector = CypressCollector;
579
+ function attemptKey(spec, titlePath) {
580
+ return String(spec ?? '').split('\\').join('/') + '\u0000' + titlePath.map(String).join('\u0000');
581
+ }
582
+ /** Bodies are kept up to apiMaxBody characters (default 64 KB), as for Playwright. */
583
+ function trimApi(c, options) {
584
+ const max = options.apiMaxBody ?? 64 * 1024;
585
+ const cut = (v) => { if (v === undefined || v === null)
586
+ return v; const s = typeof v === 'string' ? v : JSON.stringify(v); return s.length > max ? s.slice(0, max) + '…' : v; };
587
+ return { ...c, requestBody: cut(c.requestBody), responseBody: cut(c.responseBody) };
588
+ }
589
+ function cyStatus(state) {
590
+ return state === 'passed' ? 'passed' : state === 'failed' ? 'failed' : 'skipped';
591
+ }
592
+ function firstFailed(t) {
593
+ const i = t.results.findIndex(r => r.status === 'failed');
594
+ return i >= 0 ? i : t.results.length - 1;
595
+ }
596
+ function browserLabel(b) {
597
+ if (!b)
598
+ return '';
599
+ return String(b.name || b.displayName || '').toLowerCase();
600
+ }
601
+ function stripAnsi(s) { return s.replace(/\x1b\[[0-9;]*m/g, ''); }
602
+ function sanitize(s) { return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'file'; }
603
+ /** The lines around `line` with a marker, like Playwright's error snippet. */
604
+ function codeFrame(file, line, column) {
605
+ let src;
606
+ try {
607
+ src = fs.readFileSync(file, 'utf8').split(/\r?\n/);
608
+ }
609
+ catch {
610
+ return undefined;
611
+ }
612
+ if (line < 1 || line > src.length)
613
+ return undefined;
614
+ const lo = Math.max(1, line - 2), hi = Math.min(src.length, line + 2);
615
+ const w = String(hi).length;
616
+ const rows = [];
617
+ for (let n = lo; n <= hi; n++) {
618
+ rows.push(`${n === line ? '>' : ' '} ${String(n).padStart(w)} | ${src[n - 1]}`);
619
+ if (n === line && column > 0)
620
+ rows.push(` ${' '.repeat(w)} | ${' '.repeat(column - 1)}^`);
621
+ }
622
+ return rows.join('\n');
623
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * reportingLabs support file for Cypress: runs in the browser, next to your tests.
3
+ *
4
+ * // cypress/support/e2e.js
5
+ * import 'reporting-labs/cypress/support';
6
+ *
7
+ * For every attempt of every test it collects what the Node-side plugin cannot see, and hands it over in an
8
+ * afterEach hook (cy.task, not logged):
9
+ * - the Cypress commands as steps (cy.get → type / click, assertions), hooks grouped, timings, the failing step
10
+ * - cy.request calls with their request and response, and the app's own fetch / XHR calls, for the API tab
11
+ * - the error of every attempt with Cypress's code frame (the Node side only gets the last one)
12
+ * - meta({ owner, priority, … }) called in the test
13
+ * - with @badeball/cypress-cucumber-preprocessor: the Gherkin steps (Given / When / Then) with the commands each ran,
14
+ * Before / After hooks, the steps a failure left unrun, and the scenario's line, tags, example row, data tables
15
+ * A value typed into a password field is masked here; everything else is masked by the plugin with the report's
16
+ * masking rules. Nothing in this file may ever fail a test: every handler is guarded.
17
+ *
18
+ * In a spec: import { meta } from 'reporting-labs/cypress/support'; … meta({ owner: 'asha', priority: 'P1' });
19
+ */
20
+ /** Meta for the running test: priority, severity, owner, feature, story, issue… The same keys as meta() in Playwright. */
21
+ export declare function meta(values: Record<string, unknown>): void;