playwright-performance-regression 0.1.0-next.1 → 0.1.0-next.4

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +431 -0
  2. package/README.md +96 -64
  3. package/dist/{chunk-L5C63HEF.js → chunk-CISGJCFW.js} +378 -48
  4. package/dist/chunk-CXE5IWZY.js +1648 -0
  5. package/dist/{chunk-B64P2D5A.js → chunk-E2IX265O.js} +395 -206
  6. package/dist/chunk-IUI4AFE5.cjs +658 -0
  7. package/dist/{chunk-WZVQK7CQ.cjs → chunk-KELMALEG.cjs} +408 -218
  8. package/dist/{chunk-GCA73FFP.cjs → chunk-LUA4WRIQ.cjs} +382 -47
  9. package/dist/chunk-RL27E3AB.js +595 -0
  10. package/dist/{chunk-DYLCGMI2.js → chunk-S6UH6QPK.js} +6 -1
  11. package/dist/cli.js +2761 -2339
  12. package/dist/config.cjs +122 -137
  13. package/dist/config.d.cts +3 -2
  14. package/dist/config.d.ts +3 -2
  15. package/dist/config.js +117 -132
  16. package/dist/fixture.cjs +9 -5
  17. package/dist/fixture.d.cts +10 -4
  18. package/dist/fixture.d.ts +10 -4
  19. package/dist/fixture.js +4 -4
  20. package/dist/index.cjs +3 -3
  21. package/dist/index.d.cts +121 -25
  22. package/dist/index.d.ts +121 -25
  23. package/dist/index.js +1 -1
  24. package/dist/perf-api-2DH_keLh.d.cts +17 -0
  25. package/dist/perf-api-2DH_keLh.d.ts +17 -0
  26. package/dist/reporter.cjs +5713 -1237
  27. package/dist/reporter.js +6905 -693
  28. package/dist/test.cjs +4 -4
  29. package/dist/test.js +4 -4
  30. package/package.json +19 -1
  31. package/schemas/common.schema.json +2 -2
  32. package/schemas/config.schema.json +72 -26
  33. package/schemas/outcome.schema.json +2 -2
  34. package/schemas/run-report.schema.json +549 -20
  35. package/schemas/samples.schema.json +48 -37
  36. package/schemas/thresholds.schema.json +1 -1
  37. package/dist/chunk-3CLCMD2Q.js +0 -3411
  38. package/dist/chunk-4SFI55HF.cjs +0 -319
  39. package/dist/chunk-HBGADXLP.js +0 -254
  40. package/dist/perf-api-V4PeHVE0.d.cts +0 -22
  41. package/dist/perf-api-V4PeHVE0.d.ts +0 -22
@@ -1,7 +1,125 @@
1
1
  'use strict';
2
2
 
