@ctrl/sentry-tests 0.1.1 → 0.1.2

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,545 +0,0 @@
1
- import { execFileSync } from "node:child_process";
2
- import { randomBytes, randomUUID } from "node:crypto";
3
- import { readFileSync } from "node:fs";
4
- import { isAbsolute, relative } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { stripVTControlCharacters } from "node:util";
7
-
8
- // src/envelope.ts
9
- /** https://develop.sentry.dev/sdk/overview/#parsing-the-dsn */
10
- function parseDsn(dsn) {
11
- let parsed;
12
- try {
13
- parsed = new URL(dsn);
14
- } catch {
15
- throw new Error(`@ctrl/sentry-tests: invalid DSN ${JSON.stringify(dsn)}`);
16
- }
17
- const segments = parsed.pathname.split("/").filter(Boolean);
18
- const projectId = segments.pop();
19
- if (!parsed.username || projectId === void 0) throw new Error(`@ctrl/sentry-tests: invalid DSN ${JSON.stringify(dsn)} (expected https://<key>@<host>/<project>)`);
20
- const prefix = segments.length > 0 ? `/${segments.join("/")}` : "";
21
- const query = new URLSearchParams({
22
- sentry_key: parsed.username,
23
- sentry_version: "7",
24
- sentry_client: `${SDK.name}/${SDK.version}`
25
- });
26
- return {
27
- dsn,
28
- url: `${parsed.protocol}//${parsed.host}${prefix}/api/${projectId}/envelope/?${query}`,
29
- host: parsed.host,
30
- projectId
31
- };
32
- }
33
- const SDK = {
34
- name: "ctrl.sentry-tests",
35
- version: "0.0.0"
36
- };
37
- /** 32 hex characters (event and trace ids). */
38
- const uuid = () => randomUUID().replaceAll("-", "");
39
- /** 16 hex characters. */
40
- const spanId = () => randomBytes(8).toString("hex");
41
- const encoder = new TextEncoder();
42
- /** https://develop.sentry.dev/sdk/data-model/envelopes/#serialization-format */
43
- function serializeEnvelope(envelope, dsn) {
44
- const parts = [];
45
- const line = (text) => parts.push(encoder.encode(`${text}\n`));
46
- line(JSON.stringify({
47
- event_id: envelope.eventId,
48
- sent_at: (/* @__PURE__ */ new Date()).toISOString(),
49
- sdk: SDK,
50
- ...dsn ? { dsn: dsn.dsn } : {}
51
- }));
52
- for (const item of envelope.items) {
53
- const payload = encoder.encode(typeof item.payload === "string" ? item.payload : JSON.stringify(item.payload));
54
- const header = item.type === "attachment" ? {
55
- type: "attachment",
56
- length: payload.byteLength,
57
- filename: item.filename,
58
- content_type: item.contentType,
59
- attachment_type: "event.attachment"
60
- } : {
61
- type: item.type,
62
- length: payload.byteLength
63
- };
64
- line(JSON.stringify(header));
65
- parts.push(payload, encoder.encode("\n"));
66
- }
67
- const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0));
68
- let at = 0;
69
- for (const p of parts) {
70
- out.set(p, at);
71
- at += p.byteLength;
72
- }
73
- return out;
74
- }
75
- const SEND_TIMEOUT_MS = 15e3;
76
- /** POST one envelope; resolves to an error message, or null when it was accepted. */
77
- async function sendEnvelope(envelope, target) {
78
- try {
79
- const response = await fetch(target.url, {
80
- method: "POST",
81
- headers: { "content-type": "application/x-sentry-envelope" },
82
- body: serializeEnvelope(envelope, target.dsn),
83
- signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
84
- });
85
- if (response.ok) return null;
86
- return `${target.label} answered ${response.status} ${(await response.text().catch(() => "")).slice(0, 200)}`.trim();
87
- } catch (error) {
88
- return `${target.label}: ${error.message}`;
89
- }
90
- }
91
- const V8_FRAME = /^\s*at (?:(?:async )?(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
92
- /** V8 stack lines as frames, oldest first (Sentry's order). */
93
- function parseStack(stack) {
94
- if (!stack) return [];
95
- const frames = [];
96
- for (const line of stack.split("\n")) {
97
- const m = V8_FRAME.exec(line);
98
- if (m !== null) frames.push({
99
- method: m[1],
100
- file: m[2],
101
- line: Number(m[3]),
102
- column: Number(m[4])
103
- });
104
- }
105
- return frames.reverse();
106
- }
107
- const sources = /* @__PURE__ */ new Map();
108
- function sourceLines(path) {
109
- let lines = sources.get(path);
110
- if (lines === void 0) {
111
- try {
112
- lines = readFileSync(path, "utf8").split("\n");
113
- } catch {
114
- lines = null;
115
- }
116
- sources.set(path, lines);
117
- }
118
- return lines;
119
- }
120
- const CONTEXT_LINES = 5;
121
- /**
122
- * Library code outside node_modules: the directory holding this package (node_modules/@ctrl/ when
123
- * installed, the workspace's packages/ here, where @ctrl/dom's packages sit next to it). Frames
124
- * there (query wrappers, tracing channels, the runner) are not the test's even when linked.
125
- */
126
- const OWN_CODE = fileURLToPath(new URL("../../", import.meta.url));
127
- /**
128
- * Sentry frames from parsed ones, oldest first: paths relative to `root`, the test's own code in
129
- * app (not node_modules, Node's internals or the packages next to this one), with source context
130
- * read from disk (Sentry cannot fetch a local file).
131
- */
132
- function toSentryFrames(frames, root) {
133
- return frames.map((f) => {
134
- const absPath = f.file.startsWith("file://") ? fileURLToPath(f.file) : f.file;
135
- const local = isAbsolute(absPath);
136
- const inApp = local && !absPath.includes("/node_modules/") && !absPath.startsWith(OWN_CODE);
137
- const frame = {
138
- filename: local ? relative(root, absPath) : absPath,
139
- abs_path: absPath,
140
- ...f.method ? { function: f.method } : {},
141
- ...f.line !== void 0 ? { lineno: f.line } : {},
142
- ...f.column !== void 0 ? { colno: f.column } : {},
143
- in_app: inApp
144
- };
145
- const lines = inApp && f.line !== void 0 ? sourceLines(absPath) : null;
146
- if (lines !== null && f.line >= 1 && f.line <= lines.length) {
147
- const at = f.line - 1;
148
- frame.pre_context = lines.slice(Math.max(0, at - CONTEXT_LINES), at);
149
- frame.context_line = lines[at];
150
- frame.post_context = lines.slice(at + 1, at + 1 + CONTEXT_LINES);
151
- }
152
- return frame;
153
- });
154
- }
155
-
156
- // src/options.ts
157
- const SPOTLIGHT_DEFAULT = "http://localhost:8969/stream";
158
- /** Where reports go and what they contain, or null when there is nowhere to send them. */
159
- function resolveOptions(options = {}, env = process.env) {
160
- const targets = [];
161
- const dsn = options.dsn ?? env.SENTRY_DSN;
162
- if (dsn) {
163
- const parsed = parseDsn(dsn);
164
- targets.push({
165
- label: parsed.host,
166
- url: parsed.url,
167
- dsn: parsed
168
- });
169
- }
170
- const spotlight = options.spotlight ?? spotlightFromEnv(env.SENTRY_SPOTLIGHT);
171
- if (spotlight) targets.push({
172
- label: "Spotlight",
173
- url: spotlight === true ? SPOTLIGHT_DEFAULT : spotlight,
174
- dsn: null
175
- });
176
- if (targets.length === 0) return null;
177
- return {
178
- targets,
179
- environment: options.environment ?? env.SENTRY_ENVIRONMENT ?? (env.CI ? "ci" : "local"),
180
- release: options.release ?? env.SENTRY_RELEASE ?? env.GITHUB_SHA ?? gitCommit(),
181
- traces: options.traces ?? true,
182
- tracesSampleRate: sampleRate(options.tracesSampleRate ?? env.SENTRY_TRACES_SAMPLE_RATE),
183
- failures: options.failures ?? true,
184
- flaky: options.flaky ?? true,
185
- attachments: options.attachments ?? true,
186
- tags: options.tags ?? {}
187
- };
188
- }
189
- function sampleRate(value) {
190
- const rate = typeof value === "string" ? Number(value) : value ?? 1;
191
- return Number.isFinite(rate) ? Math.min(1, Math.max(0, rate)) : 1;
192
- }
193
- function spotlightFromEnv(value) {
194
- if (value === void 0 || value === "" || value === "0" || value.toLowerCase() === "false") return false;
195
- if (value === "1" || value.toLowerCase() === "true") return true;
196
- return value;
197
- }
198
- function gitCommit() {
199
- try {
200
- return execFileSync("git", ["rev-parse", "HEAD"], {
201
- encoding: "utf8",
202
- stdio: [
203
- "ignore",
204
- "pipe",
205
- "ignore"
206
- ]
207
- }).trim() || void 0;
208
- } catch {
209
- return;
210
- }
211
- }
212
-
213
- // src/report.ts
214
- /** Sentry keeps at most 1000 spans per transaction. */
215
- const MAX_SPANS = 1e3;
216
- const MAX_CONSOLE_MESSAGE = 1e3;
217
- /** The test name a file-level failure is reported under. */
218
- const FILE_FAILURE = "(file failed to load)";
219
- const MAX_MESSAGE = 8192;
220
- /** Sentry truncates tag values longer than this. */
221
- const MAX_TAG = 200;
222
- const ORIGIN = "auto.test.sentry_tests";
223
- /** Structure spans that say nothing a breadcrumb list needs. */
224
- const NOT_BREADCRUMBS = /* @__PURE__ */ new Set([
225
- "test.case",
226
- "test.fn",
227
- "test.suite",
228
- "test.collect"
229
- ]);
230
- function buildReport(report, options) {
231
- const out = {
232
- envelopes: [],
233
- traces: 0,
234
- failures: 0,
235
- flaky: 0
236
- };
237
- const tests = report.tests.filter((t) => t.state !== "skip");
238
- const outsideTests = report.outsideTests ?? [];
239
- if (tests.length === 0 && outsideTests.length === 0) return out;
240
- const relativePath = relative(report.root, report.file);
241
- const file = relativePath === "" || relativePath.startsWith("..") ? report.file : relativePath;
242
- const traceId = uuid();
243
- const rootSpanId = spanId();
244
- const tags = {
245
- runner: report.runner,
246
- "test.file": tag(file),
247
- ...report.project ? { "test.project": tag(report.project) } : {},
248
- ...options.tags
249
- };
250
- const base = {
251
- platform: "node",
252
- environment: options.environment,
253
- ...options.release ? { release: options.release } : {},
254
- sdk: SDK,
255
- contexts: { runtime: {
256
- name: "node",
257
- version: process.version
258
- } }
259
- };
260
- const collected = report.collected;
261
- const spans = [...collected?.spans ?? []].sort((a, b) => a.start_timestamp - b.start_timestamp);
262
- const byId = new Map(spans.map((s) => [s.span_id, s]));
263
- for (const test of tests) {
264
- const record = collected?.tests[test.key];
265
- const last = record?.spanIds.at(-1);
266
- if (record === void 0 || last === void 0) continue;
267
- const span = byId.get(last);
268
- span.status = test.state === "pass" ? "ok" : "internal_error";
269
- span.data = {
270
- ...span.data,
271
- "test.retries": test.retries,
272
- "test.flaky": test.flaky,
273
- ...record.droppedSpans ? { "spans.dropped": record.droppedSpans } : {}
274
- };
275
- }
276
- const owners = /* @__PURE__ */ new Map();
277
- const ownerOf = (span) => {
278
- let owner = owners.get(span.span_id);
279
- if (owner !== void 0) return owner;
280
- const parent = span.parent_span_id === void 0 ? void 0 : byId.get(span.parent_span_id);
281
- owner = span.op === "test.case" ? span.span_id : parent === void 0 ? null : ownerOf(parent);
282
- owners.set(span.span_id, owner);
283
- return owner;
284
- };
285
- const fileLevel = [];
286
- const groups = /* @__PURE__ */ new Map();
287
- for (const span of spans) {
288
- const owner = ownerOf(span);
289
- if (owner === null) fileLevel.push(span);
290
- else {
291
- let group = groups.get(owner);
292
- if (group === void 0) groups.set(owner, group = []);
293
- group.push(span);
294
- }
295
- }
296
- let dropped = Math.max(0, fileLevel.length - MAX_SPANS) + (collected?.droppedSpans ?? 0);
297
- const chunks = [fileLevel.slice(0, MAX_SPANS)];
298
- for (const group of groups.values()) {
299
- const kept = group.slice(0, MAX_SPANS);
300
- dropped += group.length - kept.length;
301
- if (chunks.at(-1).length + kept.length > MAX_SPANS && chunks.at(-1).length > 0) chunks.push([]);
302
- chunks.at(-1).push(...kept);
303
- }
304
- /** The parent each span was sent with: an error event's trace context links to the same. */
305
- const sentParent = /* @__PURE__ */ new Map();
306
- const traced = collected !== null && spans.length > 0 && options.traces && (options.tracesSampleRate >= 1 || Math.random() < options.tracesSampleRate);
307
- if (traced) {
308
- chunks.forEach((chunk, index) => {
309
- const first = index === 0;
310
- const chunkSpanId = first ? rootSpanId : spanId();
311
- const ids = new Set(chunk.map((s) => s.span_id));
312
- const eventId = uuid();
313
- const payloadSpans = chunk.map((span) => {
314
- const parent = span.parent_span_id !== void 0 && ids.has(span.parent_span_id) ? span.parent_span_id : chunkSpanId;
315
- sentParent.set(span.span_id, parent);
316
- return {
317
- ...span,
318
- trace_id: traceId,
319
- parent_span_id: parent,
320
- origin: ORIGIN
321
- };
322
- });
323
- const failed = chunk.some((s) => s.op === "test.case" && s.status !== "ok");
324
- out.envelopes.push({
325
- eventId,
326
- items: [{
327
- type: "transaction",
328
- payload: {
329
- ...base,
330
- type: "transaction",
331
- event_id: eventId,
332
- transaction: first ? file : `${file} (part ${index + 1} of ${chunks.length})`,
333
- transaction_info: { source: "custom" },
334
- ...first ? {
335
- start_timestamp: collected.startedAt,
336
- timestamp: collected.endedAt
337
- } : bounds(chunk),
338
- tags,
339
- contexts: {
340
- ...base.contexts,
341
- trace: {
342
- trace_id: traceId,
343
- span_id: chunkSpanId,
344
- ...first ? {} : { parent_span_id: rootSpanId },
345
- op: "test.file",
346
- status: (first ? tests.some((t) => t.state === "fail") : failed) ? "internal_error" : "ok",
347
- origin: ORIGIN,
348
- ...first && dropped || chunks.length > 1 ? { data: {
349
- ...first && dropped ? { "spans.dropped": dropped } : {},
350
- ...chunks.length > 1 ? {
351
- "test.part": index + 1,
352
- "test.parts": chunks.length
353
- } : {}
354
- } } : {}
355
- }
356
- },
357
- spans: payloadSpans,
358
- ...first && report.environmentSetupMs !== void 0 ? { measurements: { environment_setup: {
359
- value: report.environmentSetupMs,
360
- unit: "millisecond"
361
- } } } : {}
362
- }
363
- }]
364
- });
365
- });
366
- out.traces++;
367
- }
368
- for (const test of tests) {
369
- const failed = test.state === "fail";
370
- if (!(failed ? options.failures : test.flaky && options.flaky)) continue;
371
- const record = collected?.tests[test.key];
372
- const context = failed ? record?.failures.at(-1) : record?.failures[0];
373
- const attempt = failed ? record?.spanIds.at(-1) : record?.spanIds[0];
374
- const reported = failed ? test.errors.at(-1) ?? context?.error : context?.error ?? test.errors[0];
375
- const error = reported !== void 0 && !reported.name && context?.error?.name ? {
376
- ...reported,
377
- name: context.error.name
378
- } : reported;
379
- const attached = options.attachments ? context?.attachments ?? [] : [];
380
- const exception = toException(error ?? { message: "Test failed" }, report.root, attached.map((a) => a.filename));
381
- if (!failed) {
382
- exception.value = `${test.name} failed, then passed on retry ${test.retries}. The failed attempt:\n\n${exception.type}: ${exception.value}`;
383
- exception.type = "FlakyTest";
384
- }
385
- const testSpan = attempt === void 0 ? void 0 : byId.get(attempt);
386
- const eventId = uuid();
387
- const items = [{
388
- type: "event",
389
- payload: {
390
- ...base,
391
- event_id: eventId,
392
- timestamp: testSpan?.timestamp ?? Date.now() / 1e3,
393
- level: failed ? "error" : "warning",
394
- logger: `${report.runner}.test`,
395
- transaction: `${file} > ${test.name}`,
396
- fingerprint: [
397
- failed ? "sentry-tests.test-failure" : "sentry-tests.flaky-test",
398
- file,
399
- test.name
400
- ],
401
- exception: { values: [exception] },
402
- tags: {
403
- ...tags,
404
- "test.name": tag(test.name),
405
- flaky: String(test.flaky),
406
- retries: String(test.retries)
407
- },
408
- contexts: {
409
- ...base.contexts,
410
- ...context?.contexts,
411
- ...traced && attempt !== void 0 ? { trace: {
412
- trace_id: traceId,
413
- span_id: attempt,
414
- parent_span_id: sentParent.get(attempt),
415
- op: "test.case"
416
- } } : {},
417
- test: {
418
- name: test.name,
419
- file,
420
- duration_ms: test.duration,
421
- retries: test.retries,
422
- flaky: test.flaky
423
- }
424
- },
425
- breadcrumbs: { values: breadcrumbs(attempt !== void 0 && groups.get(attempt) || [], test.console ?? []) }
426
- }
427
- }];
428
- for (const a of attached) items.push({
429
- type: "attachment",
430
- filename: a.filename,
431
- contentType: a.contentType,
432
- payload: a.data
433
- });
434
- out.envelopes.push({
435
- eventId,
436
- items
437
- });
438
- if (failed) out.failures++;
439
- else out.flaky++;
440
- }
441
- if (options.failures) for (const { name, error } of outsideTests) {
442
- const eventId = uuid();
443
- out.envelopes.push({
444
- eventId,
445
- items: [{
446
- type: "event",
447
- payload: {
448
- ...base,
449
- event_id: eventId,
450
- timestamp: Date.now() / 1e3,
451
- level: "error",
452
- logger: `${report.runner}.test`,
453
- transaction: `${file} > ${name}`,
454
- fingerprint: [
455
- "sentry-tests.test-failure",
456
- file,
457
- name
458
- ],
459
- exception: { values: [toException(error, report.root)] },
460
- tags: {
461
- ...tags,
462
- "test.name": tag(name),
463
- flaky: "false",
464
- retries: "0"
465
- },
466
- contexts: {
467
- ...base.contexts,
468
- test: {
469
- name,
470
- file
471
- }
472
- }
473
- }
474
- }]
475
- });
476
- out.failures++;
477
- }
478
- return out;
479
- }
480
- /** A part transaction's extent: its spans' earliest start and latest end. */
481
- function bounds(spans) {
482
- let start = Infinity;
483
- let end = 0;
484
- for (const s of spans) {
485
- if (s.start_timestamp < start) start = s.start_timestamp;
486
- if (s.timestamp > end) end = s.timestamp;
487
- }
488
- return {
489
- start_timestamp: start,
490
- timestamp: end
491
- };
492
- }
493
- function tag(value) {
494
- return value.length > MAX_TAG ? `${value.slice(0, 199)}…` : value;
495
- }
496
- /**
497
- * Where a Testing Library message starts dumping the page: the DOM (`Ignored nodes: …` then the
498
- * markup), the role listing, or @ctrl/dom's agent mode snapshot. Redundant once the page is attached.
499
- */
500
- const PAGE_DUMP = /\n\n(?:Ignored nodes: |Here are the accessible roles:|Accessibility snapshot of <body>|DOM of <body>|<body)/;
501
- function toException(error, root, attachments = []) {
502
- let text = stripVTControlCharacters(error.message);
503
- const dump = attachments.length > 0 ? PAGE_DUMP.exec(text) : null;
504
- if (dump !== null) text = `${text.slice(0, dump.index)}\n\n(The page when the test failed is attached: ${attachments.join(", ")}.)`;
505
- const message = text.length > MAX_MESSAGE ? `${text.slice(0, 8191)}…` : text;
506
- const frames = error.frames !== void 0 ? [...error.frames].reverse() : parseStack(error.stack);
507
- return {
508
- type: error.name || "Error",
509
- value: message,
510
- mechanism: {
511
- type: "sentry-tests",
512
- handled: true
513
- },
514
- ...frames.length > 0 ? { stacktrace: { frames: toSentryFrames(frames, root) } } : {}
515
- };
516
- }
517
- /** What the test did and printed before it failed, oldest first: the issue page's breadcrumb timeline. */
518
- function breadcrumbs(spans, output) {
519
- return [...spans.filter((s) => !NOT_BREADCRUMBS.has(s.op)).map((s) => ({
520
- type: "default",
521
- category: s.op,
522
- message: `${s.description} (${spanDetails(s)})`,
523
- timestamp: s.start_timestamp,
524
- level: s.status === "ok" ? "info" : "error"
525
- })), ...output.map((c) => ({
526
- type: "default",
527
- category: "console",
528
- message: c.message.length > MAX_CONSOLE_MESSAGE ? `${c.message.slice(0, 999)}…` : c.message,
529
- timestamp: c.timestamp,
530
- level: c.stream === "stderr" ? "error" : "info"
531
- }))].sort((a, b) => a.timestamp - b.timestamp).slice(-100);
532
- }
533
- /** `10.4 ms, 40 checks, 0 matches, 1994 ms skipped` */
534
- function spanDetails(span) {
535
- const ms = (span.timestamp - span.start_timestamp) * 1e3;
536
- const parts = [`${ms < 10 ? ms.toFixed(1) : Math.round(ms)} ms`];
537
- const { checks, matches } = span.data;
538
- if (typeof checks === "number") parts.push(`${checks} ${checks === 1 ? "check" : "checks"}`);
539
- if (typeof matches === "number") parts.push(`${matches} ${matches === 1 ? "match" : "matches"}`);
540
- const skipped = span.data["clock.skipped_ms"];
541
- if (typeof skipped === "number") parts.push(`${Math.round(skipped)} ms skipped`);
542
- return parts.join(", ");
543
- }
544
-
545
- export { sendEnvelope as i, buildReport as n, resolveOptions as r, FILE_FAILURE as t };