playwright-opentelemetry 0.3.4 → 0.5.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,12 +1,7 @@
1
- import * as _playwright_test0 from "@playwright/test";
1
+ import { createPlaywrightOtelTest } from "./fixture/factory.mjs";
2
+ export * from "@playwright/test";
2
3
 
3
4
  //#region src/fixture/index.d.ts
4
- type TestTraceInfo = {
5
- testId: string;
6
- outputDir: string;
7
- };
8
- declare const test: _playwright_test0.TestType<_playwright_test0.PlaywrightTestArgs & _playwright_test0.PlaywrightTestOptions & {
9
- testTraceInfo: TestTraceInfo;
10
- }, _playwright_test0.PlaywrightWorkerArgs & _playwright_test0.PlaywrightWorkerOptions>;
5
+ declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
11
6
  //#endregion
12
- export { test };
7
+ export { createPlaywrightOtelTest, test };
package/dist/fixture.mjs CHANGED
@@ -1,193 +1,7 @@
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
- import path from "node:path";
1
+ import { t as createPlaywrightOtelTest } from "./factory-Df7HwxXO.mjs";
3
2
  import { test as test$1 } from "@playwright/test";
4
-
5
- //#region src/fixture/network-propagator.ts
6
- /**
7
- * Intercepts network requests to propagate trace context via traceparent header.
8
- * Also records the parent span ID for later correlation by the response handler.
9
- *
10
- * This function only:
11
- * 1. Creates a span ID for the request
12
- * 2. Injects the traceparent header
13
- * 3. Writes a parent file with the current parent span ID
14
- *
15
- * The actual span data (timing, status, attributes) is captured by
16
- * fixtureCaptureRequestResponse when the response is received.
17
- *
18
- * @param options - The propagator options
19
- */
20
- async function fixtureOtelHeaderPropagator({ route, request, testId, outputDir }) {
21
- const traceId = getOrCreateTraceId(outputDir, testId);
22
- const parentSpanId = getCurrentSpanId(outputDir, testId);
23
- const traceHeader = `00-${traceId}-${generateSpanId()}-01`;
24
- writeNetworkSpanParent({
25
- outputDir,
26
- testId,
27
- parentSpanId,
28
- traceHeader
29
- });
30
- await route.fallback({ headers: {
31
- traceparent: traceHeader,
32
- ...request.headers()
33
- } });
34
- }
35
-
36
- //#endregion
37
- //#region src/fixture/request-response-capture.ts
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
- /**
86
- * OpenTelemetry SpanKind values
87
- * @see https://opentelemetry.io/docs/specs/otel/trace/api/#spankind
88
- */
89
- const SPAN_KIND_CLIENT = 3;
90
- /**
91
- * OpenTelemetry SpanStatusCode values
92
- * @see https://opentelemetry.io/docs/specs/otel/trace/api/#set-status
93
- */
94
- const SPAN_STATUS_CODE_UNSET = 0;
95
- const SPAN_STATUS_CODE_ERROR = 2;
96
- /**
97
- * Captures request/response data and writes the complete network span.
98
- * Called from page.on("response") after the request has completed.
99
- *
100
- * This function:
101
- * 1. Extracts the traceparent header to find the parent file
102
- * 2. Reads the parent span ID from the parent file
103
- * 3. Builds the complete span with all HTTP attributes
104
- * 4. Writes the network span for the reporter to collect
105
- *
106
- * @param options - The capture options
107
- */
108
- async function fixtureCaptureRequestResponse({ request, response, testId, outputDir }) {
109
- const url = request.url();
110
- const method = request.method();
111
- const statusCode = response.status();
112
- const traceHeader = await request.headerValue("traceparent");
113
- if (!traceHeader) throw new Error(`No traceparent header found for request ${request.url()}`);
114
- const parentSpanId = readNetworkSpanParent(outputDir, testId, traceHeader);
115
- if (!parentSpanId) throw new Error(`No parent span ID found for trace header ${traceHeader}`);
116
- const parts = traceHeader.split("-");
117
- if (parts.length !== 4) return;
118
- const [, traceId, spanId] = parts;
119
- const timing = request.timing();
120
- const startTime = new Date(timing.startTime);
121
- const endTime = timing.responseEnd >= 0 ? new Date(timing.startTime + timing.responseEnd) : new Date(timing.startTime);
122
- const parsedUrl = new URL(url);
123
- const serverAddress = parsedUrl.hostname;
124
- const serverPort = parsedUrl.port !== "" ? Number.parseInt(parsedUrl.port, 10) : parsedUrl.protocol === "https:" ? 443 : 80;
125
- let statusCodeValue = SPAN_STATUS_CODE_UNSET;
126
- if (statusCode >= 400) statusCodeValue = SPAN_STATUS_CODE_ERROR;
127
- const resourceType = detectResourceType(await response.headerValue("content-type"), url);
128
- const attributes = {
129
- "http.request.method": method,
130
- "url.full": url,
131
- "url.path": parsedUrl.pathname,
132
- "server.address": serverAddress,
133
- "server.port": serverPort,
134
- "http.response.status_code": statusCode,
135
- "http.resource.type": resourceType
136
- };
137
- if (parsedUrl.search) attributes["url.query"] = parsedUrl.search.slice(1);
138
- if (statusCodeValue === SPAN_STATUS_CODE_ERROR) attributes["error.type"] = statusCode.toString();
139
- writeNetworkSpan(outputDir, testId, traceHeader, {
140
- traceId,
141
- spanId,
142
- parentSpanId,
143
- name: `HTTP ${method}`,
144
- kind: SPAN_KIND_CLIENT,
145
- startTime,
146
- endTime,
147
- status: { code: statusCodeValue },
148
- attributes,
149
- serviceName: "playwright-browser"
150
- });
151
- }
152
-
153
- //#endregion
3
+ export * from "@playwright/test";
154
4
  //#region src/fixture/index.ts
155
- const test = test$1.extend({
156
- testTraceInfo: [async ({ playwright }, use, testInfo) => {
157
- const outputDir = path.dirname(testInfo.outputDir);
158
- await use({
159
- testId: testInfo.testId,
160
- outputDir
161
- });
162
- }, { auto: true }],
163
- context: async ({ context, testTraceInfo: { testId, outputDir } }, use) => {
164
- context.route("**", async (route, request) => await fixtureOtelHeaderPropagator({
165
- route,
166
- request,
167
- testId,
168
- outputDir
169
- }));
170
- await use(context);
171
- },
172
- page: async ({ page, testTraceInfo: { testId, outputDir } }, use) => {
173
- const pendingRequests = /* @__PURE__ */ new Map();
174
- page.on("response", (response) => {
175
- pendingRequests.set(response.request(), response);
176
- });
177
- page.on("requestfinished", async (request) => {
178
- const response = pendingRequests.get(request);
179
- pendingRequests.delete(request);
180
- if (!response) return;
181
- await fixtureCaptureRequestResponse({
182
- request,
183
- response,
184
- testId,
185
- outputDir
186
- });
187
- });
188
- await use(page);
189
- }
190
- });
191
-
5
+ const test = createPlaywrightOtelTest(test$1);
192
6
  //#endregion
193
- export { test };
7
+ export { createPlaywrightOtelTest, test };
@@ -39,7 +39,7 @@ declare class PlaywrightOpentelemetryReporter implements Reporter {
39
39
  onStdErr(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
40
40
  printsToStdio(): boolean;
41
41
  private getOutputDir;
42
- private sendTestJsonToTraceApi;
42
+ private sendScreenshotsToTraceApi;
43
43
  }
44
44
  //#endregion
45
45
  export { PlaywrightOpentelemetryReporterOptions as n, PlaywrightOpentelemetryReporter as t };
@@ -0,0 +1,45 @@
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
+ playwrightTraceApiEndpoint?: string;
8
+ playwrightTraceApiHeaders?: Record<string, string>;
9
+ storeTraceZip?: boolean;
10
+ serviceName?: string;
11
+ debug?: boolean;
12
+ }
13
+ declare class PlaywrightOpentelemetryReporter implements Reporter {
14
+ private options;
15
+ private spans;
16
+ private rootDir?;
17
+ private playwrightVersion?;
18
+ private resolvedEndpoint;
19
+ private resolvedHeaders;
20
+ private resolvedTraceApiEndpoint;
21
+ private resolvedTraceApiHeaders;
22
+ private resolvedServiceName;
23
+ /** Maps test.id to its project's outputDir */
24
+ private testOutputDirs;
25
+ private testSpans;
26
+ private testTraceIds;
27
+ private stepSpanIds;
28
+ /** Tracks the span context stack per test for append-only file writes */
29
+ private spanContextStacks;
30
+ constructor(options?: PlaywrightOpentelemetryReporterOptions);
31
+ onBegin(config: FullConfig, suite: Suite): void;
32
+ onTestBegin(test: TestCase, result: TestResult): void;
33
+ onStepBegin(test: TestCase, _result: TestResult, step: TestStep): Promise<void>;
34
+ onStepEnd(test: TestCase, _result: TestResult, _step: TestStep): void;
35
+ onTestEnd(test: TestCase, result: TestResult): Promise<void>;
36
+ onEnd(_result: FullResult): Promise<void>;
37
+ private processTestStep;
38
+ onStdOut(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
39
+ onStdErr(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
40
+ printsToStdio(): boolean;
41
+ private getOutputDir;
42
+ private sendScreenshotsToTraceApi;
43
+ }
44
+ //#endregion
45
+ export { PlaywrightOpentelemetryReporterOptions as n, PlaywrightOpentelemetryReporter as t };
package/dist/index.cjs ADDED
@@ -0,0 +1,4 @@
1
+ //#region src/index.ts
2
+ var src_default = require("./reporter-BzHSG-gx.cjs").PlaywrightOpentelemetryReporter;
3
+ //#endregion
4
+ module.exports = src_default;
@@ -0,0 +1,2 @@
1
+ import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-BNfDd8Mg.cjs";
2
+ export { type PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
package/dist/index.d.mts CHANGED
@@ -1,28 +1,2 @@
1
- import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-CD_ZrFf2.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 };
1
+ import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-BNfDd8Mg.mjs";
2
+ export { type PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
package/dist/index.mjs CHANGED
@@ -1,7 +1,5 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-DuWkTUh0.mjs";
2
-
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-BE9S9CtV.mjs";
3
2
  //#region src/index.ts
4
3
  var src_default = PlaywrightOpentelemetryReporter;
5
-
6
4
  //#endregion
7
- export { src_default as default };
5
+ export { src_default as default };
@@ -1,16 +1,14 @@
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";
1
+ import { a as createNetworkDirs, c as getOrCreateTraceId, d as writeCurrentSpanId, i as collectNetworkSpans, n as cleanupTestFiles, o as generateSpanId, r as collectBrowserPageSpans, t as PW_OTEL_DIR } from "./trace-files-B6bmvwUq.mjs";
2
2
  import { mkdirSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import fs from "node:fs/promises";
5
- import { BlobReader, BlobWriter, TextReader, ZipReader, ZipWriter } from "@zip.js/zip.js";
6
-
5
+ import { BlobReader, BlobWriter, ZipReader, ZipWriter } from "@zip.js/zip.js";
7
6
  //#region src/reporter/otel-attributes.ts
8
7
  const ATTR_CODE_FILE_PATH = "code.file.path";
9
8
  const ATTR_CODE_LINE_NUMBER = "code.line.number";
10
9
  const ATTR_TEST_CASE_NAME = "test.case.name";
11
10
  const ATTR_TEST_CASE_TITLE = "test.case.title";
12
11
  const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
13
-
14
12
  //#endregion
15
13
  //#region src/reporter/reporter-attributes.ts
16
14
  const TEST_SPAN_NAME = "playwright.test";
@@ -18,11 +16,9 @@ const TEST_STEP_SPAN_NAME = "playwright.test.step";
18
16
  const ATTR_TEST_STEP_NAME = "test.step.name";
19
17
  const ATTR_TEST_STEP_TITLE = "test.step.title";
20
18
  const ATTR_TEST_STEP_CATEGORY = "test.step.category";
21
-
22
19
  //#endregion
23
20
  //#region package.json
24
- var version = "0.3.4";
25
-
21
+ var version = "0.5.0";
26
22
  //#endregion
27
23
  //#region src/reporter/sender.ts
28
24
  function dateToNanoseconds(date) {
@@ -30,7 +26,11 @@ function dateToNanoseconds(date) {
30
26
  }
31
27
  function toOtlpAttributes(attributes) {
32
28
  return Object.entries(attributes).map(([key, value]) => {
33
- if (typeof value === "number") return {
29
+ if (Array.isArray(value)) return {
30
+ key,
31
+ value: { arrayValue: { values: value.map((item) => ({ stringValue: item })) } }
32
+ };
33
+ else if (typeof value === "number") return {
34
34
  key,
35
35
  value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
36
36
  };
@@ -117,7 +117,6 @@ async function sendSpans(spans, options) {
117
117
  throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
118
118
  }
119
119
  }
120
-
121
120
  //#endregion
122
121
  //#region src/reporter/trace-zip-builder.ts
123
122
  /**
@@ -166,38 +165,14 @@ async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
166
165
  return screenshots;
167
166
  }
168
167
  /**
169
- * Build the TestInfo object for test.json.
170
- */
171
- function buildTestInfo(options, traceId) {
172
- const { test, relativeFilePath, status, startTime, duration } = options;
173
- const titlePath = test.titlePath();
174
- const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
175
- const line = test.location?.line ?? 0;
176
- const startTimeUnixNano = (startTime.getTime() * 1e6).toString();
177
- const endTimeUnixNano = ((startTime.getTime() + duration) * 1e6).toString();
178
- return {
179
- name: test.title,
180
- describes,
181
- file: relativeFilePath,
182
- line,
183
- status,
184
- traceId,
185
- startTimeUnixNano,
186
- endTimeUnixNano
187
- };
188
- }
189
- /**
190
- * Create a zip file containing the OTLP trace JSON, test.json, and screenshots for a test.
168
+ * Create a zip file containing the OTLP trace JSON and screenshots for a test.
191
169
  */
192
170
  async function createTraceZip(options) {
193
171
  const { outputDir, test, spans, serviceName, playwrightVersion, screenshots } = options;
194
172
  const otlpRequest = buildOtlpRequest(spans, serviceName, playwrightVersion);
195
173
  const traceJson = JSON.stringify(otlpRequest, null, 2);
196
- const testInfo = buildTestInfo(options, spans.find((s) => s.name === "playwright.test")?.traceId ?? "");
197
- const testInfoJson = JSON.stringify(testInfo, null, 2);
198
174
  const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
199
- await zipWriter.add("test.json", new TextReader(testInfoJson));
200
- await zipWriter.add("opentelemetry-protocol/playwright-opentelemetry.json", new TextReader(traceJson));
175
+ await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
201
176
  await Promise.all(Array.from(screenshots.entries()).map(([filename, blob]) => zipWriter.add(`screenshots/${filename}`, blob.stream())));
202
177
  const zipBlob = await zipWriter.close();
203
178
  const zipFilename = getZipFilename(test, test.id);
@@ -208,10 +183,10 @@ async function createTraceZip(options) {
208
183
  function isFileEntry(entry) {
209
184
  return !entry.directory;
210
185
  }
211
-
212
186
  //#endregion
213
187
  //#region src/reporter/reporter.ts
214
188
  var PlaywrightOpentelemetryReporter = class {
189
+ options;
215
190
  spans = [];
216
191
  rootDir;
217
192
  playwrightVersion;
@@ -256,11 +231,6 @@ var PlaywrightOpentelemetryReporter = class {
256
231
  const outputDir = this.getOutputDir(testId);
257
232
  const traceId = getOrCreateTraceId(outputDir, testId);
258
233
  this.testTraceIds.set(testId, traceId);
259
- result.attachments.push({
260
- name: "playwright-opentelemetry-trace-id",
261
- contentType: "text/plain",
262
- body: Buffer.from(traceId, "utf-8")
263
- });
264
234
  const testSpanId = generateSpanId();
265
235
  this.testSpans.set(testId, testSpanId);
266
236
  this.spanContextStacks.set(testId, [testSpanId]);
@@ -295,11 +265,21 @@ var PlaywrightOpentelemetryReporter = class {
295
265
  const traceId = this.testTraceIds.get(testId);
296
266
  const testSpanId = this.testSpans.get(testId);
297
267
  if (!traceId || !testSpanId) throw new Error(`Test ${testId} not found`);
268
+ const traceAttachment = result.attachments.find((attachment) => attachment.name === "trace" && attachment.contentType === "application/zip" && attachment.path);
269
+ if (!traceAttachment?.path) return;
270
+ result.attachments.push({
271
+ name: "playwright-opentelemetry-trace-id",
272
+ contentType: "text/plain",
273
+ body: Buffer.from(traceId, "utf-8")
274
+ });
298
275
  const attributes = {};
299
276
  const titlePath = test.titlePath();
300
277
  if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
278
+ const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
301
279
  attributes[ATTR_TEST_CASE_TITLE] = test.title;
302
- attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status;
280
+ attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status === "passed" ? "pass" : "fail";
281
+ attributes["playwright.test.status"] = result.status;
282
+ attributes["playwright.test.describes"] = describes;
303
283
  if (test.location) {
304
284
  const { file, line } = test.location;
305
285
  attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
@@ -310,15 +290,16 @@ var PlaywrightOpentelemetryReporter = class {
310
290
  const stepSpans = [];
311
291
  for (const [key, stepSpan] of processedSteps.entries()) if (!key.startsWith("__skip__")) stepSpans.push(stepSpan);
312
292
  const networkSpans = await collectNetworkSpans(outputDir, testId);
293
+ const browserPageSpans = await collectBrowserPageSpans(outputDir, testId, networkSpans, new Date(result.startTime.getTime() + result.duration));
313
294
  let minStartTime = result.startTime;
314
295
  let maxEndTime = new Date(result.startTime.getTime() + result.duration);
315
296
  for (const stepSpan of stepSpans) {
316
297
  if (stepSpan.startTime < minStartTime) minStartTime = stepSpan.startTime;
317
298
  if (stepSpan.endTime > maxEndTime) maxEndTime = stepSpan.endTime;
318
299
  }
319
- for (const networkSpan of networkSpans) {
320
- if (networkSpan.startTime < minStartTime) minStartTime = networkSpan.startTime;
321
- if (networkSpan.endTime > maxEndTime) maxEndTime = networkSpan.endTime;
300
+ for (const browserSpan of [...browserPageSpans, ...networkSpans]) {
301
+ if (browserSpan.startTime < minStartTime) minStartTime = browserSpan.startTime;
302
+ if (browserSpan.endTime > maxEndTime) maxEndTime = browserSpan.endTime;
322
303
  }
323
304
  const testSpans = [
324
305
  {
@@ -331,14 +312,13 @@ var PlaywrightOpentelemetryReporter = class {
331
312
  status: { code: result.status === test.expectedStatus ? 1 : 2 }
332
313
  },
333
314
  ...stepSpans,
315
+ ...browserPageSpans,
334
316
  ...networkSpans
335
317
  ];
336
318
  this.spans.push(...testSpans);
337
319
  const relativeFilePath = test.location && this.rootDir ? path.relative(this.rootDir, test.location.file) : test.location?.file ?? "";
338
320
  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);
321
+ const screenshots = await extractScreenshotsFromPlaywrightTrace(traceAttachment.path);
342
322
  if (this.options.storeTraceZip) await createTraceZip({
343
323
  outputDir,
344
324
  testId,
@@ -352,25 +332,20 @@ var PlaywrightOpentelemetryReporter = class {
352
332
  duration: computedDuration,
353
333
  screenshots
354
334
  });
355
- if (this.resolvedTraceApiEndpoint) await this.sendTestJsonToTraceApi({
356
- test,
357
- result,
335
+ if (this.resolvedTraceApiEndpoint) await this.sendScreenshotsToTraceApi({
358
336
  traceId,
359
- relativeFilePath,
360
- startTime: minStartTime,
361
- computedDuration,
362
337
  screenshots
363
338
  });
364
339
  }
365
340
  async onEnd(_result) {
366
- if (this.resolvedEndpoint) await sendSpans(this.spans, {
341
+ if (this.resolvedEndpoint && this.spans.length > 0) await sendSpans(this.spans, {
367
342
  tracesEndpoint: this.resolvedEndpoint,
368
343
  headers: this.resolvedHeaders,
369
344
  serviceName: this.resolvedServiceName,
370
345
  playwrightVersion: this.playwrightVersion || "unknown",
371
346
  debug: this.options.debug ?? false
372
347
  });
373
- if (this.resolvedTraceApiEndpoint) await sendSpans(this.spans, {
348
+ if (this.resolvedTraceApiEndpoint && this.spans.length > 0) await sendSpans(this.spans, {
374
349
  tracesEndpoint: `${this.resolvedTraceApiEndpoint}/v1/traces`,
375
350
  headers: this.resolvedTraceApiHeaders,
376
351
  serviceName: this.resolvedServiceName,
@@ -396,7 +371,7 @@ var PlaywrightOpentelemetryReporter = class {
396
371
  const stepSpanId = this.stepSpanIds.get(stepId) ?? generateSpanId();
397
372
  const existingSpan = processedSteps.get(stepId);
398
373
  if (existingSpan) {
399
- if (step.location && !existingSpan.attributes[ATTR_CODE_FILE_PATH]) {
374
+ if (step.location && !existingSpan.attributes["code.file.path"]) {
400
375
  const { file, line } = step.location;
401
376
  const relativePath = this.rootDir ? path.relative(this.rootDir, file) : file;
402
377
  existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
@@ -441,36 +416,11 @@ var PlaywrightOpentelemetryReporter = class {
441
416
  if (!outputDir) throw new Error(`No outputDir found for test "${testId}" - onBegin must be called first and test must exist in suite`);
442
417
  return outputDir;
443
418
  }
444
- async sendTestJsonToTraceApi(params) {
445
- const { test, result, traceId, relativeFilePath, startTime, computedDuration, screenshots } = params;
446
- const titlePath = test.titlePath();
447
- const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
448
- const line = test.location?.line ?? 0;
449
- const startTimeUnixNano = (startTime.getTime() * 1e6).toString();
450
- const endTimeUnixNano = ((startTime.getTime() + computedDuration) * 1e6).toString();
451
- const testJson = {
452
- name: test.title,
453
- describes,
454
- file: relativeFilePath,
455
- line,
456
- status: result.status,
457
- traceId,
458
- startTimeUnixNano,
459
- endTimeUnixNano
460
- };
461
- const testJsonUrl = `${this.resolvedTraceApiEndpoint}/otel-playwright-reporter/test.json`;
462
- await fetch(testJsonUrl, {
463
- method: "PUT",
464
- headers: {
465
- "content-type": "application/json",
466
- "x-trace-id": traceId,
467
- ...this.resolvedTraceApiHeaders
468
- },
469
- body: JSON.stringify(testJson)
470
- });
419
+ async sendScreenshotsToTraceApi(params) {
420
+ const { traceId, screenshots } = params;
471
421
  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, {
422
+ const screenshotUrl = `${this.resolvedTraceApiEndpoint}/playwright-otel-reporter/v1/screenshots/${filename}`;
423
+ const response = await fetch(screenshotUrl, {
474
424
  method: "PUT",
475
425
  headers: {
476
426
  "content-type": "image/jpeg",
@@ -479,6 +429,10 @@ var PlaywrightOpentelemetryReporter = class {
479
429
  },
480
430
  body: blob
481
431
  });
432
+ if (!response.ok) {
433
+ const error = await response.text();
434
+ throw new Error(`Failed to send screenshot ${filename}: ${response.status} ${response.statusText}, ${error}`);
435
+ }
482
436
  }));
483
437
  }
484
438
  };
@@ -503,6 +457,5 @@ function getStepId(test, step) {
503
457
  ...step.titlePath()
504
458
  ].join(" > ");
505
459
  }
506
-
507
460
  //#endregion
508
- export { PlaywrightOpentelemetryReporter as t };
461
+ export { PlaywrightOpentelemetryReporter as t };