@ctrl/sentry-tests 0.0.0-stage → 0.1.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.
@@ -0,0 +1,271 @@
1
+ import { n as SPAN_CHANNELS, t as FAILURE_CHANNEL } from "./channels-CLjUmyuI.js";
2
+ import { randomBytes } from "node:crypto";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { channel, tracingChannel } from "node:diagnostics_channel";
5
+ import { performance } from "node:perf_hooks";
6
+ import { setTimeout } from "node:timers/promises";
7
+
8
+ // src/html.ts
9
+ const VOID = /* @__PURE__ */ new Set([
10
+ "area",
11
+ "base",
12
+ "br",
13
+ "col",
14
+ "embed",
15
+ "hr",
16
+ "img",
17
+ "input",
18
+ "link",
19
+ "meta",
20
+ "source",
21
+ "track",
22
+ "wbr"
23
+ ]);
24
+ const SKIP_CONTENT = /* @__PURE__ */ new Set([
25
+ "style",
26
+ "script",
27
+ "template"
28
+ ]);
29
+ /** `document.body` as indented HTML, cut at `max` characters; undefined without a body. */
30
+ function pageHtml(document, max = 2e5) {
31
+ const body = document?.body;
32
+ if (body == null) return void 0;
33
+ const lines = [];
34
+ let size = 0;
35
+ const push = (line) => {
36
+ lines.push(line);
37
+ size += line.length + 1;
38
+ return size < max;
39
+ };
40
+ const write = (node, depth) => {
41
+ const indent = " ".repeat(depth);
42
+ if (node.nodeType === 3) {
43
+ const text = (node.data ?? "").replace(/\s+/g, " ").trim();
44
+ return text === "" || push(indent + escapeText(text));
45
+ }
46
+ if (node.nodeType !== 1 || node.localName === void 0) return true;
47
+ const open = `<${node.localName}${attributes(node)}`;
48
+ if (VOID.has(node.localName)) return push(`${indent}${open} />`);
49
+ const children = SKIP_CONTENT.has(node.localName) ? [] : childList(node);
50
+ if (children.length === 0) return push(`${indent}${open}></${node.localName}>`);
51
+ if (children.length === 1 && children[0].nodeType === 3) {
52
+ const text = (children[0].data ?? "").replace(/\s+/g, " ").trim();
53
+ if (text.length <= 80) return push(`${indent}${open}>${escapeText(text)}</${node.localName}>`);
54
+ }
55
+ if (!push(`${indent}${open}>`)) return false;
56
+ for (const child of children) if (!write(child, depth + 1)) return false;
57
+ return push(`${indent}</${node.localName}>`);
58
+ };
59
+ try {
60
+ if (!write(body, 0)) lines.push("<!-- truncated -->");
61
+ } catch {
62
+ return;
63
+ }
64
+ return lines.join("\n");
65
+ }
66
+ function childList(node) {
67
+ const out = [];
68
+ const list = node.childNodes;
69
+ if (list === void 0) return out;
70
+ for (let i = 0; i < list.length; i++) if (list[i].nodeType === 1 || list[i].nodeType === 3) out.push(list[i]);
71
+ return out;
72
+ }
73
+ function attributes(node) {
74
+ const list = node.attributes;
75
+ if (list === void 0) return "";
76
+ let out = "";
77
+ for (let i = 0; i < list.length; i++) out += ` ${list[i].name}="${list[i].value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}"`;
78
+ return out;
79
+ }
80
+ function escapeText(text) {
81
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
82
+ }
83
+
84
+ // src/collector.ts
85
+ /** Library spans kept per test (a waitFor polling a query can publish hundreds), and outside tests. */
86
+ const MAX_TEST_SPANS = 300;
87
+ const MAX_FILE_SPANS = 1e3;
88
+ const MAX_ATTACHMENT = 2e5;
89
+ const MAX_WAIT_MS = 5e3;
90
+ /** Epoch seconds from the real clock. */
91
+ const realNow = () => (performance.timeOrigin + performance.now()) / 1e3;
92
+ /**
93
+ * Span ids: 16 hex characters, unique within a test file's trace. 4 random bytes per worker and a
94
+ * counter, hex-encoded in one go: 6x faster than 8 random bytes per span, and a flat string (a
95
+ * prefix concatenated with the counter would keep both alive as a cons string).
96
+ */
97
+ function spanIds() {
98
+ const bytes = randomBytes(8);
99
+ let next = 0;
100
+ return () => {
101
+ bytes.writeUInt32BE(next++, 4);
102
+ return bytes.toString("hex");
103
+ };
104
+ }
105
+ function createCollector() {
106
+ const current = new AsyncLocalStorage();
107
+ const OPEN = Symbol("sentry-tests.span");
108
+ const spanId = spanIds();
109
+ let entered = null;
110
+ let file = emptyFile();
111
+ let fileOwner = {
112
+ kept: 0,
113
+ limit: MAX_FILE_SPANS,
114
+ counts: file
115
+ };
116
+ const owners = /* @__PURE__ */ new Map();
117
+ const parent = () => current.getStore() ?? entered;
118
+ const open = (op, description, data = {}, test) => {
119
+ const up = parent();
120
+ const now = realNow();
121
+ if (file.startedAt === 0) file.startedAt = now;
122
+ return {
123
+ span: {
124
+ span_id: spanId(),
125
+ parent_span_id: up?.span.span_id,
126
+ op,
127
+ description,
128
+ start_timestamp: now,
129
+ timestamp: 0,
130
+ status: "ok",
131
+ data
132
+ },
133
+ owner: test !== void 0 ? owners.get(test) : up?.owner ?? fileOwner
134
+ };
135
+ };
136
+ const openTraced = (context) => {
137
+ const up = parent();
138
+ if (up === null) return void 0;
139
+ const owner = up.owner;
140
+ if (owner.kept === owner.limit) {
141
+ owner.counts.droppedSpans++;
142
+ return up;
143
+ }
144
+ owner.kept++;
145
+ const span = open(context.op, context.description, context.data);
146
+ context[OPEN] = span;
147
+ return span;
148
+ };
149
+ const closeTraced = (context) => {
150
+ const span = context[OPEN];
151
+ if (span === void 0) return;
152
+ context[OPEN] = void 0;
153
+ span.span.data = context.data;
154
+ close(span, context.error !== void 0);
155
+ };
156
+ const close = (o, failed = false) => {
157
+ o.span.timestamp = realNow();
158
+ if (failed) o.span.status = "internal_error";
159
+ file.spans.push(o.span);
160
+ };
161
+ const subscribers = {
162
+ start() {},
163
+ end(context) {
164
+ if (!context.async || context.error !== void 0) closeTraced(context);
165
+ },
166
+ asyncStart() {},
167
+ asyncEnd(context) {
168
+ closeTraced(context);
169
+ },
170
+ error() {}
171
+ };
172
+ const channels = SPAN_CHANNELS.map((name) => tracingChannel(name));
173
+ for (const spans of channels) {
174
+ spans.start.bindStore(current, openTraced);
175
+ spans.subscribe(subscribers);
176
+ }
177
+ const failures = channel(FAILURE_CHANNEL);
178
+ return {
179
+ open,
180
+ close,
181
+ run: (o, fn) => current.run(o, fn),
182
+ current: parent,
183
+ enter(o) {
184
+ entered = o;
185
+ },
186
+ test(key) {
187
+ let test = file.tests[key];
188
+ if (test === void 0) {
189
+ test = file.tests[key] = {
190
+ spanIds: [],
191
+ droppedSpans: 0,
192
+ failures: []
193
+ };
194
+ owners.set(test, {
195
+ kept: 0,
196
+ limit: MAX_TEST_SPANS,
197
+ counts: test
198
+ });
199
+ }
200
+ return test;
201
+ },
202
+ async captureFailure(test, name, error, document) {
203
+ const context = {
204
+ attachments: [],
205
+ contexts: {}
206
+ };
207
+ if (typeof error === "object" && error !== null && typeof error.message === "string") {
208
+ const e = error;
209
+ context.error = {
210
+ name: e.name,
211
+ message: e.message,
212
+ stack: e.stack
213
+ };
214
+ }
215
+ const html = pageHtml(document, MAX_ATTACHMENT);
216
+ if (html !== void 0) context.attachments.push({
217
+ filename: "page.html",
218
+ contentType: "text/html",
219
+ data: html
220
+ });
221
+ if (failures.hasSubscribers) {
222
+ const pending = [];
223
+ const message = {
224
+ test: name,
225
+ error,
226
+ document,
227
+ attachments: [],
228
+ contexts: context.contexts,
229
+ waitUntil: (p) => void pending.push(p)
230
+ };
231
+ failures.publish(message);
232
+ if (pending.length > 0) await Promise.race([Promise.allSettled(pending), setTimeout(MAX_WAIT_MS, void 0, { ref: false })]);
233
+ for (const a of message.attachments) if (!context.attachments.some((b) => b.filename === a.filename)) context.attachments.push({
234
+ ...a,
235
+ data: a.data.slice(0, MAX_ATTACHMENT)
236
+ });
237
+ }
238
+ test.failures.push(context);
239
+ },
240
+ finish() {
241
+ const done = file;
242
+ done.endedAt = realNow();
243
+ file = emptyFile();
244
+ fileOwner = {
245
+ kept: 0,
246
+ limit: MAX_FILE_SPANS,
247
+ counts: file
248
+ };
249
+ owners.clear();
250
+ entered = null;
251
+ return done;
252
+ },
253
+ stop() {
254
+ for (const spans of channels) {
255
+ spans.unsubscribe(subscribers);
256
+ spans.start.unbindStore(current);
257
+ }
258
+ }
259
+ };
260
+ }
261
+ function emptyFile() {
262
+ return {
263
+ startedAt: 0,
264
+ endedAt: 0,
265
+ spans: [],
266
+ tests: Object.create(null),
267
+ droppedSpans: 0
268
+ };
269
+ }
270
+
271
+ export { realNow as n, createCollector as t };
@@ -0,0 +1,61 @@
1
+ // src/delivery.ts
2
+ const CONCURRENCY = 6;
3
+ var Delivery = class {
4
+ #options;
5
+ #send;
6
+ #queue = [];
7
+ #active = 0;
8
+ #idle = [];
9
+ #errors = /* @__PURE__ */ new Set();
10
+ #totals = {
11
+ traces: 0,
12
+ failures: 0,
13
+ flaky: 0
14
+ };
15
+ constructor(options, send) {
16
+ this.#options = options;
17
+ this.#send = send;
18
+ }
19
+ add(report) {
20
+ this.#totals.traces += report.traces;
21
+ this.#totals.failures += report.failures;
22
+ this.#totals.flaky += report.flaky;
23
+ for (const envelope of report.envelopes) for (const target of this.#options.targets) this.#queue.push([envelope, target]);
24
+ this.#pump();
25
+ }
26
+ /** Wait for every envelope; a one-line summary of the run (null when nothing was reported). Starts a new run's totals. */
27
+ async flush() {
28
+ if (this.#queue.length > 0 || this.#active > 0) await new Promise((resolve) => this.#idle.push(resolve));
29
+ const { traces, failures, flaky } = this.#totals;
30
+ const errors = [...this.#errors];
31
+ this.#totals = {
32
+ traces: 0,
33
+ failures: 0,
34
+ flaky: 0
35
+ };
36
+ this.#errors.clear();
37
+ if (traces + failures + flaky === 0) return null;
38
+ return `@ctrl/sentry-tests: ${[
39
+ plural(traces, "trace"),
40
+ plural(failures, "failed test"),
41
+ plural(flaky, "flaky test")
42
+ ].join(", ")} → ${this.#options.targets.map((t) => t.label).join(" and ")}${errors.length > 0 ? `; not delivered: ${errors.join("; ")}` : ""}`;
43
+ }
44
+ #pump() {
45
+ while (this.#active < CONCURRENCY && this.#queue.length > 0) {
46
+ const [envelope, target] = this.#queue.shift();
47
+ this.#active++;
48
+ this.#send(envelope, target).then((error) => {
49
+ if (error !== null) this.#errors.add(error);
50
+ this.#active--;
51
+ this.#pump();
52
+ if (this.#active === 0 && this.#queue.length === 0) for (const resolve of this.#idle.splice(0)) resolve();
53
+ });
54
+ }
55
+ }
56
+ };
57
+ function plural(n, noun) {
58
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
59
+ }
60
+
61
+ export { Delivery as t };
@@ -0,0 +1,135 @@
1
+ import { n as realNow, t as createCollector } from "./collector-DiJaNK5H.js";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdirSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+
6
+ // src/jest-collector.ts
7
+ /** Jest's own per-test hook (resetModules, clearMocks, resetMocks): registered by jest-circus itself. */
8
+ const isJestsOwn = (hook) => /[\\/]jest-circus[\\/]/.test(hook.asyncError?.stack?.split("\n")[1] ?? "");
9
+ /** Where a test file's data goes in the reporter's directory. */
10
+ function jestDataFile(dir, testPath) {
11
+ return join(dir, `${createHash("sha1").update(testPath).digest("hex")}.json`);
12
+ }
13
+ /** describe blocks and the test, joined with " > " (the root describe block has no name of its own). */
14
+ function circusTestName(test) {
15
+ const names = [test.name];
16
+ for (let block = test.parent; block?.parent !== void 0; block = block.parent) names.unshift(block.name);
17
+ return names.join(" > ");
18
+ }
19
+ function createJestCollector(options) {
20
+ const collector = createCollector();
21
+ const stack = [];
22
+ const skipped = /* @__PURE__ */ new WeakSet();
23
+ const push = (span) => {
24
+ stack.push(span);
25
+ collector.enter(span);
26
+ };
27
+ const pop = (failed = false) => {
28
+ const span = stack.pop();
29
+ if (span !== void 0) collector.close(span, failed);
30
+ collector.enter(stack.at(-1) ?? null);
31
+ };
32
+ /** The hooks running now, all of one kind: their span ends with the last of them. */
33
+ let phase = null;
34
+ const endPhase = () => {
35
+ if (phase === null) return;
36
+ const { open, hooks, failed, end } = phase;
37
+ phase = null;
38
+ open.span.data.hooks = hooks;
39
+ pop(failed);
40
+ if (end > 0) open.span.timestamp = end;
41
+ };
42
+ return {
43
+ async handleTestEvent(event) {
44
+ if (!event.name.startsWith("hook_")) endPhase();
45
+ switch (event.name) {
46
+ case "setup":
47
+ push(collector.open("test.collect", "collect"));
48
+ break;
49
+ case "run_start":
50
+ pop();
51
+ break;
52
+ case "run_describe_start":
53
+ if (event.describeBlock?.parent !== void 0) push(collector.open("test.suite", circusTestName(event.describeBlock)));
54
+ break;
55
+ case "run_describe_finish":
56
+ if (event.describeBlock?.parent !== void 0) pop();
57
+ break;
58
+ case "test_start": {
59
+ const name = circusTestName(event.test);
60
+ const test = collector.test(name);
61
+ const span = collector.open("test.case", name, test.spanIds.length > 0 ? { "test.retry": test.spanIds.length } : {}, test);
62
+ test.spanIds.push(span.span.span_id);
63
+ push(span);
64
+ break;
65
+ }
66
+ case "test_done":
67
+ pop(event.test.errors.length > 0);
68
+ break;
69
+ case "test_skip":
70
+ case "test_todo":
71
+ stack.pop();
72
+ collector.enter(stack.at(-1) ?? null);
73
+ collector.test(circusTestName(event.test)).spanIds.pop();
74
+ break;
75
+ case "hook_start": {
76
+ const hook = event.hook;
77
+ if (isJestsOwn(hook)) {
78
+ skipped.add(hook);
79
+ break;
80
+ }
81
+ if (phase?.type !== hook.type) {
82
+ endPhase();
83
+ phase = {
84
+ type: hook.type,
85
+ open: collector.open("test.hook", hook.type),
86
+ hooks: 0,
87
+ failed: false,
88
+ end: 0
89
+ };
90
+ push(phase.open);
91
+ }
92
+ phase.hooks++;
93
+ break;
94
+ }
95
+ case "hook_success":
96
+ if (phase !== null && !skipped.has(event.hook)) phase.end = realNow();
97
+ break;
98
+ case "hook_failure":
99
+ if (phase !== null && !skipped.has(event.hook)) {
100
+ phase.failed = true;
101
+ phase.end = realNow();
102
+ }
103
+ if (event.test !== void 0 && event.hook?.type === "beforeEach") await capture(event.test, event.error);
104
+ break;
105
+ case "test_fn_start":
106
+ push(collector.open("test.fn", event.test.name));
107
+ break;
108
+ case "test_fn_success":
109
+ pop();
110
+ break;
111
+ case "test_fn_failure":
112
+ pop(true);
113
+ await capture(event.test, event.error);
114
+ }
115
+ },
116
+ finish() {
117
+ const collected = collector.finish();
118
+ collector.stop();
119
+ const data = {
120
+ testPath: options.testPath,
121
+ collected
122
+ };
123
+ try {
124
+ mkdirSync(options.dir, { recursive: true });
125
+ writeFileSync(jestDataFile(options.dir, options.testPath), JSON.stringify(data));
126
+ } catch {}
127
+ }
128
+ };
129
+ function capture(test, error) {
130
+ const name = circusTestName(test);
131
+ return collector.captureFailure(collector.test(name), name, error, options.getDocument());
132
+ }
133
+ }
134
+
135
+ export { jestDataFile as n, createJestCollector as t };