@andrii_kremlovskyi/playwright-traces-reader 4.1.1 → 4.2.2

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
@@ -214,13 +214,13 @@ All trace files use **Newline-Delimited JSON (NDJSON)**.
214
214
  ## Quick Start
215
215
 
216
216
  ```typescript
217
- import {
218
- getFailedTestSummaries,
219
- } from '@andrii_kremlovskyi/playwright-traces-reader';
217
+ import { getFailedTestSummaries } from "@andrii_kremlovskyi/playwright-traces-reader";
220
218
 
221
219
  // One call — returns one TraceSummary per unique failing test.
222
220
  // Retries deduplicated; passing tests excluded; last retry selected.
223
- const failures = await getFailedTestSummaries('/path/to/playwright-report/data');
221
+ const failures = await getFailedTestSummaries(
222
+ "/path/to/playwright-report/data",
223
+ );
224
224
 
225
225
  for (const f of failures) {
226
226
  console.log(`[FAILED] ${f.testTitle ?? f.title}`);
@@ -232,7 +232,9 @@ for (const f of failures) {
232
232
  }
233
233
 
234
234
  if (f.failureDomSnapshot) {
235
- console.log(`DOM ref: callId=${f.failureDomSnapshot.callId} phases=${f.failureDomSnapshot.phases}`);
235
+ console.log(
236
+ `DOM ref: callId=${f.failureDomSnapshot.callId} phases=${f.failureDomSnapshot.phases}`,
237
+ );
236
238
  // Use getDomSnapshots() with { near: f.failureDomSnapshot.callId } to fetch full HTML
237
239
  }
238
240
  }
@@ -245,13 +247,13 @@ import {
245
247
  prepareTraceDir,
246
248
  getReportMetadata,
247
249
  getSummary,
248
- } from '@andrii_kremlovskyi/playwright-traces-reader';
250
+ } from "@andrii_kremlovskyi/playwright-traces-reader";
249
251
 
250
252
  // Point at a single extracted trace directory (or a .zip)
251
- const ctx = await prepareTraceDir('/path/to/playwright-report/data/<sha1>');
253
+ const ctx = await prepareTraceDir("/path/to/playwright-report/data/<sha1>");
252
254
 
253
255
  // Load report metadata for outcome info (pass null if unavailable)
254
- const meta = await getReportMetadata('/path/to/playwright-report');
256
+ const meta = await getReportMetadata("/path/to/playwright-report");
255
257
 
256
258
  // For a single trace, pass reportMetadata directly:
257
259
  const summary = await getSummary(ctx, { reportMetadata: meta });
@@ -259,7 +261,9 @@ const summary = await getSummary(ctx, { reportMetadata: meta });
259
261
  // For many traces, pre-build maps to avoid redundant work:
260
262
  // const maps = meta ? buildReportTraceMaps(meta) : null;
261
263
  // const summary = await getSummary(ctx, { reportMetadata: meta, reportTraceMaps: maps });
262
- console.log(`[${summary.status.toUpperCase()}] ${summary.testTitle ?? summary.title}`);
264
+ console.log(
265
+ `[${summary.status.toUpperCase()}] ${summary.testTitle ?? summary.title}`,
266
+ );
263
267
  console.log(`Error: ${summary.error?.message}`);
264
268
  ```
265
269
 
@@ -275,14 +279,15 @@ Important distinction:
275
279
  ### `getFailedTestSummaries(reportDataDir, options?)`
276
280
 
277
281
  Report-level helper. Returns `TraceSummary[]` — one entry per **unique** failing test:
282
+
278
283
  - Passing tests are skipped cheaply (no `getSummary` call).
279
284
  - Retries are deduplicated by `testId` from `report.json` when `index.html` is available, falling back to `getTestTitle()` or `ctx.traceDir`. The **last retry** (highest root step `endTime`) is used so the summary reflects the most recent execution.
280
285
  - Each returned summary has an `outcome` field (`'unexpected'` | `'skipped'` | `'flaky'` | `null`) from `report.json`, so callers can filter or group by outcome.
281
286
 
282
287
  **`GetFailedTestSummariesOptions`** (optional second argument):
283
288
 
