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,8 +1,8 @@
1
- const require_config = require("./config-knifnJua.cjs");
2
- let node_path = require("node:path");
3
- node_path = require_config.__toESM(node_path, 1);
1
+ const require_screenshots_zip = require("./screenshots-zip-C3N3xvp7.cjs");
4
2
  let node_fs_promises = require("node:fs/promises");
5
- node_fs_promises = require_config.__toESM(node_fs_promises, 1);
3
+ node_fs_promises = require_screenshots_zip.__toESM(node_fs_promises, 1);
4
+ let node_path = require("node:path");
5
+ node_path = require_screenshots_zip.__toESM(node_path, 1);
6
6
  let _zip_js_zip_js = require("@zip.js/zip.js");
7
7
  //#region src/reporter/otel-attributes.ts
8
8
  const ATTR_CODE_FILE_PATH = "code.file.path";
@@ -15,20 +15,22 @@ const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
15
15
  const TEST_SPAN_NAME = "playwright.test";
16
16
  const TEST_STEP_SPAN_NAME = "playwright.test.step";
17
17
  const ATTR_TEST_STEP_NAME = "test.step.name";
18
+ /** Playwright's step title, e.g. `Click` or `Expect "toBeVisible"` */
18
19
  const ATTR_TEST_STEP_TITLE = "test.step.title";
20
+ /** What the step acted on, e.g. the locator of a `Click` or the url of a `Navigate` */
21
+ const ATTR_TEST_STEP_SUBTITLE = "test.step.subtitle";
22
+ /** Prefix for the step's reported params, e.g. `test.step.param.locator` */
23
+ const ATTR_TEST_STEP_PARAM_PREFIX = "test.step.param.";
19
24
  const ATTR_TEST_STEP_CATEGORY = "test.step.category";
20
25
  const ATTR_TEST_PHASE = "playwright.test.phase";
21
26
  //#endregion
22
- //#region src/reporter/trace-zip-builder.ts
27
+ //#region src/reporter/legacy/trace-zip-screenshots.ts
23
28
  /**
24
- * Get the zip filename based on test location and ID.
25
- * Format: {basename(file)}:{line}-{testId}-pw-otel.zip
26
- * Fallback: {testId}-pw-otel.zip (if no location info)
29
+ * LEGACY: reads screenshots out of Playwright's trace.zip, for Playwright
30
+ * older than SCREENCAST_SCREENSHOTS_MIN_PLAYWRIGHT_VERSION. Delete this
31
+ * directory, its tests and the reporter's legacy branch once the peer
32
+ * dependency requires that version.
27
33
  */
