playwright-opentelemetry 0.3.2 → 0.3.3

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/dist/fixture.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as getOrCreateTraceId, f as writeNetworkSpan, m as writePageTestMapping, o as generateSpanId, p as writeNetworkSpanParent, s as getCurrentSpanId, u as readNetworkSpanParent } from "./trace-files-BK_6TvGO.mjs";
1
+ import { a as generateSpanId, c as readNetworkSpanParent, d as writeNetworkSpanParent, o as getCurrentSpanId, s as getOrCreateTraceId, u as writeNetworkSpan } from "./trace-files-Dk9VFFGH.mjs";
2
2
  import path from "node:path";
3
3
  import { test as test$1 } from "@playwright/test";
4
4
 
@@ -170,8 +170,6 @@ const test = test$1.extend({
170
170
  await use(context);
171
171
  },
172
172
  page: async ({ page, testTraceInfo: { testId, outputDir } }, use) => {
173
- const pageGuid = page._guid;
174
- writePageTestMapping(outputDir, testId, pageGuid);
175
173
  const pendingRequests = /* @__PURE__ */ new Map();
176
174
  page.on("response", (response) => {
177
175
  pendingRequests.set(response.request(), response);
@@ -22,8 +22,6 @@ declare class PlaywrightOpentelemetryReporter implements Reporter {
22
22
  private resolvedServiceName;
23
23
  /** Maps test.id to its project's outputDir */
24
24
  private testOutputDirs;
25
- /** File system watchers for output directories */
26
- private directoryWatchers;
27
25
  private testSpans;
28
26
  private testTraceIds;
29
27
  private stepSpanIds;
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-YxCgCBKV.mjs";
1
+ import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-CD_ZrFf2.mjs";
2
2
  import { TestCase, TestStatus } from "@playwright/test/reporter";
3
3
 
4
4
  //#region src/reporter/trace-zip-builder.d.ts
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-fr3rSO0u.mjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-COidNt8o.mjs";
2
2
 
3
3
  //#region src/index.ts
4
4
  var src_default = PlaywrightOpentelemetryReporter;
@@ -1,8 +1,8 @@
1
- import { a as createNetworkDirs, c as getOrCreateTraceId, d as writeCurrentSpanId, i as copyScreenshotForTest, l as getScreenshotsDir, n as cleanupTestFiles, o as generateSpanId, r as collectNetworkSpans, t as PW_OTEL_DIR } from "./trace-files-BK_6TvGO.mjs";
2
- import { existsSync, mkdirSync, watch } from "node:fs";
3
- import fs, { readFile, readdir } from "node:fs/promises";
1
+ import { a as generateSpanId, i as createNetworkDirs, l as writeCurrentSpanId, n as cleanupTestFiles, r as collectNetworkSpans, s as getOrCreateTraceId, t as PW_OTEL_DIR } from "./trace-files-Dk9VFFGH.mjs";
2
+ import { mkdirSync } from "node:fs";
4
3
  import path from "node:path";
5
- import { BlobWriter, TextReader, ZipWriter } from "@zip.js/zip.js";
4
+ import fs from "node:fs/promises";
5
+ import { BlobReader, BlobWriter, TextReader, ZipReader, ZipWriter } from "@zip.js/zip.js";
6
6
 
7
7
  //#region src/reporter/otel-attributes.ts
8
8
  const ATTR_CODE_FILE_PATH = "code.file.path";
@@ -21,7 +21,7 @@ const ATTR_TEST_STEP_CATEGORY = "test.step.category";
21
21
 
22
22
  //#endregion
23
23
  //#region package.json
24
- var version = "0.3.2";
24
+ var version = "0.3.3";
25
25
 
26
26
  //#endregion
27
27
  //#region src/reporter/sender.ts
@@ -129,23 +129,34 @@ function getZipFilename(test, testId) {
129
129
  if (test.location) return `${path.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
130
130
  return `${testId}-pw-otel.zip`;
131
131
  }
132
+ const PLAYWRIGHT_TRACE_RESOURCES_DIR = "resources/";
132
133
  /**
133
- * Get all screenshots for a test from its dedicated screenshots directory.
134
- * Returns a Map of filename -> file buffer.
134
+ * Extract screenshots from a Playwright trace ZIP file.
135
+ * Screenshots are stored in the resources/ directory with names like:
136
+ * {pageGuid}-{timestamp}.jpeg (e.g., page@abc123-1766929201038.jpeg)
137
+ *
138
+ * @param traceZipPath - Path to the Playwright trace.zip file
139
+ * @returns Map of filename (without resources/ prefix) to Blob
135
140
  */
136
- async function getTestScreenshots(outputDir, testId) {
141
+ async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
137
142
  const screenshots = /* @__PURE__ */ new Map();
138
- const screenshotsDir = getScreenshotsDir(outputDir, testId);
139
143
  try {
140
- const files = await fs.readdir(screenshotsDir);
141
- for (const file of files) {
142
- if (!file.endsWith(".jpeg") && !file.endsWith(".jpg")) continue;
143
- const filePath = path.join(screenshotsDir, file);
144
- const buffer = await fs.readFile(filePath);
145
- screenshots.set(file, buffer);
146
- }
144
+ const zipBuffer = await fs.readFile(traceZipPath);
145
+ const zipReader = new ZipReader(new BlobReader(new Blob([zipBuffer])));
146
+ const entries = await zipReader.getEntries();
147
+ await Promise.all(entries.filter((entry) => {
148
+ if (!isFileEntry(entry)) return false;
149
+ if (!entry.filename.startsWith(PLAYWRIGHT_TRACE_RESOURCES_DIR)) return false;
150
+ const name = entry.filename.slice(10);
151
+ return name.endsWith(".jpeg") || name.endsWith(".jpg");
152
+ }).map(async (entry) => {
153
+ const filename = entry.filename.slice(10);
154
+ const blob = await entry.getData(new BlobWriter("image/jpeg"));
155
+ screenshots.set(filename, blob);
156
+ }));
157
+ await zipReader.close();
147
158
  } catch (err) {
148
- if (err.code !== "ENOENT") throw err;
159
+ if (err.code !== "ENOENT") console.warn(`Warning: Could not extract screenshots from trace ZIP: ${err}`);
149
160
  }
150
161
  return screenshots;
151
162
  }
@@ -174,25 +185,24 @@ function buildTestInfo(options, traceId) {
174
185
  * Create a zip file containing the OTLP trace JSON, test.json, and screenshots for a test.
175
186
  */
176
187
  async function createTraceZip(options) {
177
- const { outputDir, testId, test, spans, serviceName, playwrightVersion } = options;
188
+ const { outputDir, test, spans, serviceName, playwrightVersion, screenshots } = options;
178
189
  const otlpRequest = buildOtlpRequest(spans, serviceName, playwrightVersion);
179
190
  const traceJson = JSON.stringify(otlpRequest, null, 2);
180
191
  const testInfo = buildTestInfo(options, spans.find((s) => s.name === "playwright.test")?.traceId ?? "");
181
192
  const testInfoJson = JSON.stringify(testInfo, null, 2);
182
- const screenshots = await getTestScreenshots(outputDir, testId);
183
193
  const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
184
194
  await zipWriter.add("test.json", new TextReader(testInfoJson));
185
195
  await zipWriter.add("opentelemetry-protocol/playwright-opentelemetry.json", new TextReader(traceJson));
186
- for (const [filename, buffer] of screenshots) {
187
- const blob = new Blob([buffer]);
188
- await zipWriter.add(`screenshots/${filename}`, blob.stream());
189
- }
196
+ await Promise.all(Array.from(screenshots.entries()).map(([filename, blob]) => zipWriter.add(`screenshots/${filename}`, blob.stream())));
190
197
  const zipBlob = await zipWriter.close();
191
- const zipFilename = getZipFilename(test, testId);
198
+ const zipFilename = getZipFilename(test, test.id);
192
199
  const zipPath = path.join(outputDir, zipFilename);
193
200
  const arrayBuffer = await zipBlob.arrayBuffer();
194
201
  await fs.writeFile(zipPath, Buffer.from(arrayBuffer));
195
202
  }
203
+ function isFileEntry(entry) {
204
+ return !entry.directory;
205
+ }
196
206
 
197
207
  //#endregion
198
208
  //#region src/reporter/reporter.ts
@@ -207,8 +217,6 @@ var PlaywrightOpentelemetryReporter = class {
207
217
  resolvedServiceName;
208
218
  /** Maps test.id to its project's outputDir */
209
219
  testOutputDirs = /* @__PURE__ */ new Map();
210
- /** File system watchers for output directories */
211
- directoryWatchers = [];
212
220
  testSpans = /* @__PURE__ */ new Map();
213
221
  testTraceIds = /* @__PURE__ */ new Map();
214
222
  stepSpanIds = /* @__PURE__ */ new Map();
@@ -230,28 +238,11 @@ var PlaywrightOpentelemetryReporter = class {
230
238
  onBegin(config, suite) {
231
239
  this.rootDir = config.rootDir;
232
240
  this.playwrightVersion = config.version;
233
- const watchedDirs = /* @__PURE__ */ new Set();
234
241
  for (const test of suite.allTests()) {
235
242
  const project = test.parent.project();
236
243
  if (project?.outputDir) {
237
244
  this.testOutputDirs.set(test.id, project.outputDir);
238
245
  mkdirSync(path.join(project.outputDir, PW_OTEL_DIR), { recursive: true });
239
- if (this.options.storeTraceZip && !watchedDirs.has(project.outputDir)) {
240
- watchedDirs.add(project.outputDir);
241
- const watcher = watch(project.outputDir, { recursive: true }, (_eventType, filename) => {
242
- if (!filename || !filename.endsWith(".jpg") && !filename.endsWith(".jpeg")) return;
243
- const sourcePath = path.join(project.outputDir, filename);
244
- if (!existsSync(sourcePath)) return;
245
- const basename = path.basename(filename);
246
- const lastDashIndex = basename.lastIndexOf("-");
247
- if (lastDashIndex === -1) return;
248
- const pageGuid = basename.slice(0, lastDashIndex);
249
- try {
250
- copyScreenshotForTest(project.outputDir, pageGuid, sourcePath, basename);
251
- } catch (_err) {}
252
- });
253
- this.directoryWatchers.push(watcher);
254
- }
255
246
  }
256
247
  }
257
248
  }
@@ -340,6 +331,9 @@ var PlaywrightOpentelemetryReporter = class {
340
331
  this.spans.push(...testSpans);
341
332
  const relativeFilePath = test.location && this.rootDir ? path.relative(this.rootDir, test.location.file) : test.location?.file ?? "";
342
333
  const computedDuration = maxEndTime.getTime() - minStartTime.getTime();
334
+ let screenshots = /* @__PURE__ */ new Map();
335
+ const traceAttachment = result.attachments.find((a) => a.name === "trace" && a.contentType === "application/zip");
336
+ if (traceAttachment?.path) screenshots = await extractScreenshotsFromPlaywrightTrace(traceAttachment.path);
343
337
  if (this.options.storeTraceZip) await createTraceZip({
344
338
  outputDir,
345
339
  testId,
@@ -350,21 +344,20 @@ var PlaywrightOpentelemetryReporter = class {
350
344
  relativeFilePath,
351
345
  status: result.status,
352
346
  startTime: minStartTime,
353
- duration: computedDuration
347
+ duration: computedDuration,
348
+ screenshots
354
349
  });
355
350
  if (this.resolvedTraceApiEndpoint) await this.sendTestJsonToTraceApi({
356
351
  test,
357
352
  result,
358
353
  traceId,
359
- outputDir,
360
354
  relativeFilePath,
361
355
  startTime: minStartTime,
362
- computedDuration
356
+ computedDuration,
357
+ screenshots
363
358
  });
364
359
  }
365
360
  async onEnd(_result) {
366
- for (const watcher of this.directoryWatchers) watcher.close();
367
- this.directoryWatchers = [];
368
361
  if (this.resolvedEndpoint) await sendSpans(this.spans, {
369
362
  tracesEndpoint: this.resolvedEndpoint,
370
363
  headers: this.resolvedHeaders,
@@ -444,7 +437,7 @@ var PlaywrightOpentelemetryReporter = class {
444
437
  return outputDir;
445
438
  }
446
439
  async sendTestJsonToTraceApi(params) {
447
- const { test, result, traceId, outputDir, relativeFilePath, startTime, computedDuration } = params;
440
+ const { test, result, traceId, relativeFilePath, startTime, computedDuration, screenshots } = params;
448
441
  const titlePath = test.titlePath();
449
442
  const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
450
443
  const line = test.location?.line ?? 0;
@@ -470,23 +463,18 @@ var PlaywrightOpentelemetryReporter = class {
470
463
  },
471
464
  body: JSON.stringify(testJson)
472
465
  });
473
- const screenshotsDir = path.join(outputDir, PW_OTEL_DIR, test.id, "screenshots");
474
- if (existsSync(screenshotsDir)) {
475
- const screenshotFiles = (await readdir(screenshotsDir)).filter((file) => file.endsWith(".jpeg") || file.endsWith(".jpg"));
476
- await Promise.all(screenshotFiles.map(async (file) => {
477
- const buffer = await readFile(path.join(screenshotsDir, file));
478
- const screenshotUrl = `${this.resolvedTraceApiEndpoint}/otel-playwright-reporter/screenshots/${file}`;
479
- await fetch(screenshotUrl, {
480
- method: "PUT",
481
- headers: {
482
- "content-type": "image/jpeg",
483
- "x-trace-id": traceId,
484
- ...this.resolvedTraceApiHeaders
485
- },
486
- body: buffer
487
- });
488
- }));
489
- }
466
+ await Promise.all(Array.from(screenshots.entries()).map(async ([filename, blob]) => {
467
+ const screenshotUrl = `${this.resolvedTraceApiEndpoint}/otel-playwright-reporter/screenshots/${filename}`;
468
+ await fetch(screenshotUrl, {
469
+ method: "PUT",
470
+ headers: {
471
+ "content-type": "image/jpeg",
472
+ "x-trace-id": traceId,
473
+ ...this.resolvedTraceApiHeaders
474
+ },
475
+ body: blob
476
+ });
477
+ }));
490
478
  }
491
479
  };
492
480
  function parseOtlpHeaders(headersString) {
@@ -1,2 +1,2 @@
1
- import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-YxCgCBKV.mjs";
1
+ import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-CD_ZrFf2.mjs";
2
2
  export { PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
package/dist/reporter.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-fr3rSO0u.mjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-COidNt8o.mjs";
2
2
 
3
3
  //#region src/reporter/index.ts
4
4
  var reporter_default = PlaywrightOpentelemetryReporter;
@@ -1,42 +1,9 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import fs from "node:fs/promises";
3
2
  import path from "node:path";
3
+ import fs from "node:fs/promises";
4
4
 
5
5
  //#region src/shared/trace-files.ts
6
6
  const PW_OTEL_DIR = "playwright-opentelemetry";
7
- /**
8
- * Get the screenshots directory for a specific test.
9
- */
10
- function getScreenshotsDir(outputDir, testId) {
11
- return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}-screenshots`);
12
- }
13
- /**
14
- * Copy a screenshot to the appropriate test's screenshots directory.
15
- * Uses the page-test mapping to determine which test owns this screenshot.
16
- *
17
- * @param outputDir - The Playwright output directory
18
- * @param pageGuid - The page GUID extracted from the screenshot filename
19
- * @param sourcePath - The source path of the screenshot file
20
- * @param filename - The screenshot filename
21
- * @returns true if the screenshot was copied, false if no matching test was found
22
- */
23
- function copyScreenshotForTest(outputDir, pageGuid, sourcePath, filename) {
24
- const mappingPath = getPageMappingPath(outputDir);
25
- let mappings = [];
26
- try {
27
- const content = readFileSync(mappingPath, "utf-8");
28
- mappings = JSON.parse(content);
29
- } catch (err) {
30
- if (err.code !== "ENOENT") throw err;
31
- return false;
32
- }
33
- const mapping = mappings.find((m) => m.pageGuid === pageGuid);
34
- if (!mapping) return false;
35
- const screenshotsDir = getScreenshotsDir(outputDir, mapping.testId);
36
- mkdirSync(screenshotsDir, { recursive: true });
37
- writeFileSync(path.join(screenshotsDir, filename), readFileSync(sourcePath));
38
- return true;
39
- }
40
7
  function getOrCreateTraceId(outputDir, testId) {
41
8
  const tracePath = getTracePath(outputDir, testId);
42
9
  if (existsSync(tracePath)) return readFileSync(tracePath, "utf-8");
@@ -114,28 +81,6 @@ async function collectNetworkSpans(outputDir, testId) {
114
81
  }
115
82
  }
116
83
  /**
117
- * Store a page GUID to test ID mapping.
118
- * This is used to filter screenshots when creating trace zip files.
119
- *
120
- * @param outputDir - The Playwright output directory
121
- * @param testId - The unique test identifier
122
- * @param pageGuid - The internal Playwright page GUID
123
- */
124
- function writePageTestMapping(outputDir, testId, pageGuid) {
125
- const mappingPath = getPageMappingPath(outputDir);
126
- mkdirSync(path.dirname(mappingPath), { recursive: true });
127
- let mappings = [];
128
- if (existsSync(mappingPath)) {
129
- const content = readFileSync(mappingPath, "utf-8");
130
- mappings = JSON.parse(content);
131
- }
132
- mappings.push({
133
- testId,
134
- pageGuid
135
- });
136
- writeFileSync(mappingPath, JSON.stringify(mappings, null, 2));
137
- }
138
- /**
139
84
  * Cleanup all trace files for a test.
140
85
  * Called by the reporter after onTestEnd has processed the spans.
141
86
  *
@@ -163,14 +108,6 @@ async function cleanupTestFiles(outputDir, testId) {
163
108
  } catch (err) {
164
109
  if (err.code !== "ENOENT") throw err;
165
110
  }
166
- try {
167
- await fs.rm(getScreenshotsDir(outputDir, testId), { recursive: true });
168
- } catch (err) {
169
- if (err.code !== "ENOENT") throw err;
170
- }
171
- }
172
- function getPageMappingPath(outputDir) {
173
- return path.join(outputDir, PW_OTEL_DIR, "page-test-mappings.json");
174
111
  }
175
112
  function getTracePath(outputDir, testId) {
176
113
  return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}.trace`);
@@ -211,4 +148,4 @@ function generateSpanId() {
211
148
  }
212
149
 
213
150
  //#endregion
214
- export { createNetworkDirs as a, getOrCreateTraceId as c, writeCurrentSpanId as d, writeNetworkSpan as f, copyScreenshotForTest as i, getScreenshotsDir as l, writePageTestMapping as m, cleanupTestFiles as n, generateSpanId as o, writeNetworkSpanParent as p, collectNetworkSpans as r, getCurrentSpanId as s, PW_OTEL_DIR as t, readNetworkSpanParent as u };
151
+ export { generateSpanId as a, readNetworkSpanParent as c, writeNetworkSpanParent as d, createNetworkDirs as i, writeCurrentSpanId as l, cleanupTestFiles as n, getCurrentSpanId as o, collectNetworkSpans as r, getOrCreateTraceId as s, PW_OTEL_DIR as t, writeNetworkSpan as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playwright-opentelemetry",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "A reporter for Playwright that can export traces and spans in opentelemetry format.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -57,7 +57,7 @@
57
57
  "scripts": {
58
58
  "build": "tsdown",
59
59
  "dev": "tsdown --watch",
60
- "test:e2e": "playwright test",
60
+ "test:e2e": "pnpm build && pnpm playwright test",
61
61
  "verify:trace-zips": "bun scripts/verify-trace-zips.ts"
62
62
  }
63
63
  }