playwright-opentelemetry 0.13.6 → 0.15.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.
@@ -1,6 +1,6 @@
1
- import { c as shouldRetainPlaywrightTrace, d as PLAYWRIGHT_TRACE_API_SOURCE_REPORTER, f as buildOtlpRequest, g as withPlaywrightTraceApiHeaders, h as sendSpans, i as TRACE_CONTEXT_ATTACHMENT_NAME, l as filterRetainedDestinations, m as generateTraceId, p as generateSpanId, r as FIXTURE_SPANS_ATTACHMENT_NAME, t as resolvePlaywrightOpentelemetryConfig, u as PLAYWRIGHT_TRACE_API_SOURCE_HEADER } from "./config-CNqq0WLw.mjs";
2
- import path from "node:path";
1
+ import { S as withPlaywrightTraceApiHeaders, _ as PLAYWRIGHT_TRACE_API_SOURCE_REPORTER, a as supportsScreencastScreenshots, b as generateTraceId, c as FIXTURE_SPANS_ATTACHMENT_NAME, g as PLAYWRIGHT_TRACE_API_SOURCE_HEADER, h as filterRetainedDestinations, i as readScreenshotsZip, l as TRACE_CONTEXT_ATTACHMENT_NAME, m as shouldRetainPlaywrightTrace, n as addScreenshotsToZip, o as resolvePlaywrightOpentelemetryConfig, r as createScreenshotsZip, v as buildOtlpRequest, x as sendSpans, y as generateSpanId } from "./screenshots-zip-BzI9Jpan.mjs";
3
2
  import fs from "node:fs/promises";
3
+ import path from "node:path";
4
4
  import { BlobReader, BlobWriter, TextWriter, ZipReader, ZipWriter } from "@zip.js/zip.js";
5
5
  //#region src/reporter/otel-attributes.ts
6
6
  const ATTR_CODE_FILE_PATH = "code.file.path";
@@ -13,20 +13,22 @@ const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
13
13
  const TEST_SPAN_NAME = "playwright.test";
14
14
  const TEST_STEP_SPAN_NAME = "playwright.test.step";
15
15
  const ATTR_TEST_STEP_NAME = "test.step.name";
16
+ /** Playwright's step title, e.g. `Click` or `Expect "toBeVisible"` */
16
17
  const ATTR_TEST_STEP_TITLE = "test.step.title";
18
+ /** What the step acted on, e.g. the locator of a `Click` or the url of a `Navigate` */
19
+ const ATTR_TEST_STEP_SUBTITLE = "test.step.subtitle";
20
+ /** Prefix for the step's reported params, e.g. `test.step.param.locator` */
21
+ const ATTR_TEST_STEP_PARAM_PREFIX = "test.step.param.";
17
22
  const ATTR_TEST_STEP_CATEGORY = "test.step.category";
18
23
  const ATTR_TEST_PHASE = "playwright.test.phase";
19
24
  //#endregion
20
- //#region src/reporter/trace-zip-builder.ts
25
+ //#region src/reporter/legacy/trace-zip-screenshots.ts
21
26
  /**
22
- * Get the zip filename based on test location and ID.
23
- * Format: {basename(file)}:{line}-{testId}-pw-otel.zip
24
- * Fallback: {testId}-pw-otel.zip (if no location info)
27
+ * LEGACY: reads screenshots out of Playwright's trace.zip, for Playwright
28
+ * older than SCREENCAST_SCREENSHOTS_MIN_PLAYWRIGHT_VERSION. Delete this
29
+ * directory, its tests and the reporter's legacy branch once the peer
30
+ * dependency requires that version.
25
31
  */
