@andrii_kremlovskyi/playwright-traces-reader 2.2.0 → 2.4.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.
@@ -36,11 +36,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getTestSteps = getTestSteps;
37
37
  exports.getTopLevelFailures = getTopLevelFailures;
38
38
  exports.getNetworkTraffic = getNetworkTraffic;
39
+ exports.getNetworkRequest = getNetworkRequest;
40
+ exports.getConsoleEntries = getConsoleEntries;
41
+ exports.getTraceIssues = getTraceIssues;
42
+ exports.getAttachments = getAttachments;
43
+ exports.extractAttachment = extractAttachment;
39
44
  exports.extractScreenshots = extractScreenshots;
40
45
  exports.getDomSnapshots = getDomSnapshots;
41
46
  exports.getTimeline = getTimeline;
42
47
  exports.getTestTitle = getTestTitle;
43
48
  exports.getSummary = getSummary;
49
+ exports.getReportFailurePatterns = getReportFailurePatterns;
50
+ exports.summarizeReportFailurePatterns = summarizeReportFailurePatterns;
44
51
  exports.getFailedTraceSelections = getFailedTraceSelections;
45
52
  exports.getFailedTestSummaries = getFailedTestSummaries;
46
53
  const fs = __importStar(require("fs"));
@@ -119,8 +126,9 @@ async function getTopLevelFailures(traceContext) {
119
126
  * 'api' (has _apiRequest, no pageref). Response and request bodies are
120
127
  * resolved from the resources/ directory when a _sha1 reference exists.
121
128
  */
122
- async function getNetworkTraffic(traceContext) {
129
+ async function getNetworkTraffic(traceContext, options) {
123
130
  const entries = [];
131
+ const actions = await getBrowserActions(traceContext);
124
132
  const files = await fs.promises.readdir(traceContext.traceDir);
125
133
  const networkFiles = files.filter(f => f.endsWith('.network')).sort();
126
134
  for (const networkFile of networkFiles) {
@@ -164,7 +172,9 @@ async function getNetworkTraffic(traceContext) {
164
172
  responseBody = content.text;
165
173
  }
166
174
  entries.push({
175
+ id: entries.length + 1,
167
176
  source,
177
+ pageId: snap.pageref ?? null,
168
178
  method: snap.request.method,
169
179
  url: snap.request.url,
170
180
  status: snap.response.status,
@@ -176,11 +186,190 @@ async function getNetworkTraffic(traceContext) {
176
186
  mimeType: content.mimeType,
177
187
  startedDateTime: snap.startedDateTime,
178
188
  durationMs: snap.time,
189
+ relatedAction: correlateAction(actions, new Date(snap.startedDateTime).getTime(), snap.pageref ?? null),
179
190
  });
180
191
  }
181
192
  }
193
+ return filterNetworkEntries(entries, options);
194
+ }
195
+ async function getNetworkRequest(traceContext, requestId) {
196
+ const entries = await getNetworkTraffic(traceContext);
197
+ const entry = entries.find(candidate => candidate.id === requestId);
198
+ if (!entry)
199
+ throw new Error(`Request '${requestId}' not found.`);
200
+ return entry;
201
+ }
202
+ // ---------- getConsoleEntries ----------
203
+ async function getConsoleEntries(traceContext) {
204
+ const entries = [];
205
+ const files = await fs.promises.readdir(traceContext.traceDir);
206
+ const traceFiles = files.filter(f => f.endsWith('.trace')).sort();
207
+ for (const traceFile of traceFiles) {
208
+ const filePath = path.join(traceContext.traceDir, traceFile);
209
+ for await (const event of (0, parseTrace_1.readNdjson)(filePath)) {
210
+ if (event.type === 'console') {
211
+ entries.push({
212
+ source: 'browser',
213
+ level: event.messageType,
214
+ text: event.text,
215
+ timestamp: event.time,
216
+ pageId: event.pageId ?? null,
217
+ location: event.location,
218
+ });
219
+ continue;
220
+ }
221
+ if (event.type === 'event' && event.method === 'pageError') {
222
+ const text = event.params.error?.error?.message ?? String(event.params.error?.value ?? '');
223
+ if (!text)
224
+ continue;
225
+ entries.push({
226
+ source: 'browser',
227
+ level: 'error',
228
+ text,
229
+ timestamp: event.time,
230
+ pageId: event.pageId ?? null,
231
+ location: null,
232
+ });
233
+ continue;
234
+ }
235
+ if (event.type === 'stdout' || event.type === 'stderr') {
236
+ let text = event.text?.trim() ?? '';
237
+ if (!text && event.base64)
238
+ text = Buffer.from(event.base64, 'base64').toString('utf8').trim();
239
+ if (!text)
240
+ continue;
241
+ entries.push({
242
+ source: event.type,
243
+ level: event.type === 'stderr' ? 'error' : 'info',
244
+ text,
245
+ timestamp: event.timestamp,
246
+ pageId: null,
247
+ location: null,
248
+ });
249
+ }
250
+ }
251
+ }
252
+ entries.sort((a, b) => a.timestamp - b.timestamp);
182
253
  return entries;
183
254
  }
255
+ // ---------- getTraceIssues ----------
256
+ async function getTraceIssues(traceContext) {
257
+ const issues = [];
258
+ const actions = await getBrowserActions(traceContext);
259
+ const steps = await getTestSteps(traceContext);
260
+ for (const step of flattenSteps(steps)) {
261
+ if (!step.error)
262
+ continue;
263
+ issues.push({
264
+ source: 'step',
265
+ message: step.error.message,
266
+ name: step.error.name,
267
+ stack: step.error.stack ?? null,
268
+ timestamp: step.endTime ?? step.startTime,
269
+ callId: step.callId,
270
+ title: step.title,
271
+ location: null,
272
+ relatedAction: resolveIssueRelatedAction(actions, step.callId, step.endTime ?? step.startTime, null),
273
+ });
274
+ }
275
+ const files = await fs.promises.readdir(traceContext.traceDir);
276
+ const traceFiles = files.filter(f => f.endsWith('.trace')).sort();
277
+ for (const traceFile of traceFiles) {
278
+ const filePath = path.join(traceContext.traceDir, traceFile);
279
+ for await (const event of (0, parseTrace_1.readNdjson)(filePath)) {
280
+ if (event.type === 'error') {
281
+ const firstFrame = event.stack?.[0];
282
+ issues.push({
283
+ source: 'trace',
284
+ message: event.message,
285
+ name: 'TraceError',
286
+ stack: formatStackFrames(event.stack),
287
+ timestamp: null,
288
+ callId: null,
289
+ title: null,
290
+ location: firstFrame ? { file: firstFrame.file, line: firstFrame.line, column: firstFrame.column } : null,
291
+ relatedAction: null,
292
+ });
293
+ continue;
294
+ }
295
+ if (event.type === 'event' && event.method === 'pageError') {
296
+ const pageError = event.params.error?.error;
297
+ const message = pageError?.message ?? String(event.params.error?.value ?? '');
298
+ if (!message)
299
+ continue;
300
+ issues.push({
301
+ source: 'page',
302
+ message,
303
+ name: pageError?.name ?? 'PageError',
304
+ stack: pageError?.stack ?? null,
305
+ timestamp: event.time,
306
+ callId: null,
307
+ title: null,
308
+ location: null,
309
+ relatedAction: resolveIssueRelatedAction(actions, null, event.time, event.pageId ?? null),
310
+ });
311
+ }
312
+ }
313
+ }
314
+ issues.sort((a, b) => {
315
+ if (a.timestamp === null && b.timestamp === null)
316
+ return 0;
317
+ if (a.timestamp === null)
318
+ return 1;
319
+ if (b.timestamp === null)
320
+ return -1;
321
+ return a.timestamp - b.timestamp;
322
+ });
323
+ return issues;
324
+ }
325
+ // ---------- getAttachments ----------
326
+ async function getAttachments(traceContext) {
327
+ const files = await fs.promises.readdir(traceContext.traceDir);
328
+ const traceFiles = files.filter(f => f.endsWith('.trace')).sort();
329
+ const actionTitleByCallId = new Map();
330
+ const attachments = [];
331
+ for (const traceFile of traceFiles) {
332
+ const filePath = path.join(traceContext.traceDir, traceFile);
333
+ for await (const event of (0, parseTrace_1.readNdjson)(filePath)) {
334
+ if (event.type === 'before') {
335
+ actionTitleByCallId.set(event.callId, event.title);
336
+ continue;
337
+ }
338
+ if (event.type !== 'after' || !event.attachments?.length)
339
+ continue;
340
+ for (const attachment of event.attachments) {
341
+ attachments.push({
342
+ id: attachments.length + 1,
343
+ callId: event.callId,
344
+ actionTitle: actionTitleByCallId.get(event.callId) ?? null,
345
+ name: attachment.name,
346
+ contentType: attachment.contentType,
347
+ path: attachment.path ?? null,
348
+ sha1: attachment.sha1 ?? null,
349
+ base64: attachment.base64 ?? null,
350
+ size: await attachmentSize(traceContext, attachment),
351
+ });
352
+ }
353
+ }
354
+ }
355
+ return attachments;
356
+ }
357
+ async function extractAttachment(traceContext, attachmentId, outputPath) {
358
+ const attachments = await getAttachments(traceContext);
359
+ const attachment = attachments.find(entry => entry.id === attachmentId);
360
+ if (!attachment)
361
+ throw new Error(`Attachment '${attachmentId}' not found.`);
362
+ const content = await attachmentContent(traceContext, attachment);
363
+ if (!content)
364
+ throw new Error(`Could not extract attachment '${attachmentId}'.`);
365
+ const savedPath = outputPath ?? path.join(process.cwd(), path.basename(attachment.name));
366
+ await fs.promises.mkdir(path.dirname(savedPath), { recursive: true });
367
+ await fs.promises.writeFile(savedPath, content);
368
+ return {
369
+ ...attachment,
370
+ savedPath,
371
+ };
372
+ }
184
373
  // ---------- extractScreenshots ----------
185
374
  /**
186
375
  * Finds all screencast-frame entries across all *-trace.trace files,
@@ -488,6 +677,263 @@ function flattenSteps(steps) {
488
677
  }
489
678
  return out;
490
679
  }
680
+ function buildActionDiagnostics(networkCalls, issues) {
681
+ const byCallId = new Map();
682
+ const ensure = (action) => {
683
+ const existing = byCallId.get(action.callId);
684
+ if (existing)
685
+ return existing;
686
+ const created = {
687
+ action,
688
+ networkCallCount: 0,
689
+ failingNetworkCallCount: 0,
690
+ issueCount: 0,
691
+ };
692
+ byCallId.set(action.callId, created);
693
+ return created;
694
+ };
695
+ for (const entry of networkCalls) {
696
+ if (!entry.relatedAction)
697
+ continue;
698
+ const bucket = ensure(entry.relatedAction);
699
+ bucket.networkCallCount += 1;
700
+ if (entry.status >= 400)
701
+ bucket.failingNetworkCallCount += 1;
702
+ }
703
+ for (const issue of issues) {
704
+ if (!issue.relatedAction)
705
+ continue;
706
+ ensure(issue.relatedAction).issueCount += 1;
707
+ }
708
+ return [...byCallId.values()].sort((left, right) => {
709
+ const leftScore = left.failingNetworkCallCount * 10 + left.issueCount * 5 + left.networkCallCount;
710
+ const rightScore = right.failingNetworkCallCount * 10 + right.issueCount * 5 + right.networkCallCount;
711
+ return rightScore - leftScore;
712
+ });
713
+ }
714
+ function buildReportFailurePatterns(selections) {
715
+ const realFailures = selections.filter(selection => selection.summary.outcome !== 'skipped');
716
+ const repeatedFailingRequests = new Map();
717
+ const repeatedIssues = new Map();
718
+ for (const selection of realFailures) {
719
+ for (const entry of selection.summary.networkCalls) {
720
+ if (entry.status < 400)
721
+ continue;
722
+ const signature = buildRequestPatternSignature(entry);
723
+ const bucket = repeatedFailingRequests.get(signature) ?? {
724
+ method: entry.method,
725
+ url: stripQuery(entry.url),
726
+ traces: new Set(),
727
+ statuses: new Set(),
728
+ relatedActions: new Map(),
729
+ };
730
+ bucket.traces.add(selection.traceSha1);
731
+ bucket.statuses.add(entry.status);
732
+ if (entry.relatedAction)
733
+ bucket.relatedActions.set(entry.relatedAction.callId, { callId: entry.relatedAction.callId, title: entry.relatedAction.title });
734
+ repeatedFailingRequests.set(signature, bucket);
735
+ }
736
+ for (const issue of selection.summary.issues) {
737
+ if (!issue.relatedAction)
738
+ continue;
739
+ const signature = buildIssuePatternSignature(issue);
740
+ const bucket = repeatedIssues.get(signature) ?? {
741
+ source: issue.source,
742
+ name: issue.name,
743
+ message: firstLine(issue.message) ?? issue.message,
744
+ traces: new Set(),
745
+ relatedActions: new Map(),
746
+ };
747
+ bucket.traces.add(selection.traceSha1);
748
+ bucket.relatedActions.set(issue.relatedAction.callId, { callId: issue.relatedAction.callId, title: issue.relatedAction.title });
749
+ repeatedIssues.set(signature, bucket);
750
+ }
751
+ }
752
+ return {
753
+ repeatedFailingRequests: [...repeatedFailingRequests.entries()]
754
+ .map(([signature, bucket]) => ({
755
+ signature,
756
+ method: bucket.method,
757
+ url: bucket.url,
758
+ count: bucket.traces.size,
759
+ traceSha1s: [...bucket.traces].sort(),
760
+ statuses: [...bucket.statuses].sort((left, right) => left - right),
761
+ relatedActions: [...bucket.relatedActions.values()],
762
+ }))
763
+ .filter(pattern => pattern.count > 1)
764
+ .sort((left, right) => right.count - left.count),
765
+ repeatedIssues: [...repeatedIssues.entries()]
766
+ .map(([signature, bucket]) => ({
767
+ signature,
768
+ source: bucket.source,
769
+ name: bucket.name,
770
+ message: bucket.message,
771
+ count: bucket.traces.size,
772
+ traceSha1s: [...bucket.traces].sort(),
773
+ relatedActions: [...bucket.relatedActions.values()],
774
+ }))
775
+ .filter(pattern => pattern.count > 1)
776
+ .sort((left, right) => right.count - left.count),
777
+ };
778
+ }
779
+ async function attachmentSize(traceContext, attachment) {
780
+ if (attachment.sha1) {
781
+ const buffer = await (0, parseTrace_1.getResourceBuffer)(traceContext, attachment.sha1);
782
+ if (buffer)
783
+ return buffer.length;
784
+ }
785
+ if (attachment.base64)
786
+ return Buffer.from(attachment.base64, 'base64').length;
787
+ if (attachment.path && fs.existsSync(attachment.path)) {
788
+ const stat = await fs.promises.stat(attachment.path);
789
+ return stat.size;
790
+ }
791
+ return null;
792
+ }
793
+ async function attachmentContent(traceContext, attachment) {
794
+ if (attachment.sha1) {
795
+ const buffer = await (0, parseTrace_1.getResourceBuffer)(traceContext, attachment.sha1);
796
+ if (buffer)
797
+ return buffer;
798
+ }
799
+ if (attachment.base64)
800
+ return Buffer.from(attachment.base64, 'base64');
801
+ if (attachment.path && fs.existsSync(attachment.path))
802
+ return fs.promises.readFile(attachment.path);
803
+ return null;
804
+ }
805
+ function formatStackFrames(stack) {
806
+ if (!stack?.length)
807
+ return null;
808
+ return stack.map(frame => `at ${frame.file}:${frame.line}:${frame.column}`).join('\n');
809
+ }
810
+ async function getBrowserActions(traceContext) {
811
+ const files = await fs.promises.readdir(traceContext.traceDir);
812
+ const traceFiles = files.filter(f => /^\d+-trace\.trace$/.test(f)).sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
813
+ const actions = new Map();
814
+ for (const traceFile of traceFiles) {
815
+ const filePath = path.join(traceContext.traceDir, traceFile);
816
+ for await (const event of (0, parseTrace_1.readNdjson)(filePath)) {
817
+ if (event.type === 'before') {
818
+ actions.set(event.callId, {
819
+ callId: event.callId,
820
+ title: event.title ?? `${event.class}.${event.method}`,
821
+ method: event.method,
822
+ pageId: event.pageId ?? null,
823
+ startTime: event.startTime,
824
+ endTime: null,
825
+ });
826
+ continue;
827
+ }
828
+ if (event.type === 'after') {
829
+ const action = actions.get(event.callId);
830
+ if (action)
831
+ action.endTime = event.endTime;
832
+ }
833
+ }
834
+ }
835
+ return [...actions.values()].sort((a, b) => a.startTime - b.startTime);
836
+ }
837
+ function correlateAction(actions, timestamp, pageId) {
838
+ let best = null;
839
+ let bestDistance = Number.POSITIVE_INFINITY;
840
+ for (const action of actions) {
841
+ if (pageId && action.pageId && action.pageId !== pageId)
842
+ continue;
843
+ const endTime = action.endTime ?? action.startTime;
844
+ const withinWindow = timestamp >= action.startTime && timestamp <= endTime;
845
+ const distance = withinWindow ? 0 : Math.min(Math.abs(timestamp - action.startTime), Math.abs(timestamp - endTime));
846
+ if (distance < bestDistance) {
847
+ best = action;
848
+ bestDistance = distance;
849
+ }
850
+ }
851
+ return best;
852
+ }
853
+ function resolveIssueRelatedAction(actions, callId, timestamp, pageId) {
854
+ if (callId) {
855
+ const directMatch = actions.find(action => action.callId === callId);
856
+ if (directMatch)
857
+ return directMatch;
858
+ }
859
+ return correlateAction(actions, timestamp, pageId);
860
+ }
861
+ function filterNetworkEntries(entries, options) {
862
+ if (!options)
863
+ return entries;
864
+ let filtered = entries;
865
+ if (options.source && options.source !== 'all')
866
+ filtered = filtered.filter(entry => entry.source === options.source);
867
+ if (options.grep) {
868
+ const pattern = new RegExp(options.grep, 'i');
869
+ filtered = filtered.filter(entry => pattern.test(entry.url));
870
+ }
871
+ if (options.method)
872
+ filtered = filtered.filter(entry => entry.method.toLowerCase() === options.method.toLowerCase());
873
+ if (options.status !== undefined)
874
+ filtered = filtered.filter(entry => entry.status === options.status);
875
+ if (options.failed)
876
+ filtered = filtered.filter(entry => entry.status >= 400);
877
+ if (options.near)
878
+ filtered = filtered.filter(entry => entry.relatedAction?.callId === options.near);
879
+ if (options.limit !== undefined)
880
+ filtered = filtered.slice(0, options.limit);
881
+ return filtered;
882
+ }
883
+ function buildRequestPatternSignature(entry) {
884
+ try {
885
+ const parsed = new URL(entry.url);
886
+ return `${entry.method.toUpperCase()} ${normalizePathname(parsed.pathname)}`;
887
+ }
888
+ catch {
889
+ return `${entry.method.toUpperCase()} ${entry.url}`;
890
+ }
891
+ }
892
+ function buildIssuePatternSignature(issue) {
893
+ return [
894
+ issue.source,
895
+ issue.name ?? 'Error',
896
+ normalizeIssueMessage(firstLine(issue.message) ?? issue.message),
897
+ ].join(' | ');
898
+ }
899
+ function normalizePathname(pathname) {
900
+ const segments = pathname.split('/').filter(Boolean);
901
+ if (segments.length === 0)
902
+ return '/';
903
+ return `/${segments.map(normalizePathSegment).join('/')}`;
904
+ }
905
+ function normalizePathSegment(segment) {
906
+ if (/^\d+$/.test(segment))
907
+ return ':id';
908
+ if (/^[0-9a-f]{8,}$/i.test(segment))
909
+ return ':id';
910
+ if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(segment))
911
+ return ':id';
912
+ if (/^trace-[\w-]+$/i.test(segment))
913
+ return ':id';
914
+ return segment;
915
+ }
916
+ function normalizeIssueMessage(message) {
917
+ return message
918
+ .replace(/trace-[\w-]+/gi, ':trace')
919
+ .replace(/call@[\w-]+/gi, 'call@:id')
920
+ .replace(/\b[0-9a-f]{8,}\b/gi, ':id')
921
+ .replace(/\b\d+\b/g, ':n');
922
+ }
923
+ function stripQuery(urlText) {
924
+ try {
925
+ const parsed = new URL(urlText);
926
+ parsed.search = '';
927
+ parsed.hash = '';
928
+ return parsed.toString();
929
+ }
930
+ catch {
931
+ return urlText;
932
+ }
933
+ }
934
+ function firstLine(value) {
935
+ return value ? value.split(/\r?\n/, 1)[0] ?? null : null;
936
+ }
491
937
  /**
492
938
  * Merges all trace event types (steps, screenshots, DOM snapshots, network
493
939
  * calls) into a single chronologically sorted array.
@@ -560,11 +1006,12 @@ async function getTestTitle(traceContext) {
560
1006
  * getNetworkTraffic(), and getDomSnapshots().
561
1007
  */
562
1008
  async function getSummary(traceContext, options) {
563
- const [roots, network, domAll, testTitle] = await Promise.all([
1009
+ const [roots, network, domAll, testTitle, issues] = await Promise.all([
564
1010
  getTestSteps(traceContext),
565
1011
  getNetworkTraffic(traceContext),
566
1012
  getDomSnapshots(traceContext),
567
1013
  getTestTitle(traceContext),
1014
+ getTraceIssues(traceContext),
568
1015
  ]);
569
1016
  // Infrastructure steps injected by Playwright — not meaningful test content.
570
1017
  const HOOK_TITLES = new Set([
@@ -591,6 +1038,7 @@ async function getSummary(traceContext, options) {
591
1038
  .sort((a, b) => (b.durationMs ?? 0) - (a.durationMs ?? 0))
592
1039
  .slice(0, 5);
593
1040
  const networkCalls = network;
1041
+ const actionDiagnostics = buildActionDiagnostics(networkCalls, issues);
594
1042
  let failureDomSnapshot = null;
595
1043
  if (error && mainRoot && domAll.length > 0) {
596
1044
  const failureTime = mainRoot.endTime ?? mainRoot.startTime;
@@ -609,12 +1057,21 @@ async function getSummary(traceContext, options) {
609
1057
  topLevelSteps,
610
1058
  slowestSteps,
611
1059
  networkCalls,
1060
+ issues,
1061
+ actionDiagnostics,
612
1062
  failureDomSnapshot,
613
1063
  outcome: options.reportMetadata
614
1064
  ? (options.reportTraceMaps ?? (0, parseTrace_1.buildReportTraceMaps)(options.reportMetadata)).outcomeByTraceSha1.get(path.basename(traceContext.traceDir)) ?? null
615
1065
  : null,
616
1066
  };
617
1067
  }
1068
+ async function getReportFailurePatterns(reportDataDir, options) {
1069
+ const selections = await getFailedTraceSelections(reportDataDir, options);
1070
+ return buildReportFailurePatterns(selections);
1071
+ }
1072
+ function summarizeReportFailurePatterns(selections) {
1073
+ return buildReportFailurePatterns(selections);
1074
+ }
618
1075
  async function getFailedTraceSelections(reportDataDir, options) {
619
1076
  const traces = await (0, parseTrace_1.listTraces)(reportDataDir);
620
1077
  const meta = await (0, parseTrace_1.getReportMetadata)(reportDataDir);