playwright-opentelemetry 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -1,67 +1,5 @@
1
- # Playwright Opentelemetry Reporter
1
+ # `playwright-opentelemetry`
2
2
 
3
- We're building a reporter for Playwright that can export traces and spans in opentelemetry format.
3
+ A combination of a Playwright reporter and a fixture that allows you to create opentelemetry spans for playwright end-to-end tests.
4
4
 
5
- We're just getting started, this project is in early development. Reach out if you're interested in learning more!
6
-
7
- ## Usage
8
-
9
- Two things need to be set up for complete opentelemetry tracing:
10
-
11
- 1. A reporter that sends traces to your provider of choice
12
- 2. A fixture that propogates opentelemetry trace headers to enable nested spans
13
-
14
- ### Configure the reporter
15
-
16
- ```ts
17
- import { defineConfig, devices } from "@playwright/test";
18
- import type { PlaywrightOpentelemetryReporterOptions } from "playwright-opentelemetry/reporter";
19
-
20
- export default defineConfig({
21
- // ... other Playwright config
22
- reporter: [
23
- [
24
- "playwright-opentelemetry/reporter",
25
- {
26
- // Or use environment variable OTEL_EXPORTER_OTLP_ENDPOINT
27
- otlpEndpoint: "https://api.eu1.honeycomb.io/v1/traces",
28
- // Or use environment variable OTEL_EXPORTER_OTLP_HEADERS
29
- otlpHeaders: {
30
- "x-honeycomb-team": "xxxabc",
31
- }
32
- } satisfies PlaywrightOpentelemetryReporterOptions,
33
- ],
34
- ],
35
- // ... rest of Playwright config
36
- });
37
- ```
38
-
39
- ### Configure the fixture
40
-
41
- ```ts
42
- import { expect } from "@playwright/test";
43
- import { test } from "playwright-opentelemetry/fixture";
44
-
45
- test("has title", async ({ page }) => {
46
- await page.goto("https://playwright.dev/");
47
-
48
- await expect(page).toHaveTitle(/Playwright/);
49
- });
50
- ```
51
-
52
- ## Contributing
53
-
54
- ### Developing `playwright-opentelemetry`
55
-
56
- - `pnpm dev` starts a dev server that outputs `dist/index.mjs`
57
- - `pnpm build` otherwise creates a one-off compiled build
58
- - `pnpm test:unit` to run the unit tests
59
- - `pnpm test:e2e` uses the compiled reporter output
60
- - `pnpm typecheck` for typescript
61
- - `pnpm format` to format files
62
-
63
- ### Releasing
64
-
65
- ```
66
- npx bumpp
67
- ```
5
+ For more information on getting started, check out the main [readme](../README.md).
package/dist/fixture.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as generateSpanId, c as readNetworkSpanParent, d as writeNetworkSpanParent, o as getCurrentSpanId, s as getOrCreateTraceId, u as writeNetworkSpan } from "./trace-files-BnO7hKxI.mjs";
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-BbTTP4-y.mjs";
2
2
  import path from "node:path";
3
3
  import { test as test$1 } from "@playwright/test";
4
4
 
