playwright-opentelemetry 0.3.2 → 0.3.4

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-DuWkTUh0.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.4";
25
25
 
26
26
  //#endregion
27
27
  //#region src/reporter/sender.ts
@@ -129,23 +129,39 @@ 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
+ * Pattern to match Playwright screenshot filenames: {name}@{hex-hash}-{timestamp}.jpeg
135
+ * Examples: page@f06f11f7c14d6ce1060d47d79f05c154-1766833384425.jpeg
135
136
  */
136
- async function getTestScreenshots(outputDir, testId) {
137
+ const PLAYWRIGHT_SCREENSHOT_PATTERN = /^.+@[a-f0-9]+-\d+\.jpe?g$/i;
138
+ /**
139
+ * Extract screenshots from a Playwright trace ZIP file.
140
+ * Screenshots are stored in the resources/ directory with names like:
141
+ * {pageGuid}-{timestamp}.jpeg (e.g., page@abc123-1766929201038.jpeg)
142
+ *
143
+ * @param traceZipPath - Path to the Playwright trace.zip file
144
+ * @returns Map of filename (without resources/ prefix) to Blob
145
+ */
146
+ async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
137
147
  const screenshots = /* @__PURE__ */ new Map();
138
- const screenshotsDir = getScreenshotsDir(outputDir, testId);
139
148
  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
- }
149
+ const zipBuffer = await fs.readFile(traceZipPath);
150
+ const zipReader = new ZipReader(new BlobReader(new Blob([zipBuffer])));
151
+ const entries = await zipReader.getEntries();
152
+ await Promise.all(entries.filter((entry) => {
153
+ if (!isFileEntry(entry)) return false;
154
+ if (!entry.filename.startsWith(PLAYWRIGHT_TRACE_RESOURCES_DIR)) return false;
155
+ const name = entry.filename.slice(10);
156
+ return PLAYWRIGHT_SCREENSHOT_PATTERN.test(name);
157
+ }).map(async (entry) => {
158
+ const filename = entry.filename.slice(10);
159
+ const blob = await entry.getData(new BlobWriter("image/jpeg"));
160
+ screenshots.set(filename, blob);
161
+ }));
162
+ await zipReader.close();
147
163
  } catch (err) {
148
- if (err.code !== "ENOENT") throw err;
164
+ if (err.code !== "ENOENT") console.warn(`Warning: Could not extract screenshots from trace ZIP: ${err}`);
149
165
  }
150
166
  return screenshots;
151
167
  }
@@ -174,25 +190,24 @@ function buildTestInfo(options, traceId) {
174
190
  * Create a zip file containing the OTLP trace JSON, test.json, and screenshots for a test.
175
191
  */
176
192
  async function createTraceZip(options) {
177
- const { outputDir, testId, test, spans, serviceName, playwrightVersion } = options;
193
+ const { outputDir, test, spans, serviceName, playwrightVersion, screenshots } = options;
178
194
  const otlpRequest = buildOtlpRequest(spans, serviceName, playwrightVersion);
179
195
  const traceJson = JSON.stringify(otlpRequest, null, 2);
180
196
  const testInfo = buildTestInfo(options, spans.find((s) => s.name === "playwright.test")?.traceId ?? "");
181
197
  const testInfoJson = JSON.stringify(testInfo, null, 2);
182
- const screenshots = await getTestScreenshots(outputDir, testId);
183
198
  const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
184
199
  await zipWriter.add("test.json", new TextReader(testInfoJson));
185
200
  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
- }
201
+ await Promise.all(Array.from(screenshots.entries()).map(([filename, blob]) => zipWriter.add(`screenshots/${filename}`, blob.stream())));
190
202
  const zipBlob = await zipWriter.close();
191
- const zipFilename = getZipFilename(test, testId);
203
+ const zipFilename = getZipFilename(test, test.id);
192
204
  const zipPath = path.join(outputDir, zipFilename);
193
205
  const arrayBuffer = await zipBlob.arrayBuffer();
194
206
  await fs.writeFile(zipPath, Buffer.from(arrayBuffer));
195
207
  }
208
+ function isFileEntry(entry) {
209
+ return !entry.directory;
210
+ }
196
211
 
197
212
  //#endregion
198
213
  //#region src/reporter/reporter.ts