28
- function getZipFilename(test, testId) {
29
- if (test.location) return `${node_path.default.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
30
- return `${testId}-pw-otel.zip`;
31
- }
32
34
  const PLAYWRIGHT_TRACE_RESOURCES_DIR = "resources/";
33
35
  const PLAYWRIGHT_TRACE_SCREENCAST_DIR = "screencast/";
34
36
  /**
@@ -42,6 +44,8 @@ const PLAYWRIGHT_SCREENSHOT_PATTERN = /^.+@[a-f0-9]+-\d+\.jpe?g$/i;
42
44
  * (e.g., page@abc123-1766929201038.jpeg) and live in resources/ for
43
45
  * Playwright <= 1.62 or screencast/ for Playwright >= 1.63.
44
46
  *
47
+ * Never rejects: a trace that can't be read gives no screenshots.
48
+ *
45
49
  * @param traceZipPath - Path to the Playwright trace.zip file
46
50
  * @returns Map of filename (without directory prefix) to screenshot resources
47
51
  */
@@ -76,47 +80,6 @@ async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
76
80
  }
77
81
  return screenshots;
78
82
  }
79
- async function createScreenshotsZip(screenshots) {
80
- const zipWriter = new _zip_js_zip_js.ZipWriter(new _zip_js_zip_js.BlobWriter("application/zip"));
81
- await addScreenshotsToZip(zipWriter, screenshots);
82
- return zipWriter.close();
83
- }
84
- async function createTraceZipBlob(options) {
85
- const { spans, fixtureSpans, playwrightVersion, screenshots } = options;
86
- const otlpRequest = require_config.buildOtlpRequest(spans, playwrightVersion);
87
- const traceJson = JSON.stringify(otlpRequest, null, 2);
88
- const zipWriter = new _zip_js_zip_js.ZipWriter(new _zip_js_zip_js.BlobWriter("application/zip"));
89
- await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
90
- if (fixtureSpans.length > 0) {
91
- const fixtureOtlpRequest = require_config.buildOtlpRequest(fixtureSpans, playwrightVersion);
92
- await zipWriter.add("traces/playwright-fixture-spans.json", new Blob([JSON.stringify(fixtureOtlpRequest, null, 2)]).stream());
93
- }
94
- await addScreenshotsToZip(zipWriter, screenshots);
95
- return zipWriter.close();
96
- }
97
- async function writeTraceZip(outputDir, test, zipBlob) {
98
- const zipFilename = getZipFilename(test, test.id);
99
- const zipPath = node_path.default.join(outputDir, zipFilename);
100
- const arrayBuffer = await zipBlob.arrayBuffer();
101
- await node_fs_promises.default.writeFile(zipPath, Buffer.from(arrayBuffer));
102
- }
103
- async function addScreenshotsToZip(zipWriter, screenshots) {
104
- const manifest = createScreenshotManifest(screenshots);
105
- await zipWriter.add("manifest.json", new Blob([JSON.stringify(manifest, null, 2)], { type: "application/json" }).stream());
106
- for (const [filename, screenshot] of screenshots.entries()) await zipWriter.add(`screenshots/${filename}`, screenshot.blob.stream());
107
- }
108
- function createScreenshotManifest(screenshots) {
109
- return {
110
- version: 3,
111
- screenshots: Array.from(screenshots.values()).map((screenshot) => ({
112
- timestamp: screenshot.timestamp,
113
- file: screenshot.file,
114
- path: `screenshots/${screenshot.file}`,
115
- contentType: screenshot.contentType,
116
- pageId: screenshot.pageId
117
- })).sort((a, b) => a.timestamp - b.timestamp)
118
- };
119
- }
120
83
  /**
121
84
  * Map screencast frame zip paths to the page that produced them.
122
85
  * Playwright <= 1.62 (trace v8) references frames via `sha1` relative to
@@ -180,6 +143,36 @@ function screenshotResourceName(filename) {
180
143
  return PLAYWRIGHT_SCREENSHOT_PATTERN.test(name) ? name : null;
181
144
  }
182
145
  //#endregion
146
+ //#region src/reporter/trace-zip-builder.ts
147
+ /**
148
+ * Get the zip filename based on test location and ID.
149
+ * Format: {basename(file)}:{line}-{testId}-pw-otel.zip
150
+ * Fallback: {testId}-pw-otel.zip (if no location info)
151
+ */
152
+ function getZipFilename(test, testId) {
153
+ if (test.location) return `${node_path.default.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
154
+ return `${testId}-pw-otel.zip`;
155
+ }
156
+ async function createTraceZipBlob(options) {
157
+ const { spans, fixtureSpans, playwrightVersion, screenshots } = options;
158
+ const otlpRequest = require_screenshots_zip.buildOtlpRequest(spans, playwrightVersion);
159
+ const traceJson = JSON.stringify(otlpRequest, null, 2);
160
+ const zipWriter = new _zip_js_zip_js.ZipWriter(new _zip_js_zip_js.BlobWriter("application/zip"));
161
+ await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
162
+ if (fixtureSpans.length > 0) {
163
+ const fixtureOtlpRequest = require_screenshots_zip.buildOtlpRequest(fixtureSpans, playwrightVersion);
164
+ await zipWriter.add("traces/playwright-fixture-spans.json", new Blob([JSON.stringify(fixtureOtlpRequest, null, 2)]).stream());
165
+ }
166
+ await require_screenshots_zip.addScreenshotsToZip(zipWriter, screenshots);
167
+ return zipWriter.close();
168
+ }
169
+ async function writeTraceZip(outputDir, test, zipBlob) {
170
+ const zipFilename = getZipFilename(test, test.id);
171
+ const zipPath = node_path.default.join(outputDir, zipFilename);
172
+ const arrayBuffer = await zipBlob.arrayBuffer();
173
+ await node_fs_promises.default.writeFile(zipPath, Buffer.from(arrayBuffer));
174
+ }
175
+ //#endregion
183
176
  //#region src/reporter/reporter.ts
184
177
  var PlaywrightOpentelemetryReporter = class {
185
178
  spanBatches = [];
@@ -193,7 +186,7 @@ var PlaywrightOpentelemetryReporter = class {
193
186
  this.playwrightVersion = config.version;
194
187
  const projects = Array.isArray(config.projects) ? config.projects : [];
195
188
  for (const project of projects) {
196
- const resolvedConfig = require_config.resolvePlaywrightOpentelemetryConfig(getProjectPlaywrightOpentelemetryConfig(project), { requireDestination: true });
189
+ const resolvedConfig = require_screenshots_zip.resolvePlaywrightOpentelemetryConfig(getProjectPlaywrightOpentelemetryConfig(project), { requireDestination: true });
197
190
  this.debug ||= resolvedConfig.debug;
198
191
  }
199
192
  }
@@ -208,12 +201,12 @@ var PlaywrightOpentelemetryReporter = class {
208
201
  retry: result.retry,
209
202
  status: result.status
210
203
  };
211
- const shouldRetainTrace = (trace) => trace === null ? Boolean(traceAttachment) : require_config.shouldRetainPlaywrightTrace(trace, traceRetentionTestInfo);
204
+ const shouldRetainTrace = (trace) => trace === null ? Boolean(traceAttachment) : require_screenshots_zip.shouldRetainPlaywrightTrace(trace, traceRetentionTestInfo);
212
205
  const shouldStoreTraceZip = config.storeTraceZip && shouldRetainTrace(config.trace);
213
206
  const retainedConfig = {
214
207
  ...config,
215
- otlpDestinations: require_config.filterRetainedDestinations(config.otlpDestinations, config.trace, shouldRetainTrace),
216
- playwrightTraceApiDestinations: require_config.filterRetainedDestinations(config.playwrightTraceApiDestinations, config.trace, shouldRetainTrace),
208
+ otlpDestinations: require_screenshots_zip.filterRetainedDestinations(config.otlpDestinations, config.trace, shouldRetainTrace),
209
+ playwrightTraceApiDestinations: require_screenshots_zip.filterRetainedDestinations(config.playwrightTraceApiDestinations, config.trace, shouldRetainTrace),
217
210
  storeTraceZip: shouldStoreTraceZip
218
211
  };
219
212
  if (!hasPlaywrightOpentelemetryDestination(retainedConfig)) return;
@@ -238,10 +231,8 @@ var PlaywrightOpentelemetryReporter = class {
238
231
  attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
239
232
  attributes[ATTR_CODE_LINE_NUMBER] = line;
240
233
  }
241
- const processedSteps = /* @__PURE__ */ new Map();
242
- const skippedStepIds = /* @__PURE__ */ new Set();
243
- if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps, skippedStepIds);
244
- const stepSpans = Array.from(processedSteps.values());
234
+ const stepSpans = [];
235
+ for (const step of result.steps ?? []) this.processTestStep(step, testSpanId, traceId, [], stepSpans);
245
236
  let minStartTime = result.startTime;
246
237
  let maxEndTime = new Date(result.startTime.getTime() + result.duration);
247
238
  for (const stepSpan of stepSpans) {
@@ -267,6 +258,7 @@ var PlaywrightOpentelemetryReporter = class {
267
258
  test,
268
259
  spans: testSpans,
269
260
  fixtureSpans,
261
+ screenshotsAttachmentPath: result.attachments.find((attachment) => attachment.name === "playwright-opentelemetry-screenshots" && attachment.path)?.path,
270
262
  traceAttachmentPath: traceAttachment?.path,
271
263
  traceId,
272
264
  config: retainedConfig,
@@ -300,16 +292,16 @@ var PlaywrightOpentelemetryReporter = class {
300
292
  if (!destination.url) continue;
301
293
  addDestinationSpans(destinations, batch.spans, {
302
294
  tracesEndpoint: `${destination.url}/v1/traces`,
303
- headers: require_config.withPlaywrightTraceApiHeaders(destination.headers),
295
+ headers: require_screenshots_zip.withPlaywrightTraceApiHeaders(destination.headers),
304
296
  playwrightVersion: this.playwrightVersion || "unknown",
305
297
  debug: batch.config.debug
306
298
  });
307
299
  }
308
300
  }
309
- for (const destination of destinations.values()) await require_config.sendSpans(destination.spans, destination.options);
301
+ for (const destination of destinations.values()) await require_screenshots_zip.sendSpans(destination.spans, destination.options);
310
302
  }
311
303
  async prepareTraceArtifact(options) {
312
- const screenshots = options.traceAttachmentPath ? await extractScreenshotsFromPlaywrightTrace(options.traceAttachmentPath) : /* @__PURE__ */ new Map();
304
+ const screenshots = await readTestScreenshots(options);
313
305
  const traceZipBlobPromise = options.config.storeTraceZip ? createTraceZipBlob({
314
306
  test: options.test,
315
307
  spans: options.spans,
@@ -317,47 +309,34 @@ var PlaywrightOpentelemetryReporter = class {
317
309
  playwrightVersion: options.playwrightVersion,
318
310
  screenshots
319
311
  }) : void 0;
320
- const uploadPromises = options.config.playwrightTraceApiDestinations.filter((destination) => destination.url).map((destination) => this.sendScreenshotsZipToTraceApi({
312
+ const screenshotsZip = screenshots.length > 0 ? await require_screenshots_zip.createScreenshotsZip(screenshots) : null;
313
+ const uploadPromises = screenshotsZip ? options.config.playwrightTraceApiDestinations.filter((destination) => destination.url).map((destination) => this.sendScreenshotsZipToTraceApi({
321
314
  traceId: options.traceId,
322
- screenshots,
315
+ screenshotsZip,
323
316
  destination
324
- }));
317
+ })) : [];
325
318
  const [traceZipBlob] = await Promise.all([traceZipBlobPromise, ...uploadPromises]);
326
319
  return { traceZipBlob };
327
320
  }
328
- processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds, inheritedPhase) {
321
+ processTestStep(step, parentSpanId, traceId, parentTitlePath, stepSpans, inheritedPhase) {
329
322
  let phase = inheritedPhase;
330
323
  if (step.category === "hook") {
331
324
  if (step.title === "Before Hooks") phase = "before";
332
325
  if (step.title === "After Hooks" || step.title === "Worker Cleanup") phase = "after";
333
326
  }
334
- const stepId = getStepId(test, step);
335
327
  if (isInternalFixtureStep(step) || isInternalApiRequestStep(step)) {
336
- skippedStepIds.add(stepId);
337
- processedSteps.delete(stepId);
338
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds, phase);
339
- return;
340
- }
341
- if (skippedStepIds.has(stepId)) {
342
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds, phase);
328
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, parentSpanId, traceId, parentTitlePath, stepSpans, phase);
343
329
  return;
344
330
  }