@@ -36,6 +36,53 @@ async function fixtureOtelHeaderPropagator({ route, request, testId, outputDir }
36
36
  //#endregion
37
37
  //#region src/fixture/request-response-capture.ts
38
38
  /**
39
+ * Detects the resource type based on Content-Type header with URL extension fallback.
40
+ * This categorization mirrors Chrome DevTools Network tab behavior.
41
+ *
42
+ * @param contentType - The Content-Type response header value (may be null)
43
+ * @param url - The request URL (used as fallback)
44
+ * @returns The detected resource type
45
+ */
46
+ function detectResourceType(contentType, url) {
47
+ if (contentType) {
48
+ const mimeType = contentType.split(";")[0].trim().toLowerCase();
49
+ if (mimeType !== "application/octet-stream") {
50
+ if (mimeType === "text/html" || mimeType === "application/xhtml+xml") return "document";
51
+ if (mimeType === "application/javascript" || mimeType === "text/javascript" || mimeType === "application/x-javascript" || mimeType === "application/ecmascript" || mimeType === "text/ecmascript" || mimeType === "module" || mimeType === "application/wasm") return "script";
52
+ if (mimeType === "text/css") return "stylesheet";
53
+ if (mimeType.startsWith("image/")) return "image";
54
+ if (mimeType.startsWith("font/") || mimeType === "application/font-woff" || mimeType === "application/font-woff2" || mimeType === "application/x-font-ttf" || mimeType === "application/x-font-opentype") return "font";
55
+ if (mimeType.startsWith("video/") || mimeType.startsWith("audio/")) return "media";
56
+ if (mimeType === "application/json" || mimeType === "text/plain" || mimeType === "application/xml" || mimeType === "text/xml" || mimeType.endsWith("+json") || mimeType.endsWith("+xml")) return "fetch";
57
+ }
58
+ }
59
+ const resourceType = detectResourceTypeFromUrl(url);
60
+ if (resourceType) return resourceType;
61
+ return "other";
62
+ }
63
+ /**
64
+ * Detects resource type from URL file extension.
65
+ * Used as fallback when Content-Type header is missing or generic.
66
+ */
67
+ function detectResourceTypeFromUrl(url) {
68
+ try {
69
+ const lastSegment = new URL(url).pathname.toLowerCase().split("/").pop() || "";
70
+ const dotIndex = lastSegment.lastIndexOf(".");
71
+ if (dotIndex === -1) return null;
72
+ const extension = lastSegment.slice(dotIndex + 1);
73
+ if (extension === "html" || extension === "htm" || extension === "xhtml") return "document";
74
+ if (extension === "js" || extension === "mjs" || extension === "cjs" || extension === "jsx" || extension === "ts" || extension === "tsx" || extension === "wasm") return "script";
75
+ if (extension === "css") return "stylesheet";
76
+ if (extension === "png" || extension === "jpg" || extension === "jpeg" || extension === "gif" || extension === "svg" || extension === "webp" || extension === "ico" || extension === "bmp" || extension === "avif") return "image";
77
+ if (extension === "woff" || extension === "woff2" || extension === "ttf" || extension === "otf" || extension === "eot") return "font";
78
+ if (extension === "mp4" || extension === "webm" || extension === "ogg" || extension === "mp3" || extension === "wav" || extension === "m4a" || extension === "aac" || extension === "flac" || extension === "avi" || extension === "mov") return "media";
79
+ if (extension === "json" || extension === "xml") return "fetch";
80
+ return null;
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+ /**
39
86
  * OpenTelemetry SpanKind values
40
87
  * @see https://opentelemetry.io/docs/specs/otel/trace/api/#spankind
41
88
  */
@@ -77,13 +124,17 @@ async function fixtureCaptureRequestResponse({ request, response, testId, output
77
124
  const serverPort = parsedUrl.port !== "" ? Number.parseInt(parsedUrl.port, 10) : parsedUrl.protocol === "https:" ? 443 : 80;
78
125
  let statusCodeValue = SPAN_STATUS_CODE_UNSET;
79
126
  if (statusCode >= 400) statusCodeValue = SPAN_STATUS_CODE_ERROR;
127
+ const resourceType = detectResourceType(await response.headerValue("content-type"), url);
80
128
  const attributes = {
81
129
  "http.request.method": method,
82
130
  "url.full": url,
131
+ "url.path": parsedUrl.pathname,
83
132
  "server.address": serverAddress,
84
133
  "server.port": serverPort,
85
- "http.response.status_code": statusCode
134
+ "http.response.status_code": statusCode,
135
+ "http.resource.type": resourceType
86
136
  };
137
+ if (parsedUrl.search) attributes["url.query"] = parsedUrl.search.slice(1);
87
138
  if (statusCodeValue === SPAN_STATUS_CODE_ERROR) attributes["error.type"] = statusCode.toString();
88
139
  writeNetworkSpan(outputDir, testId, traceHeader, {
89
140
  traceId,
@@ -94,7 +145,8 @@ async function fixtureCaptureRequestResponse({ request, response, testId, output
94
145
  startTime,
95
146
  endTime,
96
147
  status: { code: statusCodeValue },
97
- attributes
148
+ attributes,
149
+ serviceName: "playwright-browser"
98
150
  });
99
151
  }
100
152
 
@@ -118,8 +170,15 @@ const test = test$1.extend({
118
170
  await use(context);
119
171
  },
120
172
  page: async ({ page, testTraceInfo: { testId, outputDir } }, use) => {
173
+ const pageGuid = page._guid;
174
+ writePageTestMapping(outputDir, testId, pageGuid);
175
+ const pendingRequests = /* @__PURE__ */ new Map();
176
+ page.on("response", (response) => {
177
+ pendingRequests.set(response.request(), response);
178
+ });
121
179
  page.on("requestfinished", async (request) => {
122
- const response = await request.response();
180
+ const response = pendingRequests.get(request);
181
+ pendingRequests.delete(request);
123
182
  if (!response) return;
124
183
  await fixtureCaptureRequestResponse({
125
184
  request,
@@ -0,0 +1,46 @@
1
+ import { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult, TestStep } from "@playwright/test/reporter";
2
+
3
+ //#region src/reporter/reporter.d.ts
4
+ interface PlaywrightOpentelemetryReporterOptions {
5
+ otlpEndpoint?: string;
6
+ otlpHeaders?: Record<string, string>;
7
+ storeTraceZip?: boolean;
8
+ serviceName?: string;
9
+ debug?: boolean;
10
+ }
11
+ declare class PlaywrightOpentelemetryReporter implements Reporter {
12
+ private options;
13
+ private spans;
14
+ private rootDir?;
15
+ private playwrightVersion?;
16
+ private resolvedEndpoint;
17
+ private resolvedHeaders;
18
+ private resolvedServiceName;
19
+ /** Maps test.id to its project's outputDir */
20
+ private testOutputDirs;
21
+ /** File system watchers for output directories */
22
+ private directoryWatchers;
23
+ private testSpans;
24
+ private testTraceIds;
25
+ private stepSpanIds;
26
+ /** Tracks the span context stack per test for append-only file writes */
27
+ private spanContextStacks;
28
+ constructor(options?: PlaywrightOpentelemetryReporterOptions);
29
+ onBegin(config: FullConfig, suite: Suite): void;
30
+ onTestBegin(test: TestCase): void;
31
+ onStepBegin(test: TestCase, _result: TestResult, step: TestStep): Promise<void>;
32
+ onStepEnd(test: TestCase, _result: TestResult, _step: TestStep): void;
33
+ onTestEnd(test: TestCase, result: TestResult): Promise<void>;
34
+ onEnd(_result: FullResult): Promise<void>;
35
+ private processTestStep;
36
+ onStdOut(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
37
+ onStdErr(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
38
+ printsToStdio(): boolean;
39
+ /**
40
+ * Get the output directory for a test ID.
41
+ * Throws if the test ID was not registered in onBegin.
42
+ */
43
+ private getOutputDir;
44
+ }
45
+ //#endregion
46
+ export { PlaywrightOpentelemetryReporterOptions as n, PlaywrightOpentelemetryReporter as t };
@@ -0,0 +1,28 @@
1
+ import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-DnwmzWGb.mjs";
2
+ import { TestCase, TestStatus } from "@playwright/test/reporter";
3
+
4
+ //#region src/reporter/trace-zip-builder.d.ts
5
+
6
+ /**
7
+ * Test metadata stored in test.json at the root of the trace zip.
8
+ */
9
+ interface TestInfo {
10
+ /** Test name (from test.title) */
11
+ name: string;
12
+ /** Describe blocks containing this test (from titlePath, excluding root/project/file/test) */
13
+ describes: string[];
14
+ /** Relative file path to the test file */
15
+ file: string;
16
+ /** Line number where the test is defined */
17
+ line: number;
18
+ /** Test result status */
19
+ status: TestStatus;
20
+ /** OpenTelemetry trace ID for this test */
21
+ traceId: string;
22
+ /** Start time in nanoseconds since Unix epoch (as string to preserve precision) */
23
+ startTimeUnixNano: string;
24
+ /** End time in nanoseconds since Unix epoch (as string to preserve precision) */
25
+ endTimeUnixNano: string;
26
+ }
27
+ //#endregion
28
+ export { type PlaywrightOpentelemetryReporterOptions, type TestInfo, PlaywrightOpentelemetryReporter as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-Bg93NdnD.mjs";
2
+
3
+ //#region src/index.ts
4
+ var src_default = PlaywrightOpentelemetryReporter;
5
+
6
+ //#endregion
7
+ export { src_default as default };
@@ -0,0 +1,451 @@
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-BbTTP4-y.mjs";
2
+ import { existsSync, mkdirSync, watch } from "node:fs";
3
+ import path from "node:path";
4
+ import fs from "node:fs/promises";
5
+ import { BlobWriter, TextReader, ZipWriter } from "@zip.js/zip.js";
6
+
7
+ //#region src/reporter/otel-attributes.ts
8
+ const ATTR_CODE_FILE_PATH = "code.file.path";
9
+ const ATTR_CODE_LINE_NUMBER = "code.line.number";
10
+ const ATTR_TEST_CASE_NAME = "test.case.name";
11
+ const ATTR_TEST_CASE_TITLE = "test.case.title";
12
+ const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
13
+
14
+ //#endregion
15
+ //#region src/reporter/reporter-attributes.ts
16
+ const TEST_SPAN_NAME = "playwright.test";
17
+ const TEST_STEP_SPAN_NAME = "playwright.test.step";
18
+ const ATTR_TEST_STEP_NAME = "test.step.name";
19
+ const ATTR_TEST_STEP_TITLE = "test.step.title";
20
+ const ATTR_TEST_STEP_CATEGORY = "test.step.category";
21
+
22
+ //#endregion
23
+ //#region package.json
24
+ var version = "0.2.0";
25
+
26
+ //#endregion
27
+ //#region src/reporter/sender.ts
28
+ function dateToNanoseconds(date) {
29
+ return (BigInt(date.getTime()) * BigInt(1e6)).toString();
30
+ }
31
+ function toOtlpAttributes(attributes) {
32
+ return Object.entries(attributes).map(([key, value]) => {
33
+ if (typeof value === "number") return {
34
+ key,
35
+ value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
36
+ };
37
+ else if (typeof value === "boolean") return {
38
+ key,
39
+ value: { boolValue: value }
40
+ };
41
+ else return {
42
+ key,
43
+ value: { stringValue: value }
44
+ };
45
+ });
46
+ }
47
+ const SPAN_KIND_INTERNAL = 1;
48
+ function buildResourceSpan(spans, serviceName, playwrightVersion) {
49
+ const otlpSpans = spans.map((span) => ({
50
+ traceId: span.traceId,
51
+ spanId: span.spanId,
52
+ parentSpanId: span.parentSpanId || void 0,
53
+ name: span.name,
54
+ kind: span.kind ?? SPAN_KIND_INTERNAL,
55
+ startTimeUnixNano: dateToNanoseconds(span.startTime),
56
+ endTimeUnixNano: dateToNanoseconds(span.endTime),
57
+ attributes: toOtlpAttributes(span.attributes),
58
+ droppedAttributesCount: 0,
59
+ events: [],
60
+ droppedEventsCount: 0,
61
+ status: span.status,
62
+ links: [],
63
+ droppedLinksCount: 0
64
+ }));
65
+ return {
66
+ resource: { attributes: [
67
+ {
68
+ key: "service.name",
69
+ value: { stringValue: serviceName }
70
+ },
71
+ {
72
+ key: "service.namespace",
73
+ value: { stringValue: "playwright" }
74
+ },
75
+ {
76
+ key: "service.version",
77
+ value: { stringValue: playwrightVersion }
78
+ }
79
+ ] },
80
+ scopeSpans: [{
81
+ scope: {
82
+ name: "playwright-opentelemetry",
83
+ version
84
+ },
85
+ spans: otlpSpans
86
+ }]
87
+ };
88
+ }
89
+ function buildOtlpRequest(spans, serviceName, playwrightVersion) {
90
+ const spansByService = /* @__PURE__ */ new Map();
91
+ for (const span of spans) {
92
+ const spanServiceName = span.serviceName ?? serviceName;
93
+ const serviceSpans = spansByService.get(spanServiceName);
94
+ if (serviceSpans) serviceSpans.push(span);
95
+ else spansByService.set(spanServiceName, [span]);
96
+ }
97
+ const resourceSpans = [];
98
+ for (const [svcName, svcSpans] of spansByService) resourceSpans.push(buildResourceSpan(svcSpans, svcName, playwrightVersion));
99
+ return { resourceSpans };
100
+ }
101
+ async function sendSpans(spans, options) {
102
+ if (spans.length === 0) return;
103
+ const endpoint = options.tracesEndpoint;
104
+ const headers = options.headers || {};
105
+ const body = JSON.stringify(buildOtlpRequest(spans, options.serviceName, options.playwrightVersion));
106
+ if (options.debug) console.log("Sending spans to", endpoint);
107
+ const response = await fetch(endpoint, {
108
+ method: "POST",
109
+ body,
110
+ headers: {
111
+ "content-type": "application/json",
112
+ ...headers
113
+ }
114
+ });
115
+ if (!response.ok) {
116
+ const error = await response.text();
117
+ throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
118
+ }
119
+ }
120
+
121
+ //#endregion
122
+ //#region src/reporter/trace-zip-builder.ts
123
+ /**
124
+ * Get the zip filename based on test location and ID.
125
+ * Format: {basename(file)}:{line}-{testId}-pw-otel.zip
126
+ * Fallback: {testId}-pw-otel.zip (if no location info)
127
+ */
128
+ function getZipFilename(test, testId) {
129
+ if (test.location) return `${path.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
130
+ return `${testId}-pw-otel.zip`;
131
+ }
132
+ /**
133
+ * Get all screenshots for a test from its dedicated screenshots directory.
134
+ * Returns a Map of filename -> file buffer.
135
+ */
136
+ async function getTestScreenshots(outputDir, testId) {
137
+ const screenshots = /* @__PURE__ */ new Map();
138
+ const screenshotsDir = getScreenshotsDir(outputDir, testId);
139
+ 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
+ }
147
+ } catch (err) {
148
+ if (err.code !== "ENOENT") throw err;
149
+ }
150
+ return screenshots;
151
+ }
152
+ /**
153
+ * Build the TestInfo object for test.json.
154
+ */
155
+ function buildTestInfo(options, traceId) {
156
+ const { test, relativeFilePath, status, startTime, duration } = options;
157
+ const titlePath = test.titlePath();
158
+ const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
159
+ const line = test.location?.line ?? 0;
160
+ const startTimeUnixNano = (startTime.getTime() * 1e6).toString();
161
+ const endTimeUnixNano = ((startTime.getTime() + duration) * 1e6).toString();
162
+ return {
163
+ name: test.title,
164
+ describes,
165
+ file: relativeFilePath,
166
+ line,
167
+ status,
168
+ traceId,
169
+ startTimeUnixNano,
170
+ endTimeUnixNano
171
+ };
172
+ }
173
+ /**
174
+ * Create a zip file containing the OTLP trace JSON, test.json, and screenshots for a test.
175
+ */
176
+ async function createTraceZip(options) {
177
+ const { outputDir, testId, test, spans, serviceName, playwrightVersion } = options;
178
+ const otlpRequest = buildOtlpRequest(spans, serviceName, playwrightVersion);
179
+ const traceJson = JSON.stringify(otlpRequest, null, 2);
180
+ const testInfo = buildTestInfo(options, spans.find((s) => s.name === "playwright.test")?.traceId ?? "");
181
+ const testInfoJson = JSON.stringify(testInfo, null, 2);
182
+ const screenshots = await getTestScreenshots(outputDir, testId);
183
+ const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
184
+ await zipWriter.add("test.json", new TextReader(testInfoJson));
185
+ 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
+ }
190
+ const zipBlob = await zipWriter.close();
191
+ const zipFilename = getZipFilename(test, testId);
192
+ const zipPath = path.join(outputDir, zipFilename);
193
+ const arrayBuffer = await zipBlob.arrayBuffer();
194
+ await fs.writeFile(zipPath, Buffer.from(arrayBuffer));
195
+ }
196
+
197
+ //#endregion
198
+ //#region src/reporter/reporter.ts
199
+ var PlaywrightOpentelemetryReporter = class {
200
+ spans = [];
201
+ rootDir;
202
+ playwrightVersion;
203
+ resolvedEndpoint;
204
+ resolvedHeaders;
205
+ resolvedServiceName;
206
+ /** Maps test.id to its project's outputDir */
207
+ testOutputDirs = /* @__PURE__ */ new Map();
208
+ /** File system watchers for output directories */
209
+ directoryWatchers = [];
210
+ testSpans = /* @__PURE__ */ new Map();
211
+ testTraceIds = /* @__PURE__ */ new Map();
212
+ stepSpanIds = /* @__PURE__ */ new Map();
213
+ /** Tracks the span context stack per test for append-only file writes */
214
+ spanContextStacks = /* @__PURE__ */ new Map();
215
+ constructor(options = {}) {
216
+ this.options = options;
217
+ this.resolvedEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || options.otlpEndpoint || "";
218
+ const envHeaders = process.env.OTEL_EXPORTER_OTLP_HEADERS ? parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS) : {};
219
+ this.resolvedHeaders = {
220
+ ...options.otlpHeaders,
221
+ ...envHeaders
222
+ };
223
+ this.resolvedServiceName = process.env.OTEL_SERVICE_NAME || options.serviceName || "playwright-tests";
224
+ if (!this.resolvedEndpoint && !this.options.storeTraceZip) throw new Error(getConfigurationErrorMessage());
225
+ }
226
+ onBegin(config, suite) {
227
+ this.rootDir = config.rootDir;
228
+ this.playwrightVersion = config.version;
229
+ const watchedDirs = /* @__PURE__ */ new Set();
230
+ for (const test of suite.allTests()) {
231
+ const project = test.parent.project();
232
+ if (project?.outputDir) {
233
+ this.testOutputDirs.set(test.id, project.outputDir);
234
+ mkdirSync(path.join(project.outputDir, PW_OTEL_DIR), { recursive: true });
235
+ if (this.options.storeTraceZip && !watchedDirs.has(project.outputDir)) {
236
+ watchedDirs.add(project.outputDir);
237
+ const watcher = watch(project.outputDir, { recursive: true }, (_eventType, filename) => {
238
+ if (!filename || !filename.endsWith(".jpg") && !filename.endsWith(".jpeg")) return;
239
+ const sourcePath = path.join(project.outputDir, filename);
240
+ if (!existsSync(sourcePath)) return;
241
+ const basename = path.basename(filename);
242
+ const lastDashIndex = basename.lastIndexOf("-");
243
+ if (lastDashIndex === -1) return;
244
+ const pageGuid = basename.slice(0, lastDashIndex);
245
+ try {
246
+ copyScreenshotForTest(project.outputDir, pageGuid, sourcePath, basename);
247
+ } catch (_err) {}
248
+ });
249
+ this.directoryWatchers.push(watcher);
250
+ }
251
+ }
252
+ }
253
+ }
254
+ onTestBegin(test) {
255
+ const testId = test.id;
256
+ const outputDir = this.getOutputDir(testId);
257
+ const traceId = getOrCreateTraceId(outputDir, testId);
258
+ this.testTraceIds.set(testId, traceId);
259
+ const testSpanId = generateSpanId();
260
+ this.testSpans.set(testId, testSpanId);
261
+ this.spanContextStacks.set(testId, [testSpanId]);
262
+ writeCurrentSpanId(outputDir, testId, testSpanId);
263
+ createNetworkDirs(outputDir, testId);
264
+ }
265
+ async onStepBegin(test, _result, step) {
266
+ const testId = test.id;
267
+ const outputDir = this.getOutputDir(testId);
268
+ const stepId = getStepId(test, step);
269
+ const stepSpanId = generateSpanId();
270
+ this.stepSpanIds.set(stepId, stepSpanId);
271
+ const stack = this.spanContextStacks.get(testId);
272
+ if (stack) {
273
+ stack.push(stepSpanId);
274
+ writeCurrentSpanId(outputDir, testId, stepSpanId);
275
+ }
276
+ }
277
+ onStepEnd(test, _result, _step) {
278
+ const testId = test.id;
279
+ const outputDir = this.getOutputDir(testId);
280
+ const stack = this.spanContextStacks.get(testId);
281
+ if (stack && stack.length > 1) {
282
+ stack.pop();
283
+ const currentParent = stack[stack.length - 1];
284
+ writeCurrentSpanId(outputDir, testId, currentParent);
285
+ }
286
+ }
287
+ async onTestEnd(test, result) {
288
+ const testId = test.id;
289
+ const outputDir = this.getOutputDir(testId);
290
+ const traceId = this.testTraceIds.get(testId);
291
+ const testSpanId = this.testSpans.get(testId);
292
+ if (!traceId || !testSpanId) throw new Error(`Test ${testId} not found`);
293
+ const attributes = {};
294
+ const titlePath = test.titlePath();
295
+ if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
296
+ attributes[ATTR_TEST_CASE_TITLE] = test.title;
297
+ attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status;
298
+ if (test.location) {
299
+ const { file, line } = test.location;
300
+ attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
301
+ attributes[ATTR_CODE_LINE_NUMBER] = line;
302
+ }
303
+ const processedSteps = /* @__PURE__ */ new Map();
304
+ if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps);
305
+ const stepSpans = [];
306
+ for (const [key, stepSpan] of processedSteps.entries()) if (!key.startsWith("__skip__")) stepSpans.push(stepSpan);
307
+ const networkSpans = await collectNetworkSpans(outputDir, testId);
308
+ let minStartTime = result.startTime;
309
+ let maxEndTime = new Date(result.startTime.getTime() + result.duration);
310
+ for (const stepSpan of stepSpans) {
311
+ if (stepSpan.startTime < minStartTime) minStartTime = stepSpan.startTime;
312
+ if (stepSpan.endTime > maxEndTime) maxEndTime = stepSpan.endTime;
313
+ }
314
+ for (const networkSpan of networkSpans) {
315
+ if (networkSpan.startTime < minStartTime) minStartTime = networkSpan.startTime;
316
+ if (networkSpan.endTime > maxEndTime) maxEndTime = networkSpan.endTime;
317
+ }
318
+ const testSpans = [
319
+ {
320
+ traceId,
321
+ spanId: testSpanId,
322
+ name: TEST_SPAN_NAME,
323
+ startTime: minStartTime,
324
+ endTime: maxEndTime,
325
+ attributes,
326
+ status: { code: result.status === test.expectedStatus ? 1 : 2 }
327
+ },
328
+ ...stepSpans,
329
+ ...networkSpans
330
+ ];
331
+ this.spans.push(...testSpans);
332
+ if (this.options.storeTraceZip) {
333
+ const relativeFilePath = test.location && this.rootDir ? path.relative(this.rootDir, test.location.file) : test.location?.file ?? "";
334
+ const computedDuration = maxEndTime.getTime() - minStartTime.getTime();
335
+ await createTraceZip({
336
+ outputDir,
337
+ testId,
338
+ test,
339
+ spans: testSpans,
340
+ serviceName: this.resolvedServiceName,
341
+ playwrightVersion: this.playwrightVersion || "unknown",
342
+ relativeFilePath,
343
+ status: result.status,
344
+ startTime: minStartTime,
345
+ duration: computedDuration
346
+ });
347
+ }
348
+ }
349
+ async onEnd(_result) {
350
+ for (const watcher of this.directoryWatchers) watcher.close();
351
+ this.directoryWatchers = [];
352
+ if (this.resolvedEndpoint) await sendSpans(this.spans, {
353
+ tracesEndpoint: this.resolvedEndpoint,
354
+ headers: this.resolvedHeaders,
355
+ serviceName: this.resolvedServiceName,
356
+ playwrightVersion: this.playwrightVersion || "unknown",
357
+ debug: this.options.debug ?? false
358
+ });
359
+ for (const [testId, outputDir] of this.testOutputDirs.entries()) await cleanupTestFiles(outputDir, testId);
360
+ }
361
+ processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps) {
362
+ const isInternalFixture = step.category === "fixture" && step.location?.file.includes("playwright-opentelemetry") && (step.location?.file.endsWith("fixture.mjs") || step.location?.file.endsWith("fixture/index.ts"));
363
+ const stepId = getStepId(test, step);
364
+ if (isInternalFixture) {
365
+ processedSteps.set(`__skip__${stepId}`, {});
366
+ if (processedSteps.has(stepId)) processedSteps.delete(stepId);
367
+ if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
368
+ return;
369
+ }
370
+ if (processedSteps.has(`__skip__${stepId}`)) {
371
+ if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
372
+ return;
373
+ }
374
+ const currentTitlePath = [...parentTitlePath, step.title];
375
+ const stepSpanId = this.stepSpanIds.get(stepId) ?? generateSpanId();
376
+ const existingSpan = processedSteps.get(stepId);
377
+ if (existingSpan) {
378
+ if (step.location && !existingSpan.attributes[ATTR_CODE_FILE_PATH]) {
379
+ const { file, line } = step.location;
380
+ const relativePath = this.rootDir ? path.relative(this.rootDir, file) : file;
381
+ existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
382
+ existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
383
+ }
384
+ if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps);
385
+ return;
386
+ }
387
+ const attributes = {};
388
+ attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
389
+ attributes[ATTR_TEST_STEP_TITLE] = step.title;
390
+ attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
391
+ if (step.location) {
392
+ const { file, line } = step.location;
393
+ attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
394
+ attributes[ATTR_CODE_LINE_NUMBER] = line;
395
+ }
396
+ const stepSpan = {
397
+ traceId,
398
+ spanId: stepSpanId,
399
+ parentSpanId,
400
+ name: TEST_STEP_SPAN_NAME,
401
+ startTime: step.startTime,
402
+ endTime: new Date(step.startTime.getTime() + step.duration),
403
+ attributes,
404
+ status: { code: step.error ? 2 : 1 }
405
+ };
406
+ processedSteps.set(stepId, stepSpan);
407
+ if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps);
408
+ }
409
+ onStdOut(chunk, _test, _result) {
410
+ if (this.options.debug) console.log(chunk.toString().slice(0, -1));
411
+ }
412
+ onStdErr(chunk, _test, _result) {
413
+ if (this.options.debug) console.log(chunk.toString().slice(0, -1));
414
+ }
415
+ printsToStdio() {
416
+ return this.options.debug ?? false;
417
+ }
418
+ /**
419
+ * Get the output directory for a test ID.
420
+ * Throws if the test ID was not registered in onBegin.
421
+ */
422
+ getOutputDir(testId) {
423
+ const outputDir = this.testOutputDirs.get(testId);
424
+ if (!outputDir) throw new Error(`No outputDir found for test "${testId}" - onBegin must be called first and test must exist in suite`);
425
+ return outputDir;
426
+ }
427
+ };
428
+ function parseOtlpHeaders(headersString) {
429
+ const headers = {};
430
+ const pairs = headersString.split(",");
431
+ for (const pair of pairs) {
432
+ const [key, ...valueParts] = pair.split("=");
433
+ if (key && valueParts.length > 0) headers[key.trim()] = valueParts.join("=").trim();
434
+ }
435
+ return headers;
436
+ }
437
+ function getConfigurationErrorMessage() {
438
+ return "playwright-opentelemetry reporter requires an OTLP endpoint 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 export OTEL_SERVICE_NAME=\"my-service\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryReporterOptions } from 'playwright-opentelemetry';\n\nexport default defineConfig({\n reporter: [\n [\n 'playwright-opentelemetry/reporter',\n {\n otlpEndpoint: 'http://localhost:4317/v1/traces',\n otlpHeaders: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n serviceName: 'my-service',\n } satisfies PlaywrightOpentelemetryReporterOptions,\n ],\n ],\n});\n\nNote: Environment variables take precedence over config file options.\n";
439
+ }
440
+ function getStepId(test, step) {
441
+ const startTimeMs = step.startTime.getTime();
442
+ return [
443
+ test.id,
444
+ step.category,
445
+ startTimeMs,
446
+ ...step.titlePath()
447
+ ].join(" > ");
448
+ }
449
+
450
+ //#endregion
451
+ export { PlaywrightOpentelemetryReporter as t };
@@ -1,43 +1,2 @@
1
- import { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult, TestStep } from "@playwright/test/reporter";
2
-
3
- //#region src/reporter/reporter.d.ts
4
- interface PlaywrightOpentelemetryReporterOptions {
5
- otlpEndpoint?: string;
6
- otlpHeaders?: Record<string, string>;
7
- serviceName?: string;
8
- debug?: boolean;
9
- }
10
- declare class PlaywrightOpentelemetryReporter implements Reporter {
11
- private options;
12
- private spans;
13
- private rootDir?;
14
- private playwrightVersion?;
15
- private resolvedEndpoint;
16
- private resolvedHeaders;
17
- private resolvedServiceName;
18
- /** Maps test.id to its project's outputDir */
19
- private testOutputDirs;
20
- private testSpans;
21
- private testTraceIds;
22
- private stepSpanIds;
23
- /** Tracks the span context stack per test for append-only file writes */
24
- private spanContextStacks;
25
- constructor(options?: PlaywrightOpentelemetryReporterOptions);
26
- onBegin(config: FullConfig, suite: Suite): void;
27
- onTestBegin(test: TestCase): void;
28
- onStepBegin(test: TestCase, _result: TestResult, step: TestStep): Promise<void>;
29
- onStepEnd(test: TestCase, _result: TestResult, _step: TestStep): void;
30
- onTestEnd(test: TestCase, result: TestResult): Promise<void>;
31
- onEnd(_result: FullResult): Promise<void>;
32
- private processTestStep;
33
- onStdOut(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
34
- onStdErr(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
35
- printsToStdio(): boolean;
36
- /**
37
- * Get the output directory for a test ID.
38
- * Throws if the test ID was not registered in onBegin.
39
- */
40
- private getOutputDir;
41
- }
42
- //#endregion
43
- export { type PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
1
+ import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-DnwmzWGb.mjs";
2
+ export { PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
package/dist/reporter.mjs CHANGED
@@ -1,317 +1,5 @@
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-BnO7hKxI.mjs";
2
- import { mkdirSync } from "node:fs";
3
- import path from "node:path";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-Bg93NdnD.mjs";
4
2
 
5
- //#region src/reporter/otel-attributes.ts
6
- const ATTR_CODE_FILE_PATH = "code.file.path";
7
- const ATTR_CODE_LINE_NUMBER = "code.line.number";
8
- const ATTR_TEST_CASE_NAME = "test.case.name";
9
- const ATTR_TEST_CASE_TITLE = "test.case.title";
10
- const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
11
-
12
- //#endregion
13
- //#region src/reporter/reporter-attributes.ts
14
- const TEST_SPAN_NAME = "playwright.test";
15
- const TEST_STEP_SPAN_NAME = "playwright.test.step";
16
- const ATTR_TEST_STEP_NAME = "test.step.name";
17
- const ATTR_TEST_STEP_TITLE = "test.step.title";
18
- const ATTR_TEST_STEP_CATEGORY = "test.step.category";
19
-
20
- //#endregion
21
- //#region package.json
22
- var version = "0.1.1";
23
-
24
- //#endregion
25
- //#region src/reporter/sender.ts
26
- function dateToNanoseconds(date) {
27
- return (BigInt(date.getTime()) * BigInt(1e6)).toString();
28
- }
29
- function toOtlpAttributes(attributes) {
30
- return Object.entries(attributes).map(([key, value]) => {
31
- if (typeof value === "number") return {
32
- key,
33
- value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
34
- };
35
- else if (typeof value === "boolean") return {
36
- key,
37
- value: { boolValue: value }
38
- };
39
- else return {
40
- key,
41
- value: { stringValue: value }
42
- };
43
- });
44
- }
45
- const SPAN_KIND_INTERNAL = 1;
46
- function buildOtlpRequest(spans, serviceName, playwrightVersion) {
47
- const otlpSpans = spans.map((span) => ({
48
- traceId: span.traceId,
49
- spanId: span.spanId,
50
- parentSpanId: span.parentSpanId || void 0,
51
- name: span.name,
52
- kind: SPAN_KIND_INTERNAL,
53
- startTimeUnixNano: dateToNanoseconds(span.startTime),
54
- endTimeUnixNano: dateToNanoseconds(span.endTime),
55
- attributes: toOtlpAttributes(span.attributes),
56
- droppedAttributesCount: 0,
57
- events: [],
58
- droppedEventsCount: 0,
59
- status: span.status,
60
- links: [],
61
- droppedLinksCount: 0
62
- }));
63
- return { resourceSpans: [{
64
- resource: { attributes: [
65
- {
66
- key: "service.name",
67
- value: { stringValue: serviceName }
68
- },
69
- {
70
- key: "service.namespace",
71
- value: { stringValue: "playwright" }
72
- },
73
- {
74
- key: "service.version",
75
- value: { stringValue: playwrightVersion }
76
- }
77
- ] },
78
- scopeSpans: [{
79
- scope: {
80
- name: "playwright-opentelemetry",
81
- version
82
- },
83
- spans: otlpSpans
84
- }]
85
- }] };
86
- }
87
- async function sendSpans(spans, options) {
88
- if (spans.length === 0) return;
89
- const endpoint = options.tracesEndpoint;
90
- const headers = options.headers || {};
91
- const body = JSON.stringify(buildOtlpRequest(spans, options.serviceName, options.playwrightVersion));
92
- if (options.debug) console.log("Sending spans to", endpoint);
93
- const response = await fetch(endpoint, {
94
- method: "POST",
95
- body,
96
- headers: {
97
- "content-type": "application/json",
98
- ...headers
99
- }
100
- });
101
- if (!response.ok) {
102
- const error = await response.text();
103
- throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
104
- }
105
- }
106
-
107
- //#endregion
108
- //#region src/reporter/reporter.ts
109
- var PlaywrightOpentelemetryReporter = class {
110
- spans = [];
111
- rootDir;
112
- playwrightVersion;
113
- resolvedEndpoint;
114
- resolvedHeaders;
115
- resolvedServiceName;
116
- /** Maps test.id to its project's outputDir */
117
- testOutputDirs = /* @__PURE__ */ new Map();
118
- testSpans = /* @__PURE__ */ new Map();
119
- testTraceIds = /* @__PURE__ */ new Map();
120
- stepSpanIds = /* @__PURE__ */ new Map();
121
- /** Tracks the span context stack per test for append-only file writes */
122
- spanContextStacks = /* @__PURE__ */ new Map();
123
- constructor(options = {}) {
124
- this.options = options;
125
- this.resolvedEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || options.otlpEndpoint || "";
126
- const envHeaders = process.env.OTEL_EXPORTER_OTLP_HEADERS ? parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS) : {};
127
- this.resolvedHeaders = {
128
- ...options.otlpHeaders,
129
- ...envHeaders
130
- };
131
- this.resolvedServiceName = process.env.OTEL_SERVICE_NAME || options.serviceName || "playwright-tests";
132
- if (!this.resolvedEndpoint) throw new Error(getConfigurationErrorMessage());
133
- }
134
- onBegin(config, suite) {
135
- this.rootDir = config.rootDir;
136
- this.playwrightVersion = config.version;
137
- for (const test of suite.allTests()) {
138
- const project = test.parent.project();
139
- if (project?.outputDir) {
140
- mkdirSync(path.join(project.outputDir, PW_OTEL_DIR), { recursive: true });
141
- this.testOutputDirs.set(test.id, project.outputDir);
142
- }
143
- }
144
- }
145
- onTestBegin(test) {
146
- const testId = test.id;
147
- const outputDir = this.getOutputDir(testId);
148
- const traceId = getOrCreateTraceId(outputDir, testId);
149
- this.testTraceIds.set(testId, traceId);
150
- const testSpanId = generateSpanId();
151
- this.testSpans.set(testId, testSpanId);
152
- this.spanContextStacks.set(testId, [testSpanId]);
153
- writeCurrentSpanId(outputDir, testId, testSpanId);
154
- createNetworkDirs(outputDir, testId);
155
- }
156
- async onStepBegin(test, _result, step) {
157
- const testId = test.id;
158
- const outputDir = this.getOutputDir(testId);
159
- const stepId = getStepId(test, step);
160
- const stepSpanId = generateSpanId();
161
- this.stepSpanIds.set(stepId, stepSpanId);
162
- const stack = this.spanContextStacks.get(testId);
163
- if (stack) {
164
- stack.push(stepSpanId);
165
- writeCurrentSpanId(outputDir, testId, stepSpanId);
166
- }
167
- }
168
- onStepEnd(test, _result, _step) {
169
- const testId = test.id;
170
- const outputDir = this.getOutputDir(testId);
171
- const stack = this.spanContextStacks.get(testId);
172
- if (stack && stack.length > 1) {
173
- stack.pop();
174
- const currentParent = stack[stack.length - 1];
175
- writeCurrentSpanId(outputDir, testId, currentParent);
176
- }
177
- }
178
- async onTestEnd(test, result) {
179
- const testId = test.id;
180
- const outputDir = this.getOutputDir(testId);
181
- const traceId = this.testTraceIds.get(testId);
182
- const testSpanId = this.testSpans.get(testId);
183
- if (!traceId || !testSpanId) throw new Error(`Test ${testId} not found`);
184
- const attributes = {};
185
- const titlePath = test.titlePath();
186
- if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
187
- attributes[ATTR_TEST_CASE_TITLE] = test.title;
188
- attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status;
189
- if (test.location) {
190
- const { file, line } = test.location;
191
- attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
192
- attributes[ATTR_CODE_LINE_NUMBER] = line;
193
- }
194
- const span = {
195
- traceId,
196
- spanId: testSpanId,
197
- name: TEST_SPAN_NAME,
198
- startTime: result.startTime,
199
- endTime: new Date(result.startTime.getTime() + result.duration),
200
- attributes,
201
- status: { code: result.status === test.expectedStatus ? 1 : 2 }
202
- };
203
- this.spans.push(span);
204
- const processedSteps = /* @__PURE__ */ new Map();
205
- if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps);
206
- const networkSpans = await collectNetworkSpans(outputDir, testId);
207
- for (const networkSpan of networkSpans) this.spans.push(networkSpan);
208
- }
209
- async onEnd(_result) {
210
- await sendSpans(this.spans, {
211
- tracesEndpoint: this.resolvedEndpoint,
212
- headers: this.resolvedHeaders,
213
- serviceName: this.resolvedServiceName,
214
- playwrightVersion: this.playwrightVersion || "unknown",
215
- debug: this.options.debug ?? false
216
- });
217
- for (const [testId, outputDir] of this.testOutputDirs.entries()) await cleanupTestFiles(outputDir, testId);
218
- }
219
- processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps) {
220
- const isInternalFixture = step.category === "fixture" && step.location?.file.includes("playwright-opentelemetry") && (step.location?.file.endsWith("fixture.mjs") || step.location?.file.endsWith("fixture/index.ts"));
221
- const stepId = getStepId(test, step);
222
- if (isInternalFixture) {
223
- processedSteps.set(`__skip__${stepId}`, {});
224
- const existingSpan$1 = processedSteps.get(stepId);
225
- if (existingSpan$1) {
226
- const spanIndex = this.spans.indexOf(existingSpan$1);
227
- if (spanIndex !== -1) this.spans.splice(spanIndex, 1);
228
- processedSteps.delete(stepId);
229
- }
230
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
231
- return;
232
- }
233
- if (processedSteps.has(`__skip__${stepId}`)) {
234
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
235
- return;
236
- }
237
- const currentTitlePath = [...parentTitlePath, step.title];
238
- const stepSpanId = this.stepSpanIds.get(stepId) ?? generateSpanId();
239
- const existingSpan = processedSteps.get(stepId);
240
- if (existingSpan) {
241
- if (step.location && !existingSpan.attributes[ATTR_CODE_FILE_PATH]) {
242
- const { file, line } = step.location;
243
- const relativePath = this.rootDir ? path.relative(this.rootDir, file) : file;
244
- existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
245
- existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
246
- }
247
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps);
248
- return;
249
- }
250
- const attributes = {};
251
- attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
252
- attributes[ATTR_TEST_STEP_TITLE] = step.title;
253
- attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
254
- if (step.location) {
255
- const { file, line } = step.location;
256
- attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
257
- attributes[ATTR_CODE_LINE_NUMBER] = line;
258
- }
259
- const stepSpan = {
260
- traceId,
261
- spanId: stepSpanId,
262
- parentSpanId,
263
- name: TEST_STEP_SPAN_NAME,
264
- startTime: step.startTime,
265
- endTime: new Date(step.startTime.getTime() + step.duration),
266
- attributes,
267
- status: { code: step.error ? 2 : 1 }
268
- };
269
- this.spans.push(stepSpan);
270
- processedSteps.set(stepId, stepSpan);
271
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps);
272
- }
273
- onStdOut(chunk, _test, _result) {
274
- if (this.options.debug) console.log(chunk.toString().slice(0, -1));
275
- }
276
- onStdErr(chunk, _test, _result) {
277
- if (this.options.debug) console.log(chunk.toString().slice(0, -1));
278
- }
279
- printsToStdio() {
280
- return this.options.debug ?? false;
281
- }
282
- /**
283
- * Get the output directory for a test ID.
284
- * Throws if the test ID was not registered in onBegin.
285
- */
286
- getOutputDir(testId) {
287
- const outputDir = this.testOutputDirs.get(testId);
288
- if (!outputDir) throw new Error(`No outputDir found for test "${testId}" - onBegin must be called first and test must exist in suite`);
289
- return outputDir;
290
- }
291
- };
292
- function parseOtlpHeaders(headersString) {
293
- const headers = {};
294
- const pairs = headersString.split(",");
295
- for (const pair of pairs) {
296
- const [key, ...valueParts] = pair.split("=");
297
- if (key && valueParts.length > 0) headers[key.trim()] = valueParts.join("=").trim();
298
- }
299
- return headers;
300
- }
301
- function getConfigurationErrorMessage() {
302
- return "playwright-opentelemetry reporter requires an OTLP endpoint 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 export OTEL_SERVICE_NAME=\"my-service\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryReporterOptions } from 'playwright-opentelemetry';\n\nexport default defineConfig({\n reporter: [\n [\n 'playwright-opentelemetry/reporter',\n {\n otlpEndpoint: 'http://localhost:4317/v1/traces',\n otlpHeaders: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n serviceName: 'my-service',\n } satisfies PlaywrightOpentelemetryReporterOptions,\n ],\n ],\n});\n\nNote: Environment variables take precedence over config file options.\n";
303
- }
304
- function getStepId(test, step) {
305
- const startTimeMs = step.startTime.getTime();
306
- return [
307
- test.id,
308
- step.category,
309
- startTimeMs,
310
- ...step.titlePath()
311
- ].join(" > ");
312
- }
313
-
314
- //#endregion
315
3
  //#region src/reporter/index.ts
316
4
  var reporter_default = PlaywrightOpentelemetryReporter;
317
5
 
@@ -4,6 +4,39 @@ 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
+ }
7
40
  function getOrCreateTraceId(outputDir, testId) {
8
41
  const tracePath = getTracePath(outputDir, testId);
9
42
  if (existsSync(tracePath)) return readFileSync(tracePath, "utf-8");
@@ -81,6 +114,28 @@ async function collectNetworkSpans(outputDir, testId) {
81
114
  }
82
115
  }
83
116
  /**
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
+ /**
84
139
  * Cleanup all trace files for a test.
85
140
  * Called by the reporter after onTestEnd has processed the spans.
86
141
  *
@@ -108,6 +163,14 @@ async function cleanupTestFiles(outputDir, testId) {
108
163
  } catch (err) {
109
164
  if (err.code !== "ENOENT") throw err;
110
165
  }
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");
111
174
  }
112
175
  function getTracePath(outputDir, testId) {
113
176
  return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}.trace`);
@@ -148,4 +211,4 @@ function generateSpanId() {
148
211
  }
149
212
 
150
213
  //#endregion
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 };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playwright-opentelemetry",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
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",
@@ -23,7 +23,14 @@
23
23
  "files": [
24
24
  "dist"
25
25
  ],
26
+ "main": "./dist/index.mjs",
27
+ "module": "./dist/index.mjs",
28
+ "types": "./dist/index.d.mts",
26
29
  "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.mts",
32
+ "default": "./dist/index.mjs"
33
+ },
27
34
  "./fixture": {
28
35
  "types": "./dist/fixture.d.mts",
29
36
  "default": "./dist/fixture.mjs"
@@ -40,17 +47,17 @@
40
47
  "devDependencies": {
41
48
  "@biomejs/biome": "2.3.10",
42
49
  "@playwright/test": "^1.57.0",
50
+ "@types/bun": "^1.2.6",
43
51
  "@types/node": "^25.0.3",
44
- "tsdown": "^0.18.1",
45
- "typescript": "^5.9.3",
46
- "vitest": "^4.0.16"
52
+ "tsdown": "^0.18.1"
53
+ },
54
+ "dependencies": {
55
+ "@zip.js/zip.js": "^2.8.11"
47
56
  },
48
57
  "scripts": {
49
58
  "build": "tsdown",
50
59
  "dev": "tsdown --watch",
51
- "test:unit": "vitest",
52
60
  "test:e2e": "playwright test",
53
- "typecheck": "tsc --noEmit",
54
- "format": "biome format --write"
61
+ "verify:trace-zips": "bun scripts/verify-trace-zips.ts"
55
62
  }
56
63
  }