playwright-opentelemetry 0.18.2 → 0.19.1

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,4 +1,4 @@
1
- const require_screenshots_zip = require("./screenshots-zip-nJZiEIbI.cjs");
1
+ const require_screenshots_zip = require("./screenshots-zip-DN7eCklk.cjs");
2
2
  let node_fs = require("node:fs");
3
3
  node_fs = require_screenshots_zip.__toESM(node_fs, 1);
4
4
  let node_fs_promises = require("node:fs/promises");
@@ -27,6 +27,80 @@ const ATTR_TEST_STEP_PARAM_PREFIX = "test.step.param.";
27
27
  const ATTR_TEST_STEP_CATEGORY = "test.step.category";
28
28
  const ATTR_TEST_PHASE = "playwright.test.phase";
29
29
  //#endregion
30
+ //#region src/reporter/api-request-matcher.ts
31
+ const HTTP_METHODS = "DELETE|FETCH|GET|HEAD|PATCH|POST|PUT";
32
+ const QUOTED_URL_TITLE = new RegExp(`^(${HTTP_METHODS}|\\{method\\})\\s+"`);
33
+ const API_NAME_TITLE = new RegExp(`^apiRequestContext\\.(${HTTP_METHODS})\\(`, "i");
34
+ const NO_METHOD_TITLE = "{method}";
35
+ /**
36
+ * Recognises the step of an `APIRequestContext` call. From Playwright 1.63
37
+ * such a step reports the call's url and method as params; before that they
38
+ * only show in its title.
39
+ */
40
+ function apiRequestStepCall(step) {
41
+ if (step.category !== "pw:api") return;
42
+ if (step.params) {
43
+ const { url, method } = step.params;
44
+ if (typeof url !== "string") return;
45
+ if (typeof method === "string") return {
46
+ method: method.toUpperCase(),
47
+ url
48
+ };
49
+ return step.title === NO_METHOD_TITLE ? { url } : void 0;
50
+ }
51
+ const method = (QUOTED_URL_TITLE.exec(step.title) ?? API_NAME_TITLE.exec(step.title))?.[1];
52
+ if (!method) return;
53
+ const upperCased = method.toUpperCase();
54
+ return upperCased === "FETCH" || upperCased === NO_METHOD_TITLE.toUpperCase() ? {} : { method: upperCased };
55
+ }
56
+ /**
57
+ * Pairs each request step with the call the fixture recorded for it. The
58
+ * fixture records where the test made the call, which is exactly the step's
59
+ * location, so the nth call from a place belongs to the nth step from that
60
+ * place.
61
+ */
62
+ var ApiRequestMatcher = class {
63
+ rootDir;
64
+ unclaimed;
65
+ /** Whether Playwright located a step in the fixture's wrapper. */
66
+ wrapperWasVisible = false;
67
+ constructor(requests, rootDir) {
68
+ this.rootDir = rootDir;
69
+ this.unclaimed = [...requests];
70
+ }
71
+ take(step, call) {
72
+ const locatedInWrapper = isApiRequestWrapperFile(step.location?.file);
73
+ this.wrapperWasVisible ||= locatedInWrapper;
74
+ const candidates = this.unclaimed.filter((request) => locatedInWrapper || !request.location ? agreesOnMethod(call, request) : this.isSameLocation(step, request.location));
75
+ const match = candidates.find((request) => agreesOnMethod(call, request) && agreesOnUrl(call, request)) ?? candidates.find((request) => agreesOnMethod(call, request)) ?? candidates[0];
76
+ if (match) this.unclaimed.splice(this.unclaimed.indexOf(match), 1);
77
+ return match;
78
+ }
79
+ /** Recorded calls no step reported. */
80
+ unmatched() {
81
+ return [...this.unclaimed];
82
+ }
83
+ isSameLocation(step, location) {
84
+ if (!step.location) return false;
85
+ const stepFile = this.rootDir ? node_path.default.relative(this.rootDir, step.location.file) : step.location.file;
86
+ return step.location.line === location.line && step.location.column === location.column && withForwardSlashes(stepFile) === withForwardSlashes(location.file);
87
+ }
88
+ };
89
+ function isApiRequestWrapperFile(file) {
90
+ return file !== void 0 && file.includes("node:playwright-opentelemetry/api-request");
91
+ }
92
+ function agreesOnMethod(call, request) {
93
+ return call.method === void 0 || call.method === request.method;
94
+ }
95
+ const CUT_SHORT = "…";
96
+ function agreesOnUrl(call, request) {
97
+ if (call.url === void 0) return true;
98
+ return call.url.endsWith(CUT_SHORT) ? request.url.startsWith(call.url.slice(0, -1)) : call.url === request.url;
99
+ }
100
+ function withForwardSlashes(file) {
101
+ return file.replace(/\\/g, "/");
102
+ }
103
+ //#endregion
30
104
  //#region src/reporter/legacy/trace-zip-screenshots.ts
31
105
  /**
32
106
  * LEGACY: reads screenshots out of Playwright's trace.zip, for Playwright
@@ -183,6 +257,7 @@ var PlaywrightOpentelemetryReporter = class {
183
257
  fixtureHandoffRoots = /* @__PURE__ */ new Set();
184
258
  rootDir;
185
259
  playwrightVersion;
260
+ warnedAboutVisibleWrapper = false;
186
261
  debug = false;
187
262
  constructor() {}