345
331
  const currentTitlePath = [...parentTitlePath, step.title];
346
- const existingSpan = processedSteps.get(stepId);
347
- if (existingSpan) {
348
- if (step.error) existingSpan.status = errorStatus(step.error.message);
349
- if (step.location && !existingSpan.attributes["code.file.path"]) {
350
- const { file, line } = step.location;
351
- const relativePath = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
352
- existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
353
- existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
354
- }
355
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps, skippedStepIds, phase);
356
- return;
357
- }
358
332
  const attributes = {};
359
333
  attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
360
334
  attributes[ATTR_TEST_STEP_TITLE] = step.title;
335
+ if (step.subtitle) attributes[ATTR_TEST_STEP_SUBTITLE] = step.subtitle;
336
+ for (const [key, value] of Object.entries(step.params ?? {})) {
337
+ const attributeValue = toStepParamAttribute(value);
338
+ if (attributeValue !== void 0) attributes[`${ATTR_TEST_STEP_PARAM_PREFIX}${key}`] = attributeValue;
339
+ }
361
340
  attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
362
341
  if (phase) attributes[ATTR_TEST_PHASE] = phase;
363
342
  if (step.location) {
@@ -367,7 +346,7 @@ var PlaywrightOpentelemetryReporter = class {
367
346
  }
368
347
  const stepSpan = {
369
348
  traceId,
370
- spanId: require_config.generateSpanId(),
349
+ spanId: require_screenshots_zip.generateSpanId(),
371
350
  parentSpanId,
372
351
  name: TEST_STEP_SPAN_NAME,
373
352
  startTime: step.startTime,
@@ -375,8 +354,8 @@ var PlaywrightOpentelemetryReporter = class {
375
354
  attributes
376
355
  };
377
356
  if (step.error) stepSpan.status = errorStatus(step.error.message);
378
- processedSteps.set(stepId, stepSpan);
379
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps, skippedStepIds, phase);
357
+ stepSpans.push(stepSpan);
358
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, stepSpan.spanId, traceId, currentTitlePath, stepSpans, phase);
380
359
  }