@@ -207,8 +222,6 @@ var PlaywrightOpentelemetryReporter = class {
207
222
  resolvedServiceName;
208
223
  /** Maps test.id to its project's outputDir */
209
224
  testOutputDirs = /* @__PURE__ */ new Map();
210
- /** File system watchers for output directories */
211
- directoryWatchers = [];
212
225
  testSpans = /* @__PURE__ */ new Map();
213
226
  testTraceIds = /* @__PURE__ */ new Map();
214
227
  stepSpanIds = /* @__PURE__ */ new Map();
@@ -230,28 +243,11 @@ var PlaywrightOpentelemetryReporter = class {
230
243
  onBegin(config, suite) {
231
244
  this.rootDir = config.rootDir;
232
245
  this.playwrightVersion = config.version;
233
- const watchedDirs = /* @__PURE__ */ new Set();
234
246
  for (const test of suite.allTests()) {
235
247
  const project = test.parent.project();
236
248
  if (project?.outputDir) {
237
249
  this.testOutputDirs.set(test.id, project.outputDir);
238
250
  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
251
  }
256
252
  }
257
253
  }
@@ -340,6 +336,9 @@ var PlaywrightOpentelemetryReporter = class {
340
336
  this.spans.push(...testSpans);
341
337
  const relativeFilePath = test.location && this.rootDir ? path.relative(this.rootDir, test.location.file) : test.location?.file ?? "";
342
338
  const computedDuration = maxEndTime.getTime() - minStartTime.getTime();
339
+ let screenshots = /* @__PURE__ */ new Map();
340
+ const traceAttachment = result.attachments.find((a) => a.name === "trace" && a.contentType === "application/zip");
341
+ if (traceAttachment?.path) screenshots = await extractScreenshotsFromPlaywrightTrace(traceAttachment.path);
343
342
  if (this.options.storeTraceZip) await createTraceZip({
344
343
  outputDir,
345
344
  testId,
@@ -350,21 +349,20 @@ var PlaywrightOpentelemetryReporter = class {
350
349
  relativeFilePath,
351
350
  status: result.status,
352
351
  startTime: minStartTime,
353
- duration: computedDuration
352
+ duration: computedDuration,
353
+ screenshots
354
354
  });
355
355
  if (this.resolvedTraceApiEndpoint) await this.sendTestJsonToTraceApi({
356
356
  test,
357
357
  result,
358
358
  traceId,
359
- outputDir,
360
359
  relativeFilePath,
361
360
  startTime: minStartTime,
362
- computedDuration
361
+ computedDuration,
362
+ screenshots
363
363
  });
364
364
  }
365
365
  async onEnd(_result) {
366
- for (const watcher of this.directoryWatchers) watcher.close();
367
- this.directoryWatchers = [];
368
366
  if (this.resolvedEndpoint) await sendSpans(this.spans, {
369
367
  tracesEndpoint: this.resolvedEndpoint,
370
368
  headers: this.resolvedHeaders,
@@ -444,7 +442,7 @@ var PlaywrightOpentelemetryReporter = class {
444
442
  return outputDir;
445
443
  }
446
444
  async sendTestJsonToTraceApi(params) {
447
- const { test, result, traceId, outputDir, relativeFilePath, startTime, computedDuration } = params;
445
+ const { test, result, traceId, relativeFilePath, startTime, computedDuration, screenshots } = params;
448
446
  const titlePath = test.titlePath();
449
447
  const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
450
448
  const line = test.location?.line ?? 0;
@@ -470,23 +468,18 @@ var PlaywrightOpentelemetryReporter = class {
470
468
  },
471
469
  body: JSON.stringify(testJson)
472
470
  });
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
- }
471
+ await Promise.all(Array.from(screenshots.entries()).map(async ([filename, blob]) => {
472
+ const screenshotUrl = `${this.resolvedTraceApiEndpoint}/otel-playwright-reporter/screenshots/${filename}`;
473
+ await fetch(screenshotUrl, {
474
+ method: "PUT",
475
+ headers: {
476
+ "content-type": "image/jpeg",
477
+ "x-trace-id": traceId,
478
+ ...this.resolvedTraceApiHeaders
479
+ },
480
+ body: blob
481
+ });
482
+ }));
490
483
  }
491
484
  };
492
485
  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-DuWkTUh0.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.4",
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
  }