playwright-performance-regression 0.0.0 → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,756 @@
1
+ import { wrappedTests, trackedContexts, activeCollector, setActiveCollector, getRegistered } from './chunk-DYLCGMI2.js';
2
+ import { readModeState, ConfigError, version, SAMPLES_ATTACHMENT_NAME, CONTEXT_CLOSED_FAILURE_TEXT } from './chunk-6AB42SPF.js';
3
+ import { perfDefaults } from './chunk-HES6BVZT.js';
4
+
5
+ // src/collector/constants.ts
6
+ var KNOWN_THIRD_PARTY_HOSTS = Object.freeze([
7
+ "amplitude.com",
8
+ "analytics.google.com",
9
+ "browser-intake-datadoghq.com",
10
+ "bugsnag.com",
11
+ "clarity.ms",
12
+ "cookiebot.com",
13
+ "cookielaw.org",
14
+ "datadoghq.com",
15
+ "datadoghq.eu",
16
+ "doubleclick.net",
17
+ "facebook.net",
18
+ "fullstory.com",
19
+ "google-analytics.com",
20
+ "googlesyndication.com",
21
+ "googletagmanager.com",
22
+ "hotjar.com",
23
+ "hotjar.io",
24
+ "intercom.io",
25
+ "intercomcdn.com",
26
+ "launchdarkly.com",
27
+ "logrocket.com",
28
+ "lr-ingest.io",
29
+ "mixpanel.com",
30
+ "newrelic.com",
31
+ "nr-data.net",
32
+ "onetrust.com",
33
+ "optimizely.com",
34
+ "segment.com",
35
+ "segment.io",
36
+ "sentry.io"
37
+ ]);
38
+ var PENDING_RESERVE_MS = 1e3;
39
+ var SAMPLE_LIMIT_PER_TEST = 2e4;
40
+ var COLLECTOR_NAME = "playwright-js";
41
+
42
+ // src/collector/timing.ts
43
+ function roundMs(x) {
44
+ return Math.round(x * 10) / 10 + 0;
45
+ }
46
+ function partialTiming(timing) {
47
+ const { requestStart, responseStart } = timing;
48
+ const ttfb = responseStart - requestStart;
49
+ return {
50
+ requestStart: requestStart >= 0 ? roundMs(requestStart) : null,
51
+ ttfb: requestStart >= 0 && responseStart >= 0 && ttfb >= 0 ? roundMs(ttfb) : null
52
+ };
53
+ }
54
+ function computeTiming(timing, fallback) {
55
+ const browser = timing.responseEnd >= 0;
56
+ return {
57
+ startTime: Math.round(timing.startTime),
58
+ duration: roundMs(
59
+ browser ? timing.responseEnd : Math.max(0, fallback.finishedAtNode - fallback.startedAtNode)
60
+ ),
61
+ ...partialTiming(timing),
62
+ timeSource: browser ? "browser" : "node"
63
+ };
64
+ }
65
+ function pendingBudgetMs(input) {
66
+ const { pendingTimeoutMs, testTimeoutMs, sinceTeardownStartMs } = input;
67
+ if (testTimeoutMs === 0) return Math.max(0, pendingTimeoutMs);
68
+ const left = testTimeoutMs - sinceTeardownStartMs - PENDING_RESERVE_MS;
69
+ return Math.max(0, Math.min(pendingTimeoutMs, left));
70
+ }
71
+
72
+ // src/collector/custom-timer.ts
73
+ var MAX_NAME_LENGTH = 200;
74
+ var NAME = /^[^\s\u0000-\u001F\u007F](?:[^\u0000-\u001F\u007F]*[^\s\u0000-\u001F\u007F])?$/u;
75
+ function validateMeasurementName(name) {
76
+ let problem;
77
+ if (typeof name !== "string") problem = `expected a string, got ${typeof name}`;
78
+ else if ([...name].length > MAX_NAME_LENGTH) {
79
+ problem = `the name has more than ${MAX_NAME_LENGTH} characters`;
80
+ } else if (!NAME.test(name)) {
81
+ problem = name.trim() === "" ? "the name is empty" : "the name starts or ends with whitespace or contains a control character";
82
+ }
83
+ if (problem !== void 0) {
84
+ throw new TypeError(
85
+ `CUSTOM_INVALID_NAME: invalid custom measurement name ${JSON.stringify(String(name))}: ${problem}. Use 1-${MAX_NAME_LENGTH} characters without control characters and without leading or trailing whitespace, e.g. "checkout:load-cart".`
86
+ );
87
+ }
88
+ }
89
+ var CustomTimer = class {
90
+ #opts;
91
+ #diag;
92
+ #samples = [];
93
+ /** Open start() measurements by name (06-REQ-06). */
94
+ #started = /* @__PURE__ */ new Map();
95
+ /** measure() calls in progress, each with its own start (06-REQ-05). */
96
+ #measuring = /* @__PURE__ */ new Set();
97
+ #finished = false;
98
+ constructor(opts, diag) {
99
+ this.#opts = opts;
100
+ this.#diag = diag;
101
+ }
102
+ /** Measures `fn` (06-REQ-05): returns its result; on an exception records 'error' and rethrows. */
103
+ async measure(name, fn) {
104
+ validateMeasurementName(name);
105
+ const running = { name, startedAt: this.#opts.now() };
106
+ this.#measuring.add(running);
107
+ let result;
108
+ try {
109
+ result = await fn();
110
+ } catch (error) {
111
+ this.#close(running, "error");
112
+ throw error;
113
+ }
114
+ this.#close(running, "ok");
115
+ return result;
116
+ }
117
+ start(name) {
118
+ validateMeasurementName(name);
119
+ const previous = this.#started.get(name);
120
+ if (previous !== void 0) {
121
+ this.#unfinished(previous);
122
+ this.#issue(
123
+ "CUSTOM_ALREADY_STARTED",
124
+ `custom: perf.start(${JSON.stringify(name)}) was called while this measurement was running; the earlier one is recorded as unfinished`,
125
+ "Call perf.end() before starting the same measurement again, or use perf.measure()."
126
+ );
127
+ }
128
+ this.#started.set(name, { name, startedAt: this.#opts.now() });
129
+ }
130
+ /** Ends a measurement; returns its duration in ms, or undefined without a start (06-REQ-07). */
131
+ end(name) {
132
+ validateMeasurementName(name);
133
+ const running = this.#started.get(name);
134
+ if (running === void 0) {
135
+ this.#issue(
136
+ "CUSTOM_END_WITHOUT_START",
137
+ `custom: perf.end(${JSON.stringify(name)}) was called without a matching perf.start()`,
138
+ "Call perf.start() with the same name in the same test before perf.end()."
139
+ );
140
+ return void 0;
141
+ }
142
+ this.#started.delete(name);
143
+ return this.#close(running, "ok");
144
+ }
145
+ /** Closes open measurements as 'unfinished' (06-REQ-09) and returns all samples. */
146
+ finish() {
147
+ if (!this.#finished) {
148
+ this.#finished = true;
149
+ const open = [...this.#started.values(), ...this.#measuring];
150
+ this.#started.clear();
151
+ this.#measuring.clear();
152
+ for (const running of open) this.#unfinished(running);
153
+ if (open.length > 0) {
154
+ this.#issue(
155
+ "CUSTOM_UNFINISHED",
156
+ `custom: measurements still running when the test ended: ${[...new Set(open.map((r) => JSON.stringify(r.name)))].join(", ")}`,
157
+ "End every perf.start() with perf.end(), or check whether the test timed out during the measurement.",
158
+ open.length
159
+ );
160
+ }
161
+ }
162
+ return [...this.#samples];
163
+ }
164
+ #close(running, outcome) {
165
+ const duration = roundMs(Math.max(0, this.#opts.now() - running.startedAt));
166
+ this.#measuring.delete(running);
167
+ if (this.#opts.record && !this.#finished) {
168
+ this.#samples.push({
169
+ name: running.name,
170
+ outcome,
171
+ duration,
172
+ endTime: Math.round(this.#opts.wallNow())
173
+ });
174
+ }
175
+ return duration;
176
+ }
177
+ #unfinished(running) {
178
+ if (!this.#opts.record) return;
179
+ this.#samples.push({
180
+ name: running.name,
181
+ outcome: "unfinished",
182
+ duration: null,
183
+ endTime: null
184
+ });
185
+ }
186
+ #issue(code, message, hint, count) {
187
+ if (!this.#opts.record) return;
188
+ this.#diag.add({ code, message, hint, ...count === void 0 ? {} : { count } });
189
+ }
190
+ };
191
+
192
+ // src/collector/diagnostics.ts
193
+ function createDiagnostics() {
194
+ const entries = /* @__PURE__ */ new Map();
195
+ return {
196
+ add(issue) {
197
+ const id = `${issue.code}\0${issue.message}`;
198
+ const existing = entries.get(id);
199
+ if (existing === void 0) {
200
+ entries.set(id, { ...issue });
201
+ return;
202
+ }
203
+ existing.count = (existing.count ?? 1) + (issue.count ?? 1);
204
+ },
205
+ list() {
206
+ return [...entries.values()].map((issue) => ({ ...issue }));
207
+ }
208
+ };
209
+ }
210
+ function errorText(error) {
211
+ if (error instanceof Error) return error.message;
212
+ return String(error);
213
+ }
214
+
215
+ // src/collector/perf-api.ts
216
+ function createPerfApi(timer, track) {
217
+ const start = (name) => timer.start(name);
218
+ const end = (name) => timer.end(name);
219
+ return Object.freeze({
220
+ measure: (name, fn) => timer.measure(name, fn),
221
+ start,
222
+ end,
223
+ sampleStart: start,
224
+ sampleEnd: end,
225
+ track
226
+ });
227
+ }
228
+
229
+ // src/collector/filters.ts
230
+ function isKnownThirdPartyHost(host, hosts = KNOWN_THIRD_PARTY_HOSTS) {
231
+ const name = host.toLowerCase().replace(/\.$/u, "");
232
+ return hosts.some((entry) => name === entry || name.endsWith(`.${entry}`));
233
+ }
234
+ function matchesUrlPattern(url, pattern) {
235
+ return typeof pattern === "string" ? url.includes(pattern) : pattern.test(url);
236
+ }
237
+ function hasIgnoredExtension(url, extensions) {
238
+ const path = url.pathname.toLowerCase();
239
+ return extensions.some((extension) => path.endsWith(extension));
240
+ }
241
+ function shouldTrack(req, measure) {
242
+ if (req.isServiceWorker) return false;
243
+ let url;
244
+ try {
245
+ url = new URL(req.url);
246
+ } catch {
247
+ return false;
248
+ }
249
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
250
+ if (!measure.resourceTypes.includes(req.resourceType)) return false;
251
+ if (req.resourceType !== "document" && hasIgnoredExtension(url, measure.ignoreExtensions)) {
252
+ return false;
253
+ }
254
+ if (measure.include.length > 0 && !measure.include.some((pattern) => matchesUrlPattern(req.url, pattern))) {
255
+ return false;
256
+ }
257
+ if (measure.exclude.some((pattern) => matchesUrlPattern(req.url, pattern))) return false;
258
+ if (measure.excludeKnownThirdParty && isKnownThirdPartyHost(url.hostname)) return false;
259
+ return true;
260
+ }
261
+
262
+ // src/collector/request-tracker.ts
263
+ var NO_TIMING = {
264
+ startTime: -1,
265
+ requestStart: -1,
266
+ responseStart: -1,
267
+ responseEnd: -1
268
+ };
269
+ var RequestTracker = class {
270
+ context;
271
+ #opts;
272
+ #diag;
273
+ #sink;
274
+ #inflight = /* @__PURE__ */ new Map();
275
+ #idle = /* @__PURE__ */ new Set();
276
+ #pages = /* @__PURE__ */ new Map();
277
+ #detachers = [];
278
+ #accepting = true;
279
+ #closed = false;
280
+ #detached = false;
281
+ #draining;
282
+ constructor(context, opts, diag, sink) {
283
+ this.context = context;
284
+ this.#opts = opts;
285
+ this.#diag = diag;
286
+ this.#sink = sink;
287
+ this.#listen("request", (request) => this.#onRequest(request));
288
+ this.#listen("response", (response) => this.#onResponse(response));
289
+ this.#listen("requestfinished", (request) => this.#onFinished(request));
290
+ this.#listen("requestfailed", (request) => this.#onFailed(request));
291
+ this.#listen("page", (page) => this.#watchPage(page));
292
+ this.#listen("close", () => this.#onContextClose());
293
+ for (const page of context.pages()) this.#watchPage(page);
294
+ }
295
+ /** The context was closed while the tracker was attached (05-REQ-30). */
296
+ get closed() {
297
+ return this.#closed;
298
+ }
299
+ /**
300
+ * Stops accepting requests, waits up to budgetMs for requests in flight (not at all when the
301
+ * context is closed), turns the rest into samples per 05-REQ-13 and 05-REQ-31, detaches.
302
+ * Calling it again returns the first drain.
303
+ */
304
+ drain(budgetMs) {
305
+ this.#draining ??= this.#drain(budgetMs);
306
+ return this.#draining;
307
+ }
308
+ async #drain(budgetMs) {
309
+ this.#accepting = false;
310
+ if (!this.#closed && this.#inflight.size > 0 && budgetMs > 0) await this.#waitIdle(budgetMs);
311
+ for (const [request, entry] of this.#inflight) {
312
+ this.#guard("drain", () => this.#leftover(request, entry));
313
+ }
314
+ this.#inflight.clear();
315
+ this.#detach();
316
+ }
317
+ #listen(event, handler) {
318
+ const listener = (arg) => this.#guard(event, () => handler(arg));
319
+ const target = this.context;
320
+ target.on(event, listener);
321
+ this.#detachers.push(() => target.off(event, listener));
322
+ }
323
+ /** Every handler is guarded: an exception becomes a diagnostic, never a test failure (05-REQ-19). */
324
+ #guard(event, fn) {
325
+ try {
326
+ fn();
327
+ } catch (error) {
328
+ this.#diag.add({
329
+ code: "COLLECTOR_LISTENER_ERROR",
330
+ message: `collector: the "${event}" handler failed and the event was skipped: ${errorText(error)}`,
331
+ hint: "Report this as a bug of the package; the test result is not affected."
332
+ });
333
+ }
334
+ }
335
+ #onRequest(request) {
336
+ if (!this.#accepting || this.#detached) return;
337
+ const accepted = shouldTrack(
338
+ {
339
+ url: request.url(),
340
+ resourceType: request.resourceType(),
341
+ isServiceWorker: request.serviceWorker() !== null
342
+ },
343
+ this.#opts.measure
344
+ );
345
+ if (!accepted) return;
346
+ this.#inflight.set(request, {
347
+ startedAtNode: this.#opts.now(),
348
+ startedAtWall: this.#opts.wallNow(),
349
+ page: pageOf(request),
350
+ response: null,
351
+ settling: false
352
+ });
353
+ }
354
+ #onResponse(response) {
355
+ const entry = this.#inflight.get(response.request());
356
+ if (entry !== void 0) entry.response = response;
357
+ }
358
+ #onFinished(request) {
359
+ const entry = this.#inflight.get(request);
360
+ if (entry === void 0 || entry.settling) return;
361
+ entry.settling = true;
362
+ const finishedAtNode = this.#opts.now();
363
+ if (entry.response !== null) {
364
+ this.#complete(request, entry, entry.response, finishedAtNode);
365
+ return;
366
+ }
367
+ request.response().then(
368
+ (response) => this.#complete(request, entry, response, finishedAtNode),
369
+ (error) => this.#timingFailed(request, entry, error)
370
+ );
371
+ }
372
+ #complete(request, entry, response, finishedAtNode) {
373
+ if (this.#inflight.get(request) !== entry) return;
374
+ try {
375
+ if (response === null) throw new Error("the request finished without a response");
376
+ const timing = computeTiming(request.timing(), {
377
+ startedAtNode: entry.startedAtNode,
378
+ finishedAtNode
379
+ });
380
+ this.#settle(request);
381
+ this.#sink.finished({
382
+ ...base(request),
383
+ status: response.status(),
384
+ ...timing,
385
+ startTime: startTimeOf(timing.startTime, entry),
386
+ fromServiceWorker: response.fromServiceWorker()
387
+ });
388
+ } catch (error) {
389
+ this.#timingFailed(request, entry, error);
390
+ }
391
+ }
392
+ #timingFailed(request, entry, error) {
393
+ if (this.#inflight.get(request) !== entry) return;
394
+ this.#settle(request);
395
+ this.#diag.add({
396
+ code: "COLLECTOR_TIMING_FAILED",
397
+ message: `collector: reading the timing or response of a finished request failed, so its sample was skipped: ${errorText(error)}`,
398
+ hint: "Report this as a bug of the package; the test result is not affected."
399
+ });
400
+ }
401
+ #onFailed(request) {
402
+ const entry = this.#inflight.get(request);
403
+ if (entry === void 0) return;
404
+ const text = request.failure()?.errorText ?? "";
405
+ this.#settle(request);
406
+ this.#sink.finished(
407
+ failed(request, entry, text === "" ? "unknown" : text, safeTiming(request))
408
+ );
409
+ }
410
+ #watchPage(page) {
411
+ if (this.#pages.has(page) || this.#detached) return;
412
+ const listener = () => this.#guard("close", () => this.#onPageClose(page));
413
+ page.on("close", listener);
414
+ this.#pages.set(page, listener);
415
+ }
416
+ /** Requests of a page closed by the test are aborted by the client (05-REQ-30). */
417
+ #onPageClose(page) {
418
+ for (const [request, entry] of this.#inflight) {
419
+ if (entry.page === page && !entry.settling) this.#closedByClient(request, entry);
420
+ }
421
+ }
422
+ #onContextClose() {
423
+ this.#closed = true;
424
+ for (const [request, entry] of this.#inflight) {
425
+ if (!entry.settling) this.#closedByClient(request, entry);
426
+ }
427
+ }
428
+ #closedByClient(request, entry) {
429
+ this.#settle(request);
430
+ this.#sink.finished(failed(request, entry, CONTEXT_CLOSED_FAILURE_TEXT, safeTiming(request)));
431
+ }
432
+ /** A request still in flight after the wait (05-REQ-13 step 4, 05-REQ-31). */
433
+ #leftover(request, entry) {
434
+ const timing = safeTiming(request);
435
+ const startTime = startTimeOf(Math.round(timing.startTime), entry);
436
+ if (entry.response !== null) {
437
+ this.#sink.finished({
438
+ ...base(request),
439
+ status: entry.response.status(),
440
+ startTime,
441
+ duration: null,
442
+ ...partialTiming(timing),
443
+ timeSource: "browser",
444
+ fromServiceWorker: entry.response.fromServiceWorker()
445
+ });
446
+ return;
447
+ }
448
+ this.#sink.pending({
449
+ ...base(request),
450
+ status: "PENDING",
451
+ startTime,
452
+ duration: null,
453
+ requestStart: null,
454
+ ttfb: null,
455
+ timeSource: "browser",
456
+ fromServiceWorker: false
457
+ });
458
+ }
459
+ #settle(request) {
460
+ this.#inflight.delete(request);
461
+ if (this.#inflight.size > 0) return;
462
+ for (const resolve of this.#idle) resolve();
463
+ }
464
+ #waitIdle(budgetMs) {
465
+ return new Promise((resolve) => {
466
+ const done = () => {
467
+ clearTimeout(timer);
468
+ this.#idle.delete(done);
469
+ resolve();
470
+ };
471
+ const timer = setTimeout(done, budgetMs);
472
+ this.#idle.add(done);
473
+ });
474
+ }
475
+ #detach() {
476
+ if (this.#detached) return;
477
+ this.#detached = true;
478
+ for (const detach of this.#detachers) detach();
479
+ for (const [page, listener] of this.#pages) page.off("close", listener);
480
+ this.#pages.clear();
481
+ }
482
+ };
483
+ function base(request) {
484
+ return {
485
+ method: request.method().toUpperCase(),
486
+ url: request.url(),
487
+ resourceType: request.resourceType()
488
+ };
489
+ }
490
+ function failed(request, entry, failureText, timing) {
491
+ return {
492
+ ...base(request),
493
+ status: "FAILED",
494
+ failureText,
495
+ startTime: startTimeOf(Math.round(timing.startTime), entry),
496
+ duration: null,
497
+ requestStart: null,
498
+ ttfb: null,
499
+ timeSource: "browser",
500
+ fromServiceWorker: false
501
+ };
502
+ }
503
+ function startTimeOf(startTime, entry) {
504
+ return Number.isFinite(startTime) && startTime > 0 ? startTime : Math.round(entry.startedAtWall);
505
+ }
506
+ function safeTiming(request) {
507
+ try {
508
+ return request.timing();
509
+ } catch {
510
+ return NO_TIMING;
511
+ }
512
+ }
513
+ function pageOf(request) {
514
+ try {
515
+ return request.frame().page();
516
+ } catch {
517
+ return null;
518
+ }
519
+ }
520
+
521
+ // src/collector/test-collector.ts
522
+ var TestCollector = class {
523
+ api;
524
+ #opts;
525
+ #diag = createDiagnostics();
526
+ #timer;
527
+ #trackers = /* @__PURE__ */ new Map();
528
+ #requests = [];
529
+ #pending = [];
530
+ #sink;
531
+ #dropped = 0;
532
+ #browserName;
533
+ #autoTracked = false;
534
+ #teardownStart;
535
+ #draining;
536
+ constructor(opts) {
537
+ this.#opts = opts;
538
+ this.#timer = new CustomTimer(
539
+ { now: opts.now, wallNow: opts.wallNow, record: true },
540
+ this.#diag
541
+ );
542
+ this.api = createPerfApi(this.#timer, (context) => {
543
+ this.track(context);
544
+ });
545
+ const keep = (list, sample) => {
546
+ if (this.#requests.length + this.#pending.length < SAMPLE_LIMIT_PER_TEST) list.push(sample);
547
+ else this.#dropped += 1;
548
+ };
549
+ this.#sink = {
550
+ finished: (sample) => keep(this.#requests, sample),
551
+ pending: (sample) => keep(this.#pending, sample)
552
+ };
553
+ }
554
+ /**
555
+ * Attaches a tracker to `context` unless it already has one in this test (05-REQ-04) or the
556
+ * test is draining. Returns true when a tracker was attached.
557
+ */
558
+ track(context) {
559
+ if (this.#draining !== void 0 || this.#trackers.has(context)) return false;
560
+ try {
561
+ this.#trackers.set(
562
+ context,
563
+ new RequestTracker(
564
+ context,
565
+ { measure: this.#opts.measure, now: this.#opts.now, wallNow: this.#opts.wallNow },
566
+ this.#diag,
567
+ this.#sink
568
+ )
569
+ );
570
+ } catch (error) {
571
+ this.#diag.add({
572
+ code: "COLLECTOR_LISTENER_ERROR",
573
+ message: `collector: attaching to a browser context failed, so it is not measured: ${errorText(error)}`,
574
+ hint: "Report this as a bug of the package; the test result is not affected."
575
+ });
576
+ return false;
577
+ }
578
+ this.#browserName ??= engineOf(context) ?? this.#opts.browserName;
579
+ return true;
580
+ }
581
+ /** The page override: tracks the page's context when nothing else did (05-REQ-14). */
582
+ coverPage(page) {
583
+ let context;
584
+ try {
585
+ context = page.context();
586
+ } catch {
587
+ return;
588
+ }
589
+ if (!this.track(context) || this.#autoTracked) return;
590
+ this.#autoTracked = true;
591
+ this.#diag.add({
592
+ code: "COLLECTOR_CONTEXT_AUTO_TRACKED",
593
+ message: 'collector: the context of the "page" fixture was not tracked by the "context" fixture, so the page override tracks it',
594
+ hint: 'Measurement works. To track it directly, apply withPerfFixtures() last in the extend chain and build custom "context" fixtures on the base "context".'
595
+ });
596
+ }
597
+ /** Start of the teardown phase: the first collector fixture whose use() returned (05-REQ-27). */
598
+ markTeardownStart() {
599
+ this.#teardownStart ??= this.#opts.now();
600
+ }
601
+ /** Drains all trackers once per test with one shared budget (05-REQ-13). */
602
+ drain() {
603
+ this.#draining ??= this.#drain();
604
+ return this.#draining;
605
+ }
606
+ async #drain() {
607
+ this.markTeardownStart();
608
+ const budget = pendingBudgetMs({
609
+ pendingTimeoutMs: this.#opts.measure.pendingTimeoutMs,
610
+ testTimeoutMs: this.#opts.testTimeout(),
611
+ sinceTeardownStartMs: this.#opts.now() - (this.#teardownStart ?? this.#opts.now())
612
+ });
613
+ await Promise.all(
614
+ [...this.#trackers.values()].map(async (tracker) => {
615
+ try {
616
+ await tracker.drain(budget);
617
+ } catch (error) {
618
+ this.#diag.add({
619
+ code: "COLLECTOR_LISTENER_ERROR",
620
+ message: `collector: draining a browser context failed: ${errorText(error)}`,
621
+ hint: "Report this as a bug of the package; the test result is not affected."
622
+ });
623
+ }
624
+ })
625
+ );
626
+ }
627
+ /** The sample batch of the test (05-REQ-15); call after drain(). */
628
+ batch() {
629
+ const custom = this.#timer.finish();
630
+ if (this.#dropped > 0) {
631
+ this.#diag.add({
632
+ code: "COLLECTOR_SAMPLE_LIMIT_REACHED",
633
+ message: `collector: the test made more than ${SAMPLE_LIMIT_PER_TEST} measured requests; ${this.#dropped} samples were dropped`,
634
+ hint: "Split the test, or skip requests that do not need measuring with measure.exclude.",
635
+ count: this.#dropped
636
+ });
637
+ this.#dropped = 0;
638
+ }
639
+ return {
640
+ schemaVersion: 1,
641
+ collector: {
642
+ name: COLLECTOR_NAME,
643
+ version: this.#opts.version,
644
+ browserName: this.#browserName ?? null
645
+ },
646
+ requests: [...this.#requests, ...this.#pending],
647
+ custom,
648
+ diagnostics: this.#diag.list()
649
+ };
650
+ }
651
+ /** Drains and writes the attachment; never throws (05-REQ-20). */
652
+ async attach(testInfo) {
653
+ try {
654
+ await this.drain();
655
+ const body = JSON.stringify(this.batch());
656
+ await testInfo.attach(SAMPLES_ATTACHMENT_NAME, { body, contentType: "application/json" });
657
+ } catch (error) {
658
+ process.stderr.write(
659
+ `COLLECTOR_ATTACH_FAILED: ${SAMPLES_ATTACHMENT_NAME} could not be attached to the test result: ${errorText(error)}
660
+ `
661
+ );
662
+ }
663
+ }
664
+ };
665
+ function engineOf(context) {
666
+ try {
667
+ return context.browser()?.browserType().name() ?? null;
668
+ } catch {
669
+ return null;
670
+ }
671
+ }
672
+
673
+ // src/collector/fixtures.ts
674
+ var now = () => performance.now();
675
+ var wallNow = () => Date.now();
676
+ function perfModeOn() {
677
+ const mode = readModeState(process.env);
678
+ if (!mode.ok) throw new ConfigError(mode.issues);
679
+ return mode.value !== null;
680
+ }
681
+ function passiveApi() {
682
+ return createPerfApi(
683
+ new CustomTimer({ now, wallNow, record: false }, createDiagnostics()),
684
+ () => {
685
+ }
686
+ );
687
+ }
688
+ function openBuffer(browserName, testInfo) {
689
+ const state = getRegistered();
690
+ if (state !== void 0 && !state.measuredProjects.includes(testInfo.project.name)) {
691
+ return { collector: null, api: passiveApi() };
692
+ }
693
+ const collector = new TestCollector({
694
+ measure: (state?.config ?? perfDefaults).measure,
695
+ version,
696
+ browserName,
697
+ testTimeout: () => testInfo.timeout,
698
+ now,
699
+ wallNow
700
+ });
701
+ for (const context of trackedContexts()) collector.track(context);
702
+ return { collector, api: collector.api };
703
+ }
704
+ var passiveFixtures = {
705
+ perf: async ({}, use) => {
706
+ await use(passiveApi());
707
+ }
708
+ };
709
+ var perfFixtures = {
710
+ _perfBuffer: [
711
+ async ({ browserName }, use, testInfo) => {
712
+ const buffer = openBuffer(browserName ?? null, testInfo);
713
+ const { collector } = buffer;
714
+ if (collector !== null) setActiveCollector(collector);
715
+ await use(buffer);
716
+ if (collector === null) return;
717
+ if (activeCollector() === collector) setActiveCollector(void 0);
718
+ collector.markTeardownStart();
719
+ await collector.attach(testInfo);
720
+ },
721
+ { auto: true, box: true }
722
+ ],
723
+ context: async ({ context, _perfBuffer }, use) => {
724
+ _perfBuffer.collector?.track(context);
725
+ await use(context);
726
+ await _perfBuffer.collector?.drain();
727
+ },
728
+ page: async ({ page, _perfBuffer }, use) => {
729
+ _perfBuffer.collector?.coverPage(page);
730
+ await use(page);
731
+ await _perfBuffer.collector?.drain();
732
+ },
733
+ perf: async ({ _perfBuffer }, use) => {
734
+ await use(_perfBuffer.api);
735
+ _perfBuffer.collector?.markTeardownStart();
736
+ }
737
+ };
738
+ function withPerfFixtures(base2) {
739
+ const wrapped = wrappedTests();
740
+ if (wrapped.has(base2)) return base2;
741
+ const extend = base2.extend;
742
+ const result = extend.call(base2, perfModeOn() ? perfFixtures : passiveFixtures);
743
+ wrapped.add(result);
744
+ return result;
745
+ }
746
+ function trackContext(context) {
747
+ if (!perfModeOn()) return;
748
+ const contexts = trackedContexts();
749
+ if (!contexts.has(context)) {
750
+ contexts.add(context);
751
+ context.once("close", () => contexts.delete(context));
752
+ }
753
+ activeCollector()?.track(context);
754
+ }
755
+
756
+ export { trackContext, withPerfFixtures };