381
360
  onStdOut(chunk, _test, _result) {
382
361
  if (this.debug) console.log(chunk.toString().slice(0, -1));
@@ -388,8 +367,7 @@ var PlaywrightOpentelemetryReporter = class {
388
367
  return this.debug;
389
368
  }
390
369
  async sendScreenshotsZipToTraceApi(params) {
391
- const { traceId, screenshots, destination } = params;
392
- const screenshotsZip = await createScreenshotsZip(screenshots);
370
+ const { traceId, screenshotsZip, destination } = params;
393
371
  const screenshotUrl = `${destination.url}/playwright-otel-reporter/v1/screenshots.zip`;
394
372
  const response = await fetch(screenshotUrl, {
395
373
  method: "PUT",
@@ -397,7 +375,7 @@ var PlaywrightOpentelemetryReporter = class {
397
375
  "content-type": "application/zip",
398
376
  "x-trace-id": traceId,
399
377
  ...destination.headers,
400
- [require_config.PLAYWRIGHT_TRACE_API_SOURCE_HEADER]: require_config.PLAYWRIGHT_TRACE_API_SOURCE_REPORTER
378
+ [require_screenshots_zip.PLAYWRIGHT_TRACE_API_SOURCE_HEADER]: require_screenshots_zip.PLAYWRIGHT_TRACE_API_SOURCE_REPORTER
401
379
  },
402
380
  body: screenshotsZip
403
381
  });
@@ -407,11 +385,31 @@ var PlaywrightOpentelemetryReporter = class {
407
385
  }
408
386
  }
409
387
  };
