reporting-labs 0.6.16 → 0.6.17

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,231 @@
1
+ "use strict";
2
+ /**
3
+ * reportingLabs support file for Cypress: runs in the browser, next to your tests.
4
+ *
5
+ * // cypress/support/e2e.js
6
+ * import 'reporting-labs/cypress/support';
7
+ *
8
+ * For every attempt of every test it collects what the Node-side plugin cannot see, and hands it over in an
9
+ * afterEach hook (cy.task, not logged):
10
+ * - the Cypress commands as steps (cy.get → type / click, assertions), hooks grouped, timings, the failing step
11
+ * - cy.request calls with their request and response, and the app's own fetch / XHR calls, for the API tab
12
+ * - the error of every attempt with Cypress's code frame (the Node side only gets the last one)
13
+ * - meta({ owner, priority, … }) called in the test
14
+ * A value typed into a password field is masked here; everything else is masked by the plugin with the report's
15
+ * masking rules. Nothing in this file may ever fail a test: every handler is guarded.
16
+ *
17
+ * In a spec: import { meta } from 'reporting-labs/cypress/support'; … meta({ owner: 'asha', priority: 'P1' });
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.meta = meta;
21
+ const TASK = 'reportingLabs:attempt';
22
+ const ENABLED_FLAG = 'reportingLabsEnabled';
23
+ let logs = [];
24
+ let currentMeta = {};
25
+ /** Meta for the running test: priority, severity, owner, feature, story, issue… The same keys as meta() in Playwright. */
26
+ function meta(values) {
27
+ try {
28
+ if (values && typeof values === 'object')
29
+ Object.assign(currentMeta, values);
30
+ }
31
+ catch { /* never fail a test */ }
32
+ }
33
+ const guard = (fn) => { try {
34
+ fn();
35
+ }
36
+ catch { /* never fail a test */ } };
37
+ if (typeof Cypress !== 'undefined') {
38
+ Cypress.on('test:before:run', () => guard(() => { logs = []; currentMeta = {}; }));
39
+ Cypress.on('log:added', (_attrs, log) => guard(() => {
40
+ const runnable = Cypress.state && Cypress.state('runnable');
41
+ const hook = runnable && runnable.type === 'hook' ? String(runnable.hookName || runnable.title || 'hook') : undefined;
42
+ const el = log.get('$el');
43
+ const field = el && el[0];
44
+ const masked = log.get('name') === 'type' && !!field && /^(password)$/i.test(String(field.type || ''));
45
+ logs.push({ log, start: toMs(log.get('wallClockStartedAt')) || Date.now(), hook, masked });
46
+ }));
47
+ afterEach(function () {
48
+ // only when the plugin is registered in setupNodeEvents (it sets this flag); otherwise cy.task would fail the test
49
+ let enabled = false;
50
+ try {
51
+ enabled = typeof Cypress.expose === 'function' ? !!Cypress.expose(ENABLED_FLAG) : !!Cypress.env(ENABLED_FLAG);
52
+ }
53
+ catch { /* not enabled */ }
54
+ if (!enabled)
55
+ return;
56
+ let payload;
57
+ try {
58
+ payload = build(this.currentTest);
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ // log: false keeps it out of the command log; a failed handover must not fail the test
64
+ cy.task(TASK, payload, { log: false, timeout: 20000 });
65
+ });
66
+ }
67
+ function build(t) {
68
+ const start = toMs(t.wallClockStartedAt) || (logs[0]?.start ?? Date.now());
69
+ const duration = typeof t.duration === 'number' ? t.duration : Math.max(0, Date.now() - start);
70
+ const err = t.err ? {
71
+ message: String(t.err.message ?? t.err),
72
+ stack: t.err.stack ? String(t.err.stack) : undefined,
73
+ codeFrame: t.err.codeFrame ? { line: t.err.codeFrame.line, column: t.err.codeFrame.column, relativeFile: t.err.codeFrame.relativeFile, frame: t.err.codeFrame.frame } : undefined,
74
+ } : undefined;
75
+ const retry = typeof t.currentRetry === 'function' ? t.currentRetry() : (t._currentRetry ?? 0);
76
+ return {
77
+ spec: Cypress.spec && (Cypress.spec.relative || Cypress.spec.name),
78
+ titlePath: typeof t.titlePath === 'function' ? t.titlePath() : [t.title],
79
+ retry, state: t.state, start, duration, err,
80
+ steps: steps(start + duration, err?.message),
81
+ api: api(),
82
+ meta: currentMeta,
83
+ };
84
+ }
85
+ const clean = (s) => String(s ?? '').replace(/\*\*/g, '').replace(/\s+/g, ' ').trim();
86
+ const SKIP = new Set(['new url', 'page load', 'route', 'xhr', 'fetch', 'task', 'log']);
87
+ /** Commands as steps: hooks grouped, chained commands under their parent, assertions under what they check. */
88
+ function steps(end, errMsg) {
89
+ const items = logs.filter(c => {
90
+ const name = c.log.get('name');
91
+ if (SKIP.has(name) && name !== 'route')
92
+ return false;
93
+ if (c.log.get('event'))
94
+ return false; // page loads, url changes, the app's own fetch / XHR (those go to the API tab)
95
+ if (c.log.get('hidden'))
96
+ return false;
97
+ return true;
98
+ });
99
+ const out = [];
100
+ const parents = new Map(); // chainerId → parent step
101
+ let hookStep, hookName;
102
+ items.forEach((c, i) => {
103
+ const next = items[i + 1];
104
+ const name = String(c.log.get('name') || '');
105
+ let message = clean(c.log.get('message'));
106
+ if (c.masked)
107
+ message = '****';
108
+ if (name === 'request' && !message)
109
+ message = clean(display(c.log)); // "POST 200 /api/users"
110
+ const isAssert = name === 'assert';
111
+ const step = {
112
+ title: name === 'route' ? clean(routeTitle(c.log)) : isAssert ? message : `${name}${message ? ' ' + message : ''}`,
113
+ category: isAssert ? 'assert' : 'cy',
114
+ duration: Math.max(0, (next ? next.start : end) - c.start),
115
+ steps: [],
116
+ };
117
+ if (c.log.get('state') === 'failed')
118
+ step.error = clean(errMsg || c.log.get('err')?.message || 'failed');
119
+ // the hook it ran in: one step per hook, the commands inside
120
+ let container = out;
121
+ if (c.hook) {
122
+ if (!hookStep || hookName !== c.hook) {
123
+ hookName = c.hook;
124
+ hookStep = { title: `${camel(c.hook)} hook`, category: 'hook', duration: 0, steps: [] };
125
+ out.push(hookStep);
126
+ }
127
+ hookStep.duration += step.duration;
128
+ if (step.error)
129
+ hookStep.error = step.error;
130
+ container = hookStep.steps;
131
+ }
132
+ else {
133
+ hookStep = undefined;
134
+ hookName = undefined;
135
+ }
136
+ const chainer = String(c.log.get('chainerId') || '');
137
+ const parent = c.log.get('type') === 'child' ? parents.get(chainer) : undefined;
138
+ if (parent) {
139
+ parent.steps.push(step);
140
+ parent.duration += step.duration;
141
+ if (step.error)
142
+ parent.error = step.error;
143
+ }
144
+ else {
145
+ container.push(step);
146
+ if (chainer)
147
+ parents.set(chainer, step);
148
+ }
149
+ });
150
+ return out;
151
+ }
152
+ function camel(hookName) {
153
+ const m = /^(before|after) (each|all)$/i.exec(hookName.replace(/"/g, '').replace(/ hook.*$/i, '').trim());
154
+ return m ? m[1].toLowerCase() + (m[2].toLowerCase() === 'each' ? 'Each' : 'All') : hookName;
155
+ }
156
+ function routeTitle(log) {
157
+ const p = props(log);
158
+ return `intercept ${p.Method ?? ''} ${p.URL ?? p.Matcher ?? ''}${p.Alias ? ' as @' + p.Alias : ''}`;
159
+ }
160
+ /** The text Cypress shows on the command line, e.g. "POST 200 /api/users" for cy.request. */
161
+ function display(log) {
162
+ try {
163
+ const rp = log.get('renderProps');
164
+ const v = typeof rp === 'function' ? rp() : rp;
165
+ return String(v?.message ?? '');
166
+ }
167
+ catch {
168
+ return '';
169
+ }
170
+ }
171
+ function toMs(v) {
172
+ if (!v)
173
+ return 0;
174
+ const n = v instanceof Date ? v.getTime() : new Date(v).getTime();
175
+ return Number.isFinite(n) ? n : 0;
176
+ }
177
+ function props(log) {
178
+ try {
179
+ const cp = typeof log.invoke === 'function' ? log.invoke('consoleProps') : log.get('consoleProps');
180
+ const v = typeof cp === 'function' ? cp() : cp;
181
+ return (v && (v.props ?? v)) || {};
182
+ }
183
+ catch {
184
+ return {};
185
+ }
186
+ }
187
+ /** cy.request (with request and response) and the app's fetch / XHR calls. */
188
+ function api() {
189
+ const out = [];
190
+ for (const c of logs) {
191
+ const name = c.log.get('name');
192
+ if (name !== 'request' && name !== 'xhr' && name !== 'fetch')
193
+ continue;
194
+ const p = props(c.log);
195
+ if (c.log.get('event') || name !== 'request') {
196
+ // the app's own fetch / XHR: method, URL, status once answered; headers and body when Cypress kept them
197
+ const shown = display(c.log); // "GET 200 /api/users" once answered
198
+ const status = Number(p['Response Status Code'] ?? p.Status ?? (shown.match(/^\w+\s+(\d{3})\b/) || [])[1]) || undefined;
199
+ if (p.URL)
200
+ out.push({ method: String(p.Method || shown.split(' ')[0] || 'GET').toUpperCase(), url: String(p.URL), status,
201
+ requestHeaders: p['Request Headers'], requestBody: parse(p['Request Body']), responseHeaders: p['Response Headers'], responseBody: parse(p['Response Body']) });
202
+ continue;
203
+ }
204
+ const reqs = Array.isArray(p.Requests) ? p.Requests : p.Request ? [p.Request] : [];
205
+ const yielded = p.Yielded || {};
206
+ for (const r of reqs.length ? reqs : [{}]) {
207
+ const url = r['Request URL'] ?? yielded.url ?? p.URL;
208
+ if (!url)
209
+ continue;
210
+ out.push({
211
+ method: String(r['Request Method'] ?? display(c.log).split(' ')[0] ?? 'GET').toUpperCase() || 'GET',
212
+ url: String(url),
213
+ status: Number(r['Response Status'] ?? yielded.status) || undefined,
214
+ duration: typeof yielded.duration === 'number' ? yielded.duration : undefined,
215
+ requestHeaders: r['Request Headers'], requestBody: parse(r['Request Body']),
216
+ responseHeaders: r['Response Headers'], responseBody: parse(r['Response Body'] ?? yielded.body),
217
+ });
218
+ }
219
+ }
220
+ return out;
221
+ }
222
+ function parse(v) {
223
+ if (typeof v !== 'string')
224
+ return v;
225
+ try {
226
+ return JSON.parse(v);
227
+ }
228
+ catch {
229
+ return v;
230
+ }
231
+ }
package/dist/explain.js CHANGED
@@ -55,6 +55,10 @@ function explainError(raw) {
55
55
  // ── The browser process died (memory, too many workers): infrastructure, not the app or the test ──
56
56
  if (/Target crashed|Page crashed|page has crashed|Renderer process crashed|tab crashed|session deleted because of page crash|chrome not reachable|Browsing context has been discarded/i.test(msg))
57
57
  return out('crashed', 'The browser crashed while the test was running.', 'Not a bug in the app or the test: the browser process died, usually from memory pressure or too many parallel workers. Re-run it; if it keeps happening, lower workers or give the machine more memory.', { action });
58
+ // ── Cypress (and chai-style assertions): only messages in Cypress's own wording reach these rules ──
59
+ const cy = explainCypress(msg, out);
60
+ if (cy)
61
+ return cy;
58
62
  // ── Strict mode ──────────────────────────────────────────────────────────
59
63
  m = msg.match(/strict mode violation: (.+?) resolved to (\d+) elements/s);
60
64
  if (m)
@@ -162,3 +166,104 @@ function explainError(raw) {
162
166
  return out('thrown', short(first.replace(/^Error: /, '')), 'The test (or a helper) threw this error on purpose or via a failed check. The stack trace below points at the line.');
163
167
  return out('thrown', short(first), 'See the full message and stack trace below.');
164
168
  }
169
+ /** Cypress messages: `Timed out retrying after 4000ms: …`, `cy.click()` failed because …, cy.request / cy.visit /
170
+ * cy.wait failures, uncaught application errors, and chai assertions (`expected 'a' to equal 'b'`). */
171
+ function explainCypress(msg, out) {
172
+ const body = msg.replace(/^(?:AssertionError|CypressError|Error):\s*/, '');
173
+ const retry = body.match(/^Timed out retrying after (\d+)ms:\s*/);
174
+ const timeoutMs = retry ? Number(retry[1]) : undefined;
175
+ const text = retry ? body.slice(retry[0].length) : body;
176
+ const within = timeoutMs ? ' within ' + secs(timeoutMs) : '';
177
+ const cmd = pick(text, /`?(cy\.\w+)\(\)`?\s+(?:failed|timed out|could not)/);
178
+ const isCy = !!retry || !!cmd || /CypressError|originated from your application code|for your remote page to load|error preparing this test file|^`?cy\.\w+\(\)/.test(msg);
179
+ const chai = text.match(/^expected ([\s\S]+?) (?:not to|to(?: (not))?) (deeply equal|have length|have text|have value|equal|eql|be|have|include|contain|match|exist)\b\s*([\s\S]*)$/);
180
+ if (!isCy && !chai)
181
+ return undefined;
182
+ // ── the spec file itself could not be bundled / loaded: no test in it ran ──
183
+ if (/error preparing this test file/.test(msg)) {
184
+ const why = pick(msg, /Module not found: Error: ([^\n]+?)(?: in '[^']*')?$/m) ?? pick(msg, /^((?:SyntaxError|TypeError|ReferenceError|Error):(?! Webpack)[^\n]+)$/m);
185
+ return out('script', `The spec file could not be loaded${why ? ': ' + short(why, 110) : ''}. No test in it ran.`, 'Fix the import path or the syntax error in the spec (or in a file it imports).');
186
+ }
187
+ // ── the app threw, not the test ──
188
+ if (/originated from your application code, not from Cypress/.test(msg)) {
189
+ const appErr = pick(msg, /^\s*>\s*(.+)$/m);
190
+ return out('script', `The application threw an uncaught error${appErr ? ': ' + short(appErr, 100) : ''}. Cypress fails the test when the app throws.`, 'Fix the error in the app, or if it is expected, ignore it with Cypress.on(\'uncaught:exception\', () => false) for that test.');
191
+ }
192
+ // ── element lookups ──
193
+ let m = text.match(/Expected to find element: `?([^`\n]+?)`?, but never found it/);
194
+ if (m)
195
+ return out('not-found', `${m[1]} was not on the page${within}.`, 'Check the selector, and whether the element is inside an iframe, behind a login, or only shown after a click.', { locator: m[1], timeoutMs });
196
+ m = text.match(/Expected to find content: '([^']*)'(?: within the (?:element|selector): ([^\n]+?))?,? but never did/);
197
+ if (m)
198
+ return out('not-found', `The text "${short(m[1], 60)}" did not appear${m[2] ? ' inside ' + short(m[2].replace(/`/g, ''), 60) : ''}${within}.`, 'Check the expected text (case, spaces) and whether the page finished loading.', { locator: m[2]?.replace(/`/g, ''), timeoutMs });
199
+ m = text.match(/Expected not to find element: `?([^`\n]+?)`?, but it was continuously found/);
200
+ if (m)
201
+ return out('assertion', `${m[1]} was still on the page${within}, but should have gone.`, 'Something kept it on screen. Check the step that should remove or hide it.', { locator: m[1], timeoutMs });
202
+ m = text.match(/Not enough elements found\. Found '(\d+)', expected '(\d+)'|Too many elements found\. Found '(\d+)', expected '(\d+)'/);
203
+ if (m)
204
+ return out('assertion', `The selector matched ${m[1] ?? m[3]} elements, expected ${m[2] ?? m[4]}${within}.`, 'The list may not have finished loading, or the selector also matches other elements.', { timeoutMs });
205
+ // ── actions: cy.click() failed because this element … ──
206
+ if (cmd && /failed because/.test(text)) {
207
+ const el = pick(text, /this element:?\s*\n*\s*`?(<[^`\n]+>)`?/) ?? pick(text, /`(<[^`\n]+>)`/);
208
+ const base = { action: cmd, locator: el, timeoutMs };
209
+ if (/is being covered by another element/.test(text)) {
210
+ const by = pick(text, /covered by another element:?\s*\n*\s*`?(<[^`\n]+>)`?/);
211
+ return out('blocked', `${cmd}() could not reach ${el ?? 'the element'}: ${by ? short(by, 60) : 'another element'} is on top of it.`, 'A dialog, banner, overlay or spinner is in the way. Close or wait for it first.', base);
212
+ }
213
+ if (/is not visible/.test(text))
214
+ return out('not-visible', `${cmd}() could not use ${el ?? 'the element'} because it is not visible.`, 'It may be hidden by CSS, off screen in a closed menu, or still animating in.', base);
215
+ if (/is disabled/.test(text))
216
+ return out('disabled', `${cmd}() could not use ${el ?? 'the element'} because it is disabled.`, 'The form may need another field filled first, or the app is still busy.', base);
217
+ if (/page updated while this command was executing|detached from the DOM/.test(text))
218
+ return out('detached', `The element was re-rendered while ${cmd}() was using it.`, 'The UI replaced the element. Query it again after the change, or wait for the update to finish.', base);
219
+ if (/can only be called on|requires a DOM element|requires a valid subject|can only be called on a single element/.test(text))
220
+ return out('wrong-element', `${cmd}() was used on something it does not work on.`, 'Check the command before it: the subject may be several elements, or not an element at all.', base);
221
+ }
222
+ // ── cy.request / cy.visit / cy.wait ──
223
+ if (cmd === 'cy.request') {
224
+ const url = pick(text, /failed on:\s*\n+\s*(https?:\/\/\S+)/);
225
+ const st = text.match(/>\s*(\d{3}):\s*([^\n]*)/);
226
+ if (/timed out waiting/.test(text))
227
+ return out('api', `The API request${url ? ' to ' + url : ''} did not answer in time.`, 'The API may be slow or hanging. Check its logs, or raise the timeout of cy.request.', { action: cmd, url });
228
+ if (st)
229
+ return out('api', `The API answered ${st[1]}${st[2] ? ' ' + st[2].trim() : ''}${url ? ' for ' + url : ''}.`, Number(st[1]) >= 500 ? 'A server error: check the API logs for this request.' : 'Check the request (URL, auth, body). If this status is expected, pass failOnStatusCode: false.', { action: cmd, url });
230
+ if (/failed without a response|ECONNREFUSED|ENOTFOUND/.test(text))
231
+ return out('network', `The API${url ? ' at ' + url : ''} could not be reached.`, 'Check the URL and that the API is up. In CI, make sure it starts before the tests.', { action: cmd, url });
232
+ }
233
+ if (cmd === 'cy.visit' || /for your remote page to load/.test(text)) {
234
+ const url = pick(text, /failed trying to load:\s*\n+\s*(https?:\/\/\S+)/);
235
+ const st = text.match(/>\s*(\d{3}):\s*([^\n]*)/);
236
+ if (/for your remote page to load/.test(text))
237
+ return out('navigation', `The page did not finish loading${pick(text, /waiting `?(\d+)ms`?/) ? ' within ' + secs(Number(pick(text, /waiting `?(\d+)ms`?/))) : ''}.`, 'The app may be slow or stuck on a request. Raise pageLoadTimeout only if the page is really that slow.', { action: 'cy.visit', url });
238
+ if (/failed without a response|ECONNREFUSED|ENOTFOUND|ECONNRESET/.test(text))
239
+ return out('network', `The browser could not reach ${url ?? 'the site'}.`, 'Check baseUrl and that the app is running. In CI, make sure the web server starts before the tests.', { action: 'cy.visit', url });
240
+ if (st)
241
+ return out('navigation', `${url ?? 'The page'} answered ${st[1]}${st[2] ? ' ' + st[2].trim() : ''}.`, 'Check the URL. If this status is expected, pass failOnStatusCode: false to cy.visit.', { action: 'cy.visit', url });
242
+ }
243
+ m = text.match(/`?cy\.wait\(\)`? timed out waiting `?(\d+)ms`? for the \w+ (request|response) to the route: `?([^`\s.]+)`?/);
244
+ if (m)
245
+ return out('api', `No ${m[2]} for the route "${m[3]}" came within ${secs(Number(m[1]))}.`, m[2] === 'request' ? 'The app never made that call: check the cy.intercept() pattern (method, URL) and that the action triggering it ran.' : 'The call was made but did not answer in time: check the API.', { action: 'cy.wait', timeoutMs: Number(m[1]) });
246
+ if (cmd === 'cy.task' && /failed with the following error/.test(text))
247
+ return out('script', `The task ${pick(text, /cy\.task\('([^']+)'/) ?? ''} threw in the Cypress Node process.`.replace('task ', 'task '), 'See the full message below; the task code lives in setupNodeEvents.', { action: 'cy.task' });
248
+ // ── assertions (chai / should) ──
249
+ if (chai) {
250
+ const [, actual, notAfter, verb, restRaw] = chai;
251
+ const not = notAfter || (/^expected [\s\S]+? not to /.test(text) ? 'not ' : undefined);
252
+ const rest = restRaw.split('\n')[0].replace(/,\s*but[\s\S]*$/, '').replace(/ in the DOM$/, '').trim();
253
+ const butWas = pick(text, /but the (?:text|value) was '([^']*)'/);
254
+ const el = /^'?<[^>]+>'?$/.test(actual.trim()) ? actual.replace(/'/g, '') : undefined;
255
+ const base = { locator: el, timeoutMs };
256
+ if (verb === 'exist')
257
+ return out(not ? 'assertion' : 'not-found', not ? `${el ?? short(actual, 60)} still existed${within}.` : `${el ?? short(actual, 60)} did not exist${within}.`, not ? 'Something kept it on the page. Check the step that should remove it.' : 'Check the selector and whether the element appears only after another step.', base);
258
+ if (verb === 'be' && /^'?visible'?$/.test(rest) && !not)
259
+ return out('not-visible', `${el ?? 'The element'} was expected to be visible${within} but was not.`, 'It may still be loading, be hidden by CSS, or sit inside a closed menu or dialog.', base);
260
+ if ((verb === 'have text' || verb === 'have value') && butWas !== undefined)
261
+ return out('assertion', `${el ?? 'The element'} had the wrong ${verb === 'have text' ? 'text' : 'value'}: expected ${short(rest, 60)}, got '${short(butWas, 60)}'.`, 'Compare expected and received below. A copy change, a data change or a timing issue are the usual causes.', base);
262
+ if (/equal|eql/.test(verb) && !not)
263
+ return out('assertion', `Expected ${short(rest, 70)}, got ${short(actual, 70)}.`, 'Compare the two values in the full message below.', base);
264
+ if (/include|contain|match/.test(verb))
265
+ return out('assertion', `${short(actual, 70)} did ${not ? '' : 'not '}${verb === 'match' ? 'match' : 'contain'} ${short(rest, 70)}${within}.`, /^'https?:/.test(actual) ? 'The page may not have navigated yet, or went somewhere else (a redirect, a login screen, an error page).' : 'Compare the two values in the full message below.', base);
266
+ return out('assertion', `An assertion did not pass: expected ${short(actual, 60)} to ${not ?? ''}${verb} ${short(rest, 60)}${within}.`.replace(/\s+\./, '.'), 'See the full message below.', base);
267
+ }
268
+ return undefined;
269
+ }
@@ -1,40 +1,3 @@
1
- export interface ReportingLabsCompleteOptions {
2
- outputFolder?: string;
3
- outputFile?: string;
4
- jsonFile?: string;
5
- emitJson?: boolean;
6
- pdf?: boolean | {
7
- file?: string;
8
- chromePath?: string;
9
- };
10
- title?: string;
11
- logo?: string;
12
- accent?: string;
13
- theme?: 'auto' | 'light' | 'dark';
14
- palette?: 'lab' | 'ocean' | 'ember' | 'mono';
15
- metadata?: Record<string, string>;
16
- env?: Record<string, string>;
17
- sections?: {
18
- title: string;
19
- html: string;
20
- }[];
21
- customCss?: string;
22
- dimensions?: string[];
23
- dimensionOrder?: Record<string, string[]>;
24
- project?: unknown;
25
- links?: Record<string, unknown>;
26
- bdd?: boolean;
27
- announce?: boolean;
28
- history?: {
29
- enabled?: boolean;
30
- file?: string;
31
- keep?: number;
32
- };
33
- maskKeys?: string[];
34
- maskValues?: string[];
35
- maskFromEnv?: boolean;
36
- embedFonts?: boolean;
37
- editorLinks?: boolean;
38
- expandFailedSteps?: boolean;
39
- }
1
+ import { type WriteReportOptions } from '../write-report';
2
+ export type ReportingLabsCompleteOptions = WriteReportOptions;
40
3
  export declare function reportingLabsComplete(options?: ReportingLabsCompleteOptions): Promise<string | undefined>;
@@ -46,10 +46,7 @@ exports.reportingLabsComplete = reportingLabsComplete;
46
46
  */
47
47
  const fs = __importStar(require("fs"));
48
48
  const path = __importStar(require("path"));
49
- const template_1 = require("../template");
50
- const mask_1 = require("../mask");
51
- const pdf_1 = require("../pdf");
52
- const env_1 = require("./env");
49
+ const write_report_1 = require("../write-report");
53
50
  async function reportingLabsComplete(options = {}) {
54
51
  const outputFolder = options.outputFolder || 'reporting-labs';
55
52
  const partsDir = path.join(outputFolder, '.rl-wdio');
@@ -58,7 +55,6 @@ async function reportingLabsComplete(options = {}) {
58
55
  const files = fs.readdirSync(partsDir).filter(f => f.endsWith('.json'));
59
56
  if (!files.length)
60
57
  return undefined;
61
- const masker = (0, mask_1.makeMasker)(options.maskKeys || [], { knownValues: options.maskValues || [], fromEnv: options.maskFromEnv !== false });
62
58
  const tests = [];
63
59
  let startTime = Number.MAX_SAFE_INTEGER;
64
60
  let endTime = 0;
@@ -85,106 +81,11 @@ async function reportingLabsComplete(options = {}) {
85
81
  startTime = Date.now();
86
82
  if (!endTime)
87
83
  endTime = Date.now();
88
- const stats = { passed: 0, failed: 0, skipped: 0, flaky: 0, timedOut: 0, interrupted: 0, total: tests.length };
89
- for (const t of tests)
90
- stats[t.outcome]++;
91
- const projects = [...new Set(tests.map(t => t.project).filter(Boolean))];
92
- const base = process.cwd();
93
- const dims = (options.dimensions ?? ['priority', 'severity', 'feature', 'owner']).map(d => d.toLowerCase());
94
- const histOn = options.history?.enabled ?? true;
95
- const histFile = path.resolve(base, options.history?.file ?? 'reporting-labs.history.json');
96
- let entries = [];
97
- if (histOn) {
98
- try {
99
- entries = JSON.parse(fs.readFileSync(histFile, 'utf8'));
100
- }
101
- catch { /* first run */ }
102
- }
103
- const failedCount = stats.failed + stats.timedOut + stats.interrupted;
104
- const code = (o) => o === 'passed' ? 'p' : o === 'flaky' ? 'k' : o === 'skipped' ? 's' : 'f';
105
- const perTest = {};
106
- for (const t of tests) {
107
- const last = t.results[t.results.length - 1];
108
- perTest[t.key] = [code(t.outcome), Math.round(last?.duration ?? t.duration)];
109
- }
110
- const current = {
111
- time: startTime, duration: endTime - startTime,
112
- passed: stats.passed, failed: failedCount, flaky: stats.flaky, skipped: stats.skipped, total: stats.total,
113
- label: options.metadata?.build ?? (0, env_1.ciRunLabel)(process.env) ?? options.metadata?.branch, tests: perTest,
114
- };
115
- const history = [...entries, current].slice(-(options.history?.keep ?? 30));
116
- if (histOn) {
117
- try {
118
- fs.writeFileSync(histFile, JSON.stringify(history, null, 1));
119
- }
120
- catch { /* read-only fs */ }
121
- }
122
- const metadata = Object.fromEntries(Object.entries(options.metadata ?? {}).map(([k, v]) => [k, masker.maskStr(String(v))]));
123
- const bdd = options.bdd ?? tests.some(t => t.results.some(r => r.steps.some(st => /^(Given|When|Then|And|But)\b/.test(st.title))));
124
- const data = {
125
- title: masker.maskStr(options.title ?? 'Test report'),
126
- generatedAt: Date.now(),
127
- startTime,
128
- duration: endTime - startTime,
129
- metadata,
130
- projects,
131
- workers,
132
- stats,
133
- tests,
134
- history,
135
- bdd,
136
- rootDir: base,
137
- env: (0, env_1.collectEnv)(base, Object.fromEntries(Object.entries(options.env ?? {}).map(([k, v]) => [k, masker.maskStr(String(v))])), [...new Set(projects)], workers, options.metadata?.branch).map(r => ({ ...r, v: masker.maskStr(r.v) })),
138
- runStatus,
139
- globalErrors: [],
140
- globalOutput: [],
141
- options: {
142
- logo: options.logo,
143
- accent: options.accent,
144
- theme: options.theme ?? 'auto',
145
- palette: options.palette ?? 'lab',
146
- embedFonts: options.embedFonts ?? true,
147
- sections: options.sections ?? [],
148
- widgets: { runStrip: true, outcome: true, attention: true, dimensions: true, timeline: true, durations: true, tags: true, slowest: true, projects: true, flaky: true, environment: true, skipped: true },
149
- dimensions: dims,
150
- dimensionOrder: {
151
- priority: ['P0', 'P1', 'P2', 'P3', 'P4'],
152
- severity: ['blocker', 'critical', 'major', 'high', 'medium', 'normal', 'minor', 'low', 'trivial'],
153
- ...(options.dimensionOrder ?? {}),
154
- },
155
- project: options.project,
156
- links: Object.fromEntries(Object.entries(options.links ?? {}).map(([k, v]) => [k.toLowerCase(), typeof v === 'string' ? v : v.url])),
157
- customCss: options.customCss ?? '',
158
- editorLinks: options.editorLinks ?? !process.env.CI,
159
- expandFailedSteps: options.expandFailedSteps ?? true,
160
- },
161
- };
162
- fs.mkdirSync(outputFolder, { recursive: true });
163
- const htmlFile = path.join(outputFolder, options.outputFile ?? 'index.html');
164
- fs.writeFileSync(htmlFile, (0, template_1.renderHtml)(data), 'utf8');
165
- if (options.emitJson !== false)
166
- fs.writeFileSync(path.join(outputFolder, options.jsonFile ?? 'report.json'), JSON.stringify(data), 'utf8');
167
- // tidy the partials
84
+ // the partials are only needed for this report
85
+ const htmlFile = await (0, write_report_1.writeReport)(tests, { startTime, endTime, runStatus, workers }, options);
168
86
  try {
169
87
  fs.rmSync(partsDir, { recursive: true, force: true });
170
88
  }
171
89
  catch { /* leave them */ }
172
- if (options.announce !== false) {
173
- console.log(`\n reporting-labs: report written to ${path.relative(process.cwd(), htmlFile)}`);
174
- }
175
- if (options.pdf !== false)
176
- await writePdf(htmlFile, outputFolder, options);
177
- if (options.announce !== false)
178
- console.log('');
179
90
  return htmlFile;
180
91
  }
181
- /** report.pdf next to the HTML; see writeReportPdf for which browser prints it (an installed Chrome or
182
- * Edge when the project has no Playwright). Never fails the run. */
183
- async function writePdf(htmlFile, outputFolder, options) {
184
- const pdfOpt = typeof options.pdf === 'object' ? options.pdf : {};
185
- const pdfFile = path.join(outputFolder, pdfOpt.file || 'report.pdf');
186
- const r = await (0, pdf_1.writeReportPdf)(htmlFile, pdfFile, pdfOpt.chromePath);
187
- if (options.announce === false)
188
- return;
189
- console.log(r.ok ? ` reporting-labs: PDF written to ${path.relative(process.cwd(), pdfFile)}` : ` reporting-labs: PDF skipped — ${r.reason}`);
190
- }
@@ -0,0 +1,51 @@
1
+ import type { TestData, EnvRow } from './types';
2
+ export interface WriteReportOptions {
3
+ outputFolder?: string;
4
+ outputFile?: string;
5
+ jsonFile?: string;
6
+ emitJson?: boolean;
7
+ pdf?: boolean | {
8
+ file?: string;
9
+ chromePath?: string;
10
+ };
11
+ title?: string;
12
+ logo?: string;
13
+ accent?: string;
14
+ theme?: 'auto' | 'light' | 'dark';
15
+ palette?: 'lab' | 'ocean' | 'ember' | 'mono';
16
+ metadata?: Record<string, string>;
17
+ env?: Record<string, string>;
18
+ sections?: {
19
+ title: string;
20
+ html: string;
21
+ }[];
22
+ customCss?: string;
23
+ dimensions?: string[];
24
+ dimensionOrder?: Record<string, string[]>;
25
+ project?: unknown;
26
+ links?: Record<string, unknown>;
27
+ bdd?: boolean;
28
+ announce?: boolean;
29
+ history?: {
30
+ enabled?: boolean;
31
+ file?: string;
32
+ keep?: number;
33
+ };
34
+ maskKeys?: string[];
35
+ maskValues?: string[];
36
+ maskFromEnv?: boolean;
37
+ embedFonts?: boolean;
38
+ editorLinks?: boolean;
39
+ expandFailedSteps?: boolean;
40
+ }
41
+ /** Run-level facts the runner knows. */
42
+ export interface RunInfo {
43
+ startTime: number;
44
+ endTime: number;
45
+ runStatus: 'passed' | 'failed';
46
+ workers: number;
47
+ /** Rows shown first on the Environment card, e.g. the Cypress version and browser. */
48
+ envRows?: EnvRow[];
49
+ }
50
+ /** Writes the report into options.outputFolder (default reporting-labs) and returns the HTML path. */
51
+ export declare function writeReport(tests: TestData[], run: RunInfo, options?: WriteReportOptions): Promise<string>;