26
- function getZipFilename(test, testId) {
27
- if (test.location) return `${path.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
28
- return `${testId}-pw-otel.zip`;
29
- }
30
32
  const PLAYWRIGHT_TRACE_RESOURCES_DIR = "resources/";
31
33
  const PLAYWRIGHT_TRACE_SCREENCAST_DIR = "screencast/";
32
34
  /**
@@ -40,6 +42,8 @@ const PLAYWRIGHT_SCREENSHOT_PATTERN = /^.+@[a-f0-9]+-\d+\.jpe?g$/i;
40
42
  * (e.g., page@abc123-1766929201038.jpeg) and live in resources/ for
41
43
  * Playwright <= 1.62 or screencast/ for Playwright >= 1.63.
42
44
  *
45
+ * Never rejects: a trace that can't be read gives no screenshots.
46
+ *
43
47
  * @param traceZipPath - Path to the Playwright trace.zip file
44
48
  * @returns Map of filename (without directory prefix) to screenshot resources
45
49
  */
@@ -74,47 +78,6 @@ async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
74
78
  }
75
79
  return screenshots;
76
80
  }
77
- async function createScreenshotsZip(screenshots) {
78
- const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
79
- await addScreenshotsToZip(zipWriter, screenshots);
80
- return zipWriter.close();
81
- }
82
- async function createTraceZipBlob(options) {
83
- const { spans, fixtureSpans, playwrightVersion, screenshots } = options;
84
- const otlpRequest = buildOtlpRequest(spans, playwrightVersion);
85
- const traceJson = JSON.stringify(otlpRequest, null, 2);
86
- const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
87
- await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
88
- if (fixtureSpans.length > 0) {
89
- const fixtureOtlpRequest = buildOtlpRequest(fixtureSpans, playwrightVersion);
90
- await zipWriter.add("traces/playwright-fixture-spans.json", new Blob([JSON.stringify(fixtureOtlpRequest, null, 2)]).stream());
91
- }
92
- await addScreenshotsToZip(zipWriter, screenshots);
93
- return zipWriter.close();
94
- }
95
- async function writeTraceZip(outputDir, test, zipBlob) {
96
- const zipFilename = getZipFilename(test, test.id);
97
- const zipPath = path.join(outputDir, zipFilename);
98
- const arrayBuffer = await zipBlob.arrayBuffer();
99
- await fs.writeFile(zipPath, Buffer.from(arrayBuffer));
100
- }
101
- async function addScreenshotsToZip(zipWriter, screenshots) {
102
- const manifest = createScreenshotManifest(screenshots);
103
- await zipWriter.add("manifest.json", new Blob([JSON.stringify(manifest, null, 2)], { type: "application/json" }).stream());
104
- for (const [filename, screenshot] of screenshots.entries()) await zipWriter.add(`screenshots/${filename}`, screenshot.blob.stream());
105
- }
106
- function createScreenshotManifest(screenshots) {
107
- return {
108
- version: 3,
109
- screenshots: Array.from(screenshots.values()).map((screenshot) => ({
110
- timestamp: screenshot.timestamp,
111
- file: screenshot.file,
112
- path: `screenshots/${screenshot.file}`,
113
- contentType: screenshot.contentType,
114
- pageId: screenshot.pageId
115
- })).sort((a, b) => a.timestamp - b.timestamp)
116
- };
117
- }
118
81
  /**
119
82
  * Map screencast frame zip paths to the page that produced them.
120
83
  * Playwright <= 1.62 (trace v8) references frames via `sha1` relative to
@@ -178,6 +141,36 @@ function screenshotResourceName(filename) {
178
141
  return PLAYWRIGHT_SCREENSHOT_PATTERN.test(name) ? name : null;
179
142
  }
180
143
  //#endregion
144
+ //#region src/reporter/trace-zip-builder.ts
145
+ /**
146
+ * Get the zip filename based on test location and ID.
147
+ * Format: {basename(file)}:{line}-{testId}-pw-otel.zip
148
+ * Fallback: {testId}-pw-otel.zip (if no location info)
149
+ */
150
+ function getZipFilename(test, testId) {
151
+ if (test.location) return `${path.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
152
+ return `${testId}-pw-otel.zip`;
153
+ }
154
+ async function createTraceZipBlob(options) {
155
+ const { spans, fixtureSpans, playwrightVersion, screenshots } = options;
156
+ const otlpRequest = buildOtlpRequest(spans, playwrightVersion);
157
+ const traceJson = JSON.stringify(otlpRequest, null, 2);
158
+ const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
159
+ await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
160
+ if (fixtureSpans.length > 0) {
161
+ const fixtureOtlpRequest = buildOtlpRequest(fixtureSpans, playwrightVersion);
162
+ await zipWriter.add("traces/playwright-fixture-spans.json", new Blob([JSON.stringify(fixtureOtlpRequest, null, 2)]).stream());
163
+ }
164
+ await addScreenshotsToZip(zipWriter, screenshots);
165
+ return zipWriter.close();
166
+ }
167
+ async function writeTraceZip(outputDir, test, zipBlob) {
168
+ const zipFilename = getZipFilename(test, test.id);
169
+ const zipPath = path.join(outputDir, zipFilename);
170
+ const arrayBuffer = await zipBlob.arrayBuffer();
171
+ await fs.writeFile(zipPath, Buffer.from(arrayBuffer));
172
+ }
173
+ //#endregion
181
174
  //#region src/reporter/reporter.ts
182
175
  var PlaywrightOpentelemetryReporter = class {
183
176
  spanBatches = [];
@@ -236,10 +229,8 @@ var PlaywrightOpentelemetryReporter = class {
236
229
  attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
237
230
  attributes[ATTR_CODE_LINE_NUMBER] = line;
238
231
  }
239
- const processedSteps = /* @__PURE__ */ new Map();
240
- const skippedStepIds = /* @__PURE__ */ new Set();
241
- if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps, skippedStepIds);
242
- const stepSpans = Array.from(processedSteps.values());
232
+ const stepSpans = [];
233
+ for (const step of result.steps ?? []) this.processTestStep(step, testSpanId, traceId, [], stepSpans);
243
234
  let minStartTime = result.startTime;
244
235
  let maxEndTime = new Date(result.startTime.getTime() + result.duration);
245
236
  for (const stepSpan of stepSpans) {
@@ -265,6 +256,7 @@ var PlaywrightOpentelemetryReporter = class {
265
256
  test,
266
257
  spans: testSpans,
267
258
  fixtureSpans,
259
+ screenshotsAttachmentPath: result.attachments.find((attachment) => attachment.name === "playwright-opentelemetry-screenshots" && attachment.path)?.path,
268
260
  traceAttachmentPath: traceAttachment?.path,
269
261
  traceId,
270
262
  config: retainedConfig,
@@ -307,7 +299,7 @@ var PlaywrightOpentelemetryReporter = class {
307
299
  for (const destination of destinations.values()) await sendSpans(destination.spans, destination.options);
308
300
  }
309
301
  async prepareTraceArtifact(options) {
310
- const screenshots = options.traceAttachmentPath ? await extractScreenshotsFromPlaywrightTrace(options.traceAttachmentPath) : /* @__PURE__ */ new Map();
302
+ const screenshots = await readTestScreenshots(options);
311
303
  const traceZipBlobPromise = options.config.storeTraceZip ? createTraceZipBlob({
312
304
  test: options.test,
313
305
  spans: options.spans,
@@ -315,47 +307,34 @@ var PlaywrightOpentelemetryReporter = class {
315
307
  playwrightVersion: options.playwrightVersion,
316
308
  screenshots
317
309
  }) : void 0;
318
- const uploadPromises = options.config.playwrightTraceApiDestinations.filter((destination) => destination.url).map((destination) => this.sendScreenshotsZipToTraceApi({
310
+ const screenshotsZip = screenshots.length > 0 ? await createScreenshotsZip(screenshots) : null;
311
+ const uploadPromises = screenshotsZip ? options.config.playwrightTraceApiDestinations.filter((destination) => destination.url).map((destination) => this.sendScreenshotsZipToTraceApi({
319
312
  traceId: options.traceId,
320
- screenshots,
313
+ screenshotsZip,
321
314
  destination
322
- }));
315
+ })) : [];
323
316
  const [traceZipBlob] = await Promise.all([traceZipBlobPromise, ...uploadPromises]);
324
317
  return { traceZipBlob };
325
318
  }
326
- processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds, inheritedPhase) {
319
+ processTestStep(step, parentSpanId, traceId, parentTitlePath, stepSpans, inheritedPhase) {
327
320
  let phase = inheritedPhase;
328
321
  if (step.category === "hook") {
329
322
  if (step.title === "Before Hooks") phase = "before";
330
323
  if (step.title === "After Hooks" || step.title === "Worker Cleanup") phase = "after";
331
324
  }
332
- const stepId = getStepId(test, step);
333
325
  if (isInternalFixtureStep(step) || isInternalApiRequestStep(step)) {
334
- skippedStepIds.add(stepId);
335
- processedSteps.delete(stepId);
336
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds, phase);
337
- return;
338
- }
339
- if (skippedStepIds.has(stepId)) {
340
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds, phase);
326
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, parentSpanId, traceId, parentTitlePath, stepSpans, phase);
341
327
  return;
342
328
  }
343
329
  const currentTitlePath = [...parentTitlePath, step.title];
344
- const existingSpan = processedSteps.get(stepId);
345
- if (existingSpan) {
346
- if (step.error) existingSpan.status = errorStatus(step.error.message);
347
- if (step.location && !existingSpan.attributes["code.file.path"]) {
348
- const { file, line } = step.location;
349
- const relativePath = this.rootDir ? path.relative(this.rootDir, file) : file;
350
- existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
351
- existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
352
- }
353
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps, skippedStepIds, phase);
354
- return;
355
- }
356
330
  const attributes = {};
357
331
  attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
358
332
  attributes[ATTR_TEST_STEP_TITLE] = step.title;
333
+ if (step.subtitle) attributes[ATTR_TEST_STEP_SUBTITLE] = step.subtitle;
334
+ for (const [key, value] of Object.entries(step.params ?? {})) {
335
+ const attributeValue = toStepParamAttribute(value);
336
+ if (attributeValue !== void 0) attributes[`${ATTR_TEST_STEP_PARAM_PREFIX}${key}`] = attributeValue;
337
+ }
359
338
  attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
360
339
  if (phase) attributes[ATTR_TEST_PHASE] = phase;
361
340
  if (step.location) {
@@ -373,8 +352,8 @@ var PlaywrightOpentelemetryReporter = class {
373
352
  attributes
374
353
  };
375
354
  if (step.error) stepSpan.status = errorStatus(step.error.message);
376
- processedSteps.set(stepId, stepSpan);
377
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps, skippedStepIds, phase);
355
+ stepSpans.push(stepSpan);
356
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, stepSpan.spanId, traceId, currentTitlePath, stepSpans, phase);
378
357
  }