284
- | Option | Type | Default | Description |
285
- |---|---|---|---|
289
+ | Option | Type | Default | Description |
290
+ | ---------------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
286
291
  | `excludeSkipped` | `boolean` | `false` | Omit tests that were skipped via `test.skip()`. When `index.html` is found next to the `data/` directory, maps trace directories to test outcomes via `report.json` (each test result's trace attachment path contains the SHA1 directory name). Falls back to checking trace step annotations and error messages when `index.html` is not available. Pre-annotated skips (suite-level annotations or conditional `test.skip(condition)`) are already excluded automatically because they produce no root step failures. |
287
292
 
288
293
  This is the recommended entry point for failure analysis. See [`TraceSummary`](#tracesummary) for the full field list.
@@ -291,10 +296,10 @@ This is the recommended entry point for failure analysis. See [`TraceSummary`](#
291
296
 
292
297
  Builds a `TraceSummary` for a single `TraceContext`. Requires an `options: GetSummaryOptions` object:
293
298
 
294
- | Option | Type | Required | Description |
295
- |---|---|---|---|
296
- | `reportMetadata` | `ReportMetadata \| null` | Yes | Parsed report metadata from `getReportMetadata()`. When provided, `outcome` is populated from `report.json`. Pass `null` when unavailable. |
297
- | `reportTraceMaps` | `ReportTraceMaps \| null` | No | Pre-built lookup maps from `buildReportTraceMaps()`. Avoids rebuilding maps on every call when invoking `getSummary` in a loop. If omitted, maps are built on-the-fly. |
299
+ | Option | Type | Required | Description |
300
+ | ----------------- | ------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
301
+ | `reportMetadata` | `ReportMetadata \| null` | Yes | Parsed report metadata from `getReportMetadata()`. When provided, `outcome` is populated from `report.json`. Pass `null` when unavailable. |
302
+ | `reportTraceMaps` | `ReportTraceMaps \| null` | No | Pre-built lookup maps from `buildReportTraceMaps()`. Avoids rebuilding maps on every call when invoking `getSummary` in a loop. If omitted, maps are built on-the-fly. |
298
303
 
299
304
  ### `listTraces(reportDataDir)`
300
305
 
@@ -316,39 +321,39 @@ Reads numbered trace files (`0-trace.trace`, …) for a `context-options` event
316
321
 
317
322
  Returns the full step tree from `test.trace` as `TestStep[]`. Each step has:
318
323
 
319
- | Field | Type | Description |
320
- |---|---|---|
321
- | `callId` | `string` | Unique step identifier |
322
- | `title` | `string` | Human-readable step name |
323
- | `method` | `string` | API method if applicable |
324
- | `startTime` | `number` | Unix ms timestamp |
325
- | `endTime` | `number \| null` | Unix ms timestamp |
326
- | `durationMs` | `number \| null` | Wall-clock duration |
327
- | `error` | `TraceError \| null` | Error details if the step failed |
328
- | `annotations` | `StepAnnotation[]` | Step annotations (e.g. `{ type: 'skip' }` for skipped tests) |
329
- | `children` | `TestStep[]` | Nested child steps |
324
+ | Field | Type | Description |
325
+ | ------------- | -------------------- | ------------------------------------------------------------ |
326
+ | `callId` | `string` | Unique step identifier |
327
+ | `title` | `string` | Human-readable step name |
328
+ | `method` | `string` | API method if applicable |
329
+ | `startTime` | `number` | Unix ms timestamp |
330
+ | `endTime` | `number \| null` | Unix ms timestamp |
331
+ | `durationMs` | `number \| null` | Wall-clock duration |
332
+ | `error` | `TraceError \| null` | Error details if the step failed |
333
+ | `annotations` | `StepAnnotation[]` | Step annotations (e.g. `{ type: 'skip' }` for skipped tests) |
334
+ | `children` | `TestStep[]` | Nested child steps |
330
335
 
331
336
  ### `getNetworkTraffic(ctx)`
332
337
 
333
338
  Returns `NetworkEntry[]` from all `*.network` trace files. Supports optional filters for `source`, `grep`, `method`, `status`, `failed`, `near`, and `limit`. Each entry includes:
334
339
 
335
- | Field | Type | Description |
336
- |---|---|---|
337
- | `id` | `number` | Per-trace request identifier used by `getNetworkRequest()` and the CLI `request` command |
338
- | `source` | `'api' \| 'browser'` | `'api'` = Playwright `APIRequestContext`; `'browser'` = XHR / navigation |
339
- | `pageId` | `string \| null` | Page identifier when the request belongs to a browser page |
340
- | `method` | `string` | HTTP method |
341
- | `url` | `string` | Request URL |
342
- | `status` | `number` | HTTP response status |
343
- | `statusText` | `string` | HTTP status text |
344
- | `requestHeaders` | `Array<{name,value}>` | Request headers |
345
- | `responseHeaders` | `Array<{name,value}>` | Response headers |
346
- | `requestBody` | `string \| null` | Resolved request body |
347
- | `responseBody` | `string \| null` | Resolved response body (binary → `[binary: ...]` placeholder) |
348
- | `mimeType` | `string` | Response content MIME type |
349
- | `startedDateTime` | `string` | ISO 8601 request start time |
350
- | `durationMs` | `number` | Total request duration |
351
- | `relatedAction` | `RelatedActionRef \| null` | Nearest correlated browser action for this request |
340
+ | Field | Type | Description |
341
+ | ----------------- | -------------------------- | ---------------------------------------------------------------------------------------- |
342
+ | `id` | `number` | Per-trace request identifier used by `getNetworkRequest()` and the CLI `request` command |
343
+ | `source` | `'api' \| 'browser'` | `'api'` = Playwright `APIRequestContext`; `'browser'` = XHR / navigation |
344
+ | `pageId` | `string \| null` | Page identifier when the request belongs to a browser page |
345
+ | `method` | `string` | HTTP method |
346
+ | `url` | `string` | Request URL |
347
+ | `status` | `number` | HTTP response status |
348
+ | `statusText` | `string` | HTTP status text |
349
+ | `requestHeaders` | `Array<{name,value}>` | Request headers |
350
+ | `responseHeaders` | `Array<{name,value}>` | Response headers |
351
+ | `requestBody` | `string \| null` | Resolved request body |
352
+ | `responseBody` | `string \| null` | Resolved response body (binary → `[binary: ...]` placeholder) |
353
+ | `mimeType` | `string` | Response content MIME type |
354
+ | `startedDateTime` | `string` | ISO 8601 request start time |
355
+ | `durationMs` | `number` | Total request duration |
356
+ | `relatedAction` | `RelatedActionRef \| null` | Nearest correlated browser action for this request |
352
357
 
353
358
  ### `getNetworkRequest(ctx, requestId)`
354
359
 
@@ -386,41 +391,41 @@ Writes screencast frames from all `[N]-trace.trace` files to `outDir` as numbere
386
391
 
387
392
  Returns `ActionDomSnapshots[]` — one entry per browser action that has DOM snapshots. Each entry groups three phases:
388
393
 
389
- | Field | Type | Description |
390
- |---|---|---|
391
- | `callId` | `string` | Action identifier |
392
- | `before` | `DomSnapshot \| null` | DOM before the action |
394
+ | Field | Type | Description |
395
+ | -------- | --------------------- | --------------------------------------- |
396
+ | `callId` | `string` | Action identifier |
397
+ | `before` | `DomSnapshot \| null` | DOM before the action |
393
398
  | `action` | `DomSnapshot \| null` | DOM during the action (mid-interaction) |
394
- | `after` | `DomSnapshot \| null` | DOM after the action completed |
399
+ | `after` | `DomSnapshot \| null` | DOM after the action completed |
395
400
 
396
401
  Each `DomSnapshot` contains:
397
402
 
398
- | Field | Type | Description |
399
- |---|---|---|
400
- | `html` | `string` | Full serialized HTML (back-references resolved, `<script>` stripped) |
401
- | `phase` | `'before' \| 'action' \| 'after'` | Snapshot phase |
402
- | `frameUrl` | `string` | URL of the frame at snapshot time |
403
- | `targetElement` | `string \| null` | `callId` of the action that targeted an element, or `null` |
404
- | `viewport` | `{ width: number; height: number }` | Viewport dimensions |
405
- | `timestamp` | `number` | Unix ms timestamp |
403
+ | Field | Type | Description |
404
+ | --------------- | ----------------------------------- | -------------------------------------------------------------------- |
405
+ | `html` | `string` | Full serialized HTML (back-references resolved, `<script>` stripped) |
406
+ | `phase` | `'before' \| 'action' \| 'after'` | Snapshot phase |
407
+ | `frameUrl` | `string` | URL of the frame at snapshot time |
408
+ | `targetElement` | `string \| null` | `callId` of the action that targeted an element, or `null` |
409
+ | `viewport` | `{ width: number; height: number }` | Viewport dimensions |
410
+ | `timestamp` | `number` | Unix ms timestamp |
406
411
 
407
412
  **`DomSnapshotOptions`** (optional second argument):
408
413
 
409
- | Option | Type | Description |
410
- |---|---|---|
411
- | `near` | `'last' \| string` | `'last'` = last `limit` entries; any other string = window centred on that callId |
412
- | `phase` | `'before' \| 'action' \| 'after'` | Keep only entries where this phase is populated |
413
- | `limit` | `number` | Max entries to return (default 5 with `near: 'last'`; caps from beginning otherwise) |
414
+ | Option | Type | Description |
415
+ | ------- | --------------------------------- | ------------------------------------------------------------------------------------ |
416
+ | `near` | `'last' \| string` | `'last'` = last `limit` entries; any other string = window centred on that callId |
417
+ | `phase` | `'before' \| 'action' \| 'after'` | Keep only entries where this phase is populated |
418
+ | `limit` | `number` | Max entries to return (default 5 with `near: 'last'`; caps from beginning otherwise) |
414
419
 
415
420
  ### `getTimeline(ctx)`
416
421
 
417
422
  Merges all event types into a single chronologically sorted `TimelineEntry[]`:
418
423
 
419
- | Field | Type | Description |
420
- |---|---|---|
421
- | `timestamp` | `number` | Wall-clock ms since epoch |
422
- | `type` | `'step' \| 'screenshot' \| 'dom' \| 'network'` | Event category |
423
- | `data` | (typed union) | Payload — cast based on `type` |
424
+ | Field | Type | Description |
425
+ | ----------- | ---------------------------------------------- | ------------------------------ |
426
+ | `timestamp` | `number` | Wall-clock ms since epoch |
427
+ | `type` | `'step' \| 'screenshot' \| 'dom' \| 'network'` | Event category |
428
+ | `data` | (typed union) | Payload — cast based on `type` |
424
429
 
425
430
  Steps are flattened (all nesting levels). Screenshots are `ScreenshotMetadata` (no `savedPath` — no disk writes).
426
431
 
@@ -428,20 +433,20 @@ Steps are flattened (all nesting levels). Screenshots are `ScreenshotMetadata` (
428
433
 
429
434
  The bundle returned by `getSummary()` and `getFailedTestSummaries()`:
430
435
 
431
- | Field | Type | Description |
432
- |---|---|---|
433
- | `testTitle` | `string \| null` | Full unique title from `context-options` (spec path + describe + test name). Use for display. `null` for pure API traces. |
434
- | `title` | `string` | Root `test.step()` title (failing step or longest non-hook step) |
435
- | `status` | `'passed' \| 'failed'` | Test pass/fail from trace data |
436
- | `outcome` | `'expected' \| 'unexpected' \| 'flaky' \| 'skipped' \| null` | Authoritative outcome from `report.json`. Populated when `reportMetadata` is passed to `getSummary()` or automatically by `getFailedTestSummaries()`. `null` when `reportMetadata` is `null` or trace SHA1 not found. |
437
- | `durationMs` | `number \| null` | Duration of the main root step |
438
- | `error` | `TraceError \| null` | Top-level error, or `null` if passed |
439
- | `topLevelSteps` | `TestStep[]` | Non-hook root steps (the visible `test.step()` blocks), each with `.children` |
440
- | `slowestSteps` | `TestStep[]` | Top 5 slowest steps across the full step tree |
441
- | `networkCalls` | `NetworkEntry[]` | All HTTP calls (`source: 'api'` = Node.js `APIRequestContext`; `source: 'browser'` = XHR / fetch / navigation) |
442
- | `issues` | `TraceIssue[]` | Step failures, page errors, and trace-level issues for the trace |
443
- | `actionDiagnostics` | `ActionDiagnosticSummary[]` | Aggregated request and issue counts grouped by related browser action |
444
- | `failureDomSnapshot` | `FailureDomSnapshotRef \| null` | Lightweight metadata reference (callId, phases, timestamp, frameUrl) to the DOM snapshot closest to the failure. Use `getDomSnapshots()` or the `dom` CLI command with `--near <callId>` to retrieve full HTML. `null` for passed traces or when no snapshots exist. |
436
+ | Field | Type | Description |
437
+ | -------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
438
+ | `testTitle` | `string \| null` | Full unique title from `context-options` (spec path + describe + test name). Use for display. `null` for pure API traces. |
439
+ | `title` | `string` | Root `test.step()` title (failing step or longest non-hook step) |
440
+ | `status` | `'passed' \| 'failed'` | Test pass/fail from trace data |
441
+ | `outcome` | `'expected' \| 'unexpected' \| 'flaky' \| 'skipped' \| null` | Authoritative outcome from `report.json`. Populated when `reportMetadata` is passed to `getSummary()` or automatically by `getFailedTestSummaries()`. `null` when `reportMetadata` is `null` or trace SHA1 not found. |
442
+ | `durationMs` | `number \| null` | Duration of the main root step |
443
+ | `error` | `TraceError \| null` | Top-level error, or `null` if passed |
444
+ | `topLevelSteps` | `TestStep[]` | Non-hook root steps (the visible `test.step()` blocks), each with `.children` |
445
+ | `slowestSteps` | `TestStep[]` | Top 5 slowest steps across the full step tree |
446
+ | `networkCalls` | `NetworkEntry[]` | All HTTP calls (`source: 'api'` = Node.js `APIRequestContext`; `source: 'browser'` = XHR / fetch / navigation) |
447
+ | `issues` | `TraceIssue[]` | Step failures, page errors, and trace-level issues for the trace |
448
+ | `actionDiagnostics` | `ActionDiagnosticSummary[]` | Aggregated request and issue counts grouped by related browser action |
449
+ | `failureDomSnapshot` | `FailureDomSnapshotRef \| null` | Lightweight metadata reference (callId, phases, timestamp, frameUrl) to the DOM snapshot closest to the failure. Use `getDomSnapshots()` or the `dom` CLI command with `--near <callId>` to retrieve full HTML. `null` for passed traces or when no snapshots exist. |
445
450
 
446
451
  ### `getReportFailurePatterns(reportDataDir, options?)`
447
452
 
@@ -456,13 +461,14 @@ This uses the same retry-deduplication and optional skip-filtering rules as `get
456
461
 
457
462
  Returns the same `ReportFailurePatterns` shape, but starts from already prepared `FailedTraceSelection[]` values instead of rescanning a report directory. Use this when you have already called the internal selection flow and want to avoid repeating the trace scan.
458
463
 
459
- ### `getResourceBuffer(ctx, sha1)`
464
+ ### `getResourceBuffer(ctx, reference)`
460
465
 
461
- Low-level helper. Resolves a SHA1 filename to a raw `Buffer` from `resources/`. Returns `null` if not found.
466
+ Low-level helper. Resolves either a legacy bare resource name from `resources/` or a current trace-relative `file` / `_file` path. Paths are constrained to the trace root. Returns `null` if not found.
462
467
 
463
468
  ### `buildReportTraceMaps(meta)`
464
469
 
465
470
  Builds SHA1-keyed lookup maps from parsed `ReportMetadata`. Returns `ReportTraceMaps` with:
471
+
466
472
  - `outcomeByTraceSha1` — maps trace SHA1 to test outcome (`'expected'` | `'unexpected'` | `'flaky'` | `'skipped'`)
467
473
  - `testIdByTraceSha1` — maps trace SHA1 to test ID
468
474
 
@@ -481,16 +487,16 @@ Searches a Playwright HTML report for tests matching a name pattern and returns
481
487
 
482
488
  Returns `FoundTrace[]` where each entry includes:
483
489
 
484
- | Field | Type | Description |
485
- |---|---|---|
486
- | `testTitle` | `string` | Full test title (path + describe + name) |
487
- | `testId` | `string` | Unique test identifier |
488
- | `projectName` | `string` | Playwright project name |
489
- | `file` | `string` | Test file path |
490
- | `outcome` | `string` | Test-level outcome from `report.json` |
491
- | `resultIndex` | `number` | Zero-based retry index |
492
- | `traceSha1` | `string` | Trace directory name |
493
- | `tracePath` | `string` | Absolute path to the trace in `data/` |
490
+ | Field | Type | Description |
491
+ | ------------- | -------- | ---------------------------------------- |
492
+ | `testTitle` | `string` | Full test title (path + describe + name) |
493
+ | `testId` | `string` | Unique test identifier |
494
+ | `projectName` | `string` | Playwright project name |
495
+ | `file` | `string` | Test file path |
496
+ | `outcome` | `string` | Test-level outcome from `report.json` |
497
+ | `resultIndex` | `number` | Zero-based retry index |
498
+ | `traceSha1` | `string` | Trace directory name |
499
+ | `tracePath` | `string` | Absolute path to the trace in `data/` |
494
500
 
495
501
  ### `readNdjson<T>(filePath)`
496
502
 
@@ -1,5 +1,5 @@
1
- import { type ReportMetadata, type TraceContext } from './parseTrace';
2
- import { type DigestCommandJson } from './cli/json';
1
+ import { type ReportMetadata, type TraceContext } from "./parseTrace";
2
+ import { type DigestCommandJson } from "./cli/json";
3
3
  /**
4
4
  * Digests a single trace (any status) into a self-contained folder under
5
5
  * `outputDir`. Produces a chronological step tree (`digest.json`) whose leaf
@@ -1 +1 @@
1
- {"version":3,"file":"digestTrace.d.ts","sourceRoot":"","sources":["../src/digestTrace.ts"],"names":[],"mappings":"AAYA,OAAO,EAKL,KAAK,cAAc,EACnB,KAAK,YAAY,EAClB,MAAM,cAAc,CAAC;AACtB,OAAO,EAEL,KAAK,iBAAiB,EAKvB,MAAM,YAAY,CAAC;AA+LpB;;;;;;;;;;;;;GAaG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,YAAY,EACjB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE;IAAE,cAAc,CAAC,EAAE,cAAc,GAAG,IAAI,CAAA;CAAE,GACnD,OAAO,CAAC,iBAAiB,CAAC,CAoM5B"}
1
+ {"version":3,"file":"digestTrace.d.ts","sourceRoot":"","sources":["../src/digestTrace.ts"],"names":[],"mappings":"AAYA,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,YAAY,EAClB,MAAM,cAAc,CAAC;AACtB,OAAO,EAEL,KAAK,iBAAiB,EAKvB,MAAM,YAAY,CAAC;AA4OpB;;;;;;;;;;;;;GAaG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,YAAY,EACjB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE;IAAE,cAAc,CAAC,EAAE,cAAc,GAAG,IAAI,CAAA;CAAE,GACnD,OAAO,CAAC,iBAAiB,CAAC,CAkO5B"}
@@ -44,19 +44,22 @@ const BODY_SPILL_THRESHOLD_BYTES = 32 * 1024;
44
44
  // eslint-disable-next-line no-control-regex
45
45
  const ANSI_PATTERN = /\u001b\[[0-9;]*m/g;
46
46
  function stripAnsi(value) {
47
- return value.replace(ANSI_PATTERN, '');
47
+ return value.replace(ANSI_PATTERN, "");
48
48
  }
49
49
  function sanitizeFolderName(value) {
50
50
  const cleaned = value
51
51
  .toLowerCase()
52
- .replace(/[^a-z0-9]+/g, '-')
53
- .replace(/-+/g, '-')
54
- .replace(/^-|-$/g, '');
55
- return (cleaned || 'trace').slice(0, 80).replace(/-$/, '');
52
+ .replace(/[^a-z0-9]+/g, "-")
53
+ .replace(/-+/g, "-")
54
+ .replace(/^-|-$/g, "");
55
+ return (cleaned || "trace").slice(0, 80).replace(/-$/, "");
56
56
  }
57
57
  /** Sanitizes a callId (e.g. `pw:api@71`) into a filesystem-safe stem (`pw-api-71`). */
58
58
  function sanitizeCallId(callId) {
59
- return callId.replace(/[^a-zA-Z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
59
+ return callId
60
+ .replace(/[^a-zA-Z0-9]+/g, "-")
61
+ .replace(/-+/g, "-")
62
+ .replace(/^-|-$/g, "");
60
63
  }
61
64
  /** Finds the trace's retry index by matching its SHA1 against report metadata. */
62
65
  function findRetryIndex(meta, traceSha1) {
@@ -82,7 +85,7 @@ function inStepWindow(step, t) {
82
85
  return t >= step.startTime && t <= end;
83
86
  }
84
87
  function isBinaryBody(body) {
85
- return body !== null && body.startsWith('[binary:');
88
+ return body !== null && body.startsWith("[binary:");
86
89
  }
87
90
  /**
88
91
  * Builds the chronological network NDJSON lines and the spilled-body lines.
@@ -103,12 +106,16 @@ function buildNetworkLines(entries) {
103
106
  seqByEntry.set(entry, seq);
104
107
  const requestBody = entry.requestBody;
105
108
  const requestBodyIsBinary = isBinaryBody(requestBody);
106
- const requestBodySizeBytes = requestBody !== null ? Buffer.byteLength(requestBody, 'utf8') : 0;
107
- const requestBodyIsLarge = !requestBodyIsBinary && requestBody !== null && requestBodySizeBytes > BODY_SPILL_THRESHOLD_BYTES;
109
+ const requestBodySizeBytes = requestBody !== null ? Buffer.byteLength(requestBody, "utf8") : 0;
110
+ const requestBodyIsLarge = !requestBodyIsBinary &&
111
+ requestBody !== null &&
112
+ requestBodySizeBytes > BODY_SPILL_THRESHOLD_BYTES;
108
113
  const responseBody = entry.responseBody;
109
114
  const responseBodyIsBinary = isBinaryBody(responseBody);
110
- const responseBodySizeBytes = responseBody !== null ? Buffer.byteLength(responseBody, 'utf8') : 0;
111
- const responseBodyIsLarge = !responseBodyIsBinary && responseBody !== null && responseBodySizeBytes > BODY_SPILL_THRESHOLD_BYTES;
115
+ const responseBodySizeBytes = responseBody !== null ? Buffer.byteLength(responseBody, "utf8") : 0;
116
+ const responseBodyIsLarge = !responseBodyIsBinary &&
117
+ responseBody !== null &&
118
+ responseBodySizeBytes > BODY_SPILL_THRESHOLD_BYTES;
112
119
  const line = {
113
120
  seq,
114
121
  monotonicTime: entry.monotonicTime,
@@ -136,13 +143,13 @@ function buildNetworkLines(entries) {
136
143
  };
137
144
  lines.push(line);
138
145
  if (requestBodyIsLarge && requestBody !== null) {
139
- const requestContentType = entry.requestHeaders.find(header => header.name.toLowerCase() === 'content-type')?.value ?? '';
146
+ const requestContentType = entry.requestHeaders.find((header) => header.name.toLowerCase() === "content-type")?.value ?? "";
140
147
  bodies.push({
141
148
  seq,
142
- direction: 'request',
149
+ direction: "request",
143
150
  url: entry.url,
144
151
  mimeType: requestContentType,
145
- encoding: 'utf8',
152
+ encoding: "utf8",
146
153
  bodySizeBytes: requestBodySizeBytes,
147
154
  body: requestBody,
148
155
  });
@@ -150,10 +157,10 @@ function buildNetworkLines(entries) {
150
157
  if (responseBodyIsLarge && responseBody !== null) {
151
158
  bodies.push({
152
159
  seq,
153
- direction: 'response',
160
+ direction: "response",
154
161
  url: entry.url,
155
162
  mimeType: entry.mimeType,
156
- encoding: 'utf8',
163
+ encoding: "utf8",
157
164
  bodySizeBytes: responseBodySizeBytes,
158
165
  body: responseBody,
159
166
  });
@@ -163,18 +170,27 @@ function buildNetworkLines(entries) {
163
170
  return { lines, bodies, seqByEntry };
164
171
  }
165
172
  async function writeNdjson(filePath, records) {
166
- const content = records.map(r => JSON.stringify(r)).join('\n');
167
- await fs.promises.writeFile(filePath, records.length > 0 ? `${content}\n` : '', 'utf-8');
173
+ const content = records.map((r) => JSON.stringify(r)).join("\n");
174
+ await fs.promises.writeFile(filePath, records.length > 0 ? `${content}\n` : "", "utf-8");
168
175
  }
169
- /** Reads all screencast-frame events (sha1 + monotonic timestamp) across browser trace files. */
176
+ /** Reads all screencast-frame events across browser trace files. */
170
177
  async function readScreencastFrames(ctx) {
171
178
  const files = await fs.promises.readdir(ctx.traceDir);
172
- const traceFiles = files.filter(f => f.endsWith('.trace') && f !== 'test.trace').sort();
179
+ const traceFiles = files
180
+ .filter((f) => f.endsWith(".trace") && f !== "test.trace")
181
+ .sort();
173
182
  const frames = [];
174
183
  for (const traceFile of traceFiles) {
175
184
  for await (const event of (0, parseTrace_1.readNdjson)(path.join(ctx.traceDir, traceFile))) {
176
- if (event.type === 'screencast-frame')
177
- frames.push({ sha1: event.sha1, timestamp: event.timestamp, pageId: event.pageId });
185
+ if (event.type === "screencast-frame") {
186
+ const resourceFile = (0, parseTrace_1.normalizeTraceResourceReference)(event.file, event.sha1);
187
+ if (resourceFile)
188
+ frames.push({
189
+ file: resourceFile,
190
+ timestamp: event.timestamp,
191
+ pageId: event.pageId,
192
+ });
193
+ }
178
194
  }
179
195
  }
180
196
  frames.sort((a, b) => a.timestamp - b.timestamp);
@@ -209,44 +225,48 @@ function nearestFrame(frames, t) {
209
225
  */
210
226
  async function writeTraceDigest(ctx, outputDir, options) {
211
227
  const resolvedOutputDir = path.resolve(outputDir);
212
- const runDir = path.join(resolvedOutputDir, `run-${new Date().toISOString().replace(/[:.]/g, '-')}`);
228
+ const runDir = path.join(resolvedOutputDir, `run-${new Date().toISOString().replace(/[:.]/g, "-")}`);
213
229
  const traceSha1 = path.basename(ctx.traceDir);
214
- const meta = options?.reportMetadata ?? (await (0, parseTrace_1.getReportMetadata)(ctx.reportDataDir ?? path.dirname(ctx.sourcePath ?? ctx.traceDir)));
230
+ const meta = options?.reportMetadata ??
231
+ (await (0, parseTrace_1.getReportMetadata)(ctx.reportDataDir ?? path.dirname(ctx.sourcePath ?? ctx.traceDir)));
215
232
  const reportTraceMaps = meta ? (0, parseTrace_1.buildReportTraceMaps)(meta) : null;
216
233
  const [summary, roots, network, consoleEntries, domActions] = await Promise.all([
217
234
  (0, extractors_1.getSummary)(ctx, { reportMetadata: meta, reportTraceMaps }),
218
235
  (0, extractors_1.getTestSteps)(ctx),
219
236
  (0, extractors_1.getNetworkTraffic)(ctx),
220
237
  (0, extractors_1.getConsoleEntries)(ctx),
221
- (0, extractors_1.getDomSnapshots)(ctx, { phase: 'action' }),
238
+ (0, extractors_1.getDomSnapshots)(ctx, { phase: "action" }),
222
239
  ]);
223
240
  const retryIndex = findRetryIndex(meta, traceSha1);
224
241
  const folderName = `${sanitizeFolderName(summary.testTitle ?? summary.title)}__retry${retryIndex}`;
225
242
  const folderDir = path.join(runDir, folderName);
226
243
  await fs.promises.mkdir(folderDir, { recursive: true });
227
244
  // ---- Network NDJSON (chronological, global seq, large bodies spilled) ----
228
- const { lines: networkLines, bodies: networkBodies, seqByEntry } = buildNetworkLines(network);
229
- await writeNdjson(path.join(folderDir, 'network.ndjson'), networkLines);
245
+ const { lines: networkLines, bodies: networkBodies, seqByEntry, } = buildNetworkLines(network);
246
+ await writeNdjson(path.join(folderDir, "network.ndjson"), networkLines);
230
247
  if (networkBodies.length > 0)
231
- await writeNdjson(path.join(folderDir, 'network-bodies.ndjson'), networkBodies);
248
+ await writeNdjson(path.join(folderDir, "network-bodies.ndjson"), networkBodies);
232
249
  // Pre-index network seq by time for fast per-step window queries. Prefer the
233
250
  // monotonic clock (matches step times in real traces); fall back to wall-clock
234
251
  // when monotonic is unavailable. A wall-clock epoch can never fall inside a
235
252
  // monotonic step window, so the fallback never produces false links.
236
253
  const networkByTime = networkLines
237
- .map(l => ({ seq: l.seq, t: l.monotonicTime ?? Date.parse(l.startedDateTime) }))
238
- .filter(n => Number.isFinite(n.t))
254
+ .map((l) => ({
255
+ seq: l.seq,
256
+ t: l.monotonicTime ?? Date.parse(l.startedDateTime),
257
+ }))
258
+ .filter((n) => Number.isFinite(n.t))
239
259
  .sort((a, b) => a.t - b.t);
240
260
  // ---- Console NDJSON (chronological, not linked) ----
241
261
  const consoleSorted = [...consoleEntries].sort((a, b) => a.timestamp - b.timestamp);
242
- await writeNdjson(path.join(folderDir, 'console.ndjson'), consoleSorted);
243
- const consoleErrors = consoleSorted.filter(e => e.level === 'error');
262
+ await writeNdjson(path.join(folderDir, "console.ndjson"), consoleSorted);
263
+ const consoleErrors = consoleSorted.filter((e) => e.level === "error");
244
264
  // ---- DOM (Action phase) + screenshots, one per leaf action that has input@ ----
245
265
  const flat = [];
246
266
  flattenWithLeaf(roots, flat);
247
267
  // Action-phase DOM snapshot timestamps (browser clock == step clock).
248
268
  const actionSnapshots = domActions
249
- .map(a => a.action)
269
+ .map((a) => a.action)
250
270
  .filter((s) => s !== null)
251
271
  .sort((a, b) => a.timestamp - b.timestamp);
252
272
  // Match each leaf step to the action snapshot whose timestamp is inside its window.
@@ -266,18 +286,21 @@ async function writeTraceDigest(ctx, outputDir, options) {
266
286
  }
267
287
  if (chosen) {
268
288
  usedSnapshots.add(chosen);
269
- domByStepCallId.set(step.callId, { html: chosen.html, timestamp: chosen.timestamp });
289
+ domByStepCallId.set(step.callId, {
290
+ html: chosen.html,
291
+ timestamp: chosen.timestamp,
292
+ });
270
293
  }
271
294
  }
272
295
  // Write DOM html files.
273
296
  const domFileByStepCallId = new Map();
274
297
  if (domByStepCallId.size > 0) {
275
- const domDir = path.join(folderDir, 'dom');
298
+ const domDir = path.join(folderDir, "dom");
276
299
  await fs.promises.mkdir(domDir, { recursive: true });
277
300
  for (const [stepCallId, { html }] of domByStepCallId) {
278
301
  const stem = sanitizeCallId(stepCallId);
279
302
  const rel = `dom/${stem}.html`;
280
- await fs.promises.writeFile(path.join(folderDir, rel), html, 'utf-8');
303
+ await fs.promises.writeFile(path.join(folderDir, rel), html, "utf-8");
281
304
  domFileByStepCallId.set(stepCallId, rel);
282
305
  }
283
306
  }
@@ -287,16 +310,16 @@ async function writeTraceDigest(ctx, outputDir, options) {
287
310
  if (domByStepCallId.size > 0) {
288
311
  const frames = await readScreencastFrames(ctx);
289
312
  if (frames.length > 0) {
290
- const screenshotsDir = path.join(folderDir, 'screenshots');
313
+ const screenshotsDir = path.join(folderDir, "screenshots");
291
314
  await fs.promises.mkdir(screenshotsDir, { recursive: true });
292
315
  for (const [stepCallId, { timestamp }] of domByStepCallId) {
293
316
  const frame = nearestFrame(frames, timestamp);
294
317
  if (!frame)
295
318
  continue;
296
- const buf = await (0, parseTrace_1.getResourceBuffer)(ctx, frame.sha1);
319
+ const buf = await (0, parseTrace_1.getResourceBuffer)(ctx, frame.file);
297
320
  if (!buf)
298
321
  continue;
299
- const ext = frame.sha1.endsWith('.jpeg') ? 'jpeg' : 'png';
322
+ const ext = frame.file.endsWith(".jpeg") ? "jpeg" : "png";
300
323
  const rel = `screenshots/${sanitizeCallId(stepCallId)}.${ext}`;
301
324
  await fs.promises.writeFile(path.join(folderDir, rel), buf);
302
325
  screenshotFileByStepCallId.set(stepCallId, rel);
@@ -308,9 +331,9 @@ async function writeTraceDigest(ctx, outputDir, options) {
308
331
  const end = step.endTime ?? step.startTime;
309
332
  // All network calls whose monotonic time falls in this step's window.
310
333
  const networkSeq = networkByTime
311
- .filter(n => n.t >= step.startTime && n.t <= end)
312
- .map(n => n.seq);
313
- const consoleErrorCount = consoleErrors.filter(e => inStepWindow(step, e.timestamp)).length;
334
+ .filter((n) => n.t >= step.startTime && n.t <= end)
335
+ .map((n) => n.seq);
336
+ const consoleErrorCount = consoleErrors.filter((e) => inStepWindow(step, e.timestamp)).length;
314
337
  // dom/screenshot are only ever populated for leaf actions with an input@ snapshot.
315
338
  const dom = domFileByStepCallId.get(step.callId) ?? null;
316
339
  const screenshot = screenshotFileByStepCallId.get(step.callId) ?? null;
@@ -326,7 +349,9 @@ async function writeTraceDigest(ctx, outputDir, options) {
326
349
  ? {
327
350
  ...step.error,
328
351
  message: stripAnsi(step.error.message),
329
- ...(step.error.stack !== undefined ? { stack: stripAnsi(step.error.stack) } : {}),
352
+ ...(step.error.stack !== undefined
353
+ ? { stack: stripAnsi(step.error.stack) }
354
+ : {}),
330
355
  }
331
356
  : null,
332
357
  artifacts: {
@@ -341,7 +366,7 @@ async function writeTraceDigest(ctx, outputDir, options) {
341
366
  const steps = roots.map(buildNode);
342
367
  const folderJson = {
343
368
  schemaVersion: json_1.CLI_JSON_SCHEMA_VERSION,
344
- command: 'digest',
369
+ command: "digest",
345
370
  testTitle: summary.testTitle,
346
371
  title: summary.title,
347
372
  status: summary.status,
@@ -359,16 +384,16 @@ async function writeTraceDigest(ctx, outputDir, options) {
359
384
  consoleEntries: consoleSorted.length,
360
385
  },
361
386
  files: {
362
- network: 'network.ndjson',
363
- networkBodies: networkBodies.length > 0 ? 'network-bodies.ndjson' : null,
364
- console: 'console.ndjson',
387
+ network: "network.ndjson",
388
+ networkBodies: networkBodies.length > 0 ? "network-bodies.ndjson" : null,
389
+ console: "console.ndjson",
365
390
  },
366
391
  steps,
367
392
  };
368
- await fs.promises.writeFile(path.join(folderDir, 'digest.json'), `${JSON.stringify(folderJson, null, 2)}\n`, 'utf-8');
393
+ await fs.promises.writeFile(path.join(folderDir, "digest.json"), `${JSON.stringify(folderJson, null, 2)}\n`, "utf-8");
369
394
  return {
370
395
  schemaVersion: json_1.CLI_JSON_SCHEMA_VERSION,
371
- command: 'digest',
396
+ command: "digest",
372
397
  outputDir: resolvedOutputDir,
373
398
  runDir,
374
399
  folder: folderName,