388
+ /**
389
+ * A test's screenshots. Playwright versions with a usable screencast only use
390
+ * the frames the fixture captured and attached; older versions only use
391
+ * Playwright's trace. Never rejects: a test's spans are still sent without
392
+ * its screenshots.
393
+ */
394
+ async function readTestScreenshots(options) {
395
+ if (!options.config.screenshots) return [];
396
+ if (require_screenshots_zip.supportsScreencastScreenshots(options.playwrightVersion)) {
397
+ if (!options.screenshotsAttachmentPath) return [];
398
+ try {
399
+ return await require_screenshots_zip.readScreenshotsZip(new Blob([await node_fs_promises.default.readFile(options.screenshotsAttachmentPath)]));
400
+ } catch (error) {
401
+ console.warn(`Failed to read the test's screenshots: ${error instanceof Error ? error.message : String(error)}`);
402
+ return [];
403
+ }
404
+ }
405
+ if (!options.traceAttachmentPath) return [];
406
+ return Array.from((await extractScreenshotsFromPlaywrightTrace(options.traceAttachmentPath)).values());
407
+ }
410
408
  function getProjectPlaywrightOpentelemetryConfig(project) {
411
409
  return project?.use?.playwrightOpentelemetry;
412
410
  }
413
411
  function getTestConfig(test) {
414
- return require_config.resolvePlaywrightOpentelemetryConfig(getProjectPlaywrightOpentelemetryConfig(test.parent.project()), { requireDestination: true });
412
+ return require_screenshots_zip.resolvePlaywrightOpentelemetryConfig(getProjectPlaywrightOpentelemetryConfig(test.parent.project()), { requireDestination: true });
415
413
  }