3
- var chunk4SFI55HF_cjs = require('./chunk-4SFI55HF.cjs');
4
- var chunkGCA73FFP_cjs = require('./chunk-GCA73FFP.cjs');
3
+ var chunkIUI4AFE5_cjs = require('./chunk-IUI4AFE5.cjs');
4
+ var chunkLUA4WRIQ_cjs = require('./chunk-LUA4WRIQ.cjs');
5
+ var fs = require('fs');
6
+ var os = require('os');
7
+ var path = require('path');
8
+
9
+ var memory = { files: [], ran: 0 };
10
+ function checkStatePath(runId) {
11
+ return path.join(os.tmpdir(), chunkIUI4AFE5_cjs.checkStateFileName(runId));
12
+ }
13
+ function load(path) {
14
+ if (path === null) return memory;
15
+ try {
16
+ const parsed = JSON.parse(fs.readFileSync(path, "utf8"));
17
+ return { files: Array.isArray(parsed.files) ? parsed.files : [], ran: Number(parsed.ran ?? 0) };
18
+ } catch {
19
+ return { files: [], ran: 0 };
20
+ }
21
+ }
22
+ function save(path, state) {
23
+ if (path === null) memory = state;
24
+ else fs.writeFileSync(path, JSON.stringify(state));
25
+ }
26
+ function checkRunsTest(runId, maxTests, project, file) {
27
+ const path = runId === void 0 ? null : checkStatePath(runId);
28
+ const state = load(path);
29
+ const id = `${project}\0${file}`;
30
+ if (state.ran >= maxTests || state.files.includes(id)) return false;
31
+ save(path, { files: [...state.files, id], ran: state.ran + 1 });
32
+ return true;
33
+ }
34
+
35
+ // src/collector/api-requests.ts
36
+ var API_METHODS = ["fetch", "get", "post", "put", "patch", "delete", "head"];
37
+ var METHOD = /^[A-Z]+$/u;
38
+ var depth = 0;
39
+ function call(target, name) {
40
+ if (typeof target !== "object" || target === null) return void 0;
41
+ const fn = target[name];
42
+ if (typeof fn !== "function") return void 0;
43
+ const value = fn.call(target);
44
+ return typeof value === "string" ? value : void 0;
45
+ }
46
+ function resolveUrl(raw, baseURL) {
47
+ try {
48
+ return new URL(raw).toString();
49
+ } catch {
50
+ }
51
+ if (baseURL === void 0 || baseURL === "") return null;
52
+ try {
53
+ return new URL(raw, baseURL).toString();
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ function describeCall(name, args, baseURL) {
59
+ const [target, options] = args;
60
+ const rawUrl = typeof target === "string" ? target : call(target, "url") ?? String(target);
61
+ let method = name;
62
+ if (name === "fetch") {
63
+ const fromOptions = typeof options === "object" && options !== null ? options.method : void 0;
64
+ method = (typeof fromOptions === "string" ? fromOptions : void 0) ?? call(target, "method") ?? "GET";
65
+ }
66
+ method = method.toUpperCase();
67
+ if (!METHOD.test(method)) return void 0;
68
+ return { method, rawUrl, url: resolveUrl(rawUrl, baseURL) };
69
+ }
70
+ function isApiRequestContext(value) {
71
+ if (typeof value !== "object" || value === null) return false;
72
+ const target = value;
73
+ return ["fetch", "get", "post", "dispose", "storageState"].every(
74
+ (name) => typeof target[name] === "function"
75
+ );
76
+ }
77
+ function isPromise(value) {
78
+ return typeof value === "object" && value !== null && typeof value.then === "function";
79
+ }
80
+ function wrapRequestContext(context, source, baseURL, recorder) {
81
+ const wrapped = chunkIUI4AFE5_cjs.wrappedRequestContexts();
82
+ if (wrapped.has(context)) return false;
83
+ wrapped.add(context);
84
+ const target = context;
85
+ for (const name of API_METHODS) {
86
+ const original = target[name];
87
+ if (typeof original !== "function") continue;
88
+ const fn = original;
89
+ const wrapper = function(...args) {
90
+ const active = depth === 0 ? recorder() : void 0;
91
+ if (active === void 0) return fn.apply(this, args);
92
+ let described;
93
+ try {
94
+ described = describeCall(name, args, baseURL);
95
+ } catch {
96
+ described = void 0;
97
+ }
98
+ depth += 1;
99
+ let result;
100
+ try {
101
+ result = fn.apply(this, args);
102
+ } finally {
103
+ depth -= 1;
104
+ }
105
+ if (described === void 0 || !isPromise(result)) return result;
106
+ return active.observeApiCall(described, source, result);
107
+ };
108
+ Object.defineProperty(target, name, {
109
+ value: wrapper,
110
+ configurable: true,
111
+ enumerable: false,
112
+ writable: true
113
+ });
114
+ }
115
+ return true;
116
+ }
117
+
118
+ // src/collector/perf-api.ts
119
+ function createPerfApi(track, trackRequestContext2 = () => {
120
+ }) {
121
+ return Object.freeze({ track, trackRequestContext: trackRequestContext2 });
122
+ }
5
123
 
6
124
  // src/collector/constants.ts
7
125
  var KNOWN_THIRD_PARTY_HOSTS = Object.freeze([
@@ -40,156 +158,6 @@ var PENDING_RESERVE_MS = 1e3;
40
158
  var SAMPLE_LIMIT_PER_TEST = 2e4;
41
159
  var COLLECTOR_NAME = "playwright-js";
42
160
 
43
- // src/collector/timing.ts
44
- function roundMs(x) {
45
- return Math.round(x * 10) / 10 + 0;
46
- }
47
- function partialTiming(timing) {
48
- const { requestStart, responseStart } = timing;
49
- const ttfb = responseStart - requestStart;
50
- return {
51
- requestStart: requestStart >= 0 ? roundMs(requestStart) : null,
52
- ttfb: requestStart >= 0 && responseStart >= 0 && ttfb >= 0 ? roundMs(ttfb) : null
53
- };
54
- }
55
- function computeTiming(timing, fallback) {
56
- const browser = timing.responseEnd >= 0;
57
- return {
58
- startTime: Math.round(timing.startTime),
59
- duration: roundMs(
60
- browser ? timing.responseEnd : Math.max(0, fallback.finishedAtNode - fallback.startedAtNode)
61
- ),
62
- ...partialTiming(timing),
63
- timeSource: browser ? "browser" : "node"
64
- };
65
- }
66
- function pendingBudgetMs(input) {
67
- const { pendingTimeoutMs, testTimeoutMs, sinceTeardownStartMs } = input;
68
- if (testTimeoutMs === 0) return Math.max(0, pendingTimeoutMs);
69
- const left = testTimeoutMs - sinceTeardownStartMs - PENDING_RESERVE_MS;
70
- return Math.max(0, Math.min(pendingTimeoutMs, left));
71
- }
72
-
73
- // src/collector/custom-timer.ts
74
- var MAX_NAME_LENGTH = 200;
75
- var NAME = /^[^\s\u0000-\u001F\u007F](?:[^\u0000-\u001F\u007F]*[^\s\u0000-\u001F\u007F])?$/u;
76
- function validateMeasurementName(name) {
77
- let problem;
78
- if (typeof name !== "string") problem = `expected a string, got ${typeof name}`;
79
- else if ([...name].length > MAX_NAME_LENGTH) {
80
- problem = `the name has more than ${MAX_NAME_LENGTH} characters`;
81
- } else if (!NAME.test(name)) {
82
- problem = name.trim() === "" ? "the name is empty" : "the name starts or ends with whitespace or contains a control character";
83
- }
84
- if (problem !== void 0) {
85
- throw new TypeError(
86
- `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".`
87
- );
88
- }
89
- }
90
- var CustomTimer = class {
91
- #opts;
92
- #diag;
93
- #samples = [];
94
- /** Open start() measurements by name (06-REQ-06). */
95
- #started = /* @__PURE__ */ new Map();
96
- /** measure() calls in progress, each with its own start (06-REQ-05). */
97
- #measuring = /* @__PURE__ */ new Set();
98
- #finished = false;
99
- constructor(opts, diag) {
100
- this.#opts = opts;
101
- this.#diag = diag;
102
- }
103
- /** Measures `fn` (06-REQ-05): returns its result; on an exception records 'error' and rethrows. */
104
- async measure(name, fn) {
105
- validateMeasurementName(name);
106
- const running = { name, startedAt: this.#opts.now() };
107
- this.#measuring.add(running);
108
- let result;
109
- try {
110
- result = await fn();
111
- } catch (error) {
112
- this.#close(running, "error");
113
- throw error;
114
- }
115
- this.#close(running, "ok");
116
- return result;
117
- }
118
- start(name) {
119
- validateMeasurementName(name);
120
- const previous = this.#started.get(name);
121
- if (previous !== void 0) {
122
- this.#unfinished(previous);
123
- this.#issue(
124
- "CUSTOM_ALREADY_STARTED",
125
- `custom: perf.start(${JSON.stringify(name)}) was called while this measurement was running; the earlier one is recorded as unfinished`,
126
- "Call perf.end() before starting the same measurement again, or use perf.measure()."
127
- );
128
- }
129
- this.#started.set(name, { name, startedAt: this.#opts.now() });
130
- }
131
- /** Ends a measurement; returns its duration in ms, or undefined without a start (06-REQ-07). */
132
- end(name) {
133
- validateMeasurementName(name);
134
- const running = this.#started.get(name);
135
- if (running === void 0) {
136
- this.#issue(
137
- "CUSTOM_END_WITHOUT_START",
138
- `custom: perf.end(${JSON.stringify(name)}) was called without a matching perf.start()`,
139
- "Call perf.start() with the same name in the same test before perf.end()."
140
- );
141
- return void 0;
142
- }
143
- this.#started.delete(name);
144
- return this.#close(running, "ok");
145
- }
146
- /** Closes open measurements as 'unfinished' (06-REQ-09) and returns all samples. */
147
- finish() {
148
- if (!this.#finished) {
149
- this.#finished = true;
150
- const open = [...this.#started.values(), ...this.#measuring];
151
- this.#started.clear();
152
- this.#measuring.clear();
153
- for (const running of open) this.#unfinished(running);
154
- if (open.length > 0) {
155
- this.#issue(
156
- "CUSTOM_UNFINISHED",
157
- `custom: measurements still running when the test ended: ${[...new Set(open.map((r) => JSON.stringify(r.name)))].join(", ")}`,
158
- "End every perf.start() with perf.end(), or check whether the test timed out during the measurement.",
159
- open.length
160
- );
161
- }
162
- }
163
- return [...this.#samples];
164
- }
165
- #close(running, outcome) {
166
- const duration = roundMs(Math.max(0, this.#opts.now() - running.startedAt));
167
- this.#measuring.delete(running);
168
- if (this.#opts.record && !this.#finished) {
169
- this.#samples.push({
170
- name: running.name,
171
- outcome,
172
- duration,
173
- endTime: Math.round(this.#opts.wallNow())
174
- });
175
- }
176
- return duration;
177
- }
178
- #unfinished(running) {
179
- if (!this.#opts.record) return;
180
- this.#samples.push({
181
- name: running.name,
182
- outcome: "unfinished",
183
- duration: null,
184
- endTime: null
185
- });
186
- }
187
- #issue(code, message, hint, count) {
188
- if (!this.#opts.record) return;
189
- this.#diag.add({ code, message, hint, ...count === void 0 ? {} : { count } });
190
- }
191
- };
192
-
193
161
  // src/collector/diagnostics.ts
194
162
  function createDiagnostics() {
195
163
  const entries = /* @__PURE__ */ new Map();
@@ -213,20 +181,6 @@ function errorText(error) {
213
181
  return String(error);
214
182
  }
215
183
 
216
- // src/collector/perf-api.ts
217
- function createPerfApi(timer, track) {
218
- const start = (name) => timer.start(name);
219
- const end = (name) => timer.end(name);
220
- return Object.freeze({
221
- measure: (name, fn) => timer.measure(name, fn),
222
- start,
223
- end,
224
- sampleStart: start,
225
- sampleEnd: end,
226
- track
227
- });
228
- }
229
-
230
184
  // src/collector/filters.ts
231
185
  function isKnownThirdPartyHost(host, hosts = KNOWN_THIRD_PARTY_HOSTS) {
232
186
  const name = host.toLowerCase().replace(/\.$/u, "");
@@ -252,13 +206,56 @@ function shouldTrack(req, measure) {
252
206
  if (req.resourceType !== "document" && hasIgnoredExtension(url, measure.ignoreExtensions)) {
253
207
  return false;
254
208
  }
255
- if (measure.include.length > 0 && !measure.include.some((pattern) => matchesUrlPattern(req.url, pattern))) {
209
+ return passesUrlFilters(req.url, url, measure);
210
+ }
211
+ function passesUrlFilters(text, url, measure) {
212
+ if (measure.include.length > 0 && !measure.include.some((pattern) => matchesUrlPattern(text, pattern))) {
256
213
  return false;
257
214
  }
258
- if (measure.exclude.some((pattern) => matchesUrlPattern(req.url, pattern))) return false;
215
+ if (measure.exclude.some((pattern) => matchesUrlPattern(text, pattern))) return false;
259
216
  if (measure.excludeKnownThirdParty && isKnownThirdPartyHost(url.hostname)) return false;
260
217
  return true;
261
218
  }
219
+ function shouldTrackApiCall(text, measure) {
220
+ let url;
221
+ try {
222
+ url = new URL(text);
223
+ } catch {
224
+ return false;
225
+ }
226
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
227
+ return passesUrlFilters(text, url, measure);
228
+ }
229
+
230
+ // src/collector/timing.ts
231
+ function roundMs(x) {
232
+ return Math.round(x * 10) / 10 + 0;
233
+ }
234
+ function partialTiming(timing) {
235
+ const { requestStart, responseStart } = timing;
236
+ const ttfb = responseStart - requestStart;
237
+ return {
238
+ requestStart: requestStart >= 0 ? roundMs(requestStart) : null,
239
+ ttfb: requestStart >= 0 && responseStart >= 0 && ttfb >= 0 ? roundMs(ttfb) : null
240
+ };
241
+ }
242
+ function computeTiming(timing, fallback) {
243
+ const browser = timing.responseEnd >= 0;
244
+ return {
245
+ startTime: Math.round(timing.startTime),
246
+ duration: roundMs(
247
+ browser ? timing.responseEnd : Math.max(0, fallback.finishedAtNode - fallback.startedAtNode)
248
+ ),
249
+ ...partialTiming(timing),
250
+ timeSource: browser ? "browser" : "node"
251
+ };
252
+ }
253
+ function pendingBudgetMs(input) {
254
+ const { pendingTimeoutMs, testTimeoutMs, sinceTeardownStartMs } = input;
255
+ if (testTimeoutMs === 0) return Math.max(0, pendingTimeoutMs);
256
+ const left = testTimeoutMs - sinceTeardownStartMs - PENDING_RESERVE_MS;
257
+ return Math.max(0, Math.min(pendingTimeoutMs, left));
258
+ }
262
259
 
263
260
  // src/collector/request-tracker.ts
264
261
  var NO_TIMING = {
@@ -267,6 +264,10 @@ var NO_TIMING = {
267
264
  responseStart: -1,
268
265
  responseEnd: -1
269
266
  };
267
+ var BODYLESS = /* @__PURE__ */ new Set([204, 205, 304]);
268
+ var ABORTED_AFTER_RESPONSE = new Set(
269
+ chunkIUI4AFE5_cjs.ABORT_FAILURE_TEXTS.filter((text) => text !== chunkIUI4AFE5_cjs.CONTEXT_CLOSED_FAILURE_TEXT)
270
+ );
270
271
  var RequestTracker = class {
271
272
  context;
272
273
  #opts;
@@ -370,11 +371,13 @@ var RequestTracker = class {
370
371
  (error) => this.#timingFailed(request, entry, error)
371
372
  );
372
373
  }
373
- #complete(request, entry, response, finishedAtNode) {
374
+ #complete(request, entry, response, finishedAtNode, headersEnd = false) {
374
375
  if (this.#inflight.get(request) !== entry) return;
375
376
  try {
376
377
  if (response === null) throw new Error("the request finished without a response");
377
- const timing = computeTiming(request.timing(), {
378
+ const raw = request.timing();
379
+ const ended = headersEnd && raw.responseEnd < 0 ? { ...raw, responseEnd: raw.responseStart } : raw;
380
+ const timing = computeTiming(ended, {
378
381
  startedAtNode: entry.startedAtNode,
379
382
  finishedAtNode
380
383
  });
@@ -403,6 +406,11 @@ var RequestTracker = class {
403
406
  const entry = this.#inflight.get(request);
404
407
  if (entry === void 0) return;
405
408
  const text = request.failure()?.errorText ?? "";
409
+ if (entry.response !== null && !entry.settling && (BODYLESS.has(entry.response.status()) || ABORTED_AFTER_RESPONSE.has(text))) {
410
+ entry.settling = true;
411
+ this.#complete(request, entry, entry.response, this.#opts.now(), true);
412
+ return;
413
+ }
406
414
  this.#settle(request);
407
415
  this.#sink.finished(
408
416
  failed(request, entry, text === "" ? "unknown" : text, safeTiming(request))
@@ -428,7 +436,7 @@ var RequestTracker = class {
428
436
  }
429
437
  #closedByClient(request, entry) {
430
438
  this.#settle(request);
431
- this.#sink.finished(failed(request, entry, chunk4SFI55HF_cjs.CONTEXT_CLOSED_FAILURE_TEXT, safeTiming(request)));
439
+ this.#sink.finished(failed(request, entry, chunkIUI4AFE5_cjs.CONTEXT_CLOSED_FAILURE_TEXT, safeTiming(request)));
432
440
  }
433
441
  /** A request still in flight after the wait (05-REQ-13 step 4, 05-REQ-31). */
434
442
  #leftover(request, entry) {
@@ -520,14 +528,23 @@ function pageOf(request) {
520
528
  }
521
529
 
522
530
  // src/collector/test-collector.ts
531
+ function currentRecorder() {
532
+ return chunkIUI4AFE5_cjs.activeCollector();
533
+ }
534
+ function firstLine(error) {
535
+ const line = errorText(error).split("\n", 1)[0]?.trim() ?? "";
536
+ return line === "" ? "unknown" : line;
537
+ }
523
538
  var TestCollector = class {
524
539
  api;
525
540
  #opts;
526
541
  #diag = createDiagnostics();
527
- #timer;
528
542
  #trackers = /* @__PURE__ */ new Map();
529
543
  #requests = [];
530
544
  #pending = [];
545
+ #apiRequests = [];
546
+ #apiPending = [];
547
+ #apiInFlight = /* @__PURE__ */ new Set();
531
548
  #sink;
532
549
  #dropped = 0;
533
550
  #browserName;
@@ -536,28 +553,151 @@ var TestCollector = class {
536
553
  #draining;
537
554
  constructor(opts) {
538
555
  this.#opts = opts;
539
- this.#timer = new CustomTimer(
540
- { now: opts.now, wallNow: opts.wallNow, record: true },
541
- this.#diag
556
+ this.api = createPerfApi(
557
+ (context) => {
558
+ this.track(context);
559
+ },
560
+ (requestContext) => {
561
+ this.trackRequestContext(requestContext);
562
+ }
542
563
  );
543
- this.api = createPerfApi(this.#timer, (context) => {
544
- this.track(context);
564
+ this.#sink = {
565
+ finished: (sample) => this.#keep(this.#requests, sample),
566
+ pending: (sample) => this.#keep(this.#pending, sample)
567
+ };
568
+ }
569
+ /** The sample limit counts browser samples and API calls together (05-REQ-16, 15-REQ-09). */
570
+ #keep(list, sample) {
571
+ const count = this.#requests.length + this.#pending.length + this.#apiRequests.length + this.#apiPending.length;
572
+ if (count < SAMPLE_LIMIT_PER_TEST) list.push(sample);
573
+ else this.#dropped += 1;
574
+ }
575
+ /**
576
+ * Wraps an APIRequestContext of this test (15-REQ-03): the request fixture or context.request.
577
+ * Relative URLs resolve against the test's baseURL only for the request fixture and the context
578
+ * of the context fixture, which Playwright creates with that baseURL; any other context may have
579
+ * its own baseURL, so its calls take response.url() (15-REQ-05).
580
+ */
581
+ wrapRequest(requestContext, source, testBaseURL = source === "request") {
582
+ try {
583
+ wrapRequestContext(
584
+ requestContext,
585
+ source,
586
+ testBaseURL ? this.#opts.baseURL : void 0,
587
+ currentRecorder
588
+ );
589
+ } catch (error) {
590
+ this.#diag.add({
591
+ code: "COLLECTOR_LISTENER_ERROR",
592
+ message: `collector: wrapping an APIRequestContext failed, so its calls are not measured: ${errorText(error)}`,
593
+ hint: "Report this as a bug of the package; the test result is not affected."
594
+ });
595
+ }
596
+ }
597
+ /** perf.trackRequestContext() (15-REQ-03, 15-AC-07). */
598
+ trackRequestContext(requestContext) {
599
+ if (!isApiRequestContext(requestContext)) {
600
+ this.requestContextNotTracked();
601
+ return;
602
+ }
603
+ this.wrapRequest(requestContext, "tracked");
604
+ }
605
+ requestContextNotTracked() {
606
+ this.#diag.add({
607
+ code: "COLLECTOR_REQUEST_CONTEXT_NOT_TRACKED",
608
+ message: "collector: trackRequestContext() got an object that is not an APIRequestContext, so it is not measured",
609
+ hint: "Pass the object returned by playwright.request.newContext()."
545
610
  });
546
- const keep = (list, sample) => {
547
- if (this.#requests.length + this.#pending.length < SAMPLE_LIMIT_PER_TEST) list.push(sample);
548
- else this.#dropped += 1;
611
+ }
612
+ /**
613
+ * Records one APIRequestContext call (15-REQ-05): the returned promise settles like `result`
614
+ * (same value, same error); the sample is made when it settles or at the end-of-test wait.
615
+ */
616
+ observeApiCall(call2, source, result) {
617
+ if (this.#draining !== void 0) return result;
618
+ const startedAt = this.#opts.now();
619
+ const entry = {
620
+ call: call2,
621
+ source,
622
+ startTime: Math.round(this.#opts.wallNow()),
623
+ settled: Promise.resolve(),
624
+ done: false
549
625
  };
550
- this.#sink = {
551
- finished: (sample) => keep(this.#requests, sample),
552
- pending: (sample) => keep(this.#pending, sample)
626
+ const finish = (status, extra, responseUrl) => {
627
+ try {
628
+ if (entry.done) return;
629
+ entry.done = true;
630
+ this.#apiInFlight.delete(entry);
631
+ const sample = this.#apiSample(entry, status, responseUrl, extra);
632
+ if (sample !== null) this.#keep(this.#apiRequests, sample);
633
+ } catch (error) {
634
+ this.#diag.add({
635
+ code: "COLLECTOR_LISTENER_ERROR",
636
+ message: `collector: recording an APIRequestContext call failed: ${errorText(error)}`,
637
+ hint: "Report this as a bug of the package; the test result is not affected."
638
+ });
639
+ }
640
+ };
641
+ const out = result.then(
642
+ (response) => {
643
+ const duration = roundMs(this.#opts.now() - startedAt);
644
+ let status;
645
+ let url;
646
+ try {
647
+ const r = response;
648
+ const s = typeof r.status === "function" ? r.status() : void 0;
649
+ status = typeof s === "number" && Number.isInteger(s) && s >= 100 && s <= 599 ? s : void 0;
650
+ const u = typeof r.url === "function" ? r.url() : void 0;
651
+ url = typeof u === "string" && u !== "" ? u : void 0;
652
+ } catch {
653
+ status = void 0;
654
+ }
655
+ if (status === void 0) finish("FAILED", { failureText: "unknown", duration: null }, url);
656
+ else finish(status, { duration }, url);
657
+ return response;
658
+ },
659
+ (error) => {
660
+ finish("FAILED", { failureText: firstLine(error), duration: null });
661
+ throw error;
662
+ }
663
+ );
664
+ entry.settled = out.then(
665
+ () => void 0,
666
+ () => void 0
667
+ );
668
+ this.#apiInFlight.add(entry);
669
+ return out;
670
+ }
671
+ /** The sample of a call, or null when the filters skip its URL (15-REQ-06). */
672
+ #apiSample(entry, status, responseUrl, extra) {
673
+ const url = entry.call.url ?? responseUrl ?? entry.call.rawUrl;
674
+ if (url === "" || !shouldTrackApiCall(url, this.#opts.measure)) return null;
675
+ return {
676
+ method: entry.call.method,
677
+ url,
678
+ status,
679
+ ...status === "FAILED" ? { failureText: extra.failureText ?? "unknown" } : {},
680
+ startTime: entry.startTime,
681
+ duration: extra.duration ?? null,
682
+ source: entry.source
553
683
  };
554
684
  }
555
685
  /**
556
686
  * Attaches a tracker to `context` unless it already has one in this test (05-REQ-04) or the
557
- * test is draining. Returns true when a tracker was attached.
687
+ * test is draining. Returns true when a tracker was attached. `contextFixture`: the context of
688
+ * the context fixture, whose request calls resolve against the test's baseURL (15-REQ-05).
558
689
  */
559
- track(context) {
690
+ track(context, contextFixture = false) {
560
691
  if (this.#draining !== void 0 || this.#trackers.has(context)) return false;
692
+ let requestContext;
693
+ try {
694
+ requestContext = context.request;
695
+ } catch {
696
+ requestContext = void 0;
697
+ }
698
+ if (typeof requestContext === "object" && requestContext !== null) {
699
+ this.wrapRequest(requestContext, "context", contextFixture);
700
+ }
561
701
  try {
562
702
  this.#trackers.set(
563
703
  context,
@@ -611,8 +751,9 @@ var TestCollector = class {
611
751
  testTimeoutMs: this.#opts.testTimeout(),
612
752
  sinceTeardownStartMs: this.#opts.now() - (this.#teardownStart ?? this.#opts.now())
613
753
  });
614
- await Promise.all(
615
- [...this.#trackers.values()].map(async (tracker) => {
754
+ await Promise.all([
755
+ this.#drainApiCalls(budget),
756
+ ...[...this.#trackers.values()].map(async (tracker) => {
616
757
  try {
617
758
  await tracker.drain(budget);
618
759
  } catch (error) {
@@ -623,11 +764,38 @@ var TestCollector = class {
623
764
  });
624
765
  }
625
766
  })
626
- );
767
+ ]);
768
+ }
769
+ /** Waits for running API calls within the budget; the rest become PENDING (15-REQ-08). */
770
+ async #drainApiCalls(budget) {
771
+ if (this.#apiInFlight.size > 0) {
772
+ let timer;
773
+ const timeout = new Promise((resolve) => {
774
+ timer = setTimeout(resolve, Math.max(0, budget));
775
+ });
776
+ await Promise.race([
777
+ Promise.all([...this.#apiInFlight].map((entry) => entry.settled)),
778
+ timeout
779
+ ]);
780
+ clearTimeout(timer);
781
+ }
782
+ for (const entry of [...this.#apiInFlight]) {
783
+ entry.done = true;
784
+ this.#apiInFlight.delete(entry);
785
+ try {
786
+ const sample = this.#apiSample(entry, "PENDING", void 0, { duration: null });
787
+ if (sample !== null) this.#keep(this.#apiPending, sample);
788
+ } catch (error) {
789
+ this.#diag.add({
790
+ code: "COLLECTOR_LISTENER_ERROR",
791
+ message: `collector: recording an APIRequestContext call failed: ${errorText(error)}`,
792
+ hint: "Report this as a bug of the package; the test result is not affected."
793
+ });
794
+ }
795
+ }
627
796
  }
628
797
  /** The sample batch of the test (05-REQ-15); call after drain(). */
629
798
  batch() {
630
- const custom = this.#timer.finish();
631
799
  if (this.#dropped > 0) {
632
800
  this.#diag.add({
633
801
  code: "COLLECTOR_SAMPLE_LIMIT_REACHED",
@@ -638,14 +806,14 @@ var TestCollector = class {
638
806
  this.#dropped = 0;
639
807
  }
640
808
  return {
641
- schemaVersion: 1,
809
+ schemaVersion: 3,
642
810
  collector: {
643
811
  name: COLLECTOR_NAME,
644
812
  version: this.#opts.version,
645
813
  browserName: this.#browserName ?? null
646
814
  },
647
815
  requests: [...this.#requests, ...this.#pending],
648
- custom,
816
+ apiRequests: [...this.#apiRequests, ...this.#apiPending],
649
817
  diagnostics: this.#diag.list()
650
818
  };
651
819
  }
@@ -654,10 +822,10 @@ var TestCollector = class {
654
822
  try {
655
823
  await this.drain();
656
824
  const body = JSON.stringify(this.batch());
657
- await testInfo.attach(chunk4SFI55HF_cjs.SAMPLES_ATTACHMENT_NAME, { body, contentType: "application/json" });
825
+ await testInfo.attach(chunkIUI4AFE5_cjs.SAMPLES_ATTACHMENT_NAME, { body, contentType: "application/json" });
658
826
  } catch (error) {
659
827
  process.stderr.write(
660
- `COLLECTOR_ATTACH_FAILED: ${chunk4SFI55HF_cjs.SAMPLES_ATTACHMENT_NAME} could not be attached to the test result: ${errorText(error)}
828
+ `COLLECTOR_ATTACH_FAILED: ${chunkIUI4AFE5_cjs.SAMPLES_ATTACHMENT_NAME} could not be attached to the test result: ${errorText(error)}
661
829
  `
662
830
  );
663
831
  }
@@ -675,54 +843,60 @@ function engineOf(context) {
675
843
  var now = () => performance.now();
676
844
  var wallNow = () => Date.now();
677
845
  function perfModeOn() {
678
- const mode = chunk4SFI55HF_cjs.readModeState(process.env);
679
- if (!mode.ok) throw new chunk4SFI55HF_cjs.ConfigError(mode.issues);
846
+ const mode = chunkIUI4AFE5_cjs.readModeState(process.env);
847
+ if (!mode.ok) throw new chunkIUI4AFE5_cjs.ConfigError(mode.issues);
680
848
  return mode.value !== null;
681
849
  }
682
- function passiveApi() {
683
- return createPerfApi(
684
- new CustomTimer({ now, wallNow, record: false }, createDiagnostics()),
685
- () => {
686
- }
687
- );
688
- }
689
- function openBuffer(browserName, testInfo) {
690
- const state = chunk4SFI55HF_cjs.getRegistered();
691
- if (state !== void 0 && !state.measuredProjects.includes(testInfo.project.name)) {
692
- return { collector: null, api: passiveApi() };
850
+ var PASSIVE_API = createPerfApi(() => {
851
+ });
852
+ function openBuffer(browserName, baseURL, testInfo) {
853
+ const state = chunkIUI4AFE5_cjs.getRegistered();
854
+ if (state !== void 0 && (!state.config.measure.api || !state.measuredProjects.includes(testInfo.project.name))) {
855
+ return { collector: null, api: PASSIVE_API };
693
856
  }
694
857
  const collector = new TestCollector({
695
- measure: (state?.config ?? chunkGCA73FFP_cjs.perfDefaults).measure,
696
- version: chunk4SFI55HF_cjs.version,
858
+ measure: (state?.config ?? chunkLUA4WRIQ_cjs.perfDefaults).measure,
859
+ version: chunkIUI4AFE5_cjs.version,
697
860
  browserName,
698
861
  testTimeout: () => testInfo.timeout,
862
+ baseURL,
699
863
  now,
700
864
  wallNow
701
865
  });
702
- for (const context of chunk4SFI55HF_cjs.trackedContexts()) collector.track(context);
866
+ for (const context of chunkIUI4AFE5_cjs.trackedContexts()) collector.track(context);
703
867
  return { collector, api: collector.api };
704
868
  }
869
+ function skipInCheck(testInfo) {
870
+ const state = chunkIUI4AFE5_cjs.getRegistered();
871
+ if (state === void 0 || state.mode.mode !== "check") return;
872
+ if (!state.measuredProjects.includes(testInfo.project.name)) return;
873
+ const max = state.mode.maxTests ?? chunkIUI4AFE5_cjs.DEFAULT_MAX_TESTS;
874
+ if (!checkRunsTest(state.mode.runId, max, testInfo.project.name, testInfo.file)) {
875
+ testInfo.skip(true, "PW_PERF_MODE=check: only the first test of each file runs");
876
+ }
877
+ }
705
878
  var passiveFixtures = {
706
879
  perf: async ({}, use) => {
707
- await use(passiveApi());
880
+ await use(PASSIVE_API);
708
881
  }
709
882
  };
710
883
  var perfFixtures = {
711
884
  _perfBuffer: [
712
- async ({ browserName }, use, testInfo) => {
713
- const buffer = openBuffer(browserName ?? null, testInfo);
885
+ async ({ browserName, baseURL }, use, testInfo) => {
886
+ skipInCheck(testInfo);
887
+ const buffer = openBuffer(browserName ?? null, baseURL, testInfo);
714
888
  const { collector } = buffer;
715
- if (collector !== null) chunk4SFI55HF_cjs.setActiveCollector(collector);
889
+ if (collector !== null) chunkIUI4AFE5_cjs.setActiveCollector(collector);
716
890
  await use(buffer);
717
891
  if (collector === null) return;
718
- if (chunk4SFI55HF_cjs.activeCollector() === collector) chunk4SFI55HF_cjs.setActiveCollector(void 0);
892
+ if (chunkIUI4AFE5_cjs.activeCollector() === collector) chunkIUI4AFE5_cjs.setActiveCollector(void 0);
719
893
  collector.markTeardownStart();
720
894
  await collector.attach(testInfo);
721
895
  },
722
896
  { auto: true, box: true }
723
897
  ],
724
898
  context: async ({ context, _perfBuffer }, use) => {
725
- _perfBuffer.collector?.track(context);
899
+ _perfBuffer.collector?.track(context, true);
726
900
  await use(context);
727
901
  await _perfBuffer.collector?.drain();
728
902
  },
@@ -731,13 +905,18 @@ var perfFixtures = {
731
905
  await use(page);
732
906
  await _perfBuffer.collector?.drain();
733
907
  },
908
+ // The same object with its request methods measured (15-REQ-03); untouched without a collector.
909
+ request: async ({ request, _perfBuffer }, use) => {
910
+ _perfBuffer.collector?.wrapRequest(request, "request");
911
+ await use(request);
912
+ },
734
913
  perf: async ({ _perfBuffer }, use) => {
735
914
  await use(_perfBuffer.api);
736
915
  _perfBuffer.collector?.markTeardownStart();
737
916
  }
738
917
  };
739
918
  function withPerfFixtures(base2) {
740
- const wrapped = chunk4SFI55HF_cjs.wrappedTests();
919
+ const wrapped = chunkIUI4AFE5_cjs.wrappedTests();
741
920
  if (wrapped.has(base2)) return base2;
742
921
  const extend = base2.extend;
743
922
  const result = extend.call(base2, perfModeOn() ? perfFixtures : passiveFixtures);
@@ -746,13 +925,24 @@ function withPerfFixtures(base2) {
746
925
  }
747
926
  function trackContext(context) {
748
927
  if (!perfModeOn()) return;
749
- const contexts = chunk4SFI55HF_cjs.trackedContexts();
928
+ const contexts = chunkIUI4AFE5_cjs.trackedContexts();
750
929
  if (!contexts.has(context)) {
751
930
  contexts.add(context);
752
931
  context.once("close", () => contexts.delete(context));
753
932
  }
754
- chunk4SFI55HF_cjs.activeCollector()?.track(context);
933
+ chunkIUI4AFE5_cjs.activeCollector()?.track(context);
934
+ }
935
+ function trackRequestContext(requestContext) {
936
+ if (!perfModeOn()) return;
937
+ const state = chunkIUI4AFE5_cjs.getRegistered();
938
+ if (state !== void 0 && !state.config.measure.api) return;
939
+ if (!isApiRequestContext(requestContext)) {
940
+ chunkIUI4AFE5_cjs.activeCollector()?.requestContextNotTracked();
941
+ return;
942
+ }
943
+ wrapRequestContext(requestContext, "tracked", void 0, chunkIUI4AFE5_cjs.activeCollector);
755
944
  }
756
945
 
757
946
  exports.trackContext = trackContext;
947
+ exports.trackRequestContext = trackRequestContext;
758
948
  exports.withPerfFixtures = withPerfFixtures;