379
358
  onStdOut(chunk, _test, _result) {
380
359
  if (this.debug) console.log(chunk.toString().slice(0, -1));
@@ -386,8 +365,7 @@ var PlaywrightOpentelemetryReporter = class {
386
365
  return this.debug;
387
366
  }
388
367
  async sendScreenshotsZipToTraceApi(params) {
389
- const { traceId, screenshots, destination } = params;
390
- const screenshotsZip = await createScreenshotsZip(screenshots);
368
+ const { traceId, screenshotsZip, destination } = params;
391
369
  const screenshotUrl = `${destination.url}/playwright-otel-reporter/v1/screenshots.zip`;
392
370
  const response = await fetch(screenshotUrl, {
393
371
  method: "PUT",
@@ -405,6 +383,26 @@ var PlaywrightOpentelemetryReporter = class {
405
383
  }
406
384
  }
407
385
  };
386
+ /**
387
+ * A test's screenshots. Playwright versions with a usable screencast only use
388
+ * the frames the fixture captured and attached; older versions only use
389
+ * Playwright's trace. Never rejects: a test's spans are still sent without
390
+ * its screenshots.
391
+ */
392
+ async function readTestScreenshots(options) {
393
+ if (!options.config.screenshots) return [];
394
+ if (supportsScreencastScreenshots(options.playwrightVersion)) {
395
+ if (!options.screenshotsAttachmentPath) return [];
396
+ try {
397
+ return await readScreenshotsZip(new Blob([await fs.readFile(options.screenshotsAttachmentPath)]));
398
+ } catch (error) {
399
+ console.warn(`Failed to read the test's screenshots: ${error instanceof Error ? error.message : String(error)}`);
400
+ return [];
401
+ }
402
+ }
403
+ if (!options.traceAttachmentPath) return [];
404
+ return Array.from((await extractScreenshotsFromPlaywrightTrace(options.traceAttachmentPath)).values());
405
+ }
408
406
  function getProjectPlaywrightOpentelemetryConfig(project) {
409
407
  return project?.use?.playwrightOpentelemetry;
410
408
  }
@@ -514,10 +512,26 @@ function isInternalFixtureStep(step) {
514
512
  }
515
513
  function isInternalApiRequestStep(step) {
516
514
  if (step.category !== "pw:api" || !step.location?.file) return false;
517
- return isApiRequestStepTitle(step.title) && isInternalFixtureFile(step.location.file);
515
+ return isApiRequestStep(step) && isInternalFixtureFile(step.location.file);
516
+ }
517
+ /**
518
+ * `APIRequestContext` calls. From Playwright 1.63 they report a url and a
519
+ * method; before that they show up only in the title, e.g. `GET "/api"`.
520
+ */
521
+ function isApiRequestStep(step) {
522
+ if (step.params) return typeof step.params.url === "string" && typeof step.params.method === "string";
523
+ return /^(?:DELETE|FETCH|GET|HEAD|PATCH|POST|PUT)\s+"/.test(step.title);
518
524
  }
519
- function isApiRequestStepTitle(title) {
520
- return /^(?:DELETE|FETCH|GET|HEAD|PATCH|POST|PUT)\s+"/.test(title);
525
+ /**
526
+ * Span attributes hold primitives and string arrays, so other param values
527
+ * (options objects, mixed arrays) are stored as JSON.
528
+ */
529
+ function toStepParamAttribute(value) {
530
+ if (value === void 0 || value === null) return void 0;
531
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
532
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
533
+ const json = JSON.stringify(value);
534
+ return json === void 0 || json === "{}" ? void 0 : json;
521
535
  }
522
536
  function isInternalFixtureFile(filePath) {
523
537
  const file = filePath.replace(/\\/g, "/");
@@ -546,14 +560,5 @@ function isRecord(value) {
546
560
  function isTraceContextAttachment(value) {
547
561
  return typeof value === "object" && value !== null && "traceId" in value && "rootSpanId" in value && typeof value.traceId === "string" && typeof value.rootSpanId === "string";
548
562
  }
549
- function getStepId(test, step) {
550
- const startTimeMs = step.startTime.getTime();
551
- return [
552
- test.id,
553
- step.category,
554
- startTimeMs,
555
- ...step.titlePath()
556
- ].join(" > ");
557
- }
558
563
  //#endregion
559
564
  export { PlaywrightOpentelemetryReporter as t };