playwright-opentelemetry 0.5.0 → 0.6.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.
- package/dist/config-B9i3jm5s.d.cts +15 -0
- package/dist/config-B9i3jm5s.d.mts +15 -0
- package/dist/fixture/factory.cjs +2 -2
- package/dist/fixture/factory.d.cts +1 -5
- package/dist/fixture/factory.d.mts +1 -5
- package/dist/fixture/factory.mjs +1 -1
- package/dist/fixture-1Zc7Gp0b.d.cts +61 -0
- package/dist/{factory-Df7HwxXO.mjs → fixture-C3xMi3bo.mjs} +192 -99
- package/dist/fixture-IJvYGCtD.d.mts +61 -0
- package/dist/{factory-kMxwg_DI.cjs → fixture-KBHTI5WC.cjs} +193 -100
- package/dist/fixture.cjs +3 -3
- package/dist/fixture.d.cts +13 -3
- package/dist/fixture.d.mts +13 -3
- package/dist/fixture.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -2
- package/dist/index.d.mts +3 -2
- package/dist/index.mjs +1 -1
- package/dist/otel-B-kvMiiq.d.cts +18 -0
- package/dist/otel-B-kvMiiq.d.mts +18 -0
- package/dist/reporter-D-ONZUZE.mjs +429 -0
- package/dist/reporter-DaCojFom.d.cts +25 -0
- package/dist/reporter-DaCojFom.d.mts +25 -0
- package/dist/reporter-pVDPoXTx.cjs +436 -0
- package/dist/reporter.cjs +1 -1
- package/dist/reporter.d.cts +2 -2
- package/dist/reporter.d.mts +2 -2
- package/dist/reporter.mjs +1 -1
- package/dist/trace-context-Cck0LEoL.mjs +205 -0
- package/dist/trace-context-Dd2Fmx9q.cjs +286 -0
- package/package.json +1 -1
- package/dist/index-BNfDd8Mg.d.cts +0 -45
- package/dist/index-BNfDd8Mg.d.mts +0 -45
- package/dist/reporter-BE9S9CtV.mjs +0 -461
- package/dist/reporter-BzHSG-gx.cjs +0 -468
- package/dist/trace-files-B6bmvwUq.mjs +0 -218
- package/dist/trace-files-DTK0XBIq.cjs +0 -325
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
const require_trace_context = require("./trace-context-Dd2Fmx9q.cjs");
|
|
2
|
+
let node_path = require("node:path");
|
|
3
|
+
node_path = require_trace_context.__toESM(node_path, 1);
|
|
4
|
+
let node_fs_promises = require("node:fs/promises");
|
|
5
|
+
node_fs_promises = require_trace_context.__toESM(node_fs_promises, 1);
|
|
6
|
+
let _zip_js_zip_js = require("@zip.js/zip.js");
|
|
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
|
+
//#endregion
|
|
14
|
+
//#region src/reporter/reporter-attributes.ts
|
|
15
|
+
const TEST_SPAN_NAME = "playwright.test";
|
|
16
|
+
const TEST_STEP_SPAN_NAME = "playwright.test.step";
|
|
17
|
+
const ATTR_TEST_STEP_NAME = "test.step.name";
|
|
18
|
+
const ATTR_TEST_STEP_TITLE = "test.step.title";
|
|
19
|
+
const ATTR_TEST_STEP_CATEGORY = "test.step.category";
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/reporter/trace-zip-builder.ts
|
|
22
|
+
/**
|
|
23
|
+
* Get the zip filename based on test location and ID.
|
|
24
|
+
* Format: {basename(file)}:{line}-{testId}-pw-otel.zip
|
|
25
|
+
* Fallback: {testId}-pw-otel.zip (if no location info)
|
|
26
|
+
*/
|
|
27
|
+
function getZipFilename(test, testId) {
|
|
28
|
+
if (test.location) return `${node_path.default.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
|
|
29
|
+
return `${testId}-pw-otel.zip`;
|
|
30
|
+
}
|
|
31
|
+
const PLAYWRIGHT_TRACE_RESOURCES_DIR = "resources/";
|
|
32
|
+
/**
|
|
33
|
+
* Pattern to match Playwright screenshot filenames: {name}@{hex-hash}-{timestamp}.jpeg
|
|
34
|
+
* Examples: page@f06f11f7c14d6ce1060d47d79f05c154-1766833384425.jpeg
|
|
35
|
+
*/
|
|
36
|
+
const PLAYWRIGHT_SCREENSHOT_PATTERN = /^.+@[a-f0-9]+-\d+\.jpe?g$/i;
|
|
37
|
+
/**
|
|
38
|
+
* Extract screenshots from a Playwright trace ZIP file.
|
|
39
|
+
* Screenshots are stored in the resources/ directory with names like:
|
|
40
|
+
* {pageGuid}-{timestamp}.jpeg (e.g., page@abc123-1766929201038.jpeg)
|
|
41
|
+
*
|
|
42
|
+
* @param traceZipPath - Path to the Playwright trace.zip file
|
|
43
|
+
* @returns Map of filename (without resources/ prefix) to Blob
|
|
44
|
+
*/
|
|
45
|
+
async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
|
|
46
|
+
const screenshots = /* @__PURE__ */ new Map();
|
|
47
|
+
try {
|
|
48
|
+
const zipBuffer = await node_fs_promises.default.readFile(traceZipPath);
|
|
49
|
+
const zipReader = new _zip_js_zip_js.ZipReader(new _zip_js_zip_js.BlobReader(new Blob([zipBuffer])));
|
|
50
|
+
const entries = await zipReader.getEntries();
|
|
51
|
+
await Promise.all(entries.filter((entry) => {
|
|
52
|
+
if (!isFileEntry(entry)) return false;
|
|
53
|
+
if (!entry.filename.startsWith(PLAYWRIGHT_TRACE_RESOURCES_DIR)) return false;
|
|
54
|
+
const name = entry.filename.slice(10);
|
|
55
|
+
return PLAYWRIGHT_SCREENSHOT_PATTERN.test(name);
|
|
56
|
+
}).map(async (entry) => {
|
|
57
|
+
const filename = entry.filename.slice(10);
|
|
58
|
+
const blob = await entry.getData(new _zip_js_zip_js.BlobWriter("image/jpeg"));
|
|
59
|
+
screenshots.set(filename, blob);
|
|
60
|
+
}));
|
|
61
|
+
await zipReader.close();
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (err.code !== "ENOENT") console.warn(`Warning: Could not extract screenshots from trace ZIP: ${err}`);
|
|
64
|
+
}
|
|
65
|
+
return screenshots;
|
|
66
|
+
}
|
|
67
|
+
async function createScreenshotsZip(screenshots) {
|
|
68
|
+
const zipWriter = new _zip_js_zip_js.ZipWriter(new _zip_js_zip_js.BlobWriter("application/zip"));
|
|
69
|
+
await addScreenshotsToZip(zipWriter, screenshots);
|
|
70
|
+
return zipWriter.close();
|
|
71
|
+
}
|
|
72
|
+
async function createTraceZipBlob(options) {
|
|
73
|
+
const { spans, fixtureSpans, serviceName, playwrightVersion, screenshots } = options;
|
|
74
|
+
const otlpRequest = require_trace_context.buildOtlpRequest(spans, serviceName, playwrightVersion);
|
|
75
|
+
const traceJson = JSON.stringify(otlpRequest, null, 2);
|
|
76
|
+
const zipWriter = new _zip_js_zip_js.ZipWriter(new _zip_js_zip_js.BlobWriter("application/zip"));
|
|
77
|
+
await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
|
|
78
|
+
if (fixtureSpans.length > 0) {
|
|
79
|
+
const fixtureOtlpRequest = require_trace_context.buildOtlpRequest(fixtureSpans, "playwright-browser", playwrightVersion);
|
|
80
|
+
await zipWriter.add("traces/playwright-browser.json", new Blob([JSON.stringify(fixtureOtlpRequest, null, 2)]).stream());
|
|
81
|
+
}
|
|
82
|
+
await addScreenshotsToZip(zipWriter, screenshots);
|
|
83
|
+
return zipWriter.close();
|
|
84
|
+
}
|
|
85
|
+
async function writeTraceZip(outputDir, test, zipBlob) {
|
|
86
|
+
const zipFilename = getZipFilename(test, test.id);
|
|
87
|
+
const zipPath = node_path.default.join(outputDir, zipFilename);
|
|
88
|
+
const arrayBuffer = await zipBlob.arrayBuffer();
|
|
89
|
+
await node_fs_promises.default.writeFile(zipPath, Buffer.from(arrayBuffer));
|
|
90
|
+
}
|
|
91
|
+
async function addScreenshotsToZip(zipWriter, screenshots) {
|
|
92
|
+
const manifest = createScreenshotManifest(screenshots);
|
|
93
|
+
await zipWriter.add("manifest.json", new Blob([JSON.stringify(manifest, null, 2)], { type: "application/json" }).stream());
|
|
94
|
+
for (const [filename, blob] of screenshots.entries()) await zipWriter.add(`screenshots/${filename}`, blob.stream());
|
|
95
|
+
}
|
|
96
|
+
function createScreenshotManifest(screenshots) {
|
|
97
|
+
return {
|
|
98
|
+
version: 1,
|
|
99
|
+
screenshots: Array.from(screenshots.keys()).map((filename) => ({
|
|
100
|
+
timestamp: extractTimestampFromFilename(filename),
|
|
101
|
+
file: filename,
|
|
102
|
+
path: `screenshots/${filename}`,
|
|
103
|
+
contentType: getMimeType(filename)
|
|
104
|
+
})).sort((a, b) => a.timestamp - b.timestamp)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function extractTimestampFromFilename(filename) {
|
|
108
|
+
const lastDashIndex = filename.lastIndexOf("-");
|
|
109
|
+
if (lastDashIndex === -1) return 0;
|
|
110
|
+
const timestamp = Number.parseInt(filename.slice(lastDashIndex + 1).replace(/\.[^.]+$/, ""), 10);
|
|
111
|
+
return Number.isNaN(timestamp) ? 0 : timestamp;
|
|
112
|
+
}
|
|
113
|
+
function getMimeType(filename) {
|
|
114
|
+
switch (filename.split(".").pop()?.toLowerCase()) {
|
|
115
|
+
case "png": return "image/png";
|
|
116
|
+
case "jpg":
|
|
117
|
+
case "jpeg": return "image/jpeg";
|
|
118
|
+
case "webp": return "image/webp";
|
|
119
|
+
default: return "application/octet-stream";
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function isFileEntry(entry) {
|
|
123
|
+
return !entry.directory;
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/reporter/reporter.ts
|
|
127
|
+
var PlaywrightOpentelemetryReporter = class {
|
|
128
|
+
spanBatches = [];
|
|
129
|
+
pendingTraceArtifacts = [];
|
|
130
|
+
rootDir;
|
|
131
|
+
playwrightVersion;
|
|
132
|
+
debug = false;
|
|
133
|
+
constructor() {}
|
|
134
|
+
onBegin(config, _suite) {
|
|
135
|
+
this.rootDir = config.rootDir;
|
|
136
|
+
this.playwrightVersion = config.version;
|
|
137
|
+
const projects = Array.isArray(config.projects) ? config.projects : [];
|
|
138
|
+
for (const project of projects) {
|
|
139
|
+
const resolvedConfig = require_trace_context.resolvePlaywrightOpentelemetryConfig(getProjectPlaywrightOpentelemetryConfig(project), { requireDestination: true });
|
|
140
|
+
this.debug ||= resolvedConfig.debug;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
onTestBegin(_test, _result) {}
|
|
144
|
+
onStepBegin(_test, _result, _step) {}
|
|
145
|
+
onStepEnd(_test, _result, _step) {}
|
|
146
|
+
onTestEnd(test, result) {
|
|
147
|
+
const testId = test.id;
|
|
148
|
+
const outputDir = getTestOutputDir(test);
|
|
149
|
+
const config = getTestConfig(test);
|
|
150
|
+
const { traceId, rootSpanId: testSpanId } = readTraceContextAttachment(result, testId, config.storeTraceZip);
|
|
151
|
+
const traceAttachment = result.attachments.find((attachment) => attachment.name === "trace" && attachment.contentType === "application/zip" && attachment.path);
|
|
152
|
+
const fixtureSpans = config.storeTraceZip ? readFixtureSpansAttachment(result, testId) : [];
|
|
153
|
+
result.attachments.push({
|
|
154
|
+
name: "playwright-opentelemetry-trace-id",
|
|
155
|
+
contentType: "text/plain",
|
|
156
|
+
body: Buffer.from(traceId, "utf-8")
|
|
157
|
+
});
|
|
158
|
+
const attributes = {};
|
|
159
|
+
const titlePath = test.titlePath();
|
|
160
|
+
if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
|
|
161
|
+
const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
|
|
162
|
+
attributes[ATTR_TEST_CASE_TITLE] = test.title;
|
|
163
|
+
attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status === "passed" ? "pass" : "fail";
|
|
164
|
+
attributes["playwright.test.status"] = result.status;
|
|
165
|
+
attributes["playwright.test.describes"] = describes;
|
|
166
|
+
if (test.location) {
|
|
167
|
+
const { file, line } = test.location;
|
|
168
|
+
attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
|
|
169
|
+
attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
170
|
+
}
|
|
171
|
+
const processedSteps = /* @__PURE__ */ new Map();
|
|
172
|
+
const skippedStepIds = /* @__PURE__ */ new Set();
|
|
173
|
+
if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps, skippedStepIds);
|
|
174
|
+
const stepSpans = Array.from(processedSteps.values());
|
|
175
|
+
let minStartTime = result.startTime;
|
|
176
|
+
let maxEndTime = new Date(result.startTime.getTime() + result.duration);
|
|
177
|
+
for (const stepSpan of stepSpans) {
|
|
178
|
+
if (stepSpan.startTime < minStartTime) minStartTime = stepSpan.startTime;
|
|
179
|
+
if (stepSpan.endTime > maxEndTime) maxEndTime = stepSpan.endTime;
|
|
180
|
+
}
|
|
181
|
+
const testSpans = [{
|
|
182
|
+
traceId,
|
|
183
|
+
spanId: testSpanId,
|
|
184
|
+
name: TEST_SPAN_NAME,
|
|
185
|
+
startTime: minStartTime,
|
|
186
|
+
endTime: maxEndTime,
|
|
187
|
+
attributes,
|
|
188
|
+
status: { code: result.status === test.expectedStatus ? 1 : 2 }
|
|
189
|
+
}, ...stepSpans];
|
|
190
|
+
this.spanBatches.push({
|
|
191
|
+
spans: testSpans,
|
|
192
|
+
config
|
|
193
|
+
});
|
|
194
|
+
if (config.storeTraceZip || config.playwrightTraceApiEndpoint) {
|
|
195
|
+
const prepared = this.prepareTraceArtifact({
|
|
196
|
+
test,
|
|
197
|
+
spans: testSpans,
|
|
198
|
+
fixtureSpans,
|
|
199
|
+
traceAttachmentPath: traceAttachment?.path,
|
|
200
|
+
traceId,
|
|
201
|
+
config,
|
|
202
|
+
playwrightVersion: this.playwrightVersion || "unknown"
|
|
203
|
+
}).catch((error) => ({ error }));
|
|
204
|
+
this.pendingTraceArtifacts.push({
|
|
205
|
+
outputDir,
|
|
206
|
+
test,
|
|
207
|
+
prepared
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
async onEnd(_result) {
|
|
212
|
+
for (const artifact of this.pendingTraceArtifacts) {
|
|
213
|
+
const prepared = await artifact.prepared;
|
|
214
|
+
if ("error" in prepared) throw prepared.error;
|
|
215
|
+
if (prepared.traceZipBlob) await writeTraceZip(artifact.outputDir, artifact.test, prepared.traceZipBlob);
|
|
216
|
+
}
|
|
217
|
+
const destinations = /* @__PURE__ */ new Map();
|
|
218
|
+
for (const batch of this.spanBatches) {
|
|
219
|
+
if (batch.config.otlpEndpoint) addDestinationSpans(destinations, batch.spans, {
|
|
220
|
+
tracesEndpoint: batch.config.otlpEndpoint,
|
|
221
|
+
headers: batch.config.otlpHeaders,
|
|
222
|
+
serviceName: batch.config.serviceName,
|
|
223
|
+
playwrightVersion: this.playwrightVersion || "unknown",
|
|
224
|
+
debug: batch.config.debug
|
|
225
|
+
});
|
|
226
|
+
if (batch.config.playwrightTraceApiEndpoint) addDestinationSpans(destinations, batch.spans, {
|
|
227
|
+
tracesEndpoint: `${batch.config.playwrightTraceApiEndpoint}/v1/traces`,
|
|
228
|
+
headers: batch.config.playwrightTraceApiHeaders,
|
|
229
|
+
serviceName: batch.config.serviceName,
|
|
230
|
+
playwrightVersion: this.playwrightVersion || "unknown",
|
|
231
|
+
debug: batch.config.debug
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
for (const destination of destinations.values()) await require_trace_context.sendSpans(destination.spans, destination.options);
|
|
235
|
+
}
|
|
236
|
+
async prepareTraceArtifact(options) {
|
|
237
|
+
const screenshots = options.traceAttachmentPath ? await extractScreenshotsFromPlaywrightTrace(options.traceAttachmentPath) : /* @__PURE__ */ new Map();
|
|
238
|
+
const traceZipBlobPromise = options.config.storeTraceZip ? createTraceZipBlob({
|
|
239
|
+
test: options.test,
|
|
240
|
+
spans: options.spans,
|
|
241
|
+
fixtureSpans: options.fixtureSpans,
|
|
242
|
+
serviceName: options.config.serviceName,
|
|
243
|
+
playwrightVersion: options.playwrightVersion,
|
|
244
|
+
screenshots
|
|
245
|
+
}) : void 0;
|
|
246
|
+
const uploadPromise = options.config.playwrightTraceApiEndpoint ? this.sendScreenshotsZipToTraceApi({
|
|
247
|
+
traceId: options.traceId,
|
|
248
|
+
screenshots,
|
|
249
|
+
config: options.config
|
|
250
|
+
}) : void 0;
|
|
251
|
+
const [traceZipBlob] = await Promise.all([traceZipBlobPromise, uploadPromise]);
|
|
252
|
+
return { traceZipBlob };
|
|
253
|
+
}
|
|
254
|
+
processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds) {
|
|
255
|
+
const isInternalFixture = step.category === "fixture" && step.location?.file.includes("playwright-opentelemetry") && (step.location?.file.endsWith("fixture.mjs") || step.location?.file.endsWith("fixture/index.ts"));
|
|
256
|
+
const stepId = getStepId(test, step);
|
|
257
|
+
if (isInternalFixture) {
|
|
258
|
+
skippedStepIds.add(stepId);
|
|
259
|
+
processedSteps.delete(stepId);
|
|
260
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (skippedStepIds.has(stepId)) {
|
|
264
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps, skippedStepIds);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const currentTitlePath = [...parentTitlePath, step.title];
|
|
268
|
+
const existingSpan = processedSteps.get(stepId);
|
|
269
|
+
if (existingSpan) {
|
|
270
|
+
if (step.location && !existingSpan.attributes["code.file.path"]) {
|
|
271
|
+
const { file, line } = step.location;
|
|
272
|
+
const relativePath = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
|
|
273
|
+
existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
|
|
274
|
+
existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
275
|
+
}
|
|
276
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps, skippedStepIds);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const attributes = {};
|
|
280
|
+
attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
|
|
281
|
+
attributes[ATTR_TEST_STEP_TITLE] = step.title;
|
|
282
|
+
attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
|
|
283
|
+
if (step.location) {
|
|
284
|
+
const { file, line } = step.location;
|
|
285
|
+
attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
|
|
286
|
+
attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
287
|
+
}
|
|
288
|
+
const stepSpan = {
|
|
289
|
+
traceId,
|
|
290
|
+
spanId: require_trace_context.generateSpanId(),
|
|
291
|
+
parentSpanId,
|
|
292
|
+
name: TEST_STEP_SPAN_NAME,
|
|
293
|
+
startTime: step.startTime,
|
|
294
|
+
endTime: new Date(step.startTime.getTime() + step.duration),
|
|
295
|
+
attributes,
|
|
296
|
+
status: { code: step.error ? 2 : 1 }
|
|
297
|
+
};
|
|
298
|
+
processedSteps.set(stepId, stepSpan);
|
|
299
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps, skippedStepIds);
|
|
300
|
+
}
|
|
301
|
+
onStdOut(chunk, _test, _result) {
|
|
302
|
+
if (this.debug) console.log(chunk.toString().slice(0, -1));
|
|
303
|
+
}
|
|
304
|
+
onStdErr(chunk, _test, _result) {
|
|
305
|
+
if (this.debug) console.log(chunk.toString().slice(0, -1));
|
|
306
|
+
}
|
|
307
|
+
printsToStdio() {
|
|
308
|
+
return this.debug;
|
|
309
|
+
}
|
|
310
|
+
async sendScreenshotsZipToTraceApi(params) {
|
|
311
|
+
const { traceId, screenshots, config } = params;
|
|
312
|
+
const screenshotsZip = await createScreenshotsZip(screenshots);
|
|
313
|
+
const screenshotUrl = `${config.playwrightTraceApiEndpoint}/playwright-otel-reporter/v1/screenshots.zip`;
|
|
314
|
+
const response = await fetch(screenshotUrl, {
|
|
315
|
+
method: "PUT",
|
|
316
|
+
headers: {
|
|
317
|
+
"content-type": "application/zip",
|
|
318
|
+
"x-trace-id": traceId,
|
|
319
|
+
...config.playwrightTraceApiHeaders
|
|
320
|
+
},
|
|
321
|
+
body: screenshotsZip
|
|
322
|
+
});
|
|
323
|
+
if (!response.ok) {
|
|
324
|
+
const error = await response.text();
|
|
325
|
+
throw new Error(`Failed to send screenshots ZIP: ${response.status} ${response.statusText}, ${error}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
function getProjectPlaywrightOpentelemetryConfig(project) {
|
|
330
|
+
return project?.use?.playwrightOpentelemetry;
|
|
331
|
+
}
|
|
332
|
+
function getTestConfig(test) {
|
|
333
|
+
return require_trace_context.resolvePlaywrightOpentelemetryConfig(getProjectPlaywrightOpentelemetryConfig(test.parent.project()), { requireDestination: true });
|
|
334
|
+
}
|
|
335
|
+
function getTestOutputDir(test) {
|
|
336
|
+
const outputDir = test.parent.project()?.outputDir;
|
|
337
|
+
if (!outputDir) throw new Error(`No outputDir found for test "${test.id}"`);
|
|
338
|
+
return outputDir;
|
|
339
|
+
}
|
|
340
|
+
function addDestinationSpans(destinations, spans, options) {
|
|
341
|
+
const key = JSON.stringify(options);
|
|
342
|
+
const destination = destinations.get(key);
|
|
343
|
+
if (destination) {
|
|
344
|
+
destination.spans.push(...spans);
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
destinations.set(key, {
|
|
348
|
+
spans: [...spans],
|
|
349
|
+
options
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
function readTraceContextAttachment(result, testId, allowReporterOnlyFallback) {
|
|
353
|
+
const attachment = result.attachments.find((attachment) => attachment.name === require_trace_context.TRACE_CONTEXT_ATTACHMENT_NAME);
|
|
354
|
+
if (!attachment?.body) {
|
|
355
|
+
if (allowReporterOnlyFallback) return {
|
|
356
|
+
traceId: require_trace_context.generateTraceId(),
|
|
357
|
+
rootSpanId: require_trace_context.generateSpanId()
|
|
358
|
+
};
|
|
359
|
+
throw new Error(`playwright-opentelemetry fixture missing for test ${testId}: expected ${require_trace_context.TRACE_CONTEXT_ATTACHMENT_NAME} attachment. Import test from "playwright-opentelemetry/fixture" or wrap your base test with createPlaywrightOtelTest().`);
|
|
360
|
+
}
|
|
361
|
+
let parsed;
|
|
362
|
+
try {
|
|
363
|
+
parsed = JSON.parse(attachment.body.toString("utf-8"));
|
|
364
|
+
} catch (error) {
|
|
365
|
+
throw new Error(`Invalid ${require_trace_context.TRACE_CONTEXT_ATTACHMENT_NAME} attachment for test ${testId}: ${error}`);
|
|
366
|
+
}
|
|
367
|
+
if (!isTraceContextAttachment(parsed)) throw new Error(`Invalid ${require_trace_context.TRACE_CONTEXT_ATTACHMENT_NAME} attachment for test ${testId}: expected { traceId, rootSpanId }`);
|
|
368
|
+
return parsed;
|
|
369
|
+
}
|
|
370
|
+
function readFixtureSpansAttachment(result, testId) {
|
|
371
|
+
const attachment = result.attachments.find((attachment) => attachment.name === require_trace_context.FIXTURE_SPANS_ATTACHMENT_NAME);
|
|
372
|
+
if (!attachment?.body) return [];
|
|
373
|
+
let parsed;
|
|
374
|
+
try {
|
|
375
|
+
parsed = JSON.parse(attachment.body.toString("utf-8"));
|
|
376
|
+
} catch (error) {
|
|
377
|
+
throw new Error(`Invalid ${require_trace_context.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: ${error}`);
|
|
378
|
+
}
|
|
379
|
+
if (!isRecord(parsed) || !Array.isArray(parsed.spans)) throw new Error(`Invalid ${require_trace_context.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: expected { spans }`);
|
|
380
|
+
return parsed.spans.map((span, index) => parseFixtureSpan(span, testId, index));
|
|
381
|
+
}
|
|
382
|
+
function parseFixtureSpan(value, testId, index) {
|
|
383
|
+
if (!isRecord(value)) throw invalidFixtureSpanError(testId, index);
|
|
384
|
+
const startTime = parseAttachmentDate(value.startTime);
|
|
385
|
+
const endTime = parseAttachmentDate(value.endTime);
|
|
386
|
+
if (typeof value.traceId !== "string" || typeof value.spanId !== "string" || typeof value.name !== "string" || !startTime || !endTime || !isSpanAttributes(value.attributes) || !isSpanStatus(value.status)) throw invalidFixtureSpanError(testId, index);
|
|
387
|
+
return {
|
|
388
|
+
traceId: value.traceId,
|
|
389
|
+
spanId: value.spanId,
|
|
390
|
+
parentSpanId: typeof value.parentSpanId === "string" ? value.parentSpanId : void 0,
|
|
391
|
+
name: value.name,
|
|
392
|
+
startTime,
|
|
393
|
+
endTime,
|
|
394
|
+
attributes: value.attributes,
|
|
395
|
+
status: value.status,
|
|
396
|
+
kind: typeof value.kind === "number" ? value.kind : void 0,
|
|
397
|
+
serviceName: typeof value.serviceName === "string" ? value.serviceName : void 0
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function invalidFixtureSpanError(testId, index) {
|
|
401
|
+
return /* @__PURE__ */ new Error(`Invalid ${require_trace_context.FIXTURE_SPANS_ATTACHMENT_NAME} attachment for test ${testId}: invalid span at index ${index}`);
|
|
402
|
+
}
|
|
403
|
+
function parseAttachmentDate(value) {
|
|
404
|
+
if (typeof value !== "string") return;
|
|
405
|
+
const date = new Date(value);
|
|
406
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
407
|
+
}
|
|
408
|
+
function isSpanStatus(value) {
|
|
409
|
+
return isRecord(value) && typeof value.code === "number";
|
|
410
|
+
}
|
|
411
|
+
function isSpanAttributes(value) {
|
|
412
|
+
if (!isRecord(value)) return false;
|
|
413
|
+
return Object.values(value).every((attributeValue) => typeof attributeValue === "string" || typeof attributeValue === "number" || typeof attributeValue === "boolean" || Array.isArray(attributeValue) && attributeValue.every((item) => typeof item === "string"));
|
|
414
|
+
}
|
|
415
|
+
function isRecord(value) {
|
|
416
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
417
|
+
}
|
|
418
|
+
function isTraceContextAttachment(value) {
|
|
419
|
+
return typeof value === "object" && value !== null && "traceId" in value && "rootSpanId" in value && typeof value.traceId === "string" && typeof value.rootSpanId === "string";
|
|
420
|
+
}
|
|
421
|
+
function getStepId(test, step) {
|
|
422
|
+
const startTimeMs = step.startTime.getTime();
|
|
423
|
+
return [
|
|
424
|
+
test.id,
|
|
425
|
+
step.category,
|
|
426
|
+
startTimeMs,
|
|
427
|
+
...step.titlePath()
|
|
428
|
+
].join(" > ");
|
|
429
|
+
}
|
|
430
|
+
//#endregion
|
|
431
|
+
Object.defineProperty(exports, "PlaywrightOpentelemetryReporter", {
|
|
432
|
+
enumerable: true,
|
|
433
|
+
get: function() {
|
|
434
|
+
return PlaywrightOpentelemetryReporter;
|
|
435
|
+
}
|
|
436
|
+
});
|
package/dist/reporter.cjs
CHANGED
package/dist/reporter.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export
|
|
1
|
+
import { t as PlaywrightOpentelemetryReporter } from "./reporter-DaCojFom.cjs";
|
|
2
|
+
export = PlaywrightOpentelemetryReporter;
|
package/dist/reporter.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { t as PlaywrightOpentelemetryReporter } from "./reporter-DaCojFom.mjs";
|
|
2
|
+
export { PlaywrightOpentelemetryReporter as default };
|
package/dist/reporter.mjs
CHANGED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
//#region package.json
|
|
2
|
+
var version = "0.6.1";
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/shared/otel.ts
|
|
5
|
+
/** Generate a random 32-character hex trace ID. */
|
|
6
|
+
function generateTraceId() {
|
|
7
|
+
return Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
|
|
8
|
+
}
|
|
9
|
+
/** Generate a random 16-character hex span ID. */
|
|
10
|
+
function generateSpanId() {
|
|
11
|
+
return Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
|
|
12
|
+
}
|
|
13
|
+
function parseOtlpHeaders(headersString) {
|
|
14
|
+
const headers = {};
|
|
15
|
+
if (!headersString) return headers;
|
|
16
|
+
for (const pair of headersString.split(",")) {
|
|
17
|
+
const [key, ...valueParts] = pair.split("=");
|
|
18
|
+
if (key && valueParts.length > 0) headers[key.trim()] = valueParts.join("=").trim();
|
|
19
|
+
}
|
|
20
|
+
return headers;
|
|
21
|
+
}
|
|
22
|
+
function dateToNanoseconds(date) {
|
|
23
|
+
return (BigInt(date.getTime()) * BigInt(1e6)).toString();
|
|
24
|
+
}
|
|
25
|
+
function toOtlpAttributes(attributes) {
|
|
26
|
+
return Object.entries(attributes).map(([key, value]) => {
|
|
27
|
+
if (Array.isArray(value)) return {
|
|
28
|
+
key,
|
|
29
|
+
value: { arrayValue: { values: value.map((item) => ({ stringValue: item })) } }
|
|
30
|
+
};
|
|
31
|
+
if (typeof value === "number") return {
|
|
32
|
+
key,
|
|
33
|
+
value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
|
|
34
|
+
};
|
|
35
|
+
if (typeof value === "boolean") return {
|
|
36
|
+
key,
|
|
37
|
+
value: { boolValue: value }
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
key,
|
|
41
|
+
value: { stringValue: value }
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const SPAN_KIND_INTERNAL = 1;
|
|
46
|
+
function buildResourceSpan(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 ?? 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 {
|
|
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
|
+
function buildOtlpRequest(spans, serviceName, playwrightVersion) {
|
|
88
|
+
const spansByService = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const span of spans) {
|
|
90
|
+
const spanServiceName = span.serviceName ?? serviceName;
|
|
91
|
+
const serviceSpans = spansByService.get(spanServiceName);
|
|
92
|
+
if (serviceSpans) serviceSpans.push(span);
|
|
93
|
+
else spansByService.set(spanServiceName, [span]);
|
|
94
|
+
}
|
|
95
|
+
const resourceSpans = [];
|
|
96
|
+
for (const [svcName, svcSpans] of spansByService) resourceSpans.push(buildResourceSpan(svcSpans, svcName, playwrightVersion));
|
|
97
|
+
return { resourceSpans };
|
|
98
|
+
}
|
|
99
|
+
async function sendSpans(spans, options) {
|
|
100
|
+
if (spans.length === 0) return;
|
|
101
|
+
const body = JSON.stringify(buildOtlpRequest(spans, options.serviceName, options.playwrightVersion));
|
|
102
|
+
if (options.debug) console.log("Sending spans to", options.tracesEndpoint);
|
|
103
|
+
const response = await fetch(options.tracesEndpoint, {
|
|
104
|
+
method: "POST",
|
|
105
|
+
body,
|
|
106
|
+
headers: {
|
|
107
|
+
"content-type": "application/json",
|
|
108
|
+
...options.headers || {}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
if (!response.ok) {
|
|
112
|
+
const error = await response.text();
|
|
113
|
+
throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/shared/config.ts
|
|
118
|
+
function resolvePlaywrightOpentelemetryConfig(config, options = {}) {
|
|
119
|
+
const envOtlpHeaders = parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS);
|
|
120
|
+
const envTraceApiHeaders = parseOtlpHeaders(process.env.PLAYWRIGHT_TRACE_API_HEADERS);
|
|
121
|
+
const debugEnv = process.env.PLAYWRIGHT_OPENTELEMETRY_DEBUG;
|
|
122
|
+
const resolvedConfig = {
|
|
123
|
+
otlpEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || config?.otlpEndpoint || "",
|
|
124
|
+
otlpHeaders: {
|
|
125
|
+
...config?.otlpHeaders,
|
|
126
|
+
...envOtlpHeaders
|
|
127
|
+
},
|
|
128
|
+
playwrightTraceApiEndpoint: process.env.PLAYWRIGHT_TRACE_API_ENDPOINT || config?.playwrightTraceApiEndpoint || "",
|
|
129
|
+
playwrightTraceApiHeaders: {
|
|
130
|
+
...config?.playwrightTraceApiHeaders,
|
|
131
|
+
...envTraceApiHeaders
|
|
132
|
+
},
|
|
133
|
+
storeTraceZip: config?.storeTraceZip === true,
|
|
134
|
+
serviceName: process.env.OTEL_SERVICE_NAME || config?.serviceName || "playwright-tests",
|
|
135
|
+
debug: debugEnv === void 0 ? config?.debug ?? false : debugEnv === "1" || debugEnv === "true"
|
|
136
|
+
};
|
|
137
|
+
if (options.requireDestination === true && !hasPlaywrightOpentelemetryDestination(resolvedConfig)) throw new Error(getConfigurationErrorMessage());
|
|
138
|
+
return resolvedConfig;
|
|
139
|
+
}
|
|
140
|
+
function hasPlaywrightOpentelemetryDestination(config) {
|
|
141
|
+
return Boolean(config.otlpEndpoint || config.playwrightTraceApiEndpoint || config.storeTraceZip);
|
|
142
|
+
}
|
|
143
|
+
function getConfigurationErrorMessage() {
|
|
144
|
+
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 export OTEL_SERVICE_NAME=\"my-service\"\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: 'http://localhost:4317/v1/traces',\n otlpHeaders: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n serviceName: 'my-service',\n },\n },\n reporter: [['playwright-opentelemetry/reporter']],\n});\n\nNote: Environment variables take precedence over use.playwrightOpentelemetry options.\n";
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
//#region src/fixture/trace-context.ts
|
|
148
|
+
const TRACE_CONTEXT_ATTACHMENT_NAME = "playwright-opentelemetry-trace-context";
|
|
149
|
+
const FIXTURE_SPANS_ATTACHMENT_NAME = "playwright-opentelemetry-fixture-spans";
|
|
150
|
+
async function createTestTraceContext(testInfo) {
|
|
151
|
+
const traceContext = {
|
|
152
|
+
traceId: generateTraceId(),
|
|
153
|
+
rootSpanId: generateSpanId(),
|
|
154
|
+
spans: [],
|
|
155
|
+
requestContexts: /* @__PURE__ */ new WeakMap(),
|
|
156
|
+
addSpan(span) {
|
|
157
|
+
this.spans.push(span);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
await testInfo.attach(TRACE_CONTEXT_ATTACHMENT_NAME, {
|
|
161
|
+
body: JSON.stringify({
|
|
162
|
+
traceId: traceContext.traceId,
|
|
163
|
+
rootSpanId: traceContext.rootSpanId
|
|
164
|
+
}),
|
|
165
|
+
contentType: "application/json"
|
|
166
|
+
});
|
|
167
|
+
return traceContext;
|
|
168
|
+
}
|
|
169
|
+
async function flushFixtureSpans(traceContext, config, testInfo) {
|
|
170
|
+
if (traceContext.spans.length === 0) return;
|
|
171
|
+
if (config.storeTraceZip && testInfo) await testInfo.attach(FIXTURE_SPANS_ATTACHMENT_NAME, {
|
|
172
|
+
body: JSON.stringify({ spans: traceContext.spans.map(serializeSpanForAttachment) }),
|
|
173
|
+
contentType: "application/json"
|
|
174
|
+
});
|
|
175
|
+
const destinations = fixtureSpanDestinations(config);
|
|
176
|
+
if (destinations.length === 0) return;
|
|
177
|
+
await Promise.all(destinations.map((destination) => sendSpans(traceContext.spans, {
|
|
178
|
+
tracesEndpoint: destination.tracesEndpoint,
|
|
179
|
+
headers: destination.headers,
|
|
180
|
+
serviceName: "playwright-browser",
|
|
181
|
+
playwrightVersion: "unknown",
|
|
182
|
+
debug: config.debug
|
|
183
|
+
})));
|
|
184
|
+
}
|
|
185
|
+
function serializeSpanForAttachment(span) {
|
|
186
|
+
return {
|
|
187
|
+
...span,
|
|
188
|
+
startTime: span.startTime.toISOString(),
|
|
189
|
+
endTime: span.endTime.toISOString()
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function fixtureSpanDestinations(config) {
|
|
193
|
+
const destinations = [];
|
|
194
|
+
if (config.playwrightTraceApiEndpoint) destinations.push({
|
|
195
|
+
tracesEndpoint: `${config.playwrightTraceApiEndpoint}/v1/traces`,
|
|
196
|
+
headers: config.playwrightTraceApiHeaders
|
|
197
|
+
});
|
|
198
|
+
if (config.otlpEndpoint) destinations.push({
|
|
199
|
+
tracesEndpoint: config.otlpEndpoint,
|
|
200
|
+
headers: config.otlpHeaders
|
|
201
|
+
});
|
|
202
|
+
return destinations;
|
|
203
|
+
}
|
|
204
|
+
//#endregion
|
|
205
|
+
export { resolvePlaywrightOpentelemetryConfig as a, generateTraceId as c, flushFixtureSpans as i, sendSpans as l, TRACE_CONTEXT_ATTACHMENT_NAME as n, buildOtlpRequest as o, createTestTraceContext as r, generateSpanId as s, FIXTURE_SPANS_ATTACHMENT_NAME as t };
|