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,6 +1,124 @@
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-HBGADXLP.js';
3
- import { perfDefaults } from './chunk-L5C63HEF.js';
1
+ import { wrappedTests, trackedContexts, activeCollector, getRegistered, setActiveCollector, wrappedRequestContexts } from './chunk-S6UH6QPK.js';
2
+ import { ABORT_FAILURE_TEXTS, CONTEXT_CLOSED_FAILURE_TEXT, readModeState, ConfigError, DEFAULT_MAX_TESTS, version, SAMPLES_ATTACHMENT_NAME, checkStateFileName } from './chunk-RL27E3AB.js';
3
+ import { perfDefaults } from './chunk-CISGJCFW.js';
4
+ import { readFileSync, writeFileSync } from 'fs';
5
+ import { tmpdir } from 'os';
6
+ import { join } from 'path';
7
+
8
+ var memory = { files: [], ran: 0 };
9
+ function checkStatePath(runId) {
10
+ return join(tmpdir(), checkStateFileName(runId));
11
+ }
12
+ function load(path) {
13
+ if (path === null) return memory;
14
+ try {
15
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
16
+ return { files: Array.isArray(parsed.files) ? parsed.files : [], ran: Number(parsed.ran ?? 0) };
17
+ } catch {
18
+ return { files: [], ran: 0 };
19
+ }
20
+ }
21
+ function save(path, state) {
22
+ if (path === null) memory = state;
23
+ else writeFileSync(path, JSON.stringify(state));
24
+ }
25
+ function checkRunsTest(runId, maxTests, project, file) {
26
+ const path = runId === void 0 ? null : checkStatePath(runId);
27
+ const state = load(path);
28
+ const id = `${project}\0${file}`;
29
+ if (state.ran >= maxTests || state.files.includes(id)) return false;
30
+ save(path, { files: [...state.files, id], ran: state.ran + 1 });
31
+ return true;
32
+ }
33
+
34
+ // src/collector/api-requests.ts
35
+ var API_METHODS = ["fetch", "get", "post", "put", "patch", "delete", "head"];
36
+ var METHOD = /^[A-Z]+$/u;
37
+ var depth = 0;
38
+ function call(target, name) {
39
+ if (typeof target !== "object" || target === null) return void 0;
40
+ const fn = target[name];
41
+ if (typeof fn !== "function") return void 0;
42
+ const value = fn.call(target);
43
+ return typeof value === "string" ? value : void 0;
44
+ }
45
+ function resolveUrl(raw, baseURL) {
46
+ try {
47
+ return new URL(raw).toString();
48
+ } catch {
49
+ }
50
+ if (baseURL === void 0 || baseURL === "") return null;
51
+ try {
52
+ return new URL(raw, baseURL).toString();
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+ function describeCall(name, args, baseURL) {
58
+ const [target, options] = args;
59
+ const rawUrl = typeof target === "string" ? target : call(target, "url") ?? String(target);
60
+ let method = name;
61
+ if (name === "fetch") {
62
+ const fromOptions = typeof options === "object" && options !== null ? options.method : void 0;
63
+ method = (typeof fromOptions === "string" ? fromOptions : void 0) ?? call(target, "method") ?? "GET";
64
+ }
65
+ method = method.toUpperCase();
66
+ if (!METHOD.test(method)) return void 0;
67
+ return { method, rawUrl, url: resolveUrl(rawUrl, baseURL) };
68
+ }
69
+ function isApiRequestContext(value) {
70
+ if (typeof value !== "object" || value === null) return false;
71
+ const target = value;
72
+ return ["fetch", "get", "post", "dispose", "storageState"].every(
73
+ (name) => typeof target[name] === "function"
74
+ );
75
+ }
76
+ function isPromise(value) {
77
+ return typeof value === "object" && value !== null && typeof value.then === "function";
78
+ }
79
+ function wrapRequestContext(context, source, baseURL, recorder) {
80
+ const wrapped = wrappedRequestContexts();
81
+ if (wrapped.has(context)) return false;
82
+ wrapped.add(context);
83
+ const target = context;
84
+ for (const name of API_METHODS) {
85
+ const original = target[name];
86
+ if (typeof original !== "function") continue;
87
+ const fn = original;
88
+ const wrapper = function(...args) {
89
+ const active = depth === 0 ? recorder() : void 0;
90
+ if (active === void 0) return fn.apply(this, args);
91
+ let described;
92
+ try {
93
+ described = describeCall(name, args, baseURL);
94
+ } catch {
95
+ described = void 0;
96
+ }
97
+ depth += 1;
98
+ let result;
99
+ try {
100
+ result = fn.apply(this, args);
101
+ } finally {
102
+ depth -= 1;
103
+ }
104
+ if (described === void 0 || !isPromise(result)) return result;
105
+ return active.observeApiCall(described, source, result);
106
+ };
107
+ Object.defineProperty(target, name, {
108
+ value: wrapper,
109
+ configurable: true,
110
+ enumerable: false,
111
+ writable: true
112
+ });
113
+ }
114
+ return true;
115
+ }
116
+
117
+ // src/collector/perf-api.ts
118
+ function createPerfApi(track, trackRequestContext2 = () => {
119
+ }) {
120
+ return Object.freeze({ track, trackRequestContext: trackRequestContext2 });
121
+ }
4
122
 
5
123
  // src/collector/constants.ts
6
124
  var KNOWN_THIRD_PARTY_HOSTS = Object.freeze([
@@ -39,156 +157,6 @@ var PENDING_RESERVE_MS = 1e3;
39
157
  var SAMPLE_LIMIT_PER_TEST = 2e4;
40
158
  var COLLECTOR_NAME = "playwright-js";
41
159
 
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
160
  // src/collector/diagnostics.ts
193
161
  function createDiagnostics() {
194
162
  const entries = /* @__PURE__ */ new Map();
@@ -212,20 +180,6 @@ function errorText(error) {
212
180
  return String(error);
213
181
  }
214
182
 
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
183
  // src/collector/filters.ts
230
184
  function isKnownThirdPartyHost(host, hosts = KNOWN_THIRD_PARTY_HOSTS) {
231
185
  const name = host.toLowerCase().replace(/\.$/u, "");
@@ -251,13 +205,56 @@ function shouldTrack(req, measure) {
251
205
  if (req.resourceType !== "document" && hasIgnoredExtension(url, measure.ignoreExtensions)) {
252
206
  return false;
253
207
  }
254
- if (measure.include.length > 0 && !measure.include.some((pattern) => matchesUrlPattern(req.url, pattern))) {
208
+ return passesUrlFilters(req.url, url, measure);
209
+ }
210
+ function passesUrlFilters(text, url, measure) {
211
+ if (measure.include.length > 0 && !measure.include.some((pattern) => matchesUrlPattern(text, pattern))) {
255
212
  return false;
256
213
  }
257
- if (measure.exclude.some((pattern) => matchesUrlPattern(req.url, pattern))) return false;
214
+ if (measure.exclude.some((pattern) => matchesUrlPattern(text, pattern))) return false;
258
215
  if (measure.excludeKnownThirdParty && isKnownThirdPartyHost(url.hostname)) return false;
259
216
  return true;
260
217
  }
218
+ function shouldTrackApiCall(text, measure) {
219
+ let url;
220
+ try {
221
+ url = new URL(text);
222
+ } catch {
223
+ return false;
224
+ }
225
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
226
+ return passesUrlFilters(text, url, measure);
227
+ }
228
+
229
+ // src/collector/timing.ts
230
+ function roundMs(x) {
231
+ return Math.round(x * 10) / 10 + 0;
232
+ }
233
+ function partialTiming(timing) {
234
+ const { requestStart, responseStart } = timing;
235
+ const ttfb = responseStart - requestStart;
236
+ return {
237
+ requestStart: requestStart >= 0 ? roundMs(requestStart) : null,
238
+ ttfb: requestStart >= 0 && responseStart >= 0 && ttfb >= 0 ? roundMs(ttfb) : null
239
+ };
240
+ }
241
+ function computeTiming(timing, fallback) {
242
+ const browser = timing.responseEnd >= 0;
243
+ return {
244
+ startTime: Math.round(timing.startTime),
245
+ duration: roundMs(
246
+ browser ? timing.responseEnd : Math.max(0, fallback.finishedAtNode - fallback.startedAtNode)
247
+ ),
248
+ ...partialTiming(timing),
249
+ timeSource: browser ? "browser" : "node"
250
+ };
251
+ }
252
+ function pendingBudgetMs(input) {
253
+ const { pendingTimeoutMs, testTimeoutMs, sinceTeardownStartMs } = input;
254
+ if (testTimeoutMs === 0) return Math.max(0, pendingTimeoutMs);
255
+ const left = testTimeoutMs - sinceTeardownStartMs - PENDING_RESERVE_MS;
256
+ return Math.max(0, Math.min(pendingTimeoutMs, left));
257
+ }
261
258
 
262
259
  // src/collector/request-tracker.ts
263
260
  var NO_TIMING = {
@@ -266,6 +263,10 @@ var NO_TIMING = {
266
263
  responseStart: -1,
267
264
  responseEnd: -1
268
265
  };
266
+ var BODYLESS = /* @__PURE__ */ new Set([204, 205, 304]);
267
+ var ABORTED_AFTER_RESPONSE = new Set(
268
+ ABORT_FAILURE_TEXTS.filter((text) => text !== CONTEXT_CLOSED_FAILURE_TEXT)
269
+ );
269
270
  var RequestTracker = class {
270
271
  context;
271
272
  #opts;
@@ -369,11 +370,13 @@ var RequestTracker = class {
369
370
  (error) => this.#timingFailed(request, entry, error)
370
371
  );
371
372
  }
372
- #complete(request, entry, response, finishedAtNode) {
373
+ #complete(request, entry, response, finishedAtNode, headersEnd = false) {
373
374
  if (this.#inflight.get(request) !== entry) return;
374
375
  try {
375
376
  if (response === null) throw new Error("the request finished without a response");
376
- const timing = computeTiming(request.timing(), {
377
+ const raw = request.timing();
378
+ const ended = headersEnd && raw.responseEnd < 0 ? { ...raw, responseEnd: raw.responseStart } : raw;
379
+ const timing = computeTiming(ended, {
377
380
  startedAtNode: entry.startedAtNode,
378
381
  finishedAtNode
379
382
  });
@@ -402,6 +405,11 @@ var RequestTracker = class {
402
405
  const entry = this.#inflight.get(request);
403
406
  if (entry === void 0) return;
404
407
  const text = request.failure()?.errorText ?? "";
408
+ if (entry.response !== null && !entry.settling && (BODYLESS.has(entry.response.status()) || ABORTED_AFTER_RESPONSE.has(text))) {
409
+ entry.settling = true;
410
+ this.#complete(request, entry, entry.response, this.#opts.now(), true);
411
+ return;
412
+ }
405
413
  this.#settle(request);
406
414
  this.#sink.finished(
407
415
  failed(request, entry, text === "" ? "unknown" : text, safeTiming(request))
@@ -519,14 +527,23 @@ function pageOf(request) {
519
527
  }
520
528
 
521
529
  // src/collector/test-collector.ts
530
+ function currentRecorder() {
531
+ return activeCollector();
532
+ }
533
+ function firstLine(error) {
534
+ const line = errorText(error).split("\n", 1)[0]?.trim() ?? "";
535
+ return line === "" ? "unknown" : line;
536
+ }
522
537
  var TestCollector = class {
523
538
  api;
524
539
  #opts;
525
540
  #diag = createDiagnostics();
526
- #timer;
527
541
  #trackers = /* @__PURE__ */ new Map();
528
542
  #requests = [];
529
543
  #pending = [];
544
+ #apiRequests = [];
545
+ #apiPending = [];
546
+ #apiInFlight = /* @__PURE__ */ new Set();
530
547
  #sink;
531
548
  #dropped = 0;
532
549
  #browserName;
@@ -535,28 +552,151 @@ var TestCollector = class {
535
552
  #draining;
536
553
  constructor(opts) {
537
554
  this.#opts = opts;
538
- this.#timer = new CustomTimer(
539
- { now: opts.now, wallNow: opts.wallNow, record: true },
540
- this.#diag
555
+ this.api = createPerfApi(
556
+ (context) => {
557
+ this.track(context);
558
+ },
559
+ (requestContext) => {
560
+ this.trackRequestContext(requestContext);
561
+ }
541
562
  );
542
- this.api = createPerfApi(this.#timer, (context) => {
543
- this.track(context);
563
+ this.#sink = {
564
+ finished: (sample) => this.#keep(this.#requests, sample),
565
+ pending: (sample) => this.#keep(this.#pending, sample)
566
+ };
567
+ }
568
+ /** The sample limit counts browser samples and API calls together (05-REQ-16, 15-REQ-09). */
569
+ #keep(list, sample) {
570
+ const count = this.#requests.length + this.#pending.length + this.#apiRequests.length + this.#apiPending.length;
571
+ if (count < SAMPLE_LIMIT_PER_TEST) list.push(sample);
572
+ else this.#dropped += 1;
573
+ }
574
+ /**
575
+ * Wraps an APIRequestContext of this test (15-REQ-03): the request fixture or context.request.
576
+ * Relative URLs resolve against the test's baseURL only for the request fixture and the context
577
+ * of the context fixture, which Playwright creates with that baseURL; any other context may have
578
+ * its own baseURL, so its calls take response.url() (15-REQ-05).
579
+ */
580
+ wrapRequest(requestContext, source, testBaseURL = source === "request") {
581
+ try {
582
+ wrapRequestContext(
583
+ requestContext,
584
+ source,
585
+ testBaseURL ? this.#opts.baseURL : void 0,
586
+ currentRecorder
587
+ );
588
+ } catch (error) {
589
+ this.#diag.add({
590
+ code: "COLLECTOR_LISTENER_ERROR",
591
+ message: `collector: wrapping an APIRequestContext failed, so its calls are not measured: ${errorText(error)}`,
592
+ hint: "Report this as a bug of the package; the test result is not affected."
593
+ });
594
+ }
595
+ }
596
+ /** perf.trackRequestContext() (15-REQ-03, 15-AC-07). */
597
+ trackRequestContext(requestContext) {
598
+ if (!isApiRequestContext(requestContext)) {
599
+ this.requestContextNotTracked();
600
+ return;
601
+ }
602
+ this.wrapRequest(requestContext, "tracked");
603
+ }
604
+ requestContextNotTracked() {
605
+ this.#diag.add({
606
+ code: "COLLECTOR_REQUEST_CONTEXT_NOT_TRACKED",
607
+ message: "collector: trackRequestContext() got an object that is not an APIRequestContext, so it is not measured",
608
+ hint: "Pass the object returned by playwright.request.newContext()."
544
609
  });
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;
610
+ }
611
+ /**
612
+ * Records one APIRequestContext call (15-REQ-05): the returned promise settles like `result`
613
+ * (same value, same error); the sample is made when it settles or at the end-of-test wait.
614
+ */
615
+ observeApiCall(call2, source, result) {
616
+ if (this.#draining !== void 0) return result;
617
+ const startedAt = this.#opts.now();
618
+ const entry = {
619
+ call: call2,
620
+ source,
621
+ startTime: Math.round(this.#opts.wallNow()),
622
+ settled: Promise.resolve(),
623
+ done: false
548
624
  };
549
- this.#sink = {
550
- finished: (sample) => keep(this.#requests, sample),
551
- pending: (sample) => keep(this.#pending, sample)
625
+ const finish = (status, extra, responseUrl) => {
626
+ try {
627
+ if (entry.done) return;
628
+ entry.done = true;
629
+ this.#apiInFlight.delete(entry);
630
+ const sample = this.#apiSample(entry, status, responseUrl, extra);
631
+ if (sample !== null) this.#keep(this.#apiRequests, sample);
632
+ } catch (error) {
633
+ this.#diag.add({
634
+ code: "COLLECTOR_LISTENER_ERROR",
635
+ message: `collector: recording an APIRequestContext call failed: ${errorText(error)}`,
636
+ hint: "Report this as a bug of the package; the test result is not affected."
637
+ });
638
+ }
639
+ };
640
+ const out = result.then(
641
+ (response) => {
642
+ const duration = roundMs(this.#opts.now() - startedAt);
643
+ let status;
644
+ let url;
645
+ try {
646
+ const r = response;
647
+ const s = typeof r.status === "function" ? r.status() : void 0;
648
+ status = typeof s === "number" && Number.isInteger(s) && s >= 100 && s <= 599 ? s : void 0;
649
+ const u = typeof r.url === "function" ? r.url() : void 0;
650
+ url = typeof u === "string" && u !== "" ? u : void 0;
651
+ } catch {
652
+ status = void 0;
653
+ }
654
+ if (status === void 0) finish("FAILED", { failureText: "unknown", duration: null }, url);
655
+ else finish(status, { duration }, url);
656
+ return response;
657
+ },
658
+ (error) => {
659
+ finish("FAILED", { failureText: firstLine(error), duration: null });
660
+ throw error;
661
+ }
662
+ );
663
+ entry.settled = out.then(
664
+ () => void 0,
665
+ () => void 0
666
+ );
667
+ this.#apiInFlight.add(entry);
668
+ return out;
669
+ }
670
+ /** The sample of a call, or null when the filters skip its URL (15-REQ-06). */
671
+ #apiSample(entry, status, responseUrl, extra) {
672
+ const url = entry.call.url ?? responseUrl ?? entry.call.rawUrl;
673
+ if (url === "" || !shouldTrackApiCall(url, this.#opts.measure)) return null;
674
+ return {
675
+ method: entry.call.method,
676
+ url,
677
+ status,
678
+ ...status === "FAILED" ? { failureText: extra.failureText ?? "unknown" } : {},
679
+ startTime: entry.startTime,
680
+ duration: extra.duration ?? null,
681
+ source: entry.source
552
682
  };
553
683
  }
554
684
  /**
555
685
  * 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.
686
+ * test is draining. Returns true when a tracker was attached. `contextFixture`: the context of
687
+ * the context fixture, whose request calls resolve against the test's baseURL (15-REQ-05).
557
688
  */
558
- track(context) {
689
+ track(context, contextFixture = false) {
559
690
  if (this.#draining !== void 0 || this.#trackers.has(context)) return false;
691
+ let requestContext;
692
+ try {
693
+ requestContext = context.request;
694
+ } catch {
695
+ requestContext = void 0;
696
+ }
697
+ if (typeof requestContext === "object" && requestContext !== null) {
698
+ this.wrapRequest(requestContext, "context", contextFixture);
699
+ }
560
700
  try {
561
701
  this.#trackers.set(
562
702
  context,
@@ -610,8 +750,9 @@ var TestCollector = class {
610
750
  testTimeoutMs: this.#opts.testTimeout(),
611
751
  sinceTeardownStartMs: this.#opts.now() - (this.#teardownStart ?? this.#opts.now())
612
752
  });
613
- await Promise.all(
614
- [...this.#trackers.values()].map(async (tracker) => {
753
+ await Promise.all([
754
+ this.#drainApiCalls(budget),
755
+ ...[...this.#trackers.values()].map(async (tracker) => {
615
756
  try {
616
757
  await tracker.drain(budget);
617
758
  } catch (error) {
@@ -622,11 +763,38 @@ var TestCollector = class {
622
763
  });
623
764
  }
624
765
  })
625
- );
766
+ ]);
767
+ }
768
+ /** Waits for running API calls within the budget; the rest become PENDING (15-REQ-08). */
769
+ async #drainApiCalls(budget) {
770
+ if (this.#apiInFlight.size > 0) {
771
+ let timer;
772
+ const timeout = new Promise((resolve) => {
773
+ timer = setTimeout(resolve, Math.max(0, budget));
774
+ });
775
+ await Promise.race([
776
+ Promise.all([...this.#apiInFlight].map((entry) => entry.settled)),
777
+ timeout
778
+ ]);
779
+ clearTimeout(timer);
780
+ }
781
+ for (const entry of [...this.#apiInFlight]) {
782
+ entry.done = true;
783
+ this.#apiInFlight.delete(entry);
784
+ try {
785
+ const sample = this.#apiSample(entry, "PENDING", void 0, { duration: null });
786
+ if (sample !== null) this.#keep(this.#apiPending, sample);
787
+ } catch (error) {
788
+ this.#diag.add({
789
+ code: "COLLECTOR_LISTENER_ERROR",
790
+ message: `collector: recording an APIRequestContext call failed: ${errorText(error)}`,
791
+ hint: "Report this as a bug of the package; the test result is not affected."
792
+ });
793
+ }
794
+ }
626
795
  }
627
796
  /** The sample batch of the test (05-REQ-15); call after drain(). */
628
797
  batch() {
629
- const custom = this.#timer.finish();
630
798
  if (this.#dropped > 0) {
631
799
  this.#diag.add({
632
800
  code: "COLLECTOR_SAMPLE_LIMIT_REACHED",
@@ -637,14 +805,14 @@ var TestCollector = class {
637
805
  this.#dropped = 0;
638
806
  }
639
807
  return {
640
- schemaVersion: 1,
808
+ schemaVersion: 3,
641
809
  collector: {
642
810
  name: COLLECTOR_NAME,
643
811
  version: this.#opts.version,
644
812
  browserName: this.#browserName ?? null
645
813
  },
646
814
  requests: [...this.#requests, ...this.#pending],
647
- custom,
815
+ apiRequests: [...this.#apiRequests, ...this.#apiPending],
648
816
  diagnostics: this.#diag.list()
649
817
  };
650
818
  }
@@ -678,38 +846,44 @@ function perfModeOn() {
678
846
  if (!mode.ok) throw new ConfigError(mode.issues);
679
847
  return mode.value !== null;
680
848
  }
681
- function passiveApi() {
682
- return createPerfApi(
683
- new CustomTimer({ now, wallNow, record: false }, createDiagnostics()),
684
- () => {
685
- }
686
- );
687
- }
688
- function openBuffer(browserName, testInfo) {
849
+ var PASSIVE_API = createPerfApi(() => {
850
+ });
851
+ function openBuffer(browserName, baseURL, testInfo) {
689
852
  const state = getRegistered();
690
- if (state !== void 0 && !state.measuredProjects.includes(testInfo.project.name)) {
691
- return { collector: null, api: passiveApi() };
853
+ if (state !== void 0 && (!state.config.measure.api || !state.measuredProjects.includes(testInfo.project.name))) {
854
+ return { collector: null, api: PASSIVE_API };
692
855
  }
693
856
  const collector = new TestCollector({
694
857
  measure: (state?.config ?? perfDefaults).measure,
695
858
  version,
696
859
  browserName,
697
860
  testTimeout: () => testInfo.timeout,
861
+ baseURL,
698
862
  now,
699
863
  wallNow
700
864
  });
701
865
  for (const context of trackedContexts()) collector.track(context);
702
866
  return { collector, api: collector.api };
703
867
  }
868
+ function skipInCheck(testInfo) {
869
+ const state = getRegistered();
870
+ if (state === void 0 || state.mode.mode !== "check") return;
871
+ if (!state.measuredProjects.includes(testInfo.project.name)) return;
872
+ const max = state.mode.maxTests ?? DEFAULT_MAX_TESTS;
873
+ if (!checkRunsTest(state.mode.runId, max, testInfo.project.name, testInfo.file)) {
874
+ testInfo.skip(true, "PW_PERF_MODE=check: only the first test of each file runs");
875
+ }
876
+ }
704
877
  var passiveFixtures = {
705
878
  perf: async ({}, use) => {
706
- await use(passiveApi());
879
+ await use(PASSIVE_API);
707
880
  }
708
881
  };
709
882
  var perfFixtures = {
710
883
  _perfBuffer: [
711
- async ({ browserName }, use, testInfo) => {
712
- const buffer = openBuffer(browserName ?? null, testInfo);
884
+ async ({ browserName, baseURL }, use, testInfo) => {
885
+ skipInCheck(testInfo);
886
+ const buffer = openBuffer(browserName ?? null, baseURL, testInfo);
713
887
  const { collector } = buffer;
714
888
  if (collector !== null) setActiveCollector(collector);
715
889
  await use(buffer);
@@ -721,7 +895,7 @@ var perfFixtures = {
721
895
  { auto: true, box: true }
722
896
  ],
723
897
  context: async ({ context, _perfBuffer }, use) => {
724
- _perfBuffer.collector?.track(context);
898
+ _perfBuffer.collector?.track(context, true);
725
899
  await use(context);
726
900
  await _perfBuffer.collector?.drain();
727
901
  },
@@ -730,6 +904,11 @@ var perfFixtures = {
730
904
  await use(page);
731
905
  await _perfBuffer.collector?.drain();
732
906
  },
907
+ // The same object with its request methods measured (15-REQ-03); untouched without a collector.
908
+ request: async ({ request, _perfBuffer }, use) => {
909
+ _perfBuffer.collector?.wrapRequest(request, "request");
910
+ await use(request);
911
+ },
733
912
  perf: async ({ _perfBuffer }, use) => {
734
913
  await use(_perfBuffer.api);
735
914
  _perfBuffer.collector?.markTeardownStart();
@@ -752,5 +931,15 @@ function trackContext(context) {
752
931
  }
753
932
  activeCollector()?.track(context);
754
933
  }
934
+ function trackRequestContext(requestContext) {
935
+ if (!perfModeOn()) return;
936
+ const state = getRegistered();
937
+ if (state !== void 0 && !state.config.measure.api) return;
938
+ if (!isApiRequestContext(requestContext)) {
939
+ activeCollector()?.requestContextNotTracked();
940
+ return;
941
+ }
942
+ wrapRequestContext(requestContext, "tracked", void 0, activeCollector);
943
+ }
755
944
 
756
- export { trackContext, withPerfFixtures };
945
+ export { trackContext, trackRequestContext, withPerfFixtures };