416
414
  function getTestOutputDir(test) {
417
415
  const outputDir = test.parent.project()?.outputDir;
@@ -437,30 +435,30 @@ function hasPlaywrightOpentelemetryDestination(config) {
437
435
  return Boolean(config.storeTraceZip || config.otlpDestinations.some((destination) => destination.url) || config.playwrightTraceApiDestinations.some((destination) => destination.url));
438
436
  }
439
437
  function readTraceContextAttachment(result, testId) {
440
- const attachment = result.attachments.find((attachment) => attachment.name === require_config.TRACE_CONTEXT_ATTACHMENT_NAME);
438
+ const attachment = result.attachments.find((attachment) => attachment.name === require_screenshots_zip.TRACE_CONTEXT_ATTACHMENT_NAME);
441
439
  if (!attachment?.body) return {
442
- traceId: require_config.generateTraceId(),
443
- rootSpanId: require_config.generateSpanId()
440
+ traceId: require_screenshots_zip.generateTraceId(),
441
+ rootSpanId: require_screenshots_zip.generateSpanId()
444
442
  };
445
443
  let parsed;
446
444
  try {
447
445
  parsed = JSON.parse(attachment.body.toString("utf-8"));
448
446
  } catch (error) {
449
- throw new Error(`Invalid ${require_config.TRACE_CONTEXT_ATTACHMENT_NAME} attachment for test ${testId}: ${error}`);
447
+ throw new Error(`Invalid ${require_screenshots_zip.TRACE_CONTEXT_ATTACHMENT_NAME} attachment for test ${testId}: ${error}`);
450
448
  }
451
- if (!isTraceContextAttachment(parsed)) throw new Error(`Invalid ${require_config.TRACE_CONTEXT_ATTACHMENT_NAME} attachment for test ${testId}: expected { traceId, rootSpanId }`);
449
+ if (!isTraceContextAttachment(parsed)) throw new Error(`Invalid ${require_screenshots_zip.TRACE_CONTEXT_ATTACHMENT_NAME} attachment for test ${testId}: expected { traceId, rootSpanId }`);
452
450
  return parsed;
453
451
  }
454
452
  function readFixtureSpansAttachment(result, testId) {
455
- const attachment = result.attachments.find((attachment) => attachment.name === require_config.FIXTURE_SPANS_ATTACHMENT_NAME);
453
+ const attachment = result.attachments.find((attachment) => attachment.name === require_screenshots_zip.FIXTURE_SPANS_ATTACHMENT_NAME);
456
454
  if (!attachment?.body) return [];
457
455
  let parsed;
458
456
  try {
459
457
  parsed = JSON.parse(attachment.body.toString("utf-8"));
460
458
  } catch (error) {
461
- throw new Error(`Invalid ${require_config.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: ${error}`);
459
+ throw new Error(`Invalid ${require_screenshots_zip.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: ${error}`);
462
460
  }
463
- if (!isRecord(parsed) || !Array.isArray(parsed.spans)) throw new Error(`Invalid ${require_config.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: expected { spans }`);
461
+ if (!isRecord(parsed) || !Array.isArray(parsed.spans)) throw new Error(`Invalid ${require_screenshots_zip.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: expected { spans }`);
464
462
  return parsed.spans.map((span, index) => parseFixtureSpan(span, testId, index));
465
463
  }
466
464
  function parseFixtureSpan(value, testId, index) {
@@ -487,7 +485,7 @@ function parseFixtureSpan(value, testId, index) {
487
485
  };
488
486
  }
489
487
  function invalidFixtureSpanError(testId, index) {
490
- return /* @__PURE__ */ new Error(`Invalid ${require_config.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: invalid span at index ${index}`);
488
+ return /* @__PURE__ */ new Error(`Invalid ${require_screenshots_zip.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: invalid span at index ${index}`);
491
489
  }
492
490
  function parseAttachmentDate(value) {
493
491
  if (typeof value !== "string") return;
@@ -516,10 +514,26 @@ function isInternalFixtureStep(step) {
516
514
  }
517
515
  function isInternalApiRequestStep(step) {
518
516
  if (step.category !== "pw:api" || !step.location?.file) return false;
519
- return isApiRequestStepTitle(step.title) && isInternalFixtureFile(step.location.file);
517
+ return isApiRequestStep(step) && isInternalFixtureFile(step.location.file);
520
518
  }
521
- function isApiRequestStepTitle(title) {
522
- return /^(?:DELETE|FETCH|GET|HEAD|PATCH|POST|PUT)\s+"/.test(title);
519
+ /**
520
+ * `APIRequestContext` calls. From Playwright 1.63 they report a url and a
521
+ * method; before that they show up only in the title, e.g. `GET "/api"`.
522
+ */
523
+ function isApiRequestStep(step) {
524
+ if (step.params) return typeof step.params.url === "string" && typeof step.params.method === "string";
525
+ return /^(?:DELETE|FETCH|GET|HEAD|PATCH|POST|PUT)\s+"/.test(step.title);
526
+ }
527
+ /**
528
+ * Span attributes hold primitives and string arrays, so other param values
529
+ * (options objects, mixed arrays) are stored as JSON.
530
+ */
531
+ function toStepParamAttribute(value) {
532
+ if (value === void 0 || value === null) return void 0;
533
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
534
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
535
+ const json = JSON.stringify(value);
536
+ return json === void 0 || json === "{}" ? void 0 : json;
523
537
  }
524
538
  function isInternalFixtureFile(filePath) {
525
539
  const file = filePath.replace(/\\/g, "/");
@@ -548,15 +562,6 @@ function isRecord(value) {
548
562
  function isTraceContextAttachment(value) {
549
563
  return typeof value === "object" && value !== null && "traceId" in value && "rootSpanId" in value && typeof value.traceId === "string" && typeof value.rootSpanId === "string";
550
564
  }
551
- function getStepId(test, step) {
552
- const startTimeMs = step.startTime.getTime();
553
- return [
554
- test.id,
555
- step.category,
556
- startTimeMs,
557
- ...step.titlePath()
558
- ].join(" > ");
559
- }
560
565
  //#endregion
561
566
  Object.defineProperty(exports, "PlaywrightOpentelemetryReporter", {
562
567
  enumerable: true,
package/dist/reporter.cjs CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region src/reporter/index.ts
2
- var reporter_default = require("./reporter-CzP9uSdk.cjs").PlaywrightOpentelemetryReporter;
2
+ var reporter_default = require("./reporter-Dnqohjyo.cjs").PlaywrightOpentelemetryReporter;
3
3
  //#endregion
4
4
  module.exports = reporter_default;
@@ -1,2 +1,2 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-DaCojFom.cjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-CLzdtg6G.cjs";
2
2
  export = PlaywrightOpentelemetryReporter;
@@ -1,2 +1,2 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-DaCojFom.mjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-CLzdtg6G.mjs";
2
2
  export { PlaywrightOpentelemetryReporter as default };
package/dist/reporter.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-DCwosQMM.mjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-CMGLSTHi.mjs";
2
2
  //#region src/reporter/index.ts
3
3
  var reporter_default = PlaywrightOpentelemetryReporter;
4
4
  //#endregion
@@ -1,5 +1,6 @@
1
+ import { BlobReader, BlobWriter, TextWriter, ZipReader, ZipWriter } from "@zip.js/zip.js";
1
2
  //#region package.json
2
- var version = "0.13.6";
3
+ var version = "0.15.0";
3
4
  const PLAYWRIGHT_TRACE_API_SOURCE_HEADER = "x-playwright-otel-source";
4
5
  const PLAYWRIGHT_TRACE_API_SOURCE_REPORTER = "reporter";
5
6
  function withPlaywrightTraceApiHeaders(headers) {
@@ -204,7 +205,15 @@ async function createTestTraceContext(testInfo) {
204
205
  });
205
206
  return traceContext;
206
207
  }
208
+ /**
209
+ * Writes the expected-trace marker that lets the Trace API admit spans from the
210
+ * app under test. Only browser requests carry the test's traceparent, so the
211
+ * marker is skipped when propagation is off; the fixture's own spans are
212
+ * trusted and stored without it. Never rejects, so callers can start it
213
+ * without awaiting.
214
+ */
207
215
  async function registerExpectedTrace(traceContext, config, options) {
216
+ if (!config.propagateTraceHeaders) return;
208
217
  const couldRetainTrace = (trace) => couldRetainPlaywrightTrace(trace ?? options.trace, options.testInfo);
209
218
  const destinations = filterRetainedDestinations(config.playwrightTraceApiDestinations, config.trace, couldRetainTrace);
210
219
  if (destinations.length === 0) return;
@@ -294,6 +303,7 @@ function resolvePlaywrightOpentelemetryConfig(config, options = {}) {
294
303
  }),
295
304
  storeTraceZip: config?.storeTraceZip === true,
296
305
  trace: config?.trace ?? null,
306
+ screenshots: config?.screenshots ?? true,
297
307
  propagateTraceHeaders: config?.propagateTraceHeaders ?? true,
298
308
  debug: debugEnv === void 0 ? config?.debug ?? false : debugEnv === "1" || debugEnv === "true"
299
309
  };
@@ -335,4 +345,102 @@ function getConfigurationErrorMessage() {
335
345
  return "playwright-opentelemetry reporter requires an OTLP endpoint, trace API endpoint, or storeTraceZip to be configured.\n\nYou can configure it using environment variables:\n\n export OTEL_EXPORTER_OTLP_ENDPOINT=\"https://api.honeycomb.io\"\n export OTEL_EXPORTER_OTLP_HEADERS=\"x-honeycomb-team=YOUR_API_KEY\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryUseOptions } from 'playwright-opentelemetry/fixture';\n\nexport default defineConfig<PlaywrightOpentelemetryUseOptions>({\n use: {\n playwrightOpentelemetry: {\n otlpEndpoint: {\n url: 'http://localhost:4317/v1/traces',\n headers: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n },\n },\n },\n reporter: [['playwright-opentelemetry/reporter']],\n});\n\nNote: Environment variables take precedence over use.playwrightOpentelemetry options.\n";
336
346
  }
337
347
  //#endregion
338
- export { createTestTraceContext as a, shouldRetainPlaywrightTrace as c, PLAYWRIGHT_TRACE_API_SOURCE_REPORTER as d, buildOtlpRequest as f, withPlaywrightTraceApiHeaders as g, sendSpans as h, TRACE_CONTEXT_ATTACHMENT_NAME as i, filterRetainedDestinations as l, generateTraceId as m, BROWSER_SERVICE_NAME as n, flushFixtureSpans as o, generateSpanId as p, FIXTURE_SPANS_ATTACHMENT_NAME as r, registerExpectedTrace as s, resolvePlaywrightOpentelemetryConfig as t, PLAYWRIGHT_TRACE_API_SOURCE_HEADER as u };
348
+ //#region src/shared/screencast-screenshots.ts
349
+ /**
350
+ * The first Playwright version whose screencast frames carry the browser's
351
+ * presentation timestamp (1.61) and viewport size (1.60), and whose browsers
352
+ * report new contexts (1.60).
353
+ *
354
+ * From this version, screenshots only come from the fixture's screencast
355
+ * capture: tests without the fixture get none. Before it, the fixture
356
+ * captures nothing and the reporter reads screenshots from Playwright's
357
+ * trace.zip (see reporter/legacy/). Once the peer dependency requires this
358
+ * version, delete this module and that legacy path.
359
+ */
360
+ const SCREENCAST_SCREENSHOTS_MIN_PLAYWRIGHT_VERSION = "1.61.0";
361
+ /** Whether this Playwright version's screencast can provide screenshots. */
362
+ function supportsScreencastScreenshots(playwrightVersion) {
363
+ const version = parseVersion(playwrightVersion);
364
+ const minimum = parseVersion(SCREENCAST_SCREENSHOTS_MIN_PLAYWRIGHT_VERSION);
365
+ if (!version || !minimum) return false;
366
+ for (let index = 0; index < minimum.length; index++) if (version[index] !== minimum[index]) return version[index] > minimum[index];
367
+ return true;
368
+ }
369
+ /**
370
+ * Major, minor and patch of a version such as "1.61.0" or "1.61.0-next".
371
+ * Prereleases count as their release: 1.61.0-next already has the API.
372
+ */
373
+ function parseVersion(version) {
374
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
375
+ return match ? [
376
+ Number(match[1]),
377
+ Number(match[2]),
378
+ Number(match[3])
379
+ ] : void 0;
380
+ }
381
+ //#endregion
382
+ //#region src/shared/screenshots-zip.ts
383
+ /**
384
+ * The fixture attaches captured screencast frames to the test result as a
385
+ * screenshots ZIP under this name; the reporter uploads it and copies it into
386
+ * the local trace ZIP.
387
+ */
388
+ const SCREENSHOTS_ATTACHMENT_NAME = "playwright-opentelemetry-screenshots";
389
+ const MANIFEST_PATH = "manifest.json";
390
+ const SCREENSHOTS_DIR = "screenshots/";
391
+ async function createScreenshotsZip(screenshots) {
392
+ const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
393
+ await addScreenshotsToZip(zipWriter, screenshots);
394
+ return zipWriter.close();
395
+ }
396
+ /**
397
+ * Add the manifest and frames of a screenshots ZIP to another ZIP, so the same
398
+ * layout can be uploaded on its own or embedded in a local trace ZIP.
399
+ */
400
+ async function addScreenshotsToZip(zipWriter, screenshots) {
401
+ const sorted = [...screenshots].sort((a, b) => a.timestamp - b.timestamp);
402
+ const manifest = {
403
+ version: 3,
404
+ screenshots: sorted.map((screenshot) => ({
405
+ timestamp: screenshot.timestamp,
406
+ file: screenshot.file,
407
+ path: `${SCREENSHOTS_DIR}${screenshot.file}`,
408
+ contentType: screenshot.contentType,
409
+ pageId: screenshot.pageId,
410
+ ...viewportOf(screenshot)
411
+ }))
412
+ };
413
+ await zipWriter.add(MANIFEST_PATH, new Blob([JSON.stringify(manifest, null, 2)], { type: "application/json" }).stream());
414
+ for (const screenshot of sorted) await zipWriter.add(`${SCREENSHOTS_DIR}${screenshot.file}`, screenshot.blob.stream(), { level: 0 });
415
+ }
416
+ async function readScreenshotsZip(zipBlob) {
417
+ const zipReader = new ZipReader(new BlobReader(zipBlob));
418
+ try {
419
+ const entries = new Map((await zipReader.getEntries()).filter((entry) => !entry.directory).map((entry) => [entry.filename, entry]));
420
+ const manifestEntry = entries.get(MANIFEST_PATH);
421
+ if (!manifestEntry) throw new Error(`Screenshots ZIP has no ${MANIFEST_PATH}`);
422
+ const manifest = JSON.parse(await manifestEntry.getData(new TextWriter()));
423
+ return await Promise.all(manifest.screenshots.map(async (screenshot) => {
424
+ const entry = entries.get(screenshot.path);
425
+ if (!entry) throw new Error(`Screenshots ZIP has no ${screenshot.path}`);
426
+ return {
427
+ timestamp: screenshot.timestamp,
428
+ file: screenshot.file,
429
+ contentType: screenshot.contentType,
430
+ pageId: screenshot.pageId,
431
+ ...viewportOf(screenshot),
432
+ blob: await entry.getData(new BlobWriter(screenshot.contentType))
433
+ };
434
+ }));
435
+ } finally {
436
+ await zipReader.close();
437
+ }
438
+ }
439
+ function viewportOf(screenshot) {
440
+ return screenshot.viewportWidth !== void 0 && screenshot.viewportHeight !== void 0 ? {
441
+ viewportWidth: screenshot.viewportWidth,
442
+ viewportHeight: screenshot.viewportHeight
443
+ } : {};
444
+ }
445
+ //#endregion
446
+ export { withPlaywrightTraceApiHeaders as S, PLAYWRIGHT_TRACE_API_SOURCE_REPORTER as _, supportsScreencastScreenshots as a, generateTraceId as b, FIXTURE_SPANS_ATTACHMENT_NAME as c, flushFixtureSpans as d, registerExpectedTrace as f, PLAYWRIGHT_TRACE_API_SOURCE_HEADER as g, filterRetainedDestinations as h, readScreenshotsZip as i, TRACE_CONTEXT_ATTACHMENT_NAME as l, shouldRetainPlaywrightTrace as m, addScreenshotsToZip as n, resolvePlaywrightOpentelemetryConfig as o, couldRetainPlaywrightTrace as p, createScreenshotsZip as r, BROWSER_SERVICE_NAME as s, SCREENSHOTS_ATTACHMENT_NAME as t, createTestTraceContext as u, buildOtlpRequest as v, sendSpans as x, generateSpanId as y };