188
263
  onBegin(config, _suite) {
@@ -238,7 +313,16 @@ var PlaywrightOpentelemetryReporter = class {
238
313
  attributes[ATTR_CODE_COLUMN_NUMBER] = column;
239
314
  }
240
315
  const stepSpans = [];
241
- for (const step of result.steps ?? []) this.processTestStep(step, testSpanId, traceId, [], stepSpans);
316
+ const apiRequests = new ApiRequestMatcher(parseApiRequests(fixtureData.apiRequests, testId), this.rootDir);
317
+ for (const step of result.steps ?? []) this.processTestStep(step, testSpanId, traceId, [], stepSpans, apiRequests);
318
+ for (const request of apiRequests.unmatched()) stepSpans.push(unmatchedApiRequestSpan(request, {
319
+ traceId,
320
+ parentSpanId: testSpanId
321
+ }));
322
+ if (apiRequests.wrapperWasVisible && !this.warnedAboutVisibleWrapper) {
323
+ this.warnedAboutVisibleWrapper = true;
324
+ console.warn(`Playwright ${this.playwrightVersion ?? ""} reports playwright-opentelemetry's request wrapper as the location of request steps. Traces still have the right locations, but Playwright's own reports don't. Please report this to playwright-opentelemetry.`);
325
+ }
242
326
  let minStartTime = result.startTime;
243
327
  let maxEndTime = new Date(result.startTime.getTime() + result.duration);
244
328
  for (const stepSpan of stepSpans) {
@@ -331,6 +415,7 @@ var PlaywrightOpentelemetryReporter = class {
331
415
  const attached = {
332
416
  traceContext: attachment(require_screenshots_zip.TRACE_CONTEXT_ATTACHMENT_NAME)?.body,
333
417
  fixtureSpans: attachment(require_screenshots_zip.FIXTURE_SPANS_ATTACHMENT_NAME)?.body,
418
+ apiRequests: attachment(require_screenshots_zip.API_REQUESTS_ATTACHMENT_NAME)?.body,
334
419
  screenshotsZip: screenshotsAttachmentPath ? readFixtureFile(screenshotsAttachmentPath, { required: true }) : void 0
335
420
  };
336
421
  const outputDir = getProjectOutputDir(test);
@@ -341,6 +426,7 @@ var PlaywrightOpentelemetryReporter = class {
341
426
  return {
342
427
  traceContext: attached.traceContext ?? readFixtureFile(node_path.default.join(dir, "trace-context.json")),
343
428
  fixtureSpans: attached.fixtureSpans ?? readFixtureFile(node_path.default.join(dir, "fixture-spans.json")),
429
+ apiRequests: attached.apiRequests ?? readFixtureFile(node_path.default.join(dir, "api-requests.json")),
344
430
  screenshotsZip: attached.screenshotsZip ?? readFixtureFile(node_path.default.join(dir, "screenshots.zip"))
345
431
  };
346
432
  } finally {
@@ -368,14 +454,14 @@ var PlaywrightOpentelemetryReporter = class {
368
454
  const [traceZipBlob] = await Promise.all([traceZipBlobPromise, ...uploadPromises]);
369
455
  return { traceZipBlob };
370
456
  }
371
- processTestStep(step, parentSpanId, traceId, parentTitlePath, stepSpans, inheritedPhase) {
457
+ processTestStep(step, parentSpanId, traceId, parentTitlePath, stepSpans, apiRequests, inheritedPhase) {
372
458
  let phase = inheritedPhase;
373
459
  if (step.category === "hook") {
374
460
  if (step.title === "Before Hooks") phase = "before";
375
461
  if (step.title === "After Hooks" || step.title === "Worker Cleanup") phase = "after";
376
462
  }
377
463
  if (isInternalFixtureStep(step) || isInternalApiRequestStep(step)) {
378
- for (const childStep of step.steps ?? []) this.processTestStep(childStep, parentSpanId, traceId, parentTitlePath, stepSpans, phase);
464
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, parentSpanId, traceId, parentTitlePath, stepSpans, apiRequests, phase);
379
465
  return;
380
466
  }
381
467
  const currentTitlePath = [...parentTitlePath, step.title];
@@ -389,24 +475,35 @@ var PlaywrightOpentelemetryReporter = class {
389
475
  }
390
476
  attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
391
477
  if (phase) attributes[ATTR_TEST_PHASE] = phase;
392
- if (step.location) {
478
+ const apiRequestCall = apiRequestStepCall(step);
479
+ const apiRequest = apiRequestCall ? apiRequests.take(step, apiRequestCall) : void 0;
480
+ if (isApiRequestWrapperFile(step.location?.file)) {
481
+ if (apiRequest?.location) {
482
+ attributes[ATTR_CODE_FILE_PATH] = apiRequest.location.file;
483
+ attributes[ATTR_CODE_LINE_NUMBER] = apiRequest.location.line;
484
+ attributes[ATTR_CODE_COLUMN_NUMBER] = apiRequest.location.column;
485
+ }
486
+ } else if (step.location) {
393
487
  const { file, line, column } = step.location;
394
488
  attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
395
489
  attributes[ATTR_CODE_LINE_NUMBER] = line;
396
490
  attributes[ATTR_CODE_COLUMN_NUMBER] = column;
397
491
  }
492
+ const httpAttributes = apiRequest ? capturedApiRequestAttributes(apiRequest) : apiRequestCall && apiRequestStepAttributes(apiRequestCall);
493
+ Object.assign(attributes, httpAttributes);
398
494
  const stepSpan = {
399
495
  traceId,
400
- spanId: require_screenshots_zip.generateSpanId(),
496
+ spanId: sentSpanId(apiRequest) ?? require_screenshots_zip.generateSpanId(),
401
497
  parentSpanId,
402
498
  name: TEST_STEP_SPAN_NAME,
403
499
  startTime: step.startTime,
404
500
  endTime: new Date(step.startTime.getTime() + step.duration),
405
501
  attributes
406
502
  };
503
+ if (httpAttributes) stepSpan.kind = SPAN_KIND_CLIENT;
407
504
  if (step.error) stepSpan.status = errorStatus(step.error.message);
408
505
  stepSpans.push(stepSpan);
409
- for (const childStep of step.steps ?? []) this.processTestStep(childStep, stepSpan.spanId, traceId, currentTitlePath, stepSpans, phase);
506
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, stepSpan.spanId, traceId, currentTitlePath, stepSpans, apiRequests, phase);
410
507
  }
411
508
  onStdOut(chunk, _test, _result) {
412
509
  if (this.debug) console.log(chunk.toString().slice(0, -1));
@@ -581,17 +678,70 @@ function isInternalFixtureStep(step) {
581
678
  if (step.category !== "fixture" || !step.location?.file) return false;
582
679
  return isInternalFixtureFile(step.location.file);
583
680
  }
681
+ /**
682
+ * Earlier fixtures wrapped `request` in a Proxy, which made the fixture the
683
+ * location of each call's step, and recorded the calls as spans of their own.
684
+ * Their data can still arrive through `merge-reports`.
685
+ */
584
686
  function isInternalApiRequestStep(step) {
585
- if (step.category !== "pw:api" || !step.location?.file) return false;
586
- return isApiRequestStep(step) && isInternalFixtureFile(step.location.file);
687
+ if (!step.location?.file) return false;
688
+ return apiRequestStepCall(step) !== void 0 && isInternalFixtureFile(step.location.file);
689
+ }
690
+ const SPAN_KIND_CLIENT = 3;
691
+ function capturedApiRequestAttributes(request) {
692
+ return require_screenshots_zip.apiRequestHttpAttributes({
693
+ method: request.method,
694
+ url: request.responseUrl ?? request.url,
695
+ statusCode: request.statusCode,
696
+ responseHeaders: request.responseHeaders,
697
+ errorType: request.errorType
698
+ });
587
699
  }
588
700
  /**
589
- * `APIRequestContext` calls. From Playwright 1.63 they report a url and a
590
- * method; before that they show up only in the title, e.g. `GET "/api"`.
701
+ * For a call the fixture didn't record, such as one made in a `beforeAll`
702
+ * hook: what the step itself tells, from Playwright 1.63. There is no
703
+ * response to report.
591
704
  */
592
- function isApiRequestStep(step) {
593
- if (step.params) return typeof step.params.url === "string" && typeof step.params.method === "string";
594
- return /^(?:DELETE|FETCH|GET|HEAD|PATCH|POST|PUT)\s+"/.test(step.title);
705
+ function apiRequestStepAttributes(call) {
706
+ if (call.url === void 0 || call.url.endsWith("…")) return;
707
+ return require_screenshots_zip.apiRequestHttpAttributes({
708
+ method: call.method ?? "GET",
709
+ url: call.url
710
+ });
711
+ }
712
+ function unmatchedApiRequestSpan(request, options) {
713
+ const startTime = new Date(request.startTime);
714
+ const endTime = request.endTime ? new Date(request.endTime) : startTime;
715
+ const attributes = capturedApiRequestAttributes(request);
716
+ if (request.location) {
717
+ attributes[ATTR_CODE_FILE_PATH] = request.location.file;
718
+ attributes[ATTR_CODE_LINE_NUMBER] = request.location.line;
719
+ attributes[ATTR_CODE_COLUMN_NUMBER] = request.location.column;
720
+ }
721
+ const failed = request.errorType !== void 0 || request.statusCode !== void 0 && request.statusCode >= 400;
722
+ return {
723
+ traceId: options.traceId,
724
+ spanId: sentSpanId(request) ?? require_screenshots_zip.generateSpanId(),
725
+ parentSpanId: options.parentSpanId,
726
+ name: `HTTP ${request.method}`,
727
+ kind: SPAN_KIND_CLIENT,
728
+ startTime,
729
+ endTime: Number.isNaN(endTime.getTime()) ? startTime : endTime,
730
+ attributes,
731
+ status: { code: failed ? 2 : 0 }
732
+ };
733
+ }
734
+ function sentSpanId(request) {
735
+ return typeof request?.spanId === "string" && /^[0-9a-f]{16}$/.test(request.spanId) ? request.spanId : void 0;
736
+ }
737
+ function parseApiRequests(body, testId) {
738
+ if (!body) return [];
739
+ try {
740
+ return require_screenshots_zip.parseApiRequestsHandoff(body.toString("utf-8"));
741
+ } catch (error) {
742
+ console.warn(`Ignoring invalid ${require_screenshots_zip.API_REQUESTS_ATTACHMENT_NAME} for test ${testId}: ${errorMessage(error)}`);
743
+ return [];
744
+ }
595
745
  }
596
746
  /**
597
747
  * Span attributes hold primitives and string arrays, so other param values
@@ -1,4 +1,4 @@
1
- import { C as PLAYWRIGHT_TRACE_API_SOURCE_REPORTER, D as sendSpans, E as generateTraceId, O as withPlaywrightTraceApiHeaders, S as PLAYWRIGHT_TRACE_API_SOURCE_HEADER, T as generateSpanId, a as supportsScreencastScreenshots, c as FIXTURE_SPANS_ATTACHMENT_NAME, i as readScreenshotsZip, l as TRACE_CONTEXT_ATTACHMENT_NAME, m as shouldRetainPlaywrightTrace, n as addScreenshotsToZip, o as resolvePlaywrightOpentelemetryConfig, r as createScreenshotsZip, t as SCREENSHOTS_ATTACHMENT_NAME, v as fixtureHandoffDir, w as buildOtlpRequest, x as filterRetainedDestinations, y as fixtureHandoffRoot } from "./screenshots-zip-DnK_MAtf.mjs";
1
+ import { A as buildOtlpRequest, D as filterRetainedDestinations, F as withPlaywrightTraceApiHeaders, M as generateTraceId, N as sendSpans, O as PLAYWRIGHT_TRACE_API_SOURCE_HEADER, T as fixtureHandoffRoot, a as supportsScreencastScreenshots, d as resolvePlaywrightOpentelemetryConfig, i as readScreenshotsZip, j as generateSpanId, k as PLAYWRIGHT_TRACE_API_SOURCE_REPORTER, l as apiRequestHttpAttributes, m as TRACE_CONTEXT_ATTACHMENT_NAME, n as addScreenshotsToZip, o as API_REQUESTS_ATTACHMENT_NAME, p as FIXTURE_SPANS_ATTACHMENT_NAME, r as createScreenshotsZip, t as SCREENSHOTS_ATTACHMENT_NAME, u as parseApiRequestsHandoff, w as fixtureHandoffDir, y as shouldRetainPlaywrightTrace } from "./screenshots-zip-BjAJUhbe.mjs";
2
2
  import fsSync from "node:fs";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
@@ -24,6 +24,80 @@ const ATTR_TEST_STEP_PARAM_PREFIX = "test.step.param.";
24
24
  const ATTR_TEST_STEP_CATEGORY = "test.step.category";
25
25
  const ATTR_TEST_PHASE = "playwright.test.phase";
26
26
  //#endregion
27
+ //#region src/reporter/api-request-matcher.ts
28
+ const HTTP_METHODS = "DELETE|FETCH|GET|HEAD|PATCH|POST|PUT";
29
+ const QUOTED_URL_TITLE = new RegExp(`^(${HTTP_METHODS}|\\{method\\})\\s+"`);
30
+ const API_NAME_TITLE = new RegExp(`^apiRequestContext\\.(${HTTP_METHODS})\\(`, "i");
31
+ const NO_METHOD_TITLE = "{method}";
32
+ /**
33
+ * Recognises the step of an `APIRequestContext` call. From Playwright 1.63
34
+ * such a step reports the call's url and method as params; before that they
35
+ * only show in its title.
36
+ */
37
+ function apiRequestStepCall(step) {
38
+ if (step.category !== "pw:api") return;
39
+ if (step.params) {
40
+ const { url, method } = step.params;
41
+ if (typeof url !== "string") return;
42
+ if (typeof method === "string") return {
43
+ method: method.toUpperCase(),
44
+ url
45
+ };
46
+ return step.title === NO_METHOD_TITLE ? { url } : void 0;
47
+ }
48
+ const method = (QUOTED_URL_TITLE.exec(step.title) ?? API_NAME_TITLE.exec(step.title))?.[1];
49
+ if (!method) return;
50
+ const upperCased = method.toUpperCase();
51
+ return upperCased === "FETCH" || upperCased === NO_METHOD_TITLE.toUpperCase() ? {} : { method: upperCased };
52
+ }
53
+ /**
54
+ * Pairs each request step with the call the fixture recorded for it. The
55
+ * fixture records where the test made the call, which is exactly the step's
56
+ * location, so the nth call from a place belongs to the nth step from that
57
+ * place.
58
+ */
59
+ var ApiRequestMatcher = class {
60
+ rootDir;
61
+ unclaimed;
62
+ /** Whether Playwright located a step in the fixture's wrapper. */
63
+ wrapperWasVisible = false;
64
+ constructor(requests, rootDir) {
65
+ this.rootDir = rootDir;
66
+ this.unclaimed = [...requests];
67
+ }
68
+ take(step, call) {
69
+ const locatedInWrapper = isApiRequestWrapperFile(step.location?.file);
70
+ this.wrapperWasVisible ||= locatedInWrapper;
71
+ const candidates = this.unclaimed.filter((request) => locatedInWrapper || !request.location ? agreesOnMethod(call, request) : this.isSameLocation(step, request.location));
72
+ const match = candidates.find((request) => agreesOnMethod(call, request) && agreesOnUrl(call, request)) ?? candidates.find((request) => agreesOnMethod(call, request)) ?? candidates[0];
73
+ if (match) this.unclaimed.splice(this.unclaimed.indexOf(match), 1);
74
+ return match;
75
+ }
76
+ /** Recorded calls no step reported. */
77
+ unmatched() {
78
+ return [...this.unclaimed];
79
+ }
80
+ isSameLocation(step, location) {
81
+ if (!step.location) return false;
82
+ const stepFile = this.rootDir ? path.relative(this.rootDir, step.location.file) : step.location.file;
83
+ return step.location.line === location.line && step.location.column === location.column && withForwardSlashes(stepFile) === withForwardSlashes(location.file);
84
+ }
85
+ };
86
+ function isApiRequestWrapperFile(file) {
87
+ return file !== void 0 && file.includes("node:playwright-opentelemetry/api-request");
88
+ }
89
+ function agreesOnMethod(call, request) {
90
+ return call.method === void 0 || call.method === request.method;
91
+ }
92
+ const CUT_SHORT = "…";
93
+ function agreesOnUrl(call, request) {
94
+ if (call.url === void 0) return true;
95
+ return call.url.endsWith(CUT_SHORT) ? request.url.startsWith(call.url.slice(0, -1)) : call.url === request.url;
96
+ }
97
+ function withForwardSlashes(file) {
98
+ return file.replace(/\\/g, "/");
99
+ }
100
+ //#endregion
27
101
  //#region src/reporter/legacy/trace-zip-screenshots.ts
28
102
  /**
29
103
  * LEGACY: reads screenshots out of Playwright's trace.zip, for Playwright
@@ -180,6 +254,7 @@ var PlaywrightOpentelemetryReporter = class {
180
254
  fixtureHandoffRoots = /* @__PURE__ */ new Set();
181
255
  rootDir;
182
256
  playwrightVersion;
257
+ warnedAboutVisibleWrapper = false;
183
258
  debug = false;
184
259
  constructor() {}
185
260
  onBegin(config, _suite) {
@@ -235,7 +310,16 @@ var PlaywrightOpentelemetryReporter = class {
235
310
  attributes[ATTR_CODE_COLUMN_NUMBER] = column;
236
311
  }
237
312
  const stepSpans = [];
238
- for (const step of result.steps ?? []) this.processTestStep(step, testSpanId, traceId, [], stepSpans);
313
+ const apiRequests = new ApiRequestMatcher(parseApiRequests(fixtureData.apiRequests, testId), this.rootDir);
314
+ for (const step of result.steps ?? []) this.processTestStep(step, testSpanId, traceId, [], stepSpans, apiRequests);
315
+ for (const request of apiRequests.unmatched()) stepSpans.push(unmatchedApiRequestSpan(request, {
316
+ traceId,
317
+ parentSpanId: testSpanId
318
+ }));
319
+ if (apiRequests.wrapperWasVisible && !this.warnedAboutVisibleWrapper) {
320
+ this.warnedAboutVisibleWrapper = true;
321
+ console.warn(`Playwright ${this.playwrightVersion ?? ""} reports playwright-opentelemetry's request wrapper as the location of request steps. Traces still have the right locations, but Playwright's own reports don't. Please report this to playwright-opentelemetry.`);
322
+ }
239
323
  let minStartTime = result.startTime;
240
324
  let maxEndTime = new Date(result.startTime.getTime() + result.duration);
241
325
  for (const stepSpan of stepSpans) {
@@ -328,6 +412,7 @@ var PlaywrightOpentelemetryReporter = class {
328
412
  const attached = {
329
413
  traceContext: attachment(TRACE_CONTEXT_ATTACHMENT_NAME)?.body,
330
414
  fixtureSpans: attachment(FIXTURE_SPANS_ATTACHMENT_NAME)?.body,
415
+ apiRequests: attachment(API_REQUESTS_ATTACHMENT_NAME)?.body,
331
416
  screenshotsZip: screenshotsAttachmentPath ? readFixtureFile(screenshotsAttachmentPath, { required: true }) : void 0
332
417
  };
333
418
  const outputDir = getProjectOutputDir(test);
@@ -338,6 +423,7 @@ var PlaywrightOpentelemetryReporter = class {
338
423
  return {
339
424
  traceContext: attached.traceContext ?? readFixtureFile(path.join(dir, "trace-context.json")),
340
425
  fixtureSpans: attached.fixtureSpans ?? readFixtureFile(path.join(dir, "fixture-spans.json")),
426
+ apiRequests: attached.apiRequests ?? readFixtureFile(path.join(dir, "api-requests.json")),
341
427
  screenshotsZip: attached.screenshotsZip ?? readFixtureFile(path.join(dir, "screenshots.zip"))
342
428
  };
343
429
  } finally {
@@ -365,14 +451,14 @@ var PlaywrightOpentelemetryReporter = class {
365
451
  const [traceZipBlob] = await Promise.all([traceZipBlobPromise, ...uploadPromises]);
366
452
  return { traceZipBlob };
367
453
  }
368
- processTestStep(step, parentSpanId, traceId, parentTitlePath, stepSpans, inheritedPhase) {
454
+ processTestStep(step, parentSpanId, traceId, parentTitlePath, stepSpans, apiRequests, inheritedPhase) {
369
455
  let phase = inheritedPhase;
370
456
  if (step.category === "hook") {
371
457
  if (step.title === "Before Hooks") phase = "before";
372
458
  if (step.title === "After Hooks" || step.title === "Worker Cleanup") phase = "after";
373
459
  }
374
460
  if (isInternalFixtureStep(step) || isInternalApiRequestStep(step)) {
375
- for (const childStep of step.steps ?? []) this.processTestStep(childStep, parentSpanId, traceId, parentTitlePath, stepSpans, phase);
461
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, parentSpanId, traceId, parentTitlePath, stepSpans, apiRequests, phase);
376
462
  return;
377
463
  }
378
464
  const currentTitlePath = [...parentTitlePath, step.title];
@@ -386,24 +472,35 @@ var PlaywrightOpentelemetryReporter = class {
386
472
  }
387
473
  attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
388
474
  if (phase) attributes[ATTR_TEST_PHASE] = phase;
389
- if (step.location) {
475
+ const apiRequestCall = apiRequestStepCall(step);
476
+ const apiRequest = apiRequestCall ? apiRequests.take(step, apiRequestCall) : void 0;
477
+ if (isApiRequestWrapperFile(step.location?.file)) {
478
+ if (apiRequest?.location) {
479
+ attributes[ATTR_CODE_FILE_PATH] = apiRequest.location.file;
480
+ attributes[ATTR_CODE_LINE_NUMBER] = apiRequest.location.line;
481
+ attributes[ATTR_CODE_COLUMN_NUMBER] = apiRequest.location.column;
482
+ }
483
+ } else if (step.location) {
390
484
  const { file, line, column } = step.location;
391
485
  attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
392
486
  attributes[ATTR_CODE_LINE_NUMBER] = line;
393
487
  attributes[ATTR_CODE_COLUMN_NUMBER] = column;
394
488
  }
489
+ const httpAttributes = apiRequest ? capturedApiRequestAttributes(apiRequest) : apiRequestCall && apiRequestStepAttributes(apiRequestCall);
490
+ Object.assign(attributes, httpAttributes);
395
491
  const stepSpan = {
396
492
  traceId,
397
- spanId: generateSpanId(),
493
+ spanId: sentSpanId(apiRequest) ?? generateSpanId(),
398
494
  parentSpanId,
399
495
  name: TEST_STEP_SPAN_NAME,
400
496
  startTime: step.startTime,
401
497
  endTime: new Date(step.startTime.getTime() + step.duration),
402
498
  attributes
403
499
  };
500
+ if (httpAttributes) stepSpan.kind = SPAN_KIND_CLIENT;
404
501
  if (step.error) stepSpan.status = errorStatus(step.error.message);
405
502
  stepSpans.push(stepSpan);
406
- for (const childStep of step.steps ?? []) this.processTestStep(childStep, stepSpan.spanId, traceId, currentTitlePath, stepSpans, phase);
503
+ for (const childStep of step.steps ?? []) this.processTestStep(childStep, stepSpan.spanId, traceId, currentTitlePath, stepSpans, apiRequests, phase);
407
504
  }
408
505
  onStdOut(chunk, _test, _result) {
409
506
  if (this.debug) console.log(chunk.toString().slice(0, -1));
@@ -578,17 +675,70 @@ function isInternalFixtureStep(step) {
578
675
  if (step.category !== "fixture" || !step.location?.file) return false;
579
676
  return isInternalFixtureFile(step.location.file);
580
677
  }
678
+ /**
679
+ * Earlier fixtures wrapped `request` in a Proxy, which made the fixture the
680
+ * location of each call's step, and recorded the calls as spans of their own.
681
+ * Their data can still arrive through `merge-reports`.
682
+ */
581
683
  function isInternalApiRequestStep(step) {
582
- if (step.category !== "pw:api" || !step.location?.file) return false;
583
- return isApiRequestStep(step) && isInternalFixtureFile(step.location.file);
684
+ if (!step.location?.file) return false;
685
+ return apiRequestStepCall(step) !== void 0 && isInternalFixtureFile(step.location.file);
686
+ }
687
+ const SPAN_KIND_CLIENT = 3;
688
+ function capturedApiRequestAttributes(request) {
689
+ return apiRequestHttpAttributes({
690
+ method: request.method,
691
+ url: request.responseUrl ?? request.url,
692
+ statusCode: request.statusCode,
693
+ responseHeaders: request.responseHeaders,
694
+ errorType: request.errorType
695
+ });
584
696
  }
585
697
  /**
586
- * `APIRequestContext` calls. From Playwright 1.63 they report a url and a
587
- * method; before that they show up only in the title, e.g. `GET "/api"`.
698
+ * For a call the fixture didn't record, such as one made in a `beforeAll`
699
+ * hook: what the step itself tells, from Playwright 1.63. There is no
700
+ * response to report.
588
701
  */
589
- function isApiRequestStep(step) {
590
- if (step.params) return typeof step.params.url === "string" && typeof step.params.method === "string";
591
- return /^(?:DELETE|FETCH|GET|HEAD|PATCH|POST|PUT)\s+"/.test(step.title);
702
+ function apiRequestStepAttributes(call) {
703
+ if (call.url === void 0 || call.url.endsWith("…")) return;
704
+ return apiRequestHttpAttributes({
705
+ method: call.method ?? "GET",
706
+ url: call.url
707
+ });
708
+ }
709
+ function unmatchedApiRequestSpan(request, options) {
710
+ const startTime = new Date(request.startTime);
711
+ const endTime = request.endTime ? new Date(request.endTime) : startTime;
712
+ const attributes = capturedApiRequestAttributes(request);
713
+ if (request.location) {
714
+ attributes[ATTR_CODE_FILE_PATH] = request.location.file;
715
+ attributes[ATTR_CODE_LINE_NUMBER] = request.location.line;
716
+ attributes[ATTR_CODE_COLUMN_NUMBER] = request.location.column;
717
+ }
718
+ const failed = request.errorType !== void 0 || request.statusCode !== void 0 && request.statusCode >= 400;
719
+ return {
720
+ traceId: options.traceId,
721
+ spanId: sentSpanId(request) ?? generateSpanId(),
722
+ parentSpanId: options.parentSpanId,
723
+ name: `HTTP ${request.method}`,
724
+ kind: SPAN_KIND_CLIENT,
725
+ startTime,
726
+ endTime: Number.isNaN(endTime.getTime()) ? startTime : endTime,
727
+ attributes,
728
+ status: { code: failed ? 2 : 0 }
729
+ };
730
+ }
731
+ function sentSpanId(request) {
732
+ return typeof request?.spanId === "string" && /^[0-9a-f]{16}$/.test(request.spanId) ? request.spanId : void 0;
733
+ }
734
+ function parseApiRequests(body, testId) {
735
+ if (!body) return [];
736
+ try {
737
+ return parseApiRequestsHandoff(body.toString("utf-8"));
738
+ } catch (error) {
739
+ console.warn(`Ignoring invalid ${API_REQUESTS_ATTACHMENT_NAME} for test ${testId}: ${errorMessage(error)}`);
740
+ return [];
741
+ }
592
742
  }
593
743
  /**
594
744
  * Span attributes hold primitives and string arrays, so other param values
package/dist/reporter.cjs CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region src/reporter/index.ts
2
- var reporter_default = require("./reporter-D4i206BM.cjs").PlaywrightOpentelemetryReporter;
2
+ var reporter_default = require("./reporter-BPtfG3Tk.cjs").PlaywrightOpentelemetryReporter;
3
3
  //#endregion
4
4
  module.exports = reporter_default;
@@ -1,2 +1,2 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-C1TwRMjP.cjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-6ybjkG-e.cjs";
2
2
  export = PlaywrightOpentelemetryReporter;
@@ -1,2 +1,2 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-C1TwRMjP.mjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-6ybjkG-e.mjs";
2
2
  export { PlaywrightOpentelemetryReporter as default };
package/dist/reporter.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as PlaywrightOpentelemetryReporter } from "./reporter-DKhFsfiL.mjs";
1
+ import { t as PlaywrightOpentelemetryReporter } from "./reporter-BzA8_6iC.mjs";
2
2
  //#region src/reporter/index.ts
3
3
  var reporter_default = PlaywrightOpentelemetryReporter;
4
4
  //#endregion
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { BlobReader, BlobWriter, TextWriter, ZipReader, ZipWriter } from "@zip.js/zip.js";
4
4
  //#region package.json
5
- var version = "0.18.2";
5
+ var version = "0.19.1";
6
6
  const PLAYWRIGHT_TRACE_API_SOURCE_HEADER = "x-playwright-otel-source";
7
7
  const PLAYWRIGHT_TRACE_API_SOURCE_REPORTER = "reporter";
8
8
  function withPlaywrightTraceApiHeaders(headers) {
@@ -19,6 +19,10 @@ function generateTraceId() {
19
19
  function generateSpanId() {
20
20
  return Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
21
21
  }
22
+ /** A W3C `traceparent` header for a sampled span. */
23
+ function traceparentHeader(traceId, spanId) {
24
+ return `00-${traceId}-${spanId}-01`;
25
+ }
22
26
  function parseOtlpHeaders(headersString) {
23
27
  const headers = {};
24
28
  if (!headersString) return headers;
@@ -179,6 +183,7 @@ function fixtureHandoffRoot(projectOutputDir) {
179
183
  const TRACE_CONTEXT_HANDOFF_FILE = "trace-context.json";
180
184
  const FIXTURE_SPANS_HANDOFF_FILE = "fixture-spans.json";
181
185
  const SCREENSHOTS_HANDOFF_FILE = "screenshots.zip";
186
+ const API_REQUESTS_HANDOFF_FILE = "api-requests.json";
182
187
  const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/i;
183
188
  const SPAN_ID_PATTERN = /^[0-9a-f]{16}$/i;
184
189
  function isTraceContextHandoff(value) {
@@ -284,8 +289,8 @@ async function createTestTraceContext(testInfo, config) {
284
289
  }
285
290
  /**
286
291
  * Writes the expected-trace marker that lets the Trace API admit spans from the
287
- * app under test. Only browser requests carry the test's traceparent, so the
288
- * marker is skipped when propagation is off; the fixture's own spans are
292
+ * app under test. Requests only carry the test's traceparent with propagation
293
+ * on, so the marker is skipped when it is off; the fixture's own spans are
289
294
  * trusted and stored without it. Never rejects, so callers can start it
290
295
  * without awaiting.
291
296
  */
@@ -427,6 +432,57 @@ function getConfigurationErrorMessage() {
427
432
  return "playwright-opentelemetry reporter requires an OTLP endpoint, trace API endpoint, or storeTraceZip to be configured.\n\nYou can configure it using environment variables:\n\n export OTEL_EXPORTER_OTLP_ENDPOINT=\"https://api.honeycomb.io\"\n export OTEL_EXPORTER_OTLP_HEADERS=\"x-honeycomb-team=YOUR_API_KEY\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryUseOptions } from 'playwright-opentelemetry/fixture';\n\nexport default defineConfig<PlaywrightOpentelemetryUseOptions>({\n use: {\n playwrightOpentelemetry: {\n otlpEndpoint: {\n url: 'http://localhost:4317/v1/traces',\n headers: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n },\n },\n },\n reporter: [['playwright-opentelemetry/reporter']],\n});\n\nNote: Environment variables take precedence over use.playwrightOpentelemetry options.\n";
428
433
  }
429
434
  //#endregion
435
+ //#region src/shared/api-requests.ts
436
+ /**
437
+ * Calls the test made on Playwright's `APIRequestContext`s (`request`,
438
+ * `page.request`, `context.request`, `playwright.request.newContext()`). The
439
+ * fixture records what Playwright's step for the call doesn't have, the
440
+ * response, and hands it to the reporter, which adds it to that step's span.
441
+ */
442
+ const API_REQUESTS_ATTACHMENT_NAME = "playwright-opentelemetry-api-requests";
443
+ const RECORDED_RESPONSE_HEADERS = ["content-type", "cache-control"];
444
+ function parseApiRequestsHandoff(body) {
445
+ const parsed = JSON.parse(body);
446
+ if (!Array.isArray(parsed?.requests)) throw new Error("expected {requests: [...]}");
447
+ return parsed.requests.filter((request) => typeof request?.method === "string" && typeof request.url === "string" && typeof request.startTime === "string" && !Number.isNaN(new Date(request.startTime).getTime()));
448
+ }
449
+ /** HTTP client span attributes for a call on an `APIRequestContext`. */
450
+ function apiRequestHttpAttributes({ method, url, statusCode, responseHeaders, errorType }) {
451
+ const attributes = {
452
+ "http.request.method": method,
453
+ "http.resource.type": "fetch",
454
+ "playwright.request.api": true,
455
+ "url.full": url
456
+ };
457
+ try {
458
+ const parsedUrl = new URL(url);
459
+ attributes["url.path"] = parsedUrl.pathname;
460
+ attributes["server.address"] = parsedUrl.hostname;
461
+ attributes["server.port"] = serverPort(parsedUrl);
462
+ if (parsedUrl.search) attributes["url.query"] = parsedUrl.search.slice(1);
463
+ } catch {}
464
+ if (statusCode !== void 0) {
465
+ attributes["http.response.status_code"] = statusCode;
466
+ if (statusCode >= 400) attributes["error.type"] = statusCode.toString();
467
+ } else if (errorType !== void 0) attributes["error.type"] = errorType;
468
+ const contentType = responseHeaders?.["content-type"];
469
+ const cacheControl = responseHeaders?.["cache-control"];
470
+ if (contentType) attributes["http.response.header.content-type"] = [contentType];
471
+ if (cacheControl) attributes["http.response.header.cache-control"] = [cacheControl];
472
+ return attributes;
473
+ }
474
+ function serverPort(url) {
475
+ if (url.port) return Number.parseInt(url.port, 10);
476
+ return url.protocol === "https:" ? 443 : 80;
477
+ }
478
+ /**
479
+ * The file name the fixture gives its wrapper around `APIRequestContext`
480
+ * methods. Playwright leaves frames of Node's own modules out of the stack it
481
+ * takes a step's location from, so the step for a wrapped call points at the
482
+ * test's line, not at the wrapper.
483
+ */
484
+ const API_REQUEST_WRAPPER_FILE = "node:playwright-opentelemetry/api-request";
485
+ //#endregion
430
486
  //#region src/shared/screencast-screenshots.ts
431
487
  /**
432
488
  * The first Playwright version whose screencast frames carry the browser's
@@ -525,4 +581,4 @@ function viewportOf(screenshot) {
525
581
  } : {};
526
582
  }
527
583
  //#endregion
528
- export { PLAYWRIGHT_TRACE_API_SOURCE_REPORTER as C, sendSpans as D, generateTraceId as E, withPlaywrightTraceApiHeaders as O, PLAYWRIGHT_TRACE_API_SOURCE_HEADER as S, generateSpanId as T, TRACE_CONTEXT_HANDOFF_FILE as _, supportsScreencastScreenshots as a, writeFixtureHandoffFile as b, FIXTURE_SPANS_ATTACHMENT_NAME as c, flushFixtureSpans as d, registerExpectedTrace as f, SCREENSHOTS_HANDOFF_FILE as g, FIXTURE_SPANS_HANDOFF_FILE as h, readScreenshotsZip as i, TRACE_CONTEXT_ATTACHMENT_NAME as l, shouldRetainPlaywrightTrace as m, addScreenshotsToZip as n, resolvePlaywrightOpentelemetryConfig as o, couldRetainPlaywrightTrace as p, createScreenshotsZip as r, BROWSER_SERVICE_NAME as s, SCREENSHOTS_ATTACHMENT_NAME as t, createTestTraceContext as u, fixtureHandoffDir as v, buildOtlpRequest as w, filterRetainedDestinations as x, fixtureHandoffRoot as y };
584
+ export { buildOtlpRequest as A, TRACE_CONTEXT_HANDOFF_FILE as C, filterRetainedDestinations as D, writeFixtureHandoffFile as E, withPlaywrightTraceApiHeaders as F, generateTraceId as M, sendSpans as N, PLAYWRIGHT_TRACE_API_SOURCE_HEADER as O, traceparentHeader as P, SCREENSHOTS_HANDOFF_FILE as S, fixtureHandoffRoot as T, registerExpectedTrace as _, supportsScreencastScreenshots as a, API_REQUESTS_HANDOFF_FILE as b, RECORDED_RESPONSE_HEADERS as c, resolvePlaywrightOpentelemetryConfig as d, BROWSER_SERVICE_NAME as f, flushFixtureSpans as g, createTestTraceContext as h, readScreenshotsZip as i, generateSpanId as j, PLAYWRIGHT_TRACE_API_SOURCE_REPORTER as k, apiRequestHttpAttributes as l, TRACE_CONTEXT_ATTACHMENT_NAME as m, addScreenshotsToZip as n, API_REQUESTS_ATTACHMENT_NAME as o, FIXTURE_SPANS_ATTACHMENT_NAME as p, createScreenshotsZip as r, API_REQUEST_WRAPPER_FILE as s, SCREENSHOTS_ATTACHMENT_NAME as t, parseApiRequestsHandoff as u, couldRetainPlaywrightTrace as v, fixtureHandoffDir as w, FIXTURE_SPANS_HANDOFF_FILE as x, shouldRetainPlaywrightTrace as y };