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,4769 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var chunkLV3O2BAT_cjs = require('./chunk-LV3O2BAT.cjs');
6
+ var chunkGCA73FFP_cjs = require('./chunk-GCA73FFP.cjs');
7
+ var promises = require('fs/promises');
8
+ var path = require('path');
9
+ var crypto = require('crypto');
10
+ var os = require('os');
11
+
12
+ function isNotFound(error) {
13
+ return typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
14
+ }
15
+ async function readTextFile(path) {
16
+ try {
17
+ return await promises.readFile(path, "utf8");
18
+ } catch (error) {
19
+ if (isNotFound(error)) return null;
20
+ throw error;
21
+ }
22
+ }
23
+ async function fileExists(path) {
24
+ try {
25
+ await promises.access(path);
26
+ return true;
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+ function resolvePath(base, path$1) {
32
+ return path.resolve(base, path$1);
33
+ }
34
+ function directoryOf(path$1) {
35
+ return path.dirname(path$1);
36
+ }
37
+ function relativeSlashPath(from, path$1) {
38
+ const rel = path.relative(from, path$1);
39
+ const shown = rel === "" ? "." : path.isAbsolute(rel) ? path$1 : rel;
40
+ return shown.replaceAll("\\", "/");
41
+ }
42
+
43
+ // src/core/format/round.ts
44
+ function roundRatio(x) {
45
+ return Math.round(x * 1e4) / 1e4 + 0;
46
+ }
47
+ function roundMs(x) {
48
+ return Math.round(x * 10) / 10;
49
+ }
50
+ function snap(x, digits) {
51
+ return Math.round(x * 10 ** (digits + 6)) / 1e6;
52
+ }
53
+ function ceilTo(x, digits) {
54
+ return Math.ceil(snap(x, digits)) / 10 ** digits;
55
+ }
56
+ function floorTo(x, digits) {
57
+ return Math.floor(snap(x, digits)) / 10 ** digits;
58
+ }
59
+
60
+ // src/core/format/json.ts
61
+ var INDENT = " ";
62
+ function fail(pointer, what) {
63
+ throw new TypeError(
64
+ `stringifyStable: value at "${pointer}" is ${what}, which cannot be written to JSON`
65
+ );
66
+ }
67
+ function isPlainObject(value) {
68
+ const proto = Object.getPrototypeOf(value);
69
+ return proto === Object.prototype || proto === null;
70
+ }
71
+ function escapePointer(key2) {
72
+ return key2.replaceAll("~", "~0").replaceAll("/", "~1");
73
+ }
74
+ function write(value, pointer, indent, ancestors) {
75
+ switch (typeof value) {
76
+ case "string":
77
+ case "boolean":
78
+ return JSON.stringify(value);
79
+ case "number":
80
+ if (!Number.isFinite(value)) fail(pointer, String(value));
81
+ return JSON.stringify(value);
82
+ case "undefined":
83
+ return fail(pointer, "undefined");
84
+ case "object":
85
+ break;
86
+ default:
87
+ return fail(pointer, typeof value);
88
+ }
89
+ if (value === null) return "null";
90
+ if (ancestors.has(value)) fail(pointer, "a circular reference");
91
+ const inner = indent + INDENT;
92
+ ancestors.add(value);
93
+ let text;
94
+ if (Array.isArray(value)) {
95
+ const items = value.map((item, i) => inner + write(item, `${pointer}/${i}`, inner, ancestors));
96
+ text = items.length === 0 ? "[]" : `[
97
+ ${items.join(",\n")}
98
+ ${indent}]`;
99
+ } else {
100
+ if (!isPlainObject(value)) fail(pointer, "not a plain object");
101
+ const record2 = value;
102
+ const keys = Object.keys(record2).filter((key2) => record2[key2] !== void 0).sort();
103
+ const entries = keys.map(
104
+ (key2) => `${inner}${JSON.stringify(key2)}: ${write(record2[key2], `${pointer}/${escapePointer(key2)}`, inner, ancestors)}`
105
+ );
106
+ text = entries.length === 0 ? "{}" : `{
107
+ ${entries.join(",\n")}
108
+ ${indent}}`;
109
+ }
110
+ ancestors.delete(value);
111
+ return text;
112
+ }
113
+ function stringifyStable(value) {
114
+ return `${write(value, "", "", /* @__PURE__ */ new Set())}
115
+ `;
116
+ }
117
+
118
+ // src/io/json.ts
119
+ async function writeTextAtomic(path$1, text) {
120
+ const dir = path.dirname(path$1);
121
+ await promises.mkdir(dir, { recursive: true });
122
+ const temp = path.join(dir, `.${path.basename(path$1)}.${crypto.randomUUID()}.tmp`);
123
+ try {
124
+ await promises.writeFile(temp, text, "utf8");
125
+ await promises.rename(temp, path$1);
126
+ } catch (error) {
127
+ await promises.rm(temp, { force: true });
128
+ throw error;
129
+ }
130
+ }
131
+ async function writeJsonStable(path, value) {
132
+ await writeTextAtomic(path, stringifyStable(value));
133
+ }
134
+ function read(env, name) {
135
+ const value = env[name];
136
+ return value === void 0 || value === "" ? null : value;
137
+ }
138
+ function first(env, ...names) {
139
+ for (const name of names) {
140
+ const value = read(env, name);
141
+ if (value !== null) return value;
142
+ }
143
+ return null;
144
+ }
145
+ function compose(env, build, ...names) {
146
+ const values = names.map((name) => read(env, name));
147
+ return values.every((v) => v !== null) ? build(values) : null;
148
+ }
149
+ function readCiInfo(env) {
150
+ if (env.GITHUB_ACTIONS === "true") {
151
+ return {
152
+ provider: "github",
153
+ commit: read(env, "GITHUB_SHA"),
154
+ branch: first(env, "GITHUB_HEAD_REF", "GITHUB_REF_NAME"),
155
+ buildUrl: compose(
156
+ env,
157
+ ([server, repository, runId2]) => `${server}/${repository}/actions/runs/${runId2}`,
158
+ "GITHUB_SERVER_URL",
159
+ "GITHUB_REPOSITORY",
160
+ "GITHUB_RUN_ID"
161
+ )
162
+ };
163
+ }
164
+ if (env.GITLAB_CI === "true") {
165
+ return {
166
+ provider: "gitlab",
167
+ commit: read(env, "CI_COMMIT_SHA"),
168
+ branch: read(env, "CI_COMMIT_REF_NAME"),
169
+ buildUrl: read(env, "CI_JOB_URL")
170
+ };
171
+ }
172
+ if (read(env, "JENKINS_URL") !== null) {
173
+ return {
174
+ provider: "jenkins",
175
+ commit: read(env, "GIT_COMMIT"),
176
+ branch: first(env, "BRANCH_NAME", "GIT_BRANCH"),
177
+ buildUrl: read(env, "BUILD_URL")
178
+ };
179
+ }
180
+ if (env.TF_BUILD === "True") {
181
+ return {
182
+ provider: "azure",
183
+ commit: read(env, "BUILD_SOURCEVERSION"),
184
+ branch: read(env, "BUILD_SOURCEBRANCHNAME"),
185
+ buildUrl: compose(
186
+ env,
187
+ ([collection, project, buildId]) => `${collection}${project}/_build/results?buildId=${buildId}`,
188
+ "SYSTEM_COLLECTIONURI",
189
+ "SYSTEM_TEAMPROJECT",
190
+ "BUILD_BUILDID"
191
+ )
192
+ };
193
+ }
194
+ if (read(env, "CI") !== null)
195
+ return { provider: "other", commit: null, branch: null, buildUrl: null };
196
+ return null;
197
+ }
198
+ function readHostInfo(env) {
199
+ return {
200
+ platform: process.platform,
201
+ arch: process.arch,
202
+ nodeVersion: process.version,
203
+ ci: read(env, "CI") !== null,
204
+ cpuCount: os.availableParallelism(),
205
+ cpuModel: os.cpus()[0]?.model.trim() ?? ""
206
+ };
207
+ }
208
+
209
+ // src/core/schema/formats.ts
210
+ var nonEmpty = chunkGCA73FFP_cjs.str({ minLength: 1 });
211
+ var nonEmptyOrNull = chunkGCA73FFP_cjs.nullable(nonEmpty);
212
+ function present(value, pointer, sink, properties) {
213
+ for (const [name, schema] of Object.entries(properties)) {
214
+ if (Object.hasOwn(value, name)) schema.check(value[name], `${pointer}/${name}`, sink);
215
+ }
216
+ }
217
+ var noTiming = {
218
+ duration: chunkGCA73FFP_cjs.nul,
219
+ requestStart: chunkGCA73FFP_cjs.nul,
220
+ ttfb: chunkGCA73FFP_cjs.nul,
221
+ timeSource: chunkGCA73FFP_cjs.constant("browser"),
222
+ fromServiceWorker: chunkGCA73FFP_cjs.constant(false)
223
+ };
224
+ var requestSample = chunkGCA73FFP_cjs.obj(
225
+ {
226
+ method: chunkGCA73FFP_cjs.str({ pattern: /^[A-Z]+$/u }),
227
+ url: nonEmpty,
228
+ resourceType: nonEmpty,
229
+ status: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.int({ minimum: 100, maximum: 599 }), chunkGCA73FFP_cjs.constant("FAILED"), chunkGCA73FFP_cjs.constant("PENDING")),
230
+ failureText: nonEmpty,
231
+ startTime: chunkGCA73FFP_cjs.epochMs,
232
+ duration: chunkGCA73FFP_cjs.msOrNull,
233
+ requestStart: chunkGCA73FFP_cjs.msOrNull,
234
+ ttfb: chunkGCA73FFP_cjs.msOrNull,
235
+ timeSource: chunkGCA73FFP_cjs.enumOf(["browser", "node"]),
236
+ fromServiceWorker: chunkGCA73FFP_cjs.bool
237
+ },
238
+ {
239
+ required: [
240
+ "method",
241
+ "url",
242
+ "resourceType",
243
+ "status",
244
+ "startTime",
245
+ "duration",
246
+ "requestStart",
247
+ "ttfb",
248
+ "timeSource",
249
+ "fromServiceWorker"
250
+ ],
251
+ refine(value, pointer, sink) {
252
+ const status = Object.hasOwn(value, "status") ? value.status : "FAILED";
253
+ if (status === "FAILED" && !Object.hasOwn(value, "failureText")) {
254
+ sink.add(pointer, "must have required property 'failureText' when status is FAILED");
255
+ }
256
+ if (status !== "FAILED" && Object.hasOwn(value, "failureText")) {
257
+ sink.add(`${pointer}/failureText`, "must NOT be present unless status is FAILED");
258
+ }
259
+ if (status === "FAILED" || status === "PENDING" || !Object.hasOwn(value, "status")) {
260
+ present(value, pointer, sink, noTiming);
261
+ }
262
+ }
263
+ }
264
+ );
265
+ var customSample = chunkGCA73FFP_cjs.obj(
266
+ {
267
+ name: chunkGCA73FFP_cjs.str({
268
+ minLength: 1,
269
+ maxLength: 200,
270
+ // Same pattern as the schema: no control characters (06-REQ-03).
271
+ // eslint-disable-next-line no-control-regex
272
+ pattern: /^[^\s\u0000-\u001F\u007F](?:[^\u0000-\u001F\u007F]*[^\s\u0000-\u001F\u007F])?$/u
273
+ }),
274
+ outcome: chunkGCA73FFP_cjs.enumOf(["ok", "error", "unfinished"]),
275
+ duration: chunkGCA73FFP_cjs.msOrNull,
276
+ endTime: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.epochMs, chunkGCA73FFP_cjs.nul)
277
+ },
278
+ {
279
+ required: ["name", "outcome", "duration", "endTime"],
280
+ refine(value, pointer, sink) {
281
+ const unfinished = !Object.hasOwn(value, "outcome") || value.outcome === "unfinished";
282
+ present(
283
+ value,
284
+ pointer,
285
+ sink,
286
+ unfinished ? { duration: chunkGCA73FFP_cjs.nul, endTime: chunkGCA73FFP_cjs.nul } : { duration: chunkGCA73FFP_cjs.num(), endTime: chunkGCA73FFP_cjs.int() }
287
+ );
288
+ }
289
+ }
290
+ );
291
+ var sampleBatch = chunkGCA73FFP_cjs.obj(
292
+ {
293
+ schemaVersion: chunkGCA73FFP_cjs.constant(1),
294
+ collector: chunkGCA73FFP_cjs.obj(
295
+ {
296
+ name: chunkGCA73FFP_cjs.str({ pattern: /^[a-z0-9-]+$/u }),
297
+ version: nonEmpty,
298
+ browserName: nonEmptyOrNull
299
+ },
300
+ { required: ["name", "version", "browserName"] }
301
+ ),
302
+ requests: chunkGCA73FFP_cjs.arr(requestSample),
303
+ custom: chunkGCA73FFP_cjs.arr(customSample),
304
+ diagnostics: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.issue)
305
+ },
306
+ { required: ["schemaVersion", "collector", "requests", "custom", "diagnostics"] }
307
+ );
308
+ var LIMIT_FIELDS = ["t", "median", "percentile", "p99", "minApdex", "maxWilson", "maxErrorRate"];
309
+ var thresholdsEntry = chunkGCA73FFP_cjs.obj(
310
+ {
311
+ t: chunkGCA73FFP_cjs.nullable(chunkGCA73FFP_cjs.msLimit),
312
+ median: chunkGCA73FFP_cjs.msLimit,
313
+ percentile: chunkGCA73FFP_cjs.msLimit,
314
+ p99: chunkGCA73FFP_cjs.msLimit,
315
+ minApdex: chunkGCA73FFP_cjs.nullable(chunkGCA73FFP_cjs.ratio),
316
+ maxWilson: chunkGCA73FFP_cjs.nullable(chunkGCA73FFP_cjs.ratio),
317
+ maxErrorRate: chunkGCA73FFP_cjs.ratio,
318
+ locked: chunkGCA73FFP_cjs.constant(true),
319
+ note: chunkGCA73FFP_cjs.str({ minLength: 1, maxLength: 500 }),
320
+ gate: chunkGCA73FFP_cjs.constant("warn"),
321
+ until: chunkGCA73FFP_cjs.isoDate
322
+ },
323
+ {
324
+ refine(value, pointer, sink) {
325
+ if (![...LIMIT_FIELDS, "gate"].some((name) => Object.hasOwn(value, name))) {
326
+ sink.add(pointer, "must have at least one limit or gate");
327
+ }
328
+ if (Object.hasOwn(value, "gate")) {
329
+ for (const name of ["note", "until"]) {
330
+ if (!Object.hasOwn(value, name)) {
331
+ sink.add(pointer, `must have property '${name}' when property 'gate' is present`);
332
+ }
333
+ }
334
+ }
335
+ if (Object.hasOwn(value, "until") && !Object.hasOwn(value, "gate")) {
336
+ sink.add(pointer, "must have property 'gate' when property 'until' is present");
337
+ }
338
+ }
339
+ }
340
+ );
341
+ var thresholdsGenerated = chunkGCA73FFP_cjs.obj(
342
+ {
343
+ tool: chunkGCA73FFP_cjs.tool,
344
+ env: chunkGCA73FFP_cjs.envLabelOrNull,
345
+ sourceRunId: chunkGCA73FFP_cjs.runId,
346
+ sourceRunStartedAt: chunkGCA73FFP_cjs.timestamp,
347
+ sourceSampleCount: chunkGCA73FFP_cjs.count,
348
+ evaluatedPercentile: chunkGCA73FFP_cjs.percentileName,
349
+ derivation: chunkGCA73FFP_cjs.derivationSettings,
350
+ browsers: chunkGCA73FFP_cjs.arr(nonEmpty, { uniqueItems: true }),
351
+ playwrightVersion: nonEmpty,
352
+ host: chunkGCA73FFP_cjs.hostFingerprint,
353
+ normalization: chunkGCA73FFP_cjs.fingerprint
354
+ },
355
+ {
356
+ required: [
357
+ "tool",
358
+ "env",
359
+ "sourceRunId",
360
+ "sourceRunStartedAt",
361
+ "sourceSampleCount",
362
+ "evaluatedPercentile",
363
+ "derivation",
364
+ "browsers",
365
+ "playwrightVersion",
366
+ "host",
367
+ "normalization"
368
+ ]
369
+ }
370
+ );
371
+ var thresholdsFile = chunkGCA73FFP_cjs.obj(
372
+ {
373
+ schemaVersion: chunkGCA73FFP_cjs.constant(1),
374
+ kind: chunkGCA73FFP_cjs.kind,
375
+ generated: chunkGCA73FFP_cjs.oneOf(thresholdsGenerated, chunkGCA73FFP_cjs.nul),
376
+ entries: chunkGCA73FFP_cjs.record(chunkGCA73FFP_cjs.key, thresholdsEntry)
377
+ },
378
+ { required: ["schemaVersion", "kind", "generated", "entries"] }
379
+ );
380
+ var evaluationCounts = chunkGCA73FFP_cjs.obj(
381
+ Object.fromEntries(
382
+ [
383
+ "keys",
384
+ "fromFile",
385
+ "fromDefaults",
386
+ "notEvaluated",
387
+ "tooFewSamples",
388
+ "fileEntriesNotEvaluated",
389
+ "medianOnly",
390
+ "unseenThresholdEntries",
391
+ "violations",
392
+ "blockingViolations",
393
+ "muted"
394
+ ].map((name) => [name, chunkGCA73FFP_cjs.count])
395
+ ),
396
+ {
397
+ required: [
398
+ "keys",
399
+ "fromFile",
400
+ "fromDefaults",
401
+ "notEvaluated",
402
+ "tooFewSamples",
403
+ "fileEntriesNotEvaluated",
404
+ "medianOnly",
405
+ "unseenThresholdEntries",
406
+ "violations",
407
+ "blockingViolations",
408
+ "muted"
409
+ ]
410
+ }
411
+ );
412
+ var thresholdFileInfo = chunkGCA73FFP_cjs.obj(
413
+ {
414
+ kind: chunkGCA73FFP_cjs.kind,
415
+ path: nonEmpty,
416
+ status: chunkGCA73FFP_cjs.enumOf(["loaded", "missing", "invalid"]),
417
+ generated: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.anyObject, chunkGCA73FFP_cjs.nul),
418
+ unseenKeys: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.key)
419
+ },
420
+ { required: ["kind", "path", "status", "generated", "unseenKeys"] }
421
+ );
422
+ var testRef = chunkGCA73FFP_cjs.obj(
423
+ {
424
+ title: chunkGCA73FFP_cjs.str(),
425
+ project: chunkGCA73FFP_cjs.str(),
426
+ file: chunkGCA73FFP_cjs.str(),
427
+ line: chunkGCA73FFP_cjs.int({ minimum: 1 }),
428
+ repeatEachIndex: chunkGCA73FFP_cjs.int({ minimum: 0 })
429
+ },
430
+ { required: ["title", "project", "file", "line", "repeatEachIndex"] }
431
+ );
432
+ var slowSample = chunkGCA73FFP_cjs.obj(
433
+ { duration: chunkGCA73FFP_cjs.ms, startedAt: chunkGCA73FFP_cjs.timestamp, test: testRef, url: nonEmpty },
434
+ { required: ["duration", "startedAt", "test"] }
435
+ );
436
+ var stats = chunkGCA73FFP_cjs.obj(
437
+ {
438
+ min: chunkGCA73FFP_cjs.ms,
439
+ avg: chunkGCA73FFP_cjs.ms,
440
+ max: chunkGCA73FFP_cjs.ms,
441
+ percentiles: chunkGCA73FFP_cjs.record(chunkGCA73FFP_cjs.percentileName, chunkGCA73FFP_cjs.ms, { required: ["p50", "p90", "p95", "p99"] })
442
+ },
443
+ { required: ["min", "avg", "max", "percentiles"] }
444
+ );
445
+ var check = chunkGCA73FFP_cjs.obj(
446
+ {
447
+ rule: chunkGCA73FFP_cjs.enumOf(["median", "percentile", "p99", "apdex", "wilson", "errors"]),
448
+ n: chunkGCA73FFP_cjs.int({ minimum: 1 }),
449
+ actual: chunkGCA73FFP_cjs.num({ minimum: 0 }),
450
+ observed: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.num({ minimum: 0, maximum: 1 }), chunkGCA73FFP_cjs.nul),
451
+ limit: chunkGCA73FFP_cjs.num({ minimum: 0 }),
452
+ passed: chunkGCA73FFP_cjs.bool,
453
+ hardLimitExceeded: chunkGCA73FFP_cjs.bool,
454
+ blocking: chunkGCA73FFP_cjs.bool
455
+ },
456
+ {
457
+ required: [
458
+ "rule",
459
+ "n",
460
+ "actual",
461
+ "observed",
462
+ "limit",
463
+ "passed",
464
+ "hardLimitExceeded",
465
+ "blocking"
466
+ ]
467
+ }
468
+ );
469
+ var keyEvaluation = chunkGCA73FFP_cjs.obj(
470
+ {
471
+ result: chunkGCA73FFP_cjs.enumOf(["pass", "fail", "not-evaluated"]),
472
+ reason: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.enumOf(["too-few-samples", "no-rules", "thresholds-error"]), chunkGCA73FFP_cjs.nul),
473
+ thresholdSource: chunkGCA73FFP_cjs.enumOf(["file", "default"]),
474
+ limits: chunkGCA73FFP_cjs.obj(
475
+ {
476
+ t: chunkGCA73FFP_cjs.nullable(chunkGCA73FFP_cjs.msLimit),
477
+ median: chunkGCA73FFP_cjs.msLimit,
478
+ percentile: chunkGCA73FFP_cjs.msLimit,
479
+ p99: chunkGCA73FFP_cjs.msLimit,
480
+ minApdex: chunkGCA73FFP_cjs.nullable(chunkGCA73FFP_cjs.ratio),
481
+ maxWilson: chunkGCA73FFP_cjs.nullable(chunkGCA73FFP_cjs.ratio),
482
+ maxErrorRate: chunkGCA73FFP_cjs.ratio
483
+ },
484
+ { required: LIMIT_FIELDS }
485
+ ),
486
+ checks: chunkGCA73FFP_cjs.arr(check),
487
+ muted: chunkGCA73FFP_cjs.oneOf(
488
+ chunkGCA73FFP_cjs.obj(
489
+ { until: chunkGCA73FFP_cjs.isoDate, note: nonEmpty, expired: chunkGCA73FFP_cjs.bool },
490
+ { required: ["until", "note", "expired"] }
491
+ ),
492
+ chunkGCA73FFP_cjs.nul
493
+ )
494
+ },
495
+ { required: ["result", "reason", "thresholdSource", "limits", "checks", "muted"] }
496
+ );
497
+ var aggregate = chunkGCA73FFP_cjs.obj(
498
+ {
499
+ count: chunkGCA73FFP_cjs.count,
500
+ successCount: chunkGCA73FFP_cjs.count,
501
+ errorCount: chunkGCA73FFP_cjs.count,
502
+ fromFailedTests: chunkGCA73FFP_cjs.count,
503
+ testCount: chunkGCA73FFP_cjs.count,
504
+ statuses: chunkGCA73FFP_cjs.record(
505
+ chunkGCA73FFP_cjs.str({ pattern: /^(?:[1-5][0-9]{2}|FAILED|ABORTED|PENDING|ok|error|unfinished)$/u }),
506
+ chunkGCA73FFP_cjs.int({ minimum: 1 })
507
+ ),
508
+ timeSources: chunkGCA73FFP_cjs.obj({ browser: chunkGCA73FFP_cjs.count, node: chunkGCA73FFP_cjs.count }, { required: ["browser", "node"] }),
509
+ stats: chunkGCA73FFP_cjs.oneOf(stats, chunkGCA73FFP_cjs.nul),
510
+ ttfb: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.obj({ p50: chunkGCA73FFP_cjs.ms, p95: chunkGCA73FFP_cjs.ms }, { required: ["p50", "p95"] }), chunkGCA73FFP_cjs.nul),
511
+ slowest: chunkGCA73FFP_cjs.arr(slowSample, { maxItems: 3 }),
512
+ topTests: chunkGCA73FFP_cjs.arr(
513
+ chunkGCA73FFP_cjs.obj(
514
+ {
515
+ title: chunkGCA73FFP_cjs.str(),
516
+ project: chunkGCA73FFP_cjs.str(),
517
+ file: chunkGCA73FFP_cjs.str(),
518
+ line: chunkGCA73FFP_cjs.int({ minimum: 1 }),
519
+ sampleCount: chunkGCA73FFP_cjs.int({ minimum: 1 })
520
+ },
521
+ { required: ["title", "project", "file", "line", "sampleCount"] }
522
+ ),
523
+ { maxItems: 5 }
524
+ ),
525
+ samples: chunkGCA73FFP_cjs.obj({ durations: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.ms), sampled: chunkGCA73FFP_cjs.bool }, { required: ["durations", "sampled"] }),
526
+ evaluation: keyEvaluation
527
+ },
528
+ {
529
+ required: [
530
+ "count",
531
+ "successCount",
532
+ "errorCount",
533
+ "fromFailedTests",
534
+ "testCount",
535
+ "statuses",
536
+ "timeSources",
537
+ "stats",
538
+ "ttfb",
539
+ "slowest",
540
+ "topTests",
541
+ "samples",
542
+ "evaluation"
543
+ ]
544
+ }
545
+ );
546
+ chunkGCA73FFP_cjs.obj(
547
+ {
548
+ schemaVersion: chunkGCA73FFP_cjs.constant(1),
549
+ tool: chunkGCA73FFP_cjs.tool,
550
+ runId: chunkGCA73FFP_cjs.runId,
551
+ mode: chunkGCA73FFP_cjs.mode,
552
+ startedAt: chunkGCA73FFP_cjs.timestamp,
553
+ finishedAt: chunkGCA73FFP_cjs.timestamp,
554
+ env: chunkGCA73FFP_cjs.envLabelOrNull,
555
+ configDir: nonEmpty,
556
+ config: chunkGCA73FFP_cjs.packageConfig,
557
+ normalization: chunkGCA73FFP_cjs.fingerprint,
558
+ ci: chunkGCA73FFP_cjs.oneOf(
559
+ chunkGCA73FFP_cjs.obj(
560
+ {
561
+ provider: chunkGCA73FFP_cjs.enumOf(["github", "gitlab", "jenkins", "azure", "other"]),
562
+ commit: nonEmptyOrNull,
563
+ branch: nonEmptyOrNull,
564
+ buildUrl: nonEmptyOrNull
565
+ },
566
+ { required: ["provider", "commit", "branch", "buildUrl"] }
567
+ ),
568
+ chunkGCA73FFP_cjs.nul
569
+ ),
570
+ host: chunkGCA73FFP_cjs.obj(
571
+ {
572
+ platform: chunkGCA73FFP_cjs.str(),
573
+ arch: chunkGCA73FFP_cjs.str(),
574
+ nodeVersion: chunkGCA73FFP_cjs.str(),
575
+ ci: chunkGCA73FFP_cjs.bool,
576
+ cpuCount: chunkGCA73FFP_cjs.int({ minimum: 1 }),
577
+ cpuModel: chunkGCA73FFP_cjs.str()
578
+ },
579
+ { required: ["platform", "arch", "nodeVersion", "ci", "cpuCount", "cpuModel"] }
580
+ ),
581
+ playwright: chunkGCA73FFP_cjs.obj({ version: chunkGCA73FFP_cjs.str() }, { required: ["version"] }),
582
+ runConditions: chunkGCA73FFP_cjs.obj(
583
+ {
584
+ workers: chunkGCA73FFP_cjs.int({ minimum: 1 }),
585
+ projects: chunkGCA73FFP_cjs.arr(
586
+ chunkGCA73FFP_cjs.obj(
587
+ {
588
+ name: chunkGCA73FFP_cjs.str(),
589
+ role: chunkGCA73FFP_cjs.enumOf(["measured", "dependency", "teardown"]),
590
+ browserName: chunkGCA73FFP_cjs.oneOf(chunkGCA73FFP_cjs.str(), chunkGCA73FFP_cjs.nul),
591
+ repeatEach: chunkGCA73FFP_cjs.int({ minimum: 1 }),
592
+ retries: chunkGCA73FFP_cjs.int({ minimum: 0 })
593
+ },
594
+ { required: ["name", "role", "browserName", "repeatEach", "retries"] }
595
+ )
596
+ ),
597
+ overriddenSettings: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.str())
598
+ },
599
+ { required: ["workers", "projects", "overriddenSettings"] }
600
+ ),
601
+ tests: chunkGCA73FFP_cjs.obj(
602
+ {
603
+ status: chunkGCA73FFP_cjs.testsStatus,
604
+ expected: chunkGCA73FFP_cjs.count,
605
+ unexpected: chunkGCA73FFP_cjs.count,
606
+ flaky: chunkGCA73FFP_cjs.count,
607
+ skipped: chunkGCA73FFP_cjs.count
608
+ },
609
+ { required: ["status", "expected", "unexpected", "flaky", "skipped"] }
610
+ ),
611
+ evaluation: chunkGCA73FFP_cjs.obj(
612
+ {
613
+ status: chunkGCA73FFP_cjs.evaluationStatus,
614
+ gateEnabled: chunkGCA73FFP_cjs.bool,
615
+ counts: chunkGCA73FFP_cjs.obj(
616
+ { api: evaluationCounts, custom: evaluationCounts },
617
+ { required: ["api", "custom"] }
618
+ )
619
+ },
620
+ { required: ["status", "gateEnabled", "counts"] }
621
+ ),
622
+ thresholdFiles: chunkGCA73FFP_cjs.arr(thresholdFileInfo),
623
+ warnings: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.issue),
624
+ toolErrors: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.issue),
625
+ origins: chunkGCA73FFP_cjs.arr(
626
+ chunkGCA73FFP_cjs.obj(
627
+ { origin: nonEmpty, label: chunkGCA73FFP_cjs.str(), requestCount: chunkGCA73FFP_cjs.count },
628
+ { required: ["origin", "label", "requestCount"] }
629
+ )
630
+ ),
631
+ endpoints: chunkGCA73FFP_cjs.record(chunkGCA73FFP_cjs.key, aggregate),
632
+ custom: chunkGCA73FFP_cjs.record(chunkGCA73FFP_cjs.key, aggregate)
633
+ },
634
+ {
635
+ required: [
636
+ "schemaVersion",
637
+ "tool",
638
+ "runId",
639
+ "mode",
640
+ "startedAt",
641
+ "finishedAt",
642
+ "env",
643
+ "configDir",
644
+ "config",
645
+ "normalization",
646
+ "ci",
647
+ "host",
648
+ "playwright",
649
+ "runConditions",
650
+ "tests",
651
+ "evaluation",
652
+ "thresholdFiles",
653
+ "warnings",
654
+ "toolErrors",
655
+ "origins",
656
+ "endpoints",
657
+ "custom"
658
+ ]
659
+ }
660
+ );
661
+ chunkGCA73FFP_cjs.obj(
662
+ {
663
+ schemaVersion: chunkGCA73FFP_cjs.constant(1),
664
+ runId: chunkGCA73FFP_cjs.runId,
665
+ mode: chunkGCA73FFP_cjs.mode,
666
+ exitCode: chunkGCA73FFP_cjs.enumOf([0, 2, 3]),
667
+ tests: chunkGCA73FFP_cjs.obj({ status: chunkGCA73FFP_cjs.testsStatus }, { required: ["status"] }),
668
+ evaluation: chunkGCA73FFP_cjs.obj(
669
+ { status: chunkGCA73FFP_cjs.evaluationStatus, gateEnabled: chunkGCA73FFP_cjs.bool },
670
+ { required: ["status", "gateEnabled"] }
671
+ ),
672
+ toolErrors: chunkGCA73FFP_cjs.arr(chunkGCA73FFP_cjs.issue),
673
+ paths: chunkGCA73FFP_cjs.obj(
674
+ {
675
+ reportJson: nonEmptyOrNull,
676
+ reportHtml: nonEmptyOrNull,
677
+ thresholds: chunkGCA73FFP_cjs.arr(nonEmpty),
678
+ thresholdsDiff: nonEmptyOrNull
679
+ },
680
+ { required: ["reportJson", "reportHtml", "thresholds", "thresholdsDiff"] }
681
+ )
682
+ },
683
+ {
684
+ required: [
685
+ "schemaVersion",
686
+ "runId",
687
+ "mode",
688
+ "exitCode",
689
+ "tests",
690
+ "evaluation",
691
+ "toolErrors",
692
+ "paths"
693
+ ]
694
+ }
695
+ );
696
+
697
+ // src/core/schema/parse.ts
698
+ var MAX_PROBLEMS = 5;
699
+ var SCHEMA_VERSIONS = {
700
+ samples: 1,
701
+ runReport: 1,
702
+ thresholds: 1,
703
+ outcome: 1
704
+ };
705
+ var HINTS = {
706
+ SCHEMA_INVALID_JSON: "Fix the JSON syntax, or delete the file and let the package write it again.",
707
+ SCHEMA_VERSION_MISSING: 'Add the "schemaVersion" of the format at the top level, or let the package write the file again.',
708
+ SCHEMA_VERSION_TOO_NEW: "The file was written by a newer version of the package; update the package to read it.",
709
+ SCHEMA_VERSION_MISMATCH: "The attachment was written by another version of the package; use one package version in a run.",
710
+ SCHEMA_VALIDATION_FAILED: "Fix the listed fields; the JSON Schemas in the package's schemas/ directory describe the format.",
711
+ THRESHOLDS_KIND_MISMATCH: 'Each kind has its own file (perf-thresholds.api\u2026 and perf-thresholds.custom\u2026); move the entries to the right file or fix "kind".'
712
+ };
713
+ function describeProblems(problems, more) {
714
+ const list2 = problems.map((p) => `${p.pointer === "" ? "(root)" : p.pointer} ${p.message}`).join("; ");
715
+ return more ? `${list2}; \u2026` : list2;
716
+ }
717
+ function issueOf(code2, source, summary, problems = []) {
718
+ const shown = problems.slice(0, MAX_PROBLEMS).map(({ pointer, message }) => ({ pointer, message }));
719
+ const details2 = shown.length === 0 ? "" : `: ${describeProblems(shown, problems.length > shown.length)}`;
720
+ return { code: code2, source, message: `${source}: ${summary}${details2}`, problems: shown };
721
+ }
722
+ function failure(issue2) {
723
+ return { ok: false, issues: [issue2] };
724
+ }
725
+ function parseJson(text, source, format) {
726
+ try {
727
+ return { ok: true, value: JSON.parse(text) };
728
+ } catch (error) {
729
+ const reason = error instanceof Error ? error.message : String(error);
730
+ return failure(
731
+ issueOf("SCHEMA_INVALID_JSON", source, `${format.name} is not valid JSON (${reason})`)
732
+ );
733
+ }
734
+ }
735
+ function migrate(document, from, to, migrations) {
736
+ let current = document;
737
+ for (let version2 = from; version2 < to; version2++) {
738
+ const step = migrations[version2];
739
+ if (step === void 0) throw new Error(`no migration from schemaVersion ${version2}`);
740
+ current = { ...step(current), schemaVersion: version2 + 1 };
741
+ }
742
+ return current;
743
+ }
744
+ function validate(document, source, format) {
745
+ const sink = new chunkGCA73FFP_cjs.Sink(MAX_PROBLEMS + 1);
746
+ format.schema.check(document, "", sink);
747
+ if (sink.problems.length === 0) format.extraChecks?.(document, sink);
748
+ if (sink.problems.length === 0) return null;
749
+ return issueOf(
750
+ "SCHEMA_VALIDATION_FAILED",
751
+ source,
752
+ `${format.name} does not match the format`,
753
+ sink.problems
754
+ );
755
+ }
756
+ function parseVersioned(text, source, format, options = {}) {
757
+ const parsed = parseJson(text, source, format);
758
+ if (!parsed.ok) return parsed;
759
+ const document = parsed.value;
760
+ if (!chunkGCA73FFP_cjs.isRecord(document)) {
761
+ return failure(
762
+ issueOf("SCHEMA_VALIDATION_FAILED", source, `${format.name} does not match the format`, [
763
+ { pointer: "", message: "must be object" }
764
+ ])
765
+ );
766
+ }
767
+ const version2 = document.schemaVersion;
768
+ if (typeof version2 !== "number" || !Number.isInteger(version2)) {
769
+ const found = Object.hasOwn(document, "schemaVersion") ? `schemaVersion must be an integer, found ${JSON.stringify(version2)}` : "schemaVersion is missing";
770
+ return failure(issueOf("SCHEMA_VERSION_MISSING", source, `${format.name}: ${found}`));
771
+ }
772
+ if (options.exactVersion === true && version2 !== format.current) {
773
+ return failure(
774
+ issueOf(
775
+ "SCHEMA_VERSION_MISMATCH",
776
+ source,
777
+ `${format.name} has schemaVersion ${version2}, but this package version reads only ${format.current}`
778
+ )
779
+ );
780
+ }
781
+ if (version2 > format.current) {
782
+ return failure(
783
+ issueOf(
784
+ "SCHEMA_VERSION_TOO_NEW",
785
+ source,
786
+ `${format.name} has schemaVersion ${version2}, newer than ${format.current} supported by this package version`
787
+ )
788
+ );
789
+ }
790
+ if (version2 < 1) {
791
+ return failure(
792
+ issueOf("SCHEMA_VALIDATION_FAILED", source, `${format.name} does not match the format`, [
793
+ { pointer: "/schemaVersion", message: "must be >= 1" }
794
+ ])
795
+ );
796
+ }
797
+ const current = version2 < format.current ? migrate(document, version2, format.current, format.migrations) : document;
798
+ const invalid = validate(current, source, format);
799
+ if (invalid !== null) return failure(invalid);
800
+ return {
801
+ ok: true,
802
+ value: { document: current, migratedFrom: version2 < format.current ? version2 : null }
803
+ };
804
+ }
805
+ function isCalendarDate(text) {
806
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(text);
807
+ if (match === null) return false;
808
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
809
+ if (month < 1 || month > 12 || day < 1) return false;
810
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
811
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
812
+ return day <= days;
813
+ }
814
+ var SAMPLES_FORMAT = {
815
+ name: "sample batch",
816
+ schemaFile: "samples.schema.json",
817
+ current: SCHEMA_VERSIONS.samples,
818
+ migrations: {},
819
+ schema: sampleBatch
820
+ };
821
+ var THRESHOLDS_FORMAT = {
822
+ name: "thresholds file",
823
+ schemaFile: "thresholds.schema.json",
824
+ current: SCHEMA_VERSIONS.thresholds,
825
+ migrations: {},
826
+ schema: thresholdsFile,
827
+ extraChecks(document, sink) {
828
+ const entries = document.entries;
829
+ for (const [name, entry] of Object.entries(entries)) {
830
+ if (typeof entry.until === "string" && !isCalendarDate(entry.until)) {
831
+ sink.add(chunkGCA73FFP_cjs.child(chunkGCA73FFP_cjs.child("/entries", name), "until"), "must be an existing calendar date");
832
+ }
833
+ }
834
+ }
835
+ };
836
+ function parseSampleBatch(text, source) {
837
+ const parsed = parseVersioned(text, source, SAMPLES_FORMAT, { exactVersion: true });
838
+ return parsed.ok ? { ok: true, value: parsed.value.document } : parsed;
839
+ }
840
+ function parseThresholdsFile(text, source, expectedKind) {
841
+ const parsed = parseVersioned(text, source, THRESHOLDS_FORMAT);
842
+ if (!parsed.ok) return parsed;
843
+ const file = parsed.value.document;
844
+ if (file.kind !== expectedKind) {
845
+ return failure(
846
+ issueOf(
847
+ "THRESHOLDS_KIND_MISMATCH",
848
+ source,
849
+ `thresholds file has kind "${file.kind}", but this path holds "${expectedKind}" thresholds`,
850
+ [{ pointer: "/kind", message: `must be "${expectedKind}"` }]
851
+ )
852
+ );
853
+ }
854
+ return { ok: true, value: { file, migratedFrom: parsed.value.migratedFrom } };
855
+ }
856
+ function schemaIssueToIssue(issue2) {
857
+ return { code: issue2.code, message: issue2.message, hint: HINTS[issue2.code] };
858
+ }
859
+
860
+ // src/io/thresholds.ts
861
+ var KINDS = ["api", "custom"];
862
+ function thresholdsFileName(prefix, kind2, env) {
863
+ return `${prefix}.${kind2}${env === null ? "" : `.${env}`}.json`;
864
+ }
865
+ function thresholdsFilePaths(location) {
866
+ const dir = resolvePath(location.configDir, location.dir);
867
+ const path = (kind2) => resolvePath(dir, thresholdsFileName(location.filePrefix, kind2, location.env));
868
+ return { api: path("api"), custom: path("custom") };
869
+ }
870
+ async function loadFile(location, kind2) {
871
+ const absolute = thresholdsFilePaths(location)[kind2];
872
+ const path = relativeSlashPath(location.configDir, absolute);
873
+ let text;
874
+ try {
875
+ text = await readTextFile(absolute);
876
+ } catch (error) {
877
+ const reason = error instanceof Error ? error.message : String(error);
878
+ return {
879
+ status: "invalid",
880
+ kind: kind2,
881
+ path,
882
+ issues: [
883
+ {
884
+ code: "SCHEMA_INVALID_JSON",
885
+ source: path,
886
+ message: `${path}: the file cannot be read (${reason})`,
887
+ problems: []
888
+ }
889
+ ]
890
+ };
891
+ }
892
+ if (text === null) {
893
+ const envless = location.env !== null && await fileExists(
894
+ resolvePath(
895
+ resolvePath(location.configDir, location.dir),
896
+ thresholdsFileName(location.filePrefix, kind2, null)
897
+ )
898
+ );
899
+ return { status: "missing", kind: kind2, path, envlessFileExists: envless };
900
+ }
901
+ const parsed = parseThresholdsFile(text, path, kind2);
902
+ if (!parsed.ok) return { status: "invalid", kind: kind2, path, issues: parsed.issues };
903
+ const { file, migratedFrom } = parsed.value;
904
+ return {
905
+ status: "loaded",
906
+ kind: kind2,
907
+ path,
908
+ file,
909
+ ...migratedFrom === null ? {} : { migratedFrom }
910
+ };
911
+ }
912
+ async function loadThresholds(location) {
913
+ const [api, custom] = await Promise.all(KINDS.map((kind2) => loadFile(location, kind2)));
914
+ return { api, custom };
915
+ }
916
+
917
+ // src/core/evaluate/files.ts
918
+ function compareText(a, b) {
919
+ return a < b ? -1 : a > b ? 1 : 0;
920
+ }
921
+ function plural(n, word, many = `${word}s`) {
922
+ return `${n} ${n === 1 ? word : many}`;
923
+ }
924
+ var KIND_NOUN = { api: "endpoint", custom: "custom measurement" };
925
+ function envlessPath(path, env) {
926
+ const suffix = `.${env}.json`;
927
+ return path.endsWith(suffix) ? `${path.slice(0, -suffix.length)}.json` : path;
928
+ }
929
+ function missingFileWarning(file, env) {
930
+ const derive = `Derive thresholds with \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds\`${env === null ? "" : ` (environment "${env}")`}.`;
931
+ const envless = env !== null && file.envlessFileExists ? ` ${envlessPath(file.path, env)} exists but is not used for environment "${env}": thresholds of another environment would give false alarms or hide regressions.` : "";
932
+ return {
933
+ code: "THRESHOLDS_FILE_MISSING",
934
+ message: `Thresholds file ${file.path} not found; ${KIND_NOUN[file.kind]} keys are evaluated with default thresholds.`,
935
+ hint: `${derive}${envless}`
936
+ };
937
+ }
938
+ function majorMinor(version2) {
939
+ return version2.split(".").slice(0, 2).join(".");
940
+ }
941
+ function sameList(a, b) {
942
+ const x = [...new Set(a)].sort(compareText);
943
+ const y = [...new Set(b)].sort(compareText);
944
+ return x.length === y.length && x.every((v, i) => v === y[i]);
945
+ }
946
+ function listText(list2) {
947
+ const unique = [...new Set(list2)].sort(compareText);
948
+ return unique.length === 0 ? "(none)" : unique.join(", ");
949
+ }
950
+ function sourceDifferences(generated, source) {
951
+ const diffs = [];
952
+ let timing = false;
953
+ let keys = false;
954
+ if (!sameList(generated.browsers, source.browsers)) {
955
+ diffs.push(`browsers ${listText(generated.browsers)} / ${listText(source.browsers)}`);
956
+ timing = true;
957
+ }
958
+ if (majorMinor(generated.playwrightVersion) !== majorMinor(source.playwrightVersion)) {
959
+ diffs.push(`playwrightVersion ${generated.playwrightVersion} / ${source.playwrightVersion}`);
960
+ timing = true;
961
+ }
962
+ const hostFields = ["platform", "arch", "ci", "cpuCount", "cpuModel"];
963
+ for (const field2 of hostFields) {
964
+ const a = generated.host[field2];
965
+ const b = source.host[field2];
966
+ if (a !== b) {
967
+ diffs.push(`host.${field2} ${JSON.stringify(a)} / ${JSON.stringify(b)}`);
968
+ timing = true;
969
+ }
970
+ }
971
+ if (generated.normalization !== source.normalization) {
972
+ diffs.push(`normalization ${generated.normalization} / ${source.normalization}`);
973
+ keys = true;
974
+ }
975
+ return { diffs, timing, keys };
976
+ }
977
+ function generatedWarnings(path, generated, cfg, env, source) {
978
+ const issues = [];
979
+ const level = cfg.checks.time.percentile.level;
980
+ if (generated.evaluatedPercentile !== level) {
981
+ issues.push({
982
+ code: "EVAL_PERCENTILE_MISMATCH",
983
+ message: `Thresholds in ${path} were derived for ${generated.evaluatedPercentile}, but this run evaluates ${level}; the percentile limits are compared with ${level}.`,
984
+ hint: `Derive thresholds again with \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds\` after changing checks.time.percentile.level.`
985
+ });
986
+ }
987
+ if (generated.env !== env) {
988
+ const show = (v) => v === null ? "none" : `"${v}"`;
989
+ issues.push({
990
+ code: "THRESHOLDS_ENV_MISMATCH",
991
+ message: `Thresholds in ${path} were derived for environment ${show(generated.env)}, but this run uses environment ${show(env)}.`,
992
+ hint: "The file was probably copied or renamed by hand; derive thresholds for this environment."
993
+ });
994
+ }
995
+ const { diffs, timing, keys } = sourceDifferences(generated, source);
996
+ if (diffs.length > 0) {
997
+ const hints = [];
998
+ if (timing) {
999
+ hints.push(
1000
+ "Another machine, browser or Playwright version changes the timings: derive thresholds on the same infrastructure as the evaluation."
1001
+ );
1002
+ }
1003
+ if (keys) {
1004
+ hints.push(
1005
+ `Another normalization changes the keys: derive thresholds again with \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds\`.`
1006
+ );
1007
+ }
1008
+ issues.push({
1009
+ code: "THRESHOLDS_SOURCE_MISMATCH",
1010
+ message: `Thresholds in ${path} come from a run with other conditions (thresholds / this run): ${diffs.join("; ")}.`,
1011
+ hint: hints.join(" ")
1012
+ });
1013
+ }
1014
+ return issues;
1015
+ }
1016
+ function unseenWarning(path, unseen) {
1017
+ return {
1018
+ code: "THRESHOLDS_UNSEEN_ENTRIES",
1019
+ message: `${plural(unseen.length, "entry", "entries")} in ${path} ${unseen.length === 1 ? "was" : "were"} not seen in this run.`,
1020
+ hint: `Run the full suite, or remove stale entries with \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds --prune\`.`
1021
+ };
1022
+ }
1023
+ function outdatedWarning(path, from, current) {
1024
+ return {
1025
+ code: "THRESHOLDS_FILE_OUTDATED",
1026
+ message: `Thresholds file ${path} has format version ${from}; it was read after migration to version ${current}.`,
1027
+ hint: `The next \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds\` writes it in the current version and keeps locked entries.`
1028
+ };
1029
+ }
1030
+ function fileInfo(file, unseenKeys) {
1031
+ return {
1032
+ kind: file.kind,
1033
+ path: file.path,
1034
+ status: file.status,
1035
+ generated: file.status === "loaded" && file.file.generated !== null ? structuredClone(file.file.generated) : null,
1036
+ unseenKeys
1037
+ };
1038
+ }
1039
+
1040
+ // src/core/evaluate/limits.ts
1041
+ function defaultLimits(checks, kind2) {
1042
+ return {
1043
+ t: null,
1044
+ median: checks.time.median.limit[kind2],
1045
+ percentile: checks.time.percentile.limit[kind2],
1046
+ p99: checks.time.p99.limit[kind2],
1047
+ minApdex: null,
1048
+ maxWilson: null,
1049
+ maxErrorRate: checks.errors.limit[kind2]
1050
+ };
1051
+ }
1052
+ function entryLimits(entry, checks, kind2) {
1053
+ const defaults = defaultLimits(checks, kind2);
1054
+ const t = entry.t ?? null;
1055
+ return {
1056
+ t,
1057
+ median: entry.median ?? defaults.median,
1058
+ percentile: entry.percentile ?? defaults.percentile,
1059
+ p99: entry.p99 ?? defaults.p99,
1060
+ minApdex: t === null ? null : entry.minApdex === void 0 ? checks.slowShare.apdex.limit[kind2] : entry.minApdex,
1061
+ maxWilson: t === null ? null : entry.maxWilson === void 0 ? checks.slowShare.wilson.limit[kind2] : entry.maxWilson,
1062
+ maxErrorRate: entry.maxErrorRate ?? defaults.maxErrorRate
1063
+ };
1064
+ }
1065
+
1066
+ // src/core/evaluate/muting.ts
1067
+ var MUTE_EXPIRY_WARN_DAYS = 7;
1068
+ var DAY_MS = 864e5;
1069
+ function dayOf(timestamp2) {
1070
+ const time = Date.parse(timestamp2);
1071
+ if (Number.isNaN(time)) throw new Error(`evaluate: invalid startedAt "${timestamp2}"`);
1072
+ return new Date(time).toISOString().slice(0, 10);
1073
+ }
1074
+ function daysBetween(from, to) {
1075
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS);
1076
+ }
1077
+ function keyMuting(entry, runDay) {
1078
+ if (entry.gate !== "warn" || entry.until === void 0) return null;
1079
+ return {
1080
+ until: entry.until,
1081
+ note: entry.note ?? "",
1082
+ expired: daysBetween(entry.until, runDay) > 0
1083
+ };
1084
+ }
1085
+ function isMuteActive(muted) {
1086
+ return muted !== null && !muted.expired;
1087
+ }
1088
+ function keyList(keys) {
1089
+ return keys.map(({ kind: kind2, key: key2, muted }) => `${kind2} ${key2} (until ${muted.until})`).join(", ");
1090
+ }
1091
+ function mutingWarnings(keys, runDay) {
1092
+ const active = keys.filter((k) => !k.muted.expired);
1093
+ const expiring = active.filter(
1094
+ (k) => daysBetween(runDay, k.muted.until) <= MUTE_EXPIRY_WARN_DAYS
1095
+ );
1096
+ const expired = keys.filter((k) => k.muted.expired);
1097
+ const issues = [];
1098
+ if (active.length > 0) {
1099
+ issues.push({
1100
+ code: "THRESHOLDS_MUTED",
1101
+ message: `${plural(active.length, "key is", "keys are")} muted; ${active.length === 1 ? "its" : "their"} violations do not block.`,
1102
+ hint: "Muted keys are listed with their note and end date; remove gate and until from the entry once the cause is fixed."
1103
+ });
1104
+ }
1105
+ if (expiring.length > 0) {
1106
+ issues.push({
1107
+ code: "THRESHOLDS_MUTE_EXPIRING",
1108
+ message: `Muting ends within ${MUTE_EXPIRY_WARN_DAYS} days for ${plural(expiring.length, "key")}: ${keyList(expiring)}.`,
1109
+ hint: "Fix the cause before the end date, or extend until in the thresholds file on purpose."
1110
+ });
1111
+ }
1112
+ if (expired.length > 0) {
1113
+ issues.push({
1114
+ code: "THRESHOLDS_MUTE_EXPIRED",
1115
+ message: `Muting expired for ${plural(expired.length, "key")}, so ${expired.length === 1 ? "it blocks" : "they block"} again: ${keyList(expired)}.`,
1116
+ hint: "Remove gate and until from the entry, or extend until on purpose."
1117
+ });
1118
+ }
1119
+ return issues;
1120
+ }
1121
+
1122
+ // src/core/random/index.ts
1123
+ var FIXED_HASH_SEED = 0;
1124
+ function hash53(input, seed) {
1125
+ let h1 = 3735928559 ^ seed;
1126
+ let h2 = 1103547991 ^ seed;
1127
+ for (let i = 0; i < input.length; i++) {
1128
+ const ch = input.charCodeAt(i);
1129
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1130
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1131
+ }
1132
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
1133
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
1134
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
1135
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
1136
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
1137
+ }
1138
+ function hashHex(input) {
1139
+ return hash53(input, FIXED_HASH_SEED).toString(16).padStart(14, "0");
1140
+ }
1141
+
1142
+ // src/core/stats/classification.ts
1143
+ var ABORT_FAILURE_TEXTS = Object.freeze([
1144
+ "net::ERR_ABORTED",
1145
+ "NS_BINDING_ABORTED",
1146
+ "NS_ERROR_ABORT",
1147
+ "cancelled",
1148
+ chunkLV3O2BAT_cjs.CONTEXT_CLOSED_FAILURE_TEXT
1149
+ ]);
1150
+ var ABORT_TEXTS = new Set(ABORT_FAILURE_TEXTS);
1151
+ function requestStatusLabel(sample) {
1152
+ const { status } = sample;
1153
+ if (typeof status === "number") return String(status);
1154
+ if (status === "FAILED" && sample.failureText !== void 0 && ABORT_TEXTS.has(sample.failureText)) {
1155
+ return "ABORTED";
1156
+ }
1157
+ return status;
1158
+ }
1159
+ var STATUS_CLASS = /^([1-9])xx$/u;
1160
+ var HTTP_CODE = /^[1-9]\d\d$/u;
1161
+ function compileStatusMatcher(patterns) {
1162
+ const classes = /* @__PURE__ */ new Set();
1163
+ const exact = /* @__PURE__ */ new Set();
1164
+ for (const pattern of patterns) {
1165
+ const match = STATUS_CLASS.exec(pattern);
1166
+ if (match?.[1] !== void 0) classes.add(match[1]);
1167
+ else exact.add(pattern);
1168
+ }
1169
+ return (label) => exact.has(label) || HTTP_CODE.test(label) && classes.has(label.charAt(0));
1170
+ }
1171
+
1172
+ // src/core/stats/identity.ts
1173
+ function testIdentity(project, file, title) {
1174
+ return `${project}\0${file}\0${title}`;
1175
+ }
1176
+ function resultId(testId, repeatEachIndex, retry) {
1177
+ return `${testId}\0${repeatEachIndex}\0${retry}`;
1178
+ }
1179
+ function sampleId(result, kind2, ordinal) {
1180
+ return `${result}\0${kind2}\0${ordinal}`;
1181
+ }
1182
+ function isFailedTest(status, expectedStatus) {
1183
+ return status !== expectedStatus && status !== "skipped";
1184
+ }
1185
+
1186
+ // src/core/stats/percentile.ts
1187
+ function percentile(sorted, p) {
1188
+ const n = sorted.length;
1189
+ if (n === 0) return null;
1190
+ const scaled = (n - 1) * p;
1191
+ const lo = Math.min(Math.floor(scaled / 100), n - 1);
1192
+ const x = sorted[lo] ?? Number.NaN;
1193
+ if (lo + 1 >= n) return x;
1194
+ const next = sorted[lo + 1] ?? Number.NaN;
1195
+ return x + (scaled - lo * 100) / 100 * (next - x);
1196
+ }
1197
+ var ALWAYS = ["p50", "p90", "p95", "p99"];
1198
+ function parsePercentileName(name) {
1199
+ if (!/^p\d+(?:\.\d)?$/u.test(name)) {
1200
+ throw new Error(`Invalid percentile name "${name}"; expected a name like "p95".`);
1201
+ }
1202
+ const value = Number(name.slice(1));
1203
+ if (value > 100) throw new Error(`Invalid percentile name "${name}"; at most "p100".`);
1204
+ return value;
1205
+ }
1206
+ function percentileNames(evaluated) {
1207
+ const names = /* @__PURE__ */ new Set([...ALWAYS, evaluated]);
1208
+ return [...names].map((name) => [name, parsePercentileName(name)]).sort((a, b) => a[1] - b[1]);
1209
+ }
1210
+
1211
+ // src/core/stats/sampling.ts
1212
+ function at(array, i) {
1213
+ return array[i] ?? 0;
1214
+ }
1215
+ function compareText2(a, b) {
1216
+ return a < b ? -1 : a > b ? 1 : 0;
1217
+ }
1218
+ var INITIAL_CAPACITY = 16;
1219
+ var BottomK = class {
1220
+ capacity;
1221
+ size = 0;
1222
+ idOf;
1223
+ priority;
1224
+ duration;
1225
+ ttfb;
1226
+ result;
1227
+ ordinal;
1228
+ constructor(capacity, idOf) {
1229
+ this.capacity = capacity;
1230
+ this.idOf = idOf;
1231
+ const initial = Math.min(capacity, INITIAL_CAPACITY);
1232
+ this.priority = new Float64Array(initial);
1233
+ this.duration = new Int32Array(initial);
1234
+ this.ttfb = new Int32Array(initial);
1235
+ this.result = new Int32Array(initial);
1236
+ this.ordinal = new Int32Array(initial);
1237
+ }
1238
+ /** Adds a sample: priority from hash53, duration and TTFB in tenths of a ms (TTFB −1: none). */
1239
+ add(priority, duration, ttfb, resultIndex, ordinal) {
1240
+ if (this.size < this.capacity) {
1241
+ if (this.size === this.priority.length) this.grow();
1242
+ this.set(this.size, priority, duration, ttfb, resultIndex, ordinal);
1243
+ this.size += 1;
1244
+ this.siftUp(this.size - 1);
1245
+ return;
1246
+ }
1247
+ if (this.capacity === 0) return;
1248
+ if (this.compareWith(priority, resultIndex, ordinal, 0) >= 0) return;
1249
+ this.set(0, priority, duration, ttfb, resultIndex, ordinal);
1250
+ this.siftDown(0);
1251
+ }
1252
+ /** Kept durations in tenths of a ms, ascending. */
1253
+ durations() {
1254
+ return Array.from(this.duration.subarray(0, this.size)).sort((a, b) => a - b);
1255
+ }
1256
+ /** Known TTFB values of the kept samples in tenths of a ms, ascending. */
1257
+ ttfbs() {
1258
+ return Array.from(this.ttfb.subarray(0, this.size)).filter((t) => t >= 0).sort((a, b) => a - b);
1259
+ }
1260
+ grow() {
1261
+ const size = Math.min(this.capacity, this.priority.length * 2);
1262
+ const copy = (from, to) => {
1263
+ to.set(from);
1264
+ return to;
1265
+ };
1266
+ this.priority = copy(this.priority, new Float64Array(size));
1267
+ this.duration = copy(this.duration, new Int32Array(size));
1268
+ this.ttfb = copy(this.ttfb, new Int32Array(size));
1269
+ this.result = copy(this.result, new Int32Array(size));
1270
+ this.ordinal = copy(this.ordinal, new Int32Array(size));
1271
+ }
1272
+ set(i, priority, duration, ttfb, resultIndex, ordinal) {
1273
+ this.priority[i] = priority;
1274
+ this.duration[i] = duration;
1275
+ this.ttfb[i] = ttfb;
1276
+ this.result[i] = resultIndex;
1277
+ this.ordinal[i] = ordinal;
1278
+ }
1279
+ /** Order of (priority, resultIndex, ordinal) relative to the kept sample j. */
1280
+ compareWith(priority, resultIndex, ordinal, j) {
1281
+ const diff = priority - at(this.priority, j);
1282
+ if (diff !== 0) return diff;
1283
+ return compareText2(
1284
+ this.idOf(resultIndex, ordinal),
1285
+ this.idOf(at(this.result, j), at(this.ordinal, j))
1286
+ );
1287
+ }
1288
+ compare(i, j) {
1289
+ return this.compareWith(at(this.priority, i), at(this.result, i), at(this.ordinal, i), j);
1290
+ }
1291
+ swap(i, j) {
1292
+ for (const array of [this.priority, this.duration, this.ttfb, this.result, this.ordinal]) {
1293
+ const value = at(array, i);
1294
+ array[i] = at(array, j);
1295
+ array[j] = value;
1296
+ }
1297
+ }
1298
+ siftUp(start) {
1299
+ let i = start;
1300
+ while (i > 0) {
1301
+ const parent = i - 1 >>> 1;
1302
+ if (this.compare(i, parent) <= 0) return;
1303
+ this.swap(i, parent);
1304
+ i = parent;
1305
+ }
1306
+ }
1307
+ siftDown(start) {
1308
+ let i = start;
1309
+ for (; ; ) {
1310
+ const left = 2 * i + 1;
1311
+ if (left >= this.size) return;
1312
+ const right = left + 1;
1313
+ const larger = right < this.size && this.compare(right, left) > 0 ? right : left;
1314
+ if (this.compare(larger, i) <= 0) return;
1315
+ this.swap(i, larger);
1316
+ i = larger;
1317
+ }
1318
+ }
1319
+ };
1320
+
1321
+ // src/core/stats/aggregator.ts
1322
+ var SLOWEST = 3;
1323
+ var TOP_TESTS = 5;
1324
+ function compareText3(a, b) {
1325
+ return a < b ? -1 : a > b ? 1 : 0;
1326
+ }
1327
+ function toTenths(ms2) {
1328
+ return Math.round(ms2 * 10);
1329
+ }
1330
+ function compareSlow(a, b) {
1331
+ return b.tenths - a.tenths || compareText3(a.test.file, b.test.file) || a.test.line - b.test.line || a.test.repeatEachIndex - b.test.repeatEachIndex || a.ordinal - b.ordinal || compareText3(a.sampleId, b.sampleId);
1332
+ }
1333
+ function compareTopTests(a, b) {
1334
+ return b.sampleCount - a.sampleCount || compareText3(a.file, b.file) || a.line - b.line || compareText3(a.title, b.title) || compareText3(a.project, b.project);
1335
+ }
1336
+ var KeyState = class {
1337
+ kind;
1338
+ count = 0;
1339
+ successCount = 0;
1340
+ errorCount = 0;
1341
+ fromFailedTests = 0;
1342
+ browser = 0;
1343
+ node = 0;
1344
+ statuses = /* @__PURE__ */ new Map();
1345
+ /** Test identity → sample count (08-REQ-29). */
1346
+ tests = /* @__PURE__ */ new Map();
1347
+ minTenths = Infinity;
1348
+ maxTenths = -Infinity;
1349
+ /** Exact integer sum in tenths of a ms (08-REQ-16). */
1350
+ sumTenths = 0;
1351
+ slowest = [];
1352
+ sample;
1353
+ constructor(kind2, sample) {
1354
+ this.kind = kind2;
1355
+ this.sample = sample;
1356
+ }
1357
+ countSample(label, test, isError) {
1358
+ this.count += 1;
1359
+ this.statuses.set(label, (this.statuses.get(label) ?? 0) + 1);
1360
+ if (isError) this.errorCount += 1;
1361
+ if (test.failed) this.fromFailedTests += 1;
1362
+ const counter = this.tests.get(test.identity);
1363
+ if (counter === void 0) {
1364
+ this.tests.set(test.identity, {
1365
+ title: test.title,
1366
+ project: test.project,
1367
+ file: test.file,
1368
+ line: test.line,
1369
+ sampleCount: 1
1370
+ });
1371
+ } else {
1372
+ counter.sampleCount += 1;
1373
+ }
1374
+ }
1375
+ addSlow(candidate) {
1376
+ const list2 = this.slowest;
1377
+ const last = list2[SLOWEST - 1];
1378
+ if (last !== void 0 && compareSlow(candidate, last) >= 0) return;
1379
+ list2.push(candidate);
1380
+ list2.sort(compareSlow);
1381
+ if (list2.length > SLOWEST) list2.pop();
1382
+ }
1383
+ };
1384
+ var Aggregator = class {
1385
+ opts;
1386
+ isSuccess;
1387
+ isError;
1388
+ percentiles;
1389
+ endpoints = /* @__PURE__ */ new Map();
1390
+ custom = /* @__PURE__ */ new Map();
1391
+ /** Interned resultIds: the heap stores an index instead of the text (08-REQ-29). */
1392
+ resultIndex = /* @__PURE__ */ new Map();
1393
+ resultIds = [];
1394
+ origins = /* @__PURE__ */ new Map();
1395
+ browsers = /* @__PURE__ */ new Set();
1396
+ outsideProjects = /* @__PURE__ */ new Set();
1397
+ outsideSamples = 0;
1398
+ withoutBrowserTiming = 0;
1399
+ keysWithoutBrowserTiming = /* @__PURE__ */ new Set();
1400
+ finalized = false;
1401
+ constructor(opts) {
1402
+ this.opts = opts;
1403
+ this.isSuccess = compileStatusMatcher(opts.successStatuses);
1404
+ this.isError = compileStatusMatcher(opts.errors.statuses);
1405
+ this.percentiles = percentileNames(opts.evaluatedPercentile);
1406
+ }
1407
+ /**
1408
+ * Adds a request sample under `key`. `origin` and `label` come from the KeyResult (07); null
1409
+ * when the URL could not be parsed (07-REQ-23), then the sample is not counted in origins.
1410
+ * `browserName` is the batch's collector.browserName (08-REQ-32).
1411
+ */
1412
+ addRequest(key2, sample, origin, label, browserName) {
1413
+ if (!this.accept(sample.test)) return;
1414
+ if (browserName !== null) this.browsers.add(browserName);
1415
+ if (origin !== null) {
1416
+ const entry = this.origins.get(origin);
1417
+ const text = label ?? "";
1418
+ if (entry === void 0) this.origins.set(origin, { label: text, requestCount: 1 });
1419
+ else {
1420
+ entry.requestCount += 1;
1421
+ if (compareText3(text, entry.label) < 0) entry.label = text;
1422
+ }
1423
+ }
1424
+ const state = this.state(this.endpoints, "request", key2);
1425
+ const statusLabel = requestStatusLabel(sample);
1426
+ state.countSample(statusLabel, sample.test, this.isError(statusLabel));
1427
+ if (sample.timeSource === "node") state.node += 1;
1428
+ else state.browser += 1;
1429
+ if (typeof sample.status !== "number" || !this.isSuccess(statusLabel)) return;
1430
+ if (sample.timeSource === "node") {
1431
+ this.withoutBrowserTiming += 1;
1432
+ this.keysWithoutBrowserTiming.add(key2);
1433
+ }
1434
+ if (sample.timeSource !== "browser" || sample.fromServiceWorker || sample.duration === null) {
1435
+ return;
1436
+ }
1437
+ this.addTime(state, key2, sample.test, sample.ordinal, {
1438
+ duration: sample.duration,
1439
+ ttfb: sample.ttfb,
1440
+ startedAt: sample.startTime,
1441
+ ...this.opts.rawUrls ? { url: sample.url } : {}
1442
+ });
1443
+ }
1444
+ /** Adds a custom measurement sample under its name (08-REQ-04). */
1445
+ addCustom(name, sample) {
1446
+ if (!this.accept(sample.test)) return;
1447
+ const state = this.state(this.custom, "custom", name);
1448
+ state.countSample(sample.outcome, sample.test, sample.outcome !== "ok");
1449
+ state.node += 1;
1450
+ if (sample.outcome !== "ok" || sample.duration === null || sample.endTime === null) return;
1451
+ this.addTime(state, name, sample.test, sample.ordinal, {
1452
+ duration: sample.duration,
1453
+ ttfb: null,
1454
+ startedAt: Math.round(sample.endTime - sample.duration)
1455
+ });
1456
+ }
1457
+ /** Builds the aggregates; may be called once. */
1458
+ finalize() {
1459
+ if (this.finalized) throw new Error("Aggregator.finalize() may be called once.");
1460
+ this.finalized = true;
1461
+ return {
1462
+ endpoints: this.build(this.endpoints),
1463
+ custom: this.build(this.custom),
1464
+ origins: [...this.origins.keys()].sort(compareText3).map((origin) => {
1465
+ const entry = this.origins.get(origin) ?? { label: "", requestCount: 0 };
1466
+ return { origin, label: entry.label, requestCount: entry.requestCount };
1467
+ }),
1468
+ issues: this.issues()
1469
+ };
1470
+ }
1471
+ /** False for samples of projects that are not measured (08-REQ-31). */
1472
+ accept(test) {
1473
+ if (this.finalized) throw new Error("Aggregator: samples added after finalize().");
1474
+ if (this.opts.measuredProjects.has(test.project)) return true;
1475
+ this.outsideSamples += 1;
1476
+ this.outsideProjects.add(test.project);
1477
+ return false;
1478
+ }
1479
+ state(states, kind2, key2) {
1480
+ let state = states.get(key2);
1481
+ if (state === void 0) {
1482
+ const ids = this.resultIds;
1483
+ state = new KeyState(
1484
+ kind2,
1485
+ new BottomK(
1486
+ this.opts.advanced.maxSamplesPerKey,
1487
+ (r, ordinal) => sampleId(ids[r] ?? "", kind2, ordinal)
1488
+ )
1489
+ );
1490
+ states.set(key2, state);
1491
+ }
1492
+ return state;
1493
+ }
1494
+ addTime(state, key2, test, ordinal, time) {
1495
+ const tenths = toTenths(time.duration);
1496
+ state.successCount += 1;
1497
+ state.sumTenths += tenths;
1498
+ if (tenths < state.minTenths) state.minTenths = tenths;
1499
+ if (tenths > state.maxTenths) state.maxTenths = tenths;
1500
+ let r = this.resultIndex.get(test.resultId);
1501
+ if (r === void 0) {
1502
+ r = this.resultIds.length;
1503
+ this.resultIds.push(test.resultId);
1504
+ this.resultIndex.set(test.resultId, r);
1505
+ }
1506
+ const id = sampleId(test.resultId, state.kind, ordinal);
1507
+ const priority = hash53(`${key2}\0${id}`, this.opts.advanced.seed);
1508
+ state.sample.add(priority, tenths, time.ttfb === null ? -1 : toTenths(time.ttfb), r, ordinal);
1509
+ state.addSlow({
1510
+ tenths,
1511
+ startedAt: time.startedAt,
1512
+ test,
1513
+ ordinal,
1514
+ sampleId: id,
1515
+ ...time.url === void 0 ? {} : { url: time.url }
1516
+ });
1517
+ }
1518
+ build(states) {
1519
+ const result = {};
1520
+ for (const key2 of [...states.keys()].sort(compareText3)) {
1521
+ const state = states.get(key2);
1522
+ if (state !== void 0) result[key2] = this.aggregate(state);
1523
+ }
1524
+ return result;
1525
+ }
1526
+ aggregate(state) {
1527
+ const durations = state.sample.durations().map((t) => t / 10);
1528
+ const ttfbs = state.sample.ttfbs().map((t) => t / 10);
1529
+ const at2 = (sorted, p) => roundMs(percentile(sorted, p) ?? 0);
1530
+ const statuses = {};
1531
+ for (const label of [...state.statuses.keys()].sort(compareText3)) {
1532
+ statuses[label] = state.statuses.get(label) ?? 0;
1533
+ }
1534
+ const usable = state.successCount > 0;
1535
+ return {
1536
+ count: state.count,
1537
+ successCount: state.successCount,
1538
+ errorCount: state.errorCount,
1539
+ fromFailedTests: state.fromFailedTests,
1540
+ testCount: state.tests.size,
1541
+ statuses,
1542
+ timeSources: { browser: state.browser, node: state.node },
1543
+ stats: usable ? {
1544
+ min: state.minTenths / 10,
1545
+ avg: Math.round(state.sumTenths / state.successCount) / 10,
1546
+ max: state.maxTenths / 10,
1547
+ percentiles: Object.fromEntries(
1548
+ this.percentiles.map(([name, p]) => [name, at2(durations, p)])
1549
+ )
1550
+ } : null,
1551
+ ttfb: ttfbs.length === 0 ? null : { p50: at2(ttfbs, 50), p95: at2(ttfbs, 95) },
1552
+ slowest: state.slowest.map((s) => ({
1553
+ duration: s.tenths / 10,
1554
+ startedAt: new Date(s.startedAt).toISOString(),
1555
+ test: {
1556
+ title: s.test.title,
1557
+ project: s.test.project,
1558
+ file: s.test.file,
1559
+ line: s.test.line,
1560
+ repeatEachIndex: s.test.repeatEachIndex
1561
+ },
1562
+ ...s.url === void 0 ? {} : { url: s.url }
1563
+ })),
1564
+ topTests: [...state.tests.values()].map(({ title, project, file, line, sampleCount }) => ({
1565
+ title,
1566
+ project,
1567
+ file,
1568
+ line,
1569
+ sampleCount
1570
+ })).sort(compareTopTests).slice(0, TOP_TESTS),
1571
+ samples: {
1572
+ durations,
1573
+ sampled: state.successCount > this.opts.advanced.maxSamplesPerKey
1574
+ }
1575
+ };
1576
+ }
1577
+ issues() {
1578
+ const issues = [];
1579
+ const plural6 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1580
+ if (this.withoutBrowserTiming > 0) {
1581
+ const n = this.withoutBrowserTiming;
1582
+ issues.push({
1583
+ code: "STATS_SAMPLES_WITHOUT_BROWSER_TIMING",
1584
+ message: `${plural6(n, "successful request sample")} in ${plural6(this.keysWithoutBrowserTiming.size, "endpoint key")} had no browser timing (timeSource "node") and ${n === 1 ? "was" : "were"} left out of the time statistics.`,
1585
+ hint: "Browser timing is missing for some requests (e.g. when the browser reports no timing for them); they still count in count and statuses."
1586
+ });
1587
+ }
1588
+ if (this.outsideSamples > 0) {
1589
+ const projects = [...this.outsideProjects].sort(compareText3).join(", ");
1590
+ issues.push({
1591
+ code: "STATS_SAMPLES_OUTSIDE_MEASURED_PROJECTS",
1592
+ message: `${plural6(this.outsideSamples, "sample")} from projects that are not measured (${projects}) were not aggregated.`,
1593
+ hint: "Setup and teardown projects run once and are not measured; move the calls you want to measure into tests of a measured project."
1594
+ });
1595
+ }
1596
+ if (this.browsers.size > 1) {
1597
+ const names = [...this.browsers].sort(compareText3).join(", ");
1598
+ issues.push({
1599
+ code: "STATS_MULTIPLE_BROWSERS",
1600
+ message: `Request samples come from more than one browser (${names}); timings of different engines are mixed in the same keys.`,
1601
+ hint: "Measure one browser engine per run (option run.projects)."
1602
+ });
1603
+ }
1604
+ return issues;
1605
+ }
1606
+ };
1607
+ function addKeyedRequest(aggregator, keyOf, sample, browserName) {
1608
+ const result = keyOf(sample);
1609
+ if (result.ok) {
1610
+ aggregator.addRequest(result.key, sample, result.origin, result.label, browserName);
1611
+ }
1612
+ return result;
1613
+ }
1614
+
1615
+ // src/core/stats/functions.ts
1616
+ var WILSON_Z = 1.96;
1617
+ function countAtMost(sorted, t) {
1618
+ let lo = 0;
1619
+ let hi = sorted.length;
1620
+ while (lo < hi) {
1621
+ const mid = lo + hi >>> 1;
1622
+ if ((sorted[mid] ?? Number.NaN) <= t) lo = mid + 1;
1623
+ else hi = mid;
1624
+ }
1625
+ return lo;
1626
+ }
1627
+ function apdexCounts(sorted, t) {
1628
+ const s = countAtMost(sorted, t);
1629
+ const u = countAtMost(sorted, 4 * t) - s;
1630
+ return { s, u, n: sorted.length };
1631
+ }
1632
+ function apdex(sorted, t) {
1633
+ const { s, u, n } = apdexCounts(sorted, t);
1634
+ return n === 0 ? null : roundRatio((s + u / 2) / n);
1635
+ }
1636
+ function exceedingShare(sorted, t) {
1637
+ return { k: sorted.length - countAtMost(sorted, t), n: sorted.length };
1638
+ }
1639
+ function wilsonBounds(k, n) {
1640
+ if (n === 0) return null;
1641
+ const z2 = WILSON_Z * WILSON_Z;
1642
+ const share = k / n;
1643
+ const center = share + z2 / (2 * n);
1644
+ const margin = WILSON_Z * Math.sqrt(share * (1 - share) / n + z2 / (4 * n * n));
1645
+ const denominator = 1 + z2 / n;
1646
+ const clamp2 = (x) => Math.min(1, Math.max(0, roundRatio(x)));
1647
+ return {
1648
+ lower: clamp2((center - margin) / denominator),
1649
+ upper: clamp2((center + margin) / denominator)
1650
+ };
1651
+ }
1652
+
1653
+ // src/core/evaluate/rules.ts
1654
+ var TIME_RULES = /* @__PURE__ */ new Set(["median", "percentile", "p99"]);
1655
+ function timeCheck(rule, actual, limit, m) {
1656
+ return { rule, n: m, actual, observed: null, limit, passed: !(actual > limit) };
1657
+ }
1658
+ function runRules(stats2, limits, cfg) {
1659
+ const { time, slowShare, errors } = cfg.checks;
1660
+ const n = stats2.successCount;
1661
+ const bigN = stats2.count;
1662
+ const durations = [...stats2.samples.durations].sort((a, b) => a - b);
1663
+ const m = durations.length;
1664
+ const percentiles = stats2.stats?.percentiles ?? {};
1665
+ const at2 = (name) => {
1666
+ const value = percentiles[name];
1667
+ if (value === void 0) {
1668
+ throw new Error(`evaluate: aggregate has no percentile "${name}"`);
1669
+ }
1670
+ return value;
1671
+ };
1672
+ const t = limits.t;
1673
+ const inputs = [
1674
+ {
1675
+ ...time.median,
1676
+ hasLimits: true,
1677
+ count: n,
1678
+ run: () => timeCheck("median", at2("p50"), limits.median, m)
1679
+ },
1680
+ {
1681
+ ...time.percentile,
1682
+ hasLimits: true,
1683
+ count: n,
1684
+ run: () => timeCheck("percentile", at2(time.percentile.level), limits.percentile, m)
1685
+ },
1686
+ {
1687
+ ...time.p99,
1688
+ hasLimits: true,
1689
+ count: n,
1690
+ run: () => timeCheck("p99", at2("p99"), limits.p99, m)
1691
+ },
1692
+ {
1693
+ ...slowShare.apdex,
1694
+ hasLimits: t !== null && limits.minApdex !== null,
1695
+ count: n,
1696
+ run: () => {
1697
+ const tt = t ?? 0;
1698
+ const limit = limits.minApdex ?? 0;
1699
+ const { s, u } = apdexCounts(durations, tt);
1700
+ const actual = wilsonBounds(s + u / 2, m)?.upper ?? 0;
1701
+ return {
1702
+ rule: "apdex",
1703
+ n: m,
1704
+ actual,
1705
+ observed: apdex(durations, tt),
1706
+ limit,
1707
+ passed: !(actual < limit)
1708
+ };
1709
+ }
1710
+ },
1711
+ {
1712
+ ...slowShare.wilson,
1713
+ hasLimits: t !== null && limits.maxWilson !== null,
1714
+ count: n,
1715
+ run: () => {
1716
+ const limit = limits.maxWilson ?? 0;
1717
+ const { k } = exceedingShare(durations, t ?? 0);
1718
+ const actual = wilsonBounds(k, m)?.lower ?? 0;
1719
+ return {
1720
+ rule: "wilson",
1721
+ n: m,
1722
+ actual,
1723
+ observed: roundRatio(k / m),
1724
+ limit,
1725
+ passed: !(actual > limit)
1726
+ };
1727
+ }
1728
+ },
1729
+ {
1730
+ ...errors,
1731
+ hasLimits: true,
1732
+ count: bigN,
1733
+ run: () => {
1734
+ const actual = wilsonBounds(stats2.errorCount, bigN)?.lower ?? 0;
1735
+ return {
1736
+ rule: "errors",
1737
+ n: bigN,
1738
+ actual,
1739
+ observed: roundRatio(stats2.errorCount / bigN),
1740
+ limit: limits.maxErrorRate,
1741
+ passed: !(actual > limits.maxErrorRate)
1742
+ };
1743
+ }
1744
+ }
1745
+ ];
1746
+ const hardLimitFactor = cfg.gate.hardLimitFactor;
1747
+ const checks = [];
1748
+ let applicable = false;
1749
+ for (const input of inputs) {
1750
+ if (!input.enabled || !input.hasLimits) continue;
1751
+ applicable = true;
1752
+ if (input.count < Math.max(1, input.minSamples)) continue;
1753
+ const check2 = input.run();
1754
+ const hardLimitExceeded = !check2.passed && TIME_RULES.has(check2.rule) && hardLimitFactor !== null && check2.actual > check2.limit * hardLimitFactor;
1755
+ checks.push({ ...check2, hardLimitExceeded, blocking: false });
1756
+ }
1757
+ return { checks, applicable };
1758
+ }
1759
+
1760
+ // src/core/evaluate/evaluate.ts
1761
+ var KINDS2 = ["api", "custom"];
1762
+ function allowedViolations(tolerance, evaluated) {
1763
+ if (typeof tolerance === "number") return tolerance;
1764
+ const match = /^(\d+)(?:\.(\d+))?%$/u.exec(tolerance);
1765
+ if (match === null) throw new Error(`evaluate: invalid gate.tolerance "${tolerance}"`);
1766
+ const decimals = match[2] ?? "";
1767
+ const scale = 10 ** decimals.length;
1768
+ const scaledPercent = Number(match[1]) * scale + (decimals === "" ? 0 : Number(decimals));
1769
+ return Math.floor(scaledPercent * evaluated / (100 * scale));
1770
+ }
1771
+ function evaluateKey(key2, stats2, kind2, thresholds, cfg, runDay) {
1772
+ const file = thresholds[kind2];
1773
+ if (file.status === "invalid") {
1774
+ return {
1775
+ result: "not-evaluated",
1776
+ reason: "thresholds-error",
1777
+ thresholdSource: "default",
1778
+ limits: defaultLimits(cfg.checks, kind2),
1779
+ checks: [],
1780
+ muted: null
1781
+ };
1782
+ }
1783
+ const entries = file.status === "loaded" ? file.file.entries : {};
1784
+ const entry = Object.hasOwn(entries, key2) ? entries[key2] : void 0;
1785
+ const limits = entry === void 0 ? defaultLimits(cfg.checks, kind2) : entryLimits(entry, cfg.checks, kind2);
1786
+ const { checks, applicable } = runRules(stats2, limits, cfg);
1787
+ return {
1788
+ result: checks.length === 0 ? "not-evaluated" : checks.some((c) => !c.passed) ? "fail" : "pass",
1789
+ reason: checks.length > 0 ? null : applicable ? "too-few-samples" : "no-rules",
1790
+ thresholdSource: entry === void 0 ? "default" : "file",
1791
+ limits,
1792
+ checks,
1793
+ muted: entry === void 0 ? null : keyMuting(entry, runDay)
1794
+ };
1795
+ }
1796
+ function qualifies(evaluation, gate) {
1797
+ if (gate.warnOnly) return false;
1798
+ if (evaluation.thresholdSource === "default" && gate.defaultThresholds === "warn") return false;
1799
+ return !isMuteActive(evaluation.muted);
1800
+ }
1801
+ function applyGate(perKey, gate) {
1802
+ const all = KINDS2.flatMap((kind2) => Object.values(perKey[kind2]));
1803
+ const qualified = all.filter(
1804
+ (e) => qualifies(e, gate) && e.checks.some((check2) => !check2.passed)
1805
+ );
1806
+ const evaluated = all.filter((e) => e.result !== "not-evaluated").length;
1807
+ const overTolerance = qualified.length > allowedViolations(gate.tolerance, evaluated);
1808
+ for (const evaluation of qualified) {
1809
+ for (const check2 of evaluation.checks) {
1810
+ check2.blocking = !check2.passed && (overTolerance || check2.hardLimitExceeded);
1811
+ }
1812
+ }
1813
+ }
1814
+ function countKind(perKey, unseenThresholdEntries) {
1815
+ const counts = {
1816
+ keys: 0,
1817
+ fromFile: 0,
1818
+ fromDefaults: 0,
1819
+ notEvaluated: 0,
1820
+ tooFewSamples: 0,
1821
+ fileEntriesNotEvaluated: 0,
1822
+ medianOnly: 0,
1823
+ unseenThresholdEntries,
1824
+ violations: 0,
1825
+ blockingViolations: 0,
1826
+ muted: 0
1827
+ };
1828
+ for (const e of Object.values(perKey)) {
1829
+ counts.keys += 1;
1830
+ if (isMuteActive(e.muted)) counts.muted += 1;
1831
+ if (e.result === "not-evaluated") {
1832
+ counts.notEvaluated += 1;
1833
+ if (e.reason === "too-few-samples") {
1834
+ counts.tooFewSamples += 1;
1835
+ if (e.thresholdSource === "file") counts.fileEntriesNotEvaluated += 1;
1836
+ }
1837
+ continue;
1838
+ }
1839
+ if (e.thresholdSource === "file") counts.fromFile += 1;
1840
+ else counts.fromDefaults += 1;
1841
+ const timeRules = e.checks.filter((c) => TIME_RULES.has(c.rule)).map((c) => c.rule);
1842
+ if (timeRules.length === 1 && timeRules[0] === "median") counts.medianOnly += 1;
1843
+ if (e.result === "fail") counts.violations += 1;
1844
+ if (e.checks.some((c) => c.blocking)) counts.blockingViolations += 1;
1845
+ }
1846
+ return counts;
1847
+ }
1848
+ function evaluationStatus2(perKey, thresholds, fatalToolError) {
1849
+ if (fatalToolError || KINDS2.some((kind2) => thresholds[kind2].status === "invalid")) {
1850
+ return "error";
1851
+ }
1852
+ const checks = KINDS2.flatMap((kind2) => Object.values(perKey[kind2])).flatMap((e) => e.checks);
1853
+ if (checks.some((c) => c.blocking)) return "failed";
1854
+ if (checks.some((c) => !c.passed)) return "warned";
1855
+ return "passed";
1856
+ }
1857
+ function evaluate(aggregates, thresholds, cfg, opts) {
1858
+ const runDay = dayOf(opts.startedAt);
1859
+ const byKind = {
1860
+ api: aggregates.endpoints,
1861
+ custom: aggregates.custom
1862
+ };
1863
+ const perKey = { api: {}, custom: {} };
1864
+ for (const kind2 of KINDS2) {
1865
+ for (const key2 of Object.keys(byKind[kind2]).sort(compareText)) {
1866
+ const stats2 = byKind[kind2][key2];
1867
+ if (stats2 !== void 0) {
1868
+ perKey[kind2][key2] = evaluateKey(key2, stats2, kind2, thresholds, cfg, runDay);
1869
+ }
1870
+ }
1871
+ }
1872
+ applyGate(perKey, cfg.gate);
1873
+ const warnings = [];
1874
+ const toolErrors = [];
1875
+ const thresholdFiles = [];
1876
+ const unseenCount = { api: 0, custom: 0 };
1877
+ for (const kind2 of KINDS2) {
1878
+ const file = thresholds[kind2];
1879
+ if (file.kind !== kind2) {
1880
+ throw new Error(`evaluate: thresholds.${kind2} has kind "${file.kind}"`);
1881
+ }
1882
+ let unseen = [];
1883
+ if (file.status === "missing") {
1884
+ warnings.push(missingFileWarning(file, opts.env));
1885
+ } else if (file.status === "invalid") {
1886
+ toolErrors.push(...file.issues.map(schemaIssueToIssue));
1887
+ } else {
1888
+ if (file.migratedFrom !== void 0) {
1889
+ warnings.push(outdatedWarning(file.path, file.migratedFrom, SCHEMA_VERSIONS.thresholds));
1890
+ }
1891
+ if (file.file.generated !== null) {
1892
+ warnings.push(
1893
+ ...generatedWarnings(file.path, file.file.generated, cfg, opts.env, opts.source)
1894
+ );
1895
+ }
1896
+ unseen = Object.keys(file.file.entries).filter((key2) => !Object.hasOwn(byKind[kind2], key2)).sort(compareText);
1897
+ if (unseen.length > 0) warnings.push(unseenWarning(file.path, unseen));
1898
+ }
1899
+ unseenCount[kind2] = unseen.length;
1900
+ thresholdFiles.push(fileInfo(file, unseen));
1901
+ }
1902
+ const counts = {
1903
+ api: countKind(perKey.api, unseenCount.api),
1904
+ custom: countKind(perKey.custom, unseenCount.custom)
1905
+ };
1906
+ if (KINDS2.every((kind2) => Object.keys(byKind[kind2]).length === 0)) {
1907
+ warnings.push({
1908
+ code: "EVAL_NO_SAMPLES",
1909
+ message: "The run recorded no samples, so nothing was evaluated.",
1910
+ hint: "Check the integration: tests must use the fixtures from withPerfFixtures, and the measure options (include, exclude, resourceTypes) must not filter out every request."
1911
+ });
1912
+ }
1913
+ const notEvaluated = counts.api.fileEntriesNotEvaluated + counts.custom.fileEntriesNotEvaluated;
1914
+ if (notEvaluated > 0) {
1915
+ warnings.push({
1916
+ code: "THRESHOLDS_ENTRIES_NOT_EVALUATED",
1917
+ message: `${plural(notEvaluated, "key")} with an entry in the thresholds file had too few samples and ${notEvaluated === 1 ? "was" : "were"} not evaluated.`,
1918
+ hint: `Run more repetitions (run.repeat or \`${chunkLV3O2BAT_cjs.CLI_COMMAND} test --repeat\`), or accept that the endpoint is called rarely.`
1919
+ });
1920
+ }
1921
+ const mutedKeys = KINDS2.flatMap(
1922
+ (kind2) => Object.entries(perKey[kind2]).flatMap(
1923
+ ([key2, e]) => e.muted === null ? [] : [{ kind: kind2, key: key2, muted: e.muted }]
1924
+ )
1925
+ );
1926
+ warnings.push(...mutingWarnings(mutedKeys, runDay));
1927
+ return {
1928
+ status: evaluationStatus2(perKey, thresholds, opts.fatalToolError),
1929
+ gateEnabled: opts.mode === "test",
1930
+ counts,
1931
+ perKey,
1932
+ thresholdFiles,
1933
+ warnings,
1934
+ toolErrors
1935
+ };
1936
+ }
1937
+
1938
+ // src/core/evaluate/outcome.ts
1939
+ function percent(share) {
1940
+ return `${Math.round(share * 1e3) / 10}%`;
1941
+ }
1942
+ function assessRun(input, gate) {
1943
+ const { tests, maxFailures} = input;
1944
+ const warnings = [];
1945
+ const toolErrors = [];
1946
+ const executions = tests.expected + tests.unexpected + tests.flaky;
1947
+ const share = executions === 0 ? 0 : tests.unexpected / executions;
1948
+ const failedText = `${tests.unexpected} of ${plural(executions, "test execution")} failed`;
1949
+ if (share > gate.maxFailedTestShare) {
1950
+ toolErrors.push({
1951
+ code: "TESTS_FAILED_TOO_MANY",
1952
+ message: `${failedText} (${percent(share)}, more than gate.maxFailedTestShare ${percent(gate.maxFailedTestShare)}); samples of a large part of the tests are missing, so the performance result is not trustworthy.`,
1953
+ hint: "Fix the failing tests (run them without perf mode), or raise gate.maxFailedTestShare if the failures are expected."
1954
+ });
1955
+ } else if (tests.unexpected > 0) {
1956
+ warnings.push({
1957
+ code: "TESTS_FAILED",
1958
+ message: `${failedText}; the performance result still decides.`,
1959
+ hint: "Functional failures are reported by your regular test run."
1960
+ });
1961
+ }
1962
+ const stoppedByMaxFailures = maxFailures > 0 && tests.unexpected >= maxFailures;
1963
+ if (tests.status === "timedout" || tests.status === "interrupted" || stoppedByMaxFailures) {
1964
+ const why = stoppedByMaxFailures ? `it stopped after ${plural(tests.unexpected, "failure")} (maxFailures ${maxFailures})` : tests.status === "timedout" ? "it timed out" : "it was interrupted";
1965
+ toolErrors.push({
1966
+ code: "RUN_INCOMPLETE",
1967
+ message: `The run did not execute all tests: ${why}. The evaluation covers only the samples collected.`,
1968
+ hint: "Raise the global timeout or maxFailures for perf runs, or measure a smaller subset of tests."
1969
+ });
1970
+ }
1971
+ return { warnings, toolErrors };
1972
+ }
1973
+ function buildOutcome(report, paths) {
1974
+ const exitCode = report.toolErrors.length > 0 ? 3 : report.mode === "test" && report.evaluation.gateEnabled && report.evaluation.status === "failed" ? 2 : 0;
1975
+ return {
1976
+ schemaVersion: SCHEMA_VERSIONS.outcome,
1977
+ runId: report.runId,
1978
+ mode: report.mode,
1979
+ exitCode,
1980
+ tests: { status: report.tests.status },
1981
+ evaluation: { status: report.evaluation.status, gateEnabled: report.evaluation.gateEnabled },
1982
+ toolErrors: report.toolErrors.map((issue2) => ({ ...issue2 })),
1983
+ paths: { ...paths, thresholds: [...paths.thresholds] }
1984
+ };
1985
+ }
1986
+
1987
+ // src/core/normalize/constants.ts
1988
+ var NORMALIZE_RULES_VERSION = 1;
1989
+ var MAX_KEY_LENGTH = 2e3;
1990
+ var CARDINALITY_MIN_KEYS = 10;
1991
+ var MAX_KEYS_WARNING = 1e3;
1992
+
1993
+ // src/core/normalize/explosion.ts
1994
+ var EXAMPLES = 3;
1995
+ function parseKey(key2) {
1996
+ const space = key2.indexOf(" ");
1997
+ if (space <= 0) return null;
1998
+ const slash = key2.indexOf("/", space + 1);
1999
+ if (slash < 0) return null;
2000
+ const head = key2.slice(0, slash);
2001
+ if (head.slice(space + 1).includes("?")) return null;
2002
+ const rest = key2.slice(slash + 1);
2003
+ const mark = rest.indexOf("?");
2004
+ const path = mark < 0 ? rest : rest.slice(0, mark);
2005
+ return {
2006
+ head,
2007
+ segments: path === "" ? [] : path.split("/"),
2008
+ query: mark < 0 ? "" : rest.slice(mark)
2009
+ };
2010
+ }
2011
+ function detectKeyExplosion(endpointKeys) {
2012
+ const unique = [...new Set(endpointKeys)].sort();
2013
+ const groups = /* @__PURE__ */ new Map();
2014
+ for (const key2 of unique) {
2015
+ const parsed = parseKey(key2);
2016
+ if (parsed === null) continue;
2017
+ parsed.segments.forEach((_, i) => {
2018
+ const template = parsed.segments.map((s, j) => j === i ? "*" : s).join("/");
2019
+ const id = `${parsed.head}/${template}${parsed.query}`;
2020
+ const list2 = groups.get(id);
2021
+ if (list2 === void 0) groups.set(id, [key2]);
2022
+ else list2.push(key2);
2023
+ });
2024
+ }
2025
+ const issues = [];
2026
+ for (const template of [...groups.keys()].sort()) {
2027
+ const keys = groups.get(template) ?? [];
2028
+ if (keys.length < CARDINALITY_MIN_KEYS) continue;
2029
+ const examples = keys.slice(0, EXAMPLES).join(", ");
2030
+ issues.push({
2031
+ code: "NORMALIZE_HIGH_CARDINALITY",
2032
+ message: `${keys.length} endpoint keys differ only in one path segment: ${template} (e.g. ${examples}).`,
2033
+ hint: "If the segment is test data, replace it with keys.extraIdPatterns or a keys.keyBuilder function."
2034
+ });
2035
+ }
2036
+ if (unique.length > MAX_KEYS_WARNING) {
2037
+ issues.push({
2038
+ code: "NORMALIZE_TOO_MANY_KEYS",
2039
+ message: `The run has ${unique.length} endpoint keys, more than ${MAX_KEYS_WARNING}.`,
2040
+ hint: "Check the keys for test data and normalize it with keys.extraIdPatterns, keys.dropQueryParams or keys.keyBuilder."
2041
+ });
2042
+ }
2043
+ return issues;
2044
+ }
2045
+
2046
+ // src/core/normalize/patterns.ts
2047
+ var ID_PATTERNS = {
2048
+ number: /^[0-9]+$/,
2049
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
2050
+ hex: /^[0-9a-f]{16,}$/i,
2051
+ token: /^(?=[^0-9]*[0-9])(?:[A-Za-z0-9~=]{24,}|(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[A-Za-z0-9_.~=-]{24,})$/,
2052
+ mixed: /^(?=[^0-9]*[0-9])(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[A-Za-z0-9_-]{16,}$/,
2053
+ email: /^[^@\s/]+@[^@\s/]+\.[^@\s/]+$/
2054
+ };
2055
+ function compileIdMatcher(keys) {
2056
+ const email = keys.idPatterns.email ? ID_PATTERNS.email : void 0;
2057
+ const ids = [];
2058
+ for (const name of ["number", "uuid", "hex", "token", "mixed"]) {
2059
+ if (keys.idPatterns[name]) {
2060
+ const re = ID_PATTERNS[name];
2061
+ ids.push((text) => re.test(text));
2062
+ }
2063
+ }
2064
+ for (const pattern of keys.extraIdPatterns) {
2065
+ if (typeof pattern === "string") {
2066
+ ids.push((text) => text === pattern);
2067
+ } else {
2068
+ const re = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
2069
+ ids.push((text) => re.test(text));
2070
+ }
2071
+ }
2072
+ return (text) => {
2073
+ if (email?.test(text) === true) return ":email";
2074
+ return ids.some((test) => test(text)) ? ":id" : null;
2075
+ };
2076
+ }
2077
+
2078
+ // src/core/normalize/key-builder.ts
2079
+ var HINT_EXTEND = "Use keys.extraIdPatterns or keys.keyBuilder for ids in other formats.";
2080
+ function parseHttpUrl(text) {
2081
+ if (!URL.canParse(text)) return null;
2082
+ const url = new URL(text);
2083
+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;
2084
+ }
2085
+ function canonicalOrigin(text) {
2086
+ return parseHttpUrl(text)?.origin ?? null;
2087
+ }
2088
+ function canonicalOrigins(origins) {
2089
+ const set = /* @__PURE__ */ new Set();
2090
+ for (const origin of origins) {
2091
+ const canonical = canonicalOrigin(origin);
2092
+ if (canonical !== null) set.add(canonical);
2093
+ }
2094
+ return [...set].sort();
2095
+ }
2096
+ var SEGMENT_ESCAPE = /[%/?#& \u0000-\u001f\u007f-\u009f]/g;
2097
+ var NAME_ESCAPE = /[%&=# \u0000-\u001f\u007f-\u009f]/g;
2098
+ var VALUE_ESCAPE = /[%&=#, \u0000-\u001f\u007f-\u009f]/g;
2099
+ var escape = (text, chars) => text.replace(chars, encodeURIComponent);
2100
+ function normalizePath(pathname, matchId) {
2101
+ const segments2 = [];
2102
+ for (const raw of pathname.split("/")) {
2103
+ const segment = raw.split(";", 1)[0] ?? "";
2104
+ if (segment === "") continue;
2105
+ let decoded;
2106
+ try {
2107
+ decoded = decodeURIComponent(segment);
2108
+ } catch {
2109
+ segments2.push(segment);
2110
+ continue;
2111
+ }
2112
+ segments2.push(matchId(decoded) ?? escape(decoded, SEGMENT_ESCAPE));
2113
+ }
2114
+ return `/${segments2.join("/")}`;
2115
+ }
2116
+ function normalizeQuery(params, keys, matchId) {
2117
+ const drop = new Set(keys.dropQueryParams);
2118
+ const keep = new Set(keys.keepQueryValues);
2119
+ const names = /* @__PURE__ */ new Map();
2120
+ for (const [rawName, value] of params) {
2121
+ const name = rawName.replace(/\[[0-9]+\]/g, "[]");
2122
+ if (name === "" || drop.has(name) || matchId(name) !== null) continue;
2123
+ const encoded = escape(name, NAME_ESCAPE);
2124
+ if (!keep.has(name)) {
2125
+ if (!names.has(encoded)) names.set(encoded, null);
2126
+ continue;
2127
+ }
2128
+ const values = names.get(encoded) ?? /* @__PURE__ */ new Set();
2129
+ values.add(matchId(value) ?? escape(value, VALUE_ESCAPE));
2130
+ names.set(encoded, values);
2131
+ }
2132
+ return [...names.keys()].sort().map((name) => {
2133
+ const values = names.get(name);
2134
+ return values ? `${name}=${[...values].sort().join(",")}` : name;
2135
+ }).join("&");
2136
+ }
2137
+ function truncateKey(key2) {
2138
+ if (key2.length <= MAX_KEY_LENGTH) return key2;
2139
+ const suffix = `\u2026~${hashHex(key2)}`;
2140
+ let cut = MAX_KEY_LENGTH - suffix.length;
2141
+ const before = key2.charCodeAt(cut - 1);
2142
+ const after = key2.charCodeAt(cut);
2143
+ if (before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343) cut -= 1;
2144
+ return key2.slice(0, cut) + suffix;
2145
+ }
2146
+ function createKeyBuilder(cfg, ctx) {
2147
+ const matchId = compileIdMatcher(cfg);
2148
+ const labels = /* @__PURE__ */ new Map();
2149
+ for (const origin of canonicalOrigins(ctx.baseOrigins)) labels.set(origin, "");
2150
+ for (const [origin, label] of Object.entries(cfg.origins)) {
2151
+ const canonical = canonicalOrigin(origin);
2152
+ if (canonical !== null) labels.set(canonical, label);
2153
+ }
2154
+ const keyBuilder = cfg.keyBuilder;
2155
+ return (sample) => {
2156
+ const method = sample.method.toUpperCase();
2157
+ const url = parseHttpUrl(sample.url);
2158
+ const issues = [];
2159
+ let key2;
2160
+ if (keyBuilder !== void 0) {
2161
+ let custom;
2162
+ try {
2163
+ custom = keyBuilder({ method, url: sample.url, resourceType: sample.resourceType });
2164
+ } catch (error) {
2165
+ issues.push({
2166
+ code: "NORMALIZE_KEY_BUILDER_THREW",
2167
+ message: `keys.keyBuilder threw an exception: ${error instanceof Error ? error.message : String(error)}. The built-in normalization was used instead.`,
2168
+ hint: "Fix the keyBuilder function; it must not throw."
2169
+ });
2170
+ custom = void 0;
2171
+ }
2172
+ if (typeof custom === "string" && custom.trim() !== "") {
2173
+ key2 = custom;
2174
+ } else if (custom !== void 0) {
2175
+ issues.push({
2176
+ code: "NORMALIZE_KEY_BUILDER_INVALID",
2177
+ message: "keys.keyBuilder returned a value that is neither a non-empty string nor undefined. The built-in normalization was used instead.",
2178
+ hint: "Return the whole key as a non-empty string, or undefined for the built-in normalization."
2179
+ });
2180
+ }
2181
+ }
2182
+ if (key2 === void 0) {
2183
+ if (url === null) {
2184
+ issues.push({
2185
+ code: "NORMALIZE_UNSUPPORTED_URL",
2186
+ message: "A request URL could not be parsed or does not use http/https; the sample was skipped."
2187
+ });
2188
+ return { ok: false, issues };
2189
+ }
2190
+ const label = labels.get(url.origin) ?? url.host;
2191
+ const query = cfg.query === "names" ? normalizeQuery(url.searchParams, cfg, matchId) : "";
2192
+ key2 = `${method} ${label}${normalizePath(url.pathname, matchId)}${query === "" ? "" : `?${query}`}`;
2193
+ }
2194
+ const truncated = truncateKey(key2);
2195
+ if (truncated !== key2) {
2196
+ issues.push({
2197
+ code: "NORMALIZE_KEY_TRUNCATED",
2198
+ message: `An endpoint key longer than ${MAX_KEY_LENGTH} characters was truncated and suffixed with its hash.`,
2199
+ hint: HINT_EXTEND
2200
+ });
2201
+ }
2202
+ return {
2203
+ ok: true,
2204
+ key: truncated,
2205
+ origin: url?.origin ?? null,
2206
+ label: url === null ? null : labels.get(url.origin) ?? url.host,
2207
+ issues
2208
+ };
2209
+ };
2210
+ }
2211
+
2212
+ // src/core/normalize/fingerprint.ts
2213
+ function measuredBaseOrigins(projects) {
2214
+ const origins = [];
2215
+ for (const project of projects) {
2216
+ if (project.role !== "measured" || project.baseURL == null) continue;
2217
+ const origin = canonicalOrigin(project.baseURL);
2218
+ if (origin !== null) origins.push(origin);
2219
+ }
2220
+ return canonicalOrigins(origins);
2221
+ }
2222
+ function normalizationFingerprint(cfg, ctx) {
2223
+ const { keyBuilder, extraIdPatterns, ...rest } = cfg;
2224
+ const keys = {
2225
+ ...rest,
2226
+ extraIdPatterns: extraIdPatterns.map(
2227
+ (p) => typeof p === "string" ? p : { regex: p.source, flags: p.flags }
2228
+ ),
2229
+ keyBuilder: keyBuilder === void 0 ? void 0 : "[function]"
2230
+ };
2231
+ return hashHex(
2232
+ stringifyStable({
2233
+ rulesVersion: NORMALIZE_RULES_VERSION,
2234
+ keys,
2235
+ baseOrigins: canonicalOrigins(ctx.baseOrigins)
2236
+ })
2237
+ );
2238
+ }
2239
+
2240
+ // src/core/report/issues.ts
2241
+ function collapseIssues(issues) {
2242
+ const result = [];
2243
+ const index = /* @__PURE__ */ new Map();
2244
+ for (const issue2 of issues) {
2245
+ const id = `${issue2.code}\0${issue2.message}`;
2246
+ const at2 = index.get(id);
2247
+ const first2 = at2 === void 0 ? void 0 : result[at2];
2248
+ if (first2 === void 0) {
2249
+ index.set(id, result.length);
2250
+ result.push({ ...issue2 });
2251
+ } else {
2252
+ first2.count = (first2.count ?? 1) + (issue2.count ?? 1);
2253
+ }
2254
+ }
2255
+ return result;
2256
+ }
2257
+
2258
+ // src/core/report/build-run-report.ts
2259
+ function compareText4(a, b) {
2260
+ return a < b ? -1 : a > b ? 1 : 0;
2261
+ }
2262
+ function compareSlowest(a, b) {
2263
+ return b.duration - a.duration || compareText4(a.test.file, b.test.file) || a.test.line - b.test.line || a.test.repeatEachIndex - b.test.repeatEachIndex;
2264
+ }
2265
+ function buildAggregate(stats2, evaluation, rawUrls) {
2266
+ return {
2267
+ ...stats2,
2268
+ statuses: { ...stats2.statuses },
2269
+ timeSources: { ...stats2.timeSources },
2270
+ stats: stats2.stats === null ? null : {
2271
+ min: roundMs(stats2.stats.min),
2272
+ avg: roundMs(stats2.stats.avg),
2273
+ max: roundMs(stats2.stats.max),
2274
+ percentiles: Object.fromEntries(
2275
+ Object.entries(stats2.stats.percentiles).map(([name, value]) => [
2276
+ name,
2277
+ roundMs(value)
2278
+ ])
2279
+ )
2280
+ },
2281
+ ttfb: stats2.ttfb === null ? null : { p50: roundMs(stats2.ttfb.p50), p95: roundMs(stats2.ttfb.p95) },
2282
+ // Raw URLs only with report.rawUrls (D-11, 02-REQ-16).
2283
+ slowest: stats2.slowest.map(({ url, ...sample }) => ({
2284
+ ...sample,
2285
+ test: { ...sample.test },
2286
+ duration: roundMs(sample.duration),
2287
+ ...rawUrls && url !== void 0 ? { url } : {}
2288
+ })).sort(compareSlowest),
2289
+ topTests: stats2.topTests.map((t) => ({ ...t })).sort(
2290
+ (a, b) => b.sampleCount - a.sampleCount || compareText4(a.file, b.file) || a.line - b.line || compareText4(a.title, b.title) || compareText4(a.project, b.project)
2291
+ ),
2292
+ samples: {
2293
+ durations: stats2.samples.durations.map(roundMs).sort((a, b) => a - b),
2294
+ sampled: stats2.samples.sampled
2295
+ },
2296
+ evaluation: structuredClone(evaluation)
2297
+ };
2298
+ }
2299
+ function buildAggregates(kind2, aggregates, perKey, rawUrls) {
2300
+ for (const key2 of Object.keys(perKey)) {
2301
+ if (!Object.hasOwn(aggregates, key2)) {
2302
+ throw new Error(`buildRunReport: evaluation for unknown ${kind2} key "${key2}"`);
2303
+ }
2304
+ }
2305
+ const result = {};
2306
+ for (const key2 of Object.keys(aggregates).sort()) {
2307
+ const stats2 = aggregates[key2];
2308
+ const evaluation = Object.hasOwn(perKey, key2) ? perKey[key2] : void 0;
2309
+ if (stats2 === void 0 || evaluation === void 0) {
2310
+ throw new Error(`buildRunReport: no evaluation for ${kind2} key "${key2}"`);
2311
+ }
2312
+ result[key2] = buildAggregate(stats2, evaluation, rawUrls);
2313
+ }
2314
+ return result;
2315
+ }
2316
+ function buildRunReport(input) {
2317
+ const { meta, aggregates, evaluation } = input;
2318
+ const rawUrls = input.config.report?.rawUrls === true;
2319
+ const kindOrder = { api: 0, custom: 1 };
2320
+ return {
2321
+ schemaVersion: SCHEMA_VERSIONS.runReport,
2322
+ tool: { ...meta.tool },
2323
+ runId: meta.runId,
2324
+ mode: meta.mode,
2325
+ startedAt: meta.startedAt,
2326
+ finishedAt: meta.finishedAt,
2327
+ env: meta.env,
2328
+ configDir: meta.configDir,
2329
+ config: structuredClone(input.config),
2330
+ normalization: input.normalization,
2331
+ ci: meta.ci === null ? null : { ...meta.ci },
2332
+ host: { ...meta.host },
2333
+ playwright: { ...meta.playwright },
2334
+ runConditions: structuredClone(input.runConditions),
2335
+ tests: { ...input.tests },
2336
+ evaluation: {
2337
+ status: evaluation.status,
2338
+ gateEnabled: evaluation.gateEnabled,
2339
+ counts: structuredClone(evaluation.counts)
2340
+ },
2341
+ thresholdFiles: evaluation.thresholdFiles.map((file) => ({
2342
+ ...file,
2343
+ generated: file.generated === null ? null : structuredClone(file.generated),
2344
+ unseenKeys: [...file.unseenKeys].sort(compareText4)
2345
+ })).sort((a, b) => kindOrder[a.kind] - kindOrder[b.kind]),
2346
+ warnings: collapseIssues(input.warnings),
2347
+ toolErrors: collapseIssues(input.toolErrors),
2348
+ origins: aggregates.origins.map((o) => ({ ...o })).sort((a, b) => compareText4(a.origin, b.origin)),
2349
+ endpoints: buildAggregates("api", aggregates.endpoints, evaluation.perKey.api, rawUrls),
2350
+ custom: buildAggregates("custom", aggregates.custom, evaluation.perKey.custom, rawUrls)
2351
+ };
2352
+ }
2353
+
2354
+ // src/core/thresholds/constants.ts
2355
+ var WILSON_SELF_GAP = 0.01;
2356
+ var ERR_SELF_GAP = 0.01;
2357
+
2358
+ // src/core/thresholds/formulas.ts
2359
+ function minDeriveSamples(checks) {
2360
+ return Math.max(1, checks.time.median.minSamples);
2361
+ }
2362
+ function isDerivable(stats2, checks) {
2363
+ return stats2.stats !== null && stats2.successCount >= minDeriveSamples(checks);
2364
+ }
2365
+ function withPercentile(stats2, level) {
2366
+ if (stats2.stats === null || stats2.stats.percentiles[level] !== void 0) return stats2;
2367
+ const p = percentileNames(level).find(([name]) => name === level)?.[1];
2368
+ const durations = [...stats2.samples.durations].sort((a, b) => a - b);
2369
+ const value = p === void 0 ? null : percentile(durations, p);
2370
+ if (value === null) return stats2;
2371
+ return {
2372
+ ...stats2,
2373
+ stats: { ...stats2.stats, percentiles: { ...stats2.stats.percentiles, [level]: roundMs(value) } }
2374
+ };
2375
+ }
2376
+ function clamp(x, min, max) {
2377
+ return Math.min(max, Math.max(min, x));
2378
+ }
2379
+ function derivationSettings2(cfg, kind2) {
2380
+ const { time, slowShare, errors } = cfg.checks;
2381
+ return structuredClone({
2382
+ t: slowShare.t[kind2],
2383
+ smallSampleN: cfg.thresholds.smallSampleN,
2384
+ margins: {
2385
+ median: time.median.margin,
2386
+ percentile: time.percentile.margin,
2387
+ p99: time.p99.margin,
2388
+ apdex: slowShare.apdex.margin,
2389
+ wilson: slowShare.wilson.margin,
2390
+ errors: errors.margin
2391
+ }
2392
+ });
2393
+ }
2394
+ function deriveEntry(stats2, kind2, cfg) {
2395
+ const level = cfg.checks.time.percentile.level;
2396
+ const source = withPercentile(stats2, level).stats;
2397
+ if (source === null) throw new Error("deriveEntry: aggregate has no successful samples");
2398
+ const at2 = (name) => {
2399
+ const value = source.percentiles[name];
2400
+ if (value === void 0) throw new Error(`deriveEntry: aggregate has no percentile "${name}"`);
2401
+ return value;
2402
+ };
2403
+ const { time, slowShare, errors } = cfg.checks;
2404
+ const T = slowShare.t[kind2];
2405
+ const n = stats2.successCount;
2406
+ const small = n < cfg.thresholds.smallSampleN;
2407
+ const p50 = at2("p50");
2408
+ const p90 = at2("p90");
2409
+ const p99 = at2("p99");
2410
+ const pE = at2(level);
2411
+ const durations = [...stats2.samples.durations].sort((a, b) => a - b);
2412
+ const t = p50 > T.max ? null : ceilTo(clamp(Math.min(p90, T.medianFactor * p50), T.min, T.max), 0);
2413
+ const rMedian = small ? time.median.margin.smallSampleRelative : time.median.margin.relative;
2414
+ const median = ceilTo(Math.max(p50 * (1 + rMedian), p50 + time.median.margin.minMs), 0);
2415
+ const pMargin = time.percentile.margin;
2416
+ const rPercentile = small ? pMargin.smallSampleRelative : pMargin.relative;
2417
+ const percentileLimit = ceilTo(Math.max(pE * (1 + rPercentile), pE + pMargin.minMs, median), 0);
2418
+ const p99Margin = time.p99.margin;
2419
+ const p99Limit = ceilTo(
2420
+ Math.max(
2421
+ p99 * (1 + p99Margin.relative),
2422
+ percentileLimit + Math.max(p99Margin.minGapMs, p99Margin.minGapRelative * percentileLimit)
2423
+ ),
2424
+ 0
2425
+ );
2426
+ let minApdex = null;
2427
+ let maxWilson = null;
2428
+ if (t !== null) {
2429
+ const apdexMargin = slowShare.apdex.margin;
2430
+ const score = apdex(durations, t) ?? 0;
2431
+ minApdex = floorTo(
2432
+ Math.max(0, score - (small ? apdexMargin.smallSampleAbsolute : apdexMargin.absolute)),
2433
+ 3
2434
+ );
2435
+ const w = slowShare.wilson.margin;
2436
+ const { k, n: m } = exceedingShare(durations, t);
2437
+ const s = m === 0 ? 0 : k / m;
2438
+ const wLow = wilsonBounds(k, m)?.lower ?? 0;
2439
+ maxWilson = ceilTo(
2440
+ Math.min(
2441
+ 1,
2442
+ Math.max(
2443
+ clamp(s * w.factor + w.add, w.min, w.max),
2444
+ small ? w.smallSampleMin : 0,
2445
+ wLow + WILSON_SELF_GAP
2446
+ )
2447
+ ),
2448
+ 3
2449
+ );
2450
+ }
2451
+ const bigN = stats2.count;
2452
+ const e = bigN === 0 ? 0 : stats2.errorCount / bigN;
2453
+ const eLow = wilsonBounds(stats2.errorCount, bigN)?.lower ?? 0;
2454
+ const em = errors.margin;
2455
+ const maxErrorRate = ceilTo(
2456
+ Math.min(1, Math.max(e * em.factor + em.add, em.min, eLow + ERR_SELF_GAP)),
2457
+ 3
2458
+ );
2459
+ return {
2460
+ t,
2461
+ median,
2462
+ percentile: percentileLimit,
2463
+ p99: p99Limit,
2464
+ minApdex,
2465
+ maxWilson,
2466
+ maxErrorRate
2467
+ };
2468
+ }
2469
+
2470
+ // src/core/thresholds/consistency.ts
2471
+ function allRulesOn(checks) {
2472
+ const on = (rule) => ({
2473
+ ...rule,
2474
+ enabled: true,
2475
+ minSamples: 0
2476
+ });
2477
+ return {
2478
+ time: {
2479
+ median: on(checks.time.median),
2480
+ percentile: on(checks.time.percentile),
2481
+ p99: on(checks.time.p99)
2482
+ },
2483
+ slowShare: {
2484
+ t: checks.slowShare.t,
2485
+ apdex: on(checks.slowShare.apdex),
2486
+ wilson: on(checks.slowShare.wilson)
2487
+ },
2488
+ errors: on(checks.errors)
2489
+ };
2490
+ }
2491
+ function entrySelfConsistent(entry, aggregate2, kind2, cfg) {
2492
+ const checks = allRulesOn(cfg.checks);
2493
+ const stats2 = withPercentile(aggregate2, checks.time.percentile.level);
2494
+ const { checks: results } = runRules(stats2, entryLimits(entry, cfg.checks, kind2), {
2495
+ checks,
2496
+ gate: cfg.gate
2497
+ });
2498
+ return results.every((check2) => check2.passed);
2499
+ }
2500
+
2501
+ // src/core/thresholds/entries.ts
2502
+ var MS_LIMITS = /* @__PURE__ */ new Set(["t", "median", "percentile", "p99"]);
2503
+ var TIME_LIMITS = ["median", "percentile", "p99"];
2504
+ function isComplete(entry) {
2505
+ return chunkLV3O2BAT_cjs.LIMIT_NAMES.every((name) => entry[name] !== void 0);
2506
+ }
2507
+ function limitsOf(entry) {
2508
+ return {
2509
+ t: entry.t ?? null,
2510
+ median: entry.median ?? null,
2511
+ percentile: entry.percentile ?? null,
2512
+ p99: entry.p99 ?? null,
2513
+ minApdex: entry.minApdex ?? null,
2514
+ maxWilson: entry.maxWilson ?? null,
2515
+ maxErrorRate: entry.maxErrorRate ?? null
2516
+ };
2517
+ }
2518
+ function atMost(a, b) {
2519
+ return Math.round(a * 1e6) <= Math.round(b * 1e6);
2520
+ }
2521
+ function withinHysteresis(before, after, hysteresis) {
2522
+ return chunkLV3O2BAT_cjs.LIMIT_NAMES.every((name) => {
2523
+ const a = before[name];
2524
+ const b = after[name];
2525
+ if (a === null || b === null) return a === b;
2526
+ const allowed = MS_LIMITS.has(name) ? hysteresis.relative * a : hysteresis.ratio;
2527
+ return atMost(Math.abs(b - a), allowed);
2528
+ });
2529
+ }
2530
+ function changeDirection(limit, before, after) {
2531
+ if (before === after) return null;
2532
+ if (after === null) return "looser";
2533
+ if (before === null) return "stricter";
2534
+ const higher = after > before;
2535
+ return (limit === "minApdex" ? !higher : higher) ? "looser" : "stricter";
2536
+ }
2537
+ function grewMuch(limit, before, after, loosenWarnRelative) {
2538
+ if (!TIME_LIMITS.includes(limit) || before === null || after === null) return false;
2539
+ return !atMost(after - before, loosenWarnRelative * before);
2540
+ }
2541
+ function loosenedMuch(before, after, loosenWarnRelative) {
2542
+ const a = limitsOf(before);
2543
+ const b = limitsOf(after);
2544
+ return TIME_LIMITS.some((name) => grewMuch(name, a[name], b[name], loosenWarnRelative));
2545
+ }
2546
+
2547
+ // src/core/thresholds/derive.ts
2548
+ var KINDS3 = ["api", "custom"];
2549
+ var KIND_NOUN2 = { api: "endpoint", custom: "custom measurement" };
2550
+ function aggregatesOf(report, kind2) {
2551
+ return kind2 === "api" ? report.endpoints : report.custom;
2552
+ }
2553
+ function reportSource(report) {
2554
+ const browsers = report.runConditions.projects.filter((p) => p.role === "measured" && p.browserName !== null).map((p) => p.browserName ?? "");
2555
+ const { platform, arch, ci, cpuCount, cpuModel } = report.host;
2556
+ return {
2557
+ browsers: [...new Set(browsers)].sort(compareText),
2558
+ playwrightVersion: report.playwright.version,
2559
+ host: { platform, arch, ci, cpuCount, cpuModel },
2560
+ normalization: report.normalization
2561
+ };
2562
+ }
2563
+ function refusal(report, cfg, existing) {
2564
+ const incomplete = [];
2565
+ if (report.tests.status === "interrupted" || report.tests.status === "timedout") {
2566
+ incomplete.push(`tests ${report.tests.status}`);
2567
+ }
2568
+ if (report.toolErrors.length > 0) {
2569
+ const codes = [...new Set(report.toolErrors.map((issue2) => issue2.code))];
2570
+ incomplete.push(`tool errors: ${codes.join(", ")}`);
2571
+ }
2572
+ if (incomplete.length > 0) {
2573
+ return [
2574
+ {
2575
+ code: "THRESHOLDS_SOURCE_INCOMPLETE",
2576
+ message: `The source report is incomplete or untrustworthy (${incomplete.join("; ")}); no thresholds file was written.`,
2577
+ hint: `Fix the cause and derive again with \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds\`: thresholds are derived from complete runs only.`
2578
+ }
2579
+ ];
2580
+ }
2581
+ if (KINDS3.every((kind2) => Object.keys(aggregatesOf(report, kind2)).length === 0)) {
2582
+ return [
2583
+ {
2584
+ code: "THRESHOLDS_EMPTY_REPORT",
2585
+ message: "The source report has no samples; no thresholds file was written.",
2586
+ hint: "Check the integration: tests must use the fixtures from withPerfFixtures, and the measure options must not filter out every request."
2587
+ }
2588
+ ];
2589
+ }
2590
+ const derivable = KINDS3.some(
2591
+ (kind2) => Object.values(aggregatesOf(report, kind2)).some((stats2) => isDerivable(stats2, cfg.checks))
2592
+ );
2593
+ if (!derivable) {
2594
+ return [
2595
+ {
2596
+ code: "THRESHOLDS_NOTHING_TO_DERIVE",
2597
+ message: `No key has at least ${minDeriveSamples(cfg.checks)} successful samples (checks.time.median.minSamples); no thresholds file was written.`,
2598
+ hint: `Run more repetitions (run.repeat.thresholds or \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds --repeat\`).`
2599
+ }
2600
+ ];
2601
+ }
2602
+ const invalid = KINDS3.flatMap((kind2) => {
2603
+ const file = existing[kind2];
2604
+ return file.status === "invalid" ? file.issues.map(schemaIssueToIssue) : [];
2605
+ });
2606
+ return invalid.length > 0 ? invalid : null;
2607
+ }
2608
+ function generatedBlock(report, cfg, kind2, opts) {
2609
+ const source = reportSource(report);
2610
+ const sampleCount = Object.values(aggregatesOf(report, kind2)).reduce(
2611
+ (sum, stats2) => sum + stats2.successCount,
2612
+ 0
2613
+ );
2614
+ return {
2615
+ tool: { name: chunkLV3O2BAT_cjs.PACKAGE_NAME, version: opts.toolVersion },
2616
+ env: opts.env,
2617
+ sourceRunId: report.runId,
2618
+ sourceRunStartedAt: report.startedAt,
2619
+ sourceSampleCount: sampleCount,
2620
+ evaluatedPercentile: cfg.checks.time.percentile.level,
2621
+ derivation: derivationSettings2(cfg, kind2),
2622
+ browsers: source.browsers,
2623
+ playwrightVersion: source.playwrightVersion,
2624
+ host: source.host,
2625
+ normalization: source.normalization
2626
+ };
2627
+ }
2628
+ function generatedChanged(before, after) {
2629
+ return before.env !== after.env || before.evaluatedPercentile !== after.evaluatedPercentile || stringifyStable(before.derivation) !== stringifyStable(after.derivation) || !sameList(before.browsers, after.browsers) || majorMinor(before.playwrightVersion) !== majorMinor(after.playwrightVersion) || stringifyStable(before.host) !== stringifyStable(after.host) || before.normalization !== after.normalization;
2630
+ }
2631
+ function humanFields(entry) {
2632
+ const fields = {};
2633
+ if (entry.note !== void 0) fields.note = entry.note;
2634
+ if (entry.gate !== void 0) fields.gate = entry.gate;
2635
+ if (entry.until !== void 0) fields.until = entry.until;
2636
+ return fields;
2637
+ }
2638
+ function deriveKind(report, cfg, file, opts) {
2639
+ const kind2 = file.kind;
2640
+ const aggregates = aggregatesOf(report, kind2);
2641
+ const keys = Object.keys(aggregates).sort(compareText);
2642
+ const derivable = new Set(
2643
+ keys.filter((key2) => {
2644
+ const stats2 = aggregates[key2];
2645
+ return stats2 !== void 0 && isDerivable(stats2, cfg.checks);
2646
+ })
2647
+ );
2648
+ const warnings = [];
2649
+ if (derivable.size === 0) {
2650
+ if (keys.length > 0) {
2651
+ warnings.push({
2652
+ code: "THRESHOLDS_KIND_SKIPPED",
2653
+ message: `No ${KIND_NOUN2[kind2]} key has at least ${minDeriveSamples(cfg.checks)} successful samples; ${file.path} was not written.`,
2654
+ hint: `Run more repetitions (run.repeat.thresholds or \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds --repeat\`).`
2655
+ });
2656
+ }
2657
+ return { file: { kind: kind2, content: null, changed: false }, warnings, loosenedMuch: 0 };
2658
+ }
2659
+ const loaded = file.status === "loaded" ? file : null;
2660
+ if (loaded !== null && loaded.file.generated === null) {
2661
+ warnings.push({
2662
+ code: "THRESHOLDS_MANUAL_FILE",
2663
+ message: `${loaded.path} was written by hand (generated: null); its complete entries that are not locked are recomputed.`,
2664
+ hint: 'Mark entries you want to keep as they are with "locked": true.'
2665
+ });
2666
+ }
2667
+ if (loaded !== null && loaded.file.generated !== null) {
2668
+ const {
2669
+ diffs,
2670
+ timing,
2671
+ keys: keysDiffer
2672
+ } = sourceDifferences(loaded.file.generated, reportSource(report));
2673
+ if (diffs.length > 0) {
2674
+ const hints = [];
2675
+ if (timing) {
2676
+ hints.push(
2677
+ `Deriving on another machine, browser or Playwright version shifts all limits at once: derive on the CI infrastructure that evaluates the runs (\`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds --from\` with the report from CI).`
2678
+ );
2679
+ }
2680
+ if (keysDiffer) {
2681
+ hints.push(
2682
+ `Another normalization changes the keys: entries of old keys are kept as unseen until removed with \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds --prune\`.`
2683
+ );
2684
+ }
2685
+ warnings.push({
2686
+ code: "THRESHOLDS_SOURCE_MISMATCH",
2687
+ message: `Thresholds in ${loaded.path} were derived under other conditions than the source report (file / source report): ${diffs.join("; ")}.`,
2688
+ hint: hints.join(" ")
2689
+ });
2690
+ }
2691
+ }
2692
+ const before = loaded?.file.entries ?? {};
2693
+ const entries = {};
2694
+ let much = 0;
2695
+ for (const key2 of Object.keys(before).sort(compareText)) {
2696
+ const old = before[key2];
2697
+ if (old === void 0) continue;
2698
+ const stats2 = Object.hasOwn(aggregates, key2) ? aggregates[key2] : void 0;
2699
+ if (old.locked === true || !isComplete(old)) {
2700
+ entries[key2] = structuredClone(old);
2701
+ continue;
2702
+ }
2703
+ if (stats2 === void 0) {
2704
+ if (!opts.prune) entries[key2] = structuredClone(old);
2705
+ continue;
2706
+ }
2707
+ if (!derivable.has(key2) || cfg.thresholds.update === "new-only") {
2708
+ entries[key2] = structuredClone(old);
2709
+ continue;
2710
+ }
2711
+ const fresh = deriveEntry(stats2, kind2, cfg);
2712
+ if (withinHysteresis(old, fresh, cfg.thresholds.hysteresis) && entrySelfConsistent(old, stats2, kind2, cfg)) {
2713
+ entries[key2] = structuredClone(old);
2714
+ continue;
2715
+ }
2716
+ entries[key2] = { ...fresh, ...humanFields(old) };
2717
+ if (loosenedMuch(old, fresh, cfg.thresholds.loosenWarnRelative)) much += 1;
2718
+ }
2719
+ for (const key2 of derivable) {
2720
+ const stats2 = aggregates[key2];
2721
+ if (Object.hasOwn(before, key2) || stats2 === void 0) continue;
2722
+ entries[key2] = deriveEntry(stats2, kind2, cfg);
2723
+ }
2724
+ const generated = generatedBlock(report, cfg, kind2, opts);
2725
+ const content = {
2726
+ schemaVersion: SCHEMA_VERSIONS.thresholds,
2727
+ kind: kind2,
2728
+ generated,
2729
+ entries: Object.fromEntries(
2730
+ Object.keys(entries).sort(compareText).map((key2) => [key2, entries[key2] ?? {}])
2731
+ )
2732
+ };
2733
+ const changed = loaded === null || loaded.migratedFrom !== void 0 || loaded.file.generated === null || stringifyStable(loaded.file.entries) !== stringifyStable(content.entries) || generatedChanged(loaded.file.generated, generated);
2734
+ return {
2735
+ file: { kind: kind2, content: changed ? content : structuredClone(loaded.file), changed },
2736
+ warnings,
2737
+ loosenedMuch: much
2738
+ };
2739
+ }
2740
+ function deriveThresholds(report, cfg, existing, opts) {
2741
+ for (const kind2 of KINDS3) {
2742
+ if (existing[kind2].kind !== kind2) {
2743
+ throw new Error(`deriveThresholds: existing.${kind2} has kind "${existing[kind2].kind}"`);
2744
+ }
2745
+ }
2746
+ const refused = refusal(report, cfg, existing);
2747
+ if (refused !== null) return { ok: false, issues: refused };
2748
+ const warnings = [];
2749
+ if (report.env !== opts.env) {
2750
+ const show = (v) => v === null ? "none" : `"${v}"`;
2751
+ warnings.push({
2752
+ code: "THRESHOLDS_ENV_MISMATCH",
2753
+ message: `The source report was recorded for environment ${show(report.env)}, but the thresholds are written for environment ${show(opts.env)}.`,
2754
+ hint: "Check the --env flag and run.env: the files are written for the current environment label."
2755
+ });
2756
+ }
2757
+ if (report.tests.unexpected > 0) {
2758
+ warnings.push({
2759
+ code: "THRESHOLDS_SOURCE_TESTS_FAILED",
2760
+ message: `The source report has ${plural(report.tests.unexpected, "failed test execution")}; samples of failed tests may raise the thresholds.`,
2761
+ hint: "Review the diff before committing, or fix the tests and derive again."
2762
+ });
2763
+ }
2764
+ if (report.mode === "test") {
2765
+ warnings.push({
2766
+ code: "THRESHOLDS_SOURCE_TEST_MODE",
2767
+ message: "The source report comes from test mode, which runs fewer repetitions than a thresholds run.",
2768
+ hint: `Prefer a report of \`${chunkLV3O2BAT_cjs.CLI_COMMAND} thresholds\` as the source.`
2769
+ });
2770
+ }
2771
+ const files = [];
2772
+ let much = 0;
2773
+ for (const kind2 of KINDS3) {
2774
+ const file = existing[kind2];
2775
+ if (file.status === "invalid") throw new Error("deriveThresholds: unreachable invalid file");
2776
+ const result = deriveKind(report, cfg, file, opts);
2777
+ files.push(result.file);
2778
+ warnings.push(...result.warnings);
2779
+ much += result.loosenedMuch;
2780
+ }
2781
+ if (much > 0) {
2782
+ const percent2 = Math.round(cfg.thresholds.loosenWarnRelative * 100);
2783
+ warnings.push({
2784
+ code: "THRESHOLDS_LOOSENED_MUCH",
2785
+ message: `${plural(much, "entry has", "entries have")} a time limit that grew by more than ${percent2}% in this derivation.`,
2786
+ hint: "Check that the new thresholds do not accept a regression; the entries are marked with ! in the diff."
2787
+ });
2788
+ }
2789
+ return { ok: true, value: { files, warnings } };
2790
+ }
2791
+
2792
+ // src/core/thresholds/diff.ts
2793
+ function limitChanges(before, after, loosenWarnRelative) {
2794
+ const a = limitsOf(before);
2795
+ const b = limitsOf(after);
2796
+ const changes = [];
2797
+ for (const limit of chunkLV3O2BAT_cjs.LIMIT_NAMES) {
2798
+ const direction = changeDirection(limit, a[limit], b[limit]);
2799
+ if (direction === null) continue;
2800
+ const change = { limit, before: a[limit], after: b[limit], direction };
2801
+ if (grewMuch(limit, a[limit], b[limit], loosenWarnRelative)) change.large = true;
2802
+ changes.push(change);
2803
+ }
2804
+ return changes;
2805
+ }
2806
+ function keptKey(key2, before, after, stats2, kind2, cfg) {
2807
+ if (stats2 === void 0) return { key: key2, category: "unseen", changes: [] };
2808
+ if (before.locked === true || !isComplete(before)) {
2809
+ return {
2810
+ key: key2,
2811
+ category: "locked",
2812
+ changes: [],
2813
+ ...isComplete(before) ? {} : { incomplete: true }
2814
+ };
2815
+ }
2816
+ if (!isDerivable(stats2, cfg.checks)) return { key: key2, category: "skipped", changes: [] };
2817
+ const changes = limitChanges(before, after, cfg.thresholds.loosenWarnRelative);
2818
+ if (changes.length > 0) {
2819
+ const looser = changes.some((c) => c.direction === "looser");
2820
+ const stricter = changes.some((c) => c.direction === "stricter");
2821
+ const category = looser && stricter ? "mixed" : looser ? "loosened" : "tightened";
2822
+ return { key: key2, category, changes };
2823
+ }
2824
+ const fresh = cfg.thresholds.update === "all" ? deriveEntry(stats2, kind2, cfg) : null;
2825
+ const old = limitsOf(before);
2826
+ const kept = fresh !== null && chunkLV3O2BAT_cjs.LIMIT_NAMES.some((name) => fresh[name] !== old[name]);
2827
+ return { key: key2, category: "unchanged", changes: [], ...kept ? { withinHysteresis: true } : {} };
2828
+ }
2829
+ function diffThresholds(before, after, report, cfg) {
2830
+ const kind2 = after.kind;
2831
+ const old = before.status === "loaded" ? before.file.entries : {};
2832
+ const now = after.content === null ? old : after.content.entries;
2833
+ const aggregates = aggregatesOf(report, kind2);
2834
+ const runDay = dayOf(report.startedAt);
2835
+ const keys = /* @__PURE__ */ new Set([...Object.keys(old), ...Object.keys(now)]);
2836
+ for (const [key2, stats2] of Object.entries(aggregates)) {
2837
+ if (!isDerivable(stats2, cfg.checks)) keys.add(key2);
2838
+ }
2839
+ const diffs = [];
2840
+ for (const key2 of [...keys].sort(compareText)) {
2841
+ const b = Object.hasOwn(old, key2) ? old[key2] : void 0;
2842
+ const a = Object.hasOwn(now, key2) ? now[key2] : void 0;
2843
+ const stats2 = Object.hasOwn(aggregates, key2) ? aggregates[key2] : void 0;
2844
+ let diff;
2845
+ if (b !== void 0 && a !== void 0) {
2846
+ diff = keptKey(key2, b, a, stats2, kind2, cfg);
2847
+ } else if (a !== void 0) {
2848
+ diff = { key: key2, category: "added", changes: [], limits: limitsOf(a) };
2849
+ } else if (b !== void 0) {
2850
+ diff = { key: key2, category: "removed", changes: [], limits: limitsOf(b) };
2851
+ } else {
2852
+ diff = { key: key2, category: "skipped", changes: [] };
2853
+ }
2854
+ const entry = a ?? b;
2855
+ const muting = entry === void 0 ? null : keyMuting(entry, runDay);
2856
+ if (muting !== null) diff.muted = { until: muting.until, expired: muting.expired };
2857
+ diffs.push(diff);
2858
+ }
2859
+ const counts = Object.fromEntries(chunkLV3O2BAT_cjs.DIFF_CATEGORIES.map((c) => [c, 0]));
2860
+ for (const diff of diffs) counts[diff.category] += 1;
2861
+ return {
2862
+ kind: kind2,
2863
+ fileStatus: after.content === null ? "not-written" : !after.changed ? "unchanged" : before.status === "loaded" ? "updated" : "created",
2864
+ level: cfg.checks.time.percentile.level,
2865
+ keys: diffs,
2866
+ counts
2867
+ };
2868
+ }
2869
+
2870
+ // src/core/thresholds/markdown.ts
2871
+ function cell(text) {
2872
+ return text.replace(/\\/gu, "\\\\").replace(/\|/gu, "\\|").replace(/\r?\n/gu, " ");
2873
+ }
2874
+ function code(key2) {
2875
+ return key2.includes("`") ? cell(key2) : `\`${cell(key2)}\``;
2876
+ }
2877
+ function formatThresholdsDiffMarkdown(diffs, paths) {
2878
+ const lines = ["# Thresholds diff"];
2879
+ diffs.forEach((diff, i) => {
2880
+ const path = paths[i] ?? `${diff.kind} thresholds`;
2881
+ lines.push(
2882
+ "",
2883
+ `## ${cell(path)} (${diff.fileStatus === "not-written" ? "not written" : diff.fileStatus})`,
2884
+ "",
2885
+ chunkLV3O2BAT_cjs.diffCountsText(diff)
2886
+ );
2887
+ const listed = diff.keys.filter((k) => chunkLV3O2BAT_cjs.LISTED_CATEGORIES.has(k.category));
2888
+ if (listed.length > 0) {
2889
+ lines.push("", "| | Key | Before | After |", "|---|---|---|---|");
2890
+ for (const k of listed) {
2891
+ const before = chunkLV3O2BAT_cjs.diffValuesText(k, "before", diff.level, " \xB7 ");
2892
+ const after = chunkLV3O2BAT_cjs.diffValuesText(k, "after", diff.level, " \xB7 ");
2893
+ lines.push(`| ${chunkLV3O2BAT_cjs.diffMarker(k)} | ${code(k.key)} | ${cell(before)} | ${cell(after)} |`);
2894
+ }
2895
+ }
2896
+ const expired = diff.keys.filter((k) => k.muted?.expired === true);
2897
+ if (expired.length > 0) {
2898
+ lines.push("");
2899
+ for (const k of expired) {
2900
+ lines.push(`- ${code(k.key)} muted (expired ${k.muted?.until ?? ""})`);
2901
+ }
2902
+ }
2903
+ const large = listed.filter((k) => k.changes.some((c) => c.large === true)).length;
2904
+ if (large > 0) {
2905
+ lines.push(
2906
+ "",
2907
+ `Entries marked with ! loosened a time limit by a large step; check that they do not accept a regression.`
2908
+ );
2909
+ }
2910
+ });
2911
+ return `${lines.join("\n")}
2912
+ `;
2913
+ }
2914
+
2915
+ // src/console/text.ts
2916
+ function compareText5(a, b) {
2917
+ return a < b ? -1 : a > b ? 1 : 0;
2918
+ }
2919
+ function plural2(n, word, many = `${word}s`) {
2920
+ return `${n} ${n === 1 ? word : many}`;
2921
+ }
2922
+ function truncateMiddle(text, width) {
2923
+ const chars = Array.from(text);
2924
+ if (chars.length <= width) return text;
2925
+ if (width <= 1) return "\u2026".slice(0, width);
2926
+ const head = Math.ceil((width - 1) / 2);
2927
+ const tail = width - 1 - head;
2928
+ return `${chars.slice(0, head).join("")}\u2026${tail === 0 ? "" : chars.slice(-tail).join("")}`;
2929
+ }
2930
+ function textWidth(text) {
2931
+ return Array.from(text).length;
2932
+ }
2933
+ function padEnd(text, width) {
2934
+ return text + " ".repeat(Math.max(0, width - textWidth(text)));
2935
+ }
2936
+ function padStart(text, width) {
2937
+ return " ".repeat(Math.max(0, width - textWidth(text))) + text;
2938
+ }
2939
+
2940
+ // src/console/summary.ts
2941
+ var MAX_WARNINGS = 10;
2942
+ var MAX_VIOLATION_ROWS = 20;
2943
+ var MAX_SLOWEST_LINES = 5;
2944
+ var MIN_KEY_WIDTH = 30;
2945
+ var KINDS4 = ["api", "custom"];
2946
+ var RULE_ORDER = [
2947
+ "median",
2948
+ "percentile",
2949
+ "p99",
2950
+ "apdex",
2951
+ "wilson",
2952
+ "errors"
2953
+ ];
2954
+ var TIME_RULES2 = /* @__PURE__ */ new Set([
2955
+ "median",
2956
+ "percentile",
2957
+ "p99"
2958
+ ]);
2959
+ var ANSI = { red: "\x1B[31m", yellow: "\x1B[33m", green: "\x1B[32m", bold: "\x1B[1m" };
2960
+ var RESET = "\x1B[0m";
2961
+ function exceedance(check2) {
2962
+ if (check2.rule === "apdex") return check2.actual === 0 ? Infinity : check2.limit / check2.actual;
2963
+ return check2.limit === 0 ? Infinity : check2.actual / check2.limit;
2964
+ }
2965
+ function overText(check2) {
2966
+ const r = exceedance(check2);
2967
+ if (!Number.isFinite(r)) return ">999%";
2968
+ const over = Math.round((r - 1) * 100);
2969
+ return over > 999 ? ">999%" : `+${over}%`;
2970
+ }
2971
+ function violations(report) {
2972
+ const list2 = [];
2973
+ for (const kind2 of KINDS4) {
2974
+ const aggregates = kind2 === "api" ? report.endpoints : report.custom;
2975
+ for (const [key2, aggregate2] of Object.entries(aggregates)) {
2976
+ for (const check2 of aggregate2.evaluation.checks) {
2977
+ if (!check2.passed) {
2978
+ list2.push({ kind: kind2, key: key2, check: check2, evaluation: aggregate2.evaluation, r: exceedance(check2) });
2979
+ }
2980
+ }
2981
+ }
2982
+ }
2983
+ return list2.sort(
2984
+ (a, b) => Number(b.check.blocking) - Number(a.check.blocking) || (a.r === b.r ? 0 : b.r > a.r ? 1 : -1) || KINDS4.indexOf(a.kind) - KINDS4.indexOf(b.kind) || compareText5(a.key, b.key) || RULE_ORDER.indexOf(a.check.rule) - RULE_ORDER.indexOf(b.check.rule)
2985
+ );
2986
+ }
2987
+ function isMuted(evaluation) {
2988
+ return evaluation.muted !== null && !evaluation.muted.expired;
2989
+ }
2990
+ function header(report) {
2991
+ const t = report.tests;
2992
+ const executions = t.expected + t.unexpected + t.flaky;
2993
+ const details2 = [`${t.expected} passed`, `${t.unexpected} failed`];
2994
+ if (t.flaky > 0) details2.push(`${t.flaky} flaky`);
2995
+ if (t.skipped > 0) details2.push(`${t.skipped} skipped`);
2996
+ const parts = [report.tool.name, `mode: ${report.mode}`];
2997
+ if (report.env !== null) parts.push(`env: ${report.env}`);
2998
+ parts.push(`${plural2(executions, "test")} (${details2.join(", ")})`);
2999
+ const ci = report.ci;
3000
+ if (ci !== null && (ci.branch !== null || ci.commit !== null)) {
3001
+ const commit = ci.commit === null ? "" : `@${ci.commit.slice(0, 7)}`;
3002
+ parts.push(`${ci.branch ?? ""}${commit}`);
3003
+ }
3004
+ return parts.join(" \xB7 ");
3005
+ }
3006
+ function issueLines(title, issues, limit, marker, more) {
3007
+ if (issues.length === 0) return [];
3008
+ const lines = [title];
3009
+ for (const issue2 of issues.slice(0, limit)) {
3010
+ const times = issue2.count !== void 0 && issue2.count > 1 ? ` (\xD7${issue2.count})` : "";
3011
+ lines.push(` ${marker} ${issue2.code}: ${issue2.message}${times}`);
3012
+ if (issue2.hint !== void 0) lines.push(` Hint: ${issue2.hint}`);
3013
+ }
3014
+ if (issues.length > limit) {
3015
+ lines.push(` \u2026 and ${issues.length - limit} more ${more} (see report)`);
3016
+ }
3017
+ return [...lines, ""];
3018
+ }
3019
+ var LABEL_WIDTH = "Endpoints: ".length;
3020
+ function counterLines(report) {
3021
+ const counts = report.evaluation.counts;
3022
+ const shown = KINDS4.filter(
3023
+ (kind2) => kind2 === "api" || counts.custom.keys > 0 || counts.custom.unseenThresholdEntries > 0
3024
+ );
3025
+ const columns = [
3026
+ { label: "keys", value: (k) => counts[k].keys },
3027
+ { label: "from file", value: (k) => counts[k].fromFile },
3028
+ { label: "default", value: (k) => counts[k].fromDefaults },
3029
+ { label: "too few samples", value: (k) => counts[k].tooFewSamples },
3030
+ { label: "median only", value: (k) => counts[k].medianOnly },
3031
+ { label: "unseen entries", value: (k) => counts[k].unseenThresholdEntries, optional: true },
3032
+ {
3033
+ label: "not evaluated",
3034
+ value: (k) => counts[k].notEvaluated - counts[k].tooFewSamples,
3035
+ optional: true
3036
+ }
3037
+ ];
3038
+ const used = columns.filter((c) => !c.optional || shown.some((k) => c.value(k) > 0));
3039
+ const widths = used.map((c) => Math.max(...shown.map((k) => String(c.value(k)).length)));
3040
+ return shown.map((kind2) => {
3041
+ const label = padEnd(kind2 === "api" ? "Endpoints:" : "Custom:", LABEL_WIDTH);
3042
+ const cells = used.flatMap((c, i) => {
3043
+ const value = c.value(kind2);
3044
+ if (c.optional && value === 0) return [];
3045
+ const label2 = c.label === "keys" && value === 1 ? "key" : c.label;
3046
+ return [`${padStart(String(value), widths[i] ?? 0)} ${label2}`];
3047
+ });
3048
+ return label + cells.join(" \xB7 ");
3049
+ });
3050
+ }
3051
+ function mutedLines(report) {
3052
+ const lines = [];
3053
+ for (const kind2 of KINDS4) {
3054
+ const aggregates = kind2 === "api" ? report.endpoints : report.custom;
3055
+ for (const key2 of Object.keys(aggregates).sort(compareText5)) {
3056
+ const muted = aggregates[key2]?.evaluation.muted;
3057
+ if (muted === void 0 || muted === null || muted.expired) continue;
3058
+ const label = lines.length === 0 ? "Muted:" : "";
3059
+ lines.push(`${padEnd(label, LABEL_WIDTH)}${key2} until ${muted.until} \u2014 "${muted.note}"`);
3060
+ }
3061
+ }
3062
+ return lines;
3063
+ }
3064
+ function formatTime(ms2) {
3065
+ return `${Math.round(ms2)} ms`;
3066
+ }
3067
+ function formatActual(check2) {
3068
+ if (TIME_RULES2.has(check2.rule)) return formatTime(check2.actual);
3069
+ const observed = check2.observed === null ? "" : ` (${check2.observed.toFixed(3)})`;
3070
+ return `${check2.actual.toFixed(3)}${observed}`;
3071
+ }
3072
+ function formatLimit(check2) {
3073
+ return TIME_RULES2.has(check2.rule) ? formatTime(check2.limit) : check2.limit.toFixed(3);
3074
+ }
3075
+ function tableLines(report, list2, width, paint) {
3076
+ const level = report.config.checks?.time?.percentile?.level ?? "percentile";
3077
+ const shown = list2.slice(0, MAX_VIOLATION_ROWS);
3078
+ const rows = shown.map((v) => ({
3079
+ marker: v.check.blocking ? "\u2716" : "!",
3080
+ kind: v.kind,
3081
+ key: v.key,
3082
+ rule: v.check.rule === "percentile" ? level : v.check.rule,
3083
+ actual: formatActual(v.check),
3084
+ limit: formatLimit(v.check),
3085
+ over: overText(v.check),
3086
+ n: String(v.check.n),
3087
+ src: v.evaluation.thresholdSource,
3088
+ flag: [v.check.hardLimitExceeded ? "HARD" : "", isMuted(v.evaluation) ? "MUTED" : ""].filter((f) => f !== "").join(" ")
3089
+ }));
3090
+ const head = {
3091
+ marker: " ",
3092
+ kind: "kind",
3093
+ key: "key",
3094
+ rule: "rule",
3095
+ actual: "actual",
3096
+ limit: "limit",
3097
+ over: "over",
3098
+ n: "n",
3099
+ src: "src",
3100
+ flag: "flag"
3101
+ };
3102
+ const all = [head, ...rows];
3103
+ const w = (field2) => Math.max(...all.map((r) => textWidth(r[field2])));
3104
+ const widths = {
3105
+ kind: w("kind"),
3106
+ rule: w("rule"),
3107
+ actual: w("actual"),
3108
+ limit: w("limit"),
3109
+ over: w("over"),
3110
+ n: w("n"),
3111
+ src: w("src"),
3112
+ flag: w("flag")
3113
+ };
3114
+ const fixed = 4 + widths.kind + widths.rule + widths.actual + widths.limit + widths.over + widths.n + widths.src + widths.flag + 2 * 8;
3115
+ const keyWidth = Math.max(MIN_KEY_WIDTH, Math.min(width - fixed, w("key")));
3116
+ const line = (r, isHead) => {
3117
+ const marker = isHead || r.marker === " " ? r.marker : paint(r.marker, r.marker === "\u2716" ? "red" : "yellow");
3118
+ const flag = r.flag.includes("HARD") && !isHead ? paint(r.flag, "red") : r.flag;
3119
+ return [
3120
+ ` ${marker} ${padEnd(r.kind, widths.kind)}`,
3121
+ padEnd(truncateMiddle(r.key, keyWidth), keyWidth),
3122
+ padEnd(r.rule, widths.rule),
3123
+ padStart(r.actual, widths.actual),
3124
+ padStart(r.limit, widths.limit),
3125
+ padStart(r.over, widths.over),
3126
+ padStart(r.n, widths.n),
3127
+ padEnd(r.src, widths.src),
3128
+ flag
3129
+ ].join(" ").trimEnd();
3130
+ };
3131
+ const lines = [line(head, true), ...rows.map((r) => line(r, false))];
3132
+ if (list2.length > shown.length) {
3133
+ lines.push(` \u2026 and ${list2.length - shown.length} more violations (see report)`);
3134
+ }
3135
+ return lines;
3136
+ }
3137
+ function slowestLines(report, list2) {
3138
+ const seen = /* @__PURE__ */ new Set();
3139
+ const lines = [];
3140
+ for (const v of list2) {
3141
+ if (!v.check.blocking || lines.length >= MAX_SLOWEST_LINES) continue;
3142
+ const id = `${v.kind}\0${v.key}`;
3143
+ if (seen.has(id)) continue;
3144
+ seen.add(id);
3145
+ const aggregate2 = (v.kind === "api" ? report.endpoints : report.custom)[v.key];
3146
+ const slowest = aggregate2?.slowest[0];
3147
+ if (slowest === void 0) continue;
3148
+ const t = slowest.test;
3149
+ lines.push(
3150
+ ` slowest: ${v.key} \u2014 ${formatTime(slowest.duration)} in "${t.title}" (${t.file}:${t.line})`
3151
+ );
3152
+ }
3153
+ return lines;
3154
+ }
3155
+ function resultLine(report, paint) {
3156
+ const counts = report.evaluation.counts;
3157
+ const sum = (field2) => counts.api[field2] + counts.custom[field2];
3158
+ const gate = report.config.gate;
3159
+ const policy = gate?.warnOnly === true ? " (gate.warnOnly)" : gate?.tolerance === void 0 ? "" : ` (tolerance: ${gate.tolerance})`;
3160
+ let word;
3161
+ let style;
3162
+ let reason;
3163
+ const status = report.evaluation.status;
3164
+ if (report.toolErrors.length > 0 || status === "error") {
3165
+ word = "ERROR";
3166
+ style = "red";
3167
+ reason = `${plural2(report.toolErrors.length, "tool error")}; the result is not trustworthy`;
3168
+ } else if (status === "failed") {
3169
+ word = "FAILED";
3170
+ style = "red";
3171
+ reason = `${plural2(sum("blockingViolations"), "blocking violation")}${policy}`;
3172
+ } else if (status === "warned") {
3173
+ word = "PASSED WITH WARNINGS";
3174
+ style = "yellow";
3175
+ reason = `${plural2(sum("violations"), "key")} with violations, none blocking${policy}`;
3176
+ } else {
3177
+ word = "PASSED";
3178
+ style = "green";
3179
+ reason = `no violations in ${plural2(sum("keys") - sum("notEvaluated"), "evaluated key")}`;
3180
+ }
3181
+ const informational = report.mode === "thresholds" ? " (informational, gate disabled)" : "";
3182
+ return `${paint(word, style)}: ${reason}${informational}`;
3183
+ }
3184
+ function toSlash(path) {
3185
+ return path.replace(/\\/gu, "/");
3186
+ }
3187
+ function rootOf(path) {
3188
+ const drive = /^[A-Za-z]:\//u.exec(path);
3189
+ if (drive !== null) return drive[0];
3190
+ return path.startsWith("/") ? "/" : "";
3191
+ }
3192
+ function segments(path) {
3193
+ const result = [];
3194
+ for (const part of path.slice(rootOf(path).length).split("/")) {
3195
+ if (part === "" || part === ".") continue;
3196
+ if (part === ".." && result.length > 0 && result[result.length - 1] !== "..") result.pop();
3197
+ else result.push(part);
3198
+ }
3199
+ return result;
3200
+ }
3201
+ function relativePath(from, to) {
3202
+ const a = toSlash(from);
3203
+ const b = toSlash(to);
3204
+ if (rootOf(a) === "" || rootOf(a) !== rootOf(b)) return b;
3205
+ const x = segments(a);
3206
+ const y = segments(b);
3207
+ let common = 0;
3208
+ while (common < x.length && common < y.length && x[common] === y[common]) common += 1;
3209
+ const parts = [...x.slice(common).map(() => ".."), ...y.slice(common)];
3210
+ return parts.length === 0 ? "." : parts.join("/");
3211
+ }
3212
+ function resolvePath2(base, path) {
3213
+ const p = toSlash(path);
3214
+ if (rootOf(p) !== "") return rootOf(p) + segments(p).join("/");
3215
+ const b = toSlash(base);
3216
+ return rootOf(b) + segments(`${b}/${p}`).join("/");
3217
+ }
3218
+ function reportLine(report, cwd, html2) {
3219
+ const options = report.config.report;
3220
+ if (options?.dir === void 0) return [];
3221
+ const dir = resolvePath2(report.configDir, options.dir);
3222
+ const withHtml = html2 ?? options.html !== false;
3223
+ const files = [...withHtml ? ["report.html"] : [], "report.json"];
3224
+ return [`Report: ${files.map((f) => relativePath(cwd, `${dir}/${f}`)).join(" \xB7 ")}`];
3225
+ }
3226
+ function formatSummary(report, opts) {
3227
+ const paint = (text, style) => opts.color ? `${ANSI[style]}${text}${RESET}` : text;
3228
+ const list2 = violations(report);
3229
+ const lines = [header(report), ""];
3230
+ lines.push(...issueLines("Errors:", report.toolErrors, Infinity, paint("\u2716", "red"), "errors"));
3231
+ lines.push(
3232
+ ...issueLines("Warnings:", report.warnings, MAX_WARNINGS, paint("!", "yellow"), "warnings")
3233
+ );
3234
+ lines.push(...counterLines(report), ...mutedLines(report), "");
3235
+ if (list2.length > 0) {
3236
+ lines.push(...tableLines(report, list2, opts.width, paint));
3237
+ const slowest = slowestLines(report, list2);
3238
+ if (slowest.length > 0) lines.push("", ...slowest);
3239
+ lines.push("");
3240
+ }
3241
+ lines.push(resultLine(report, paint), ...reportLine(report, opts.cwd, opts.html));
3242
+ return `${lines.join("\n")}
3243
+ `;
3244
+ }
3245
+
3246
+ // src/console/thresholds-diff.ts
3247
+ var MAX_DIFF_ROWS = 30;
3248
+ var MIN_KEY_WIDTH2 = 30;
3249
+ var ANSI2 = { red: "\x1B[31m", yellow: "\x1B[33m", green: "\x1B[32m" };
3250
+ var RESET2 = "\x1B[0m";
3251
+ var MARKER_STYLE = {
3252
+ "+": "green",
3253
+ "-": "red",
3254
+ "\u2191": "yellow",
3255
+ "\u2193": "green",
3256
+ "\xB1": "yellow"
3257
+ };
3258
+ function fileLines(diff, path, opts, paint) {
3259
+ const lines = [`Thresholds: ${path} (${fileStatusText(diff)})`];
3260
+ const listed = diff.keys.filter((k) => chunkLV3O2BAT_cjs.LISTED_CATEGORIES.has(k.category));
3261
+ const expired = diff.keys.filter((k) => k.muted?.expired === true);
3262
+ if (diff.fileStatus !== "unchanged") lines.push(` ${chunkLV3O2BAT_cjs.diffCountsText(diff)}`);
3263
+ if (listed.length > 0) {
3264
+ const shown = listed.slice(0, MAX_DIFF_ROWS);
3265
+ const rows = shown.map((k) => ({
3266
+ marker: chunkLV3O2BAT_cjs.diffMarker(k),
3267
+ key: k.key,
3268
+ change: chunkLV3O2BAT_cjs.diffChangeText(k, diff.level, " ") + mutedSuffix(k)
3269
+ }));
3270
+ const markerWidth = Math.max(...rows.map((r) => textWidth(r.marker)));
3271
+ const changeWidth = Math.max(...rows.map((r) => textWidth(r.change)));
3272
+ const longest = Math.max(...rows.map((r) => textWidth(r.key)));
3273
+ const rest = opts.width - 2 - markerWidth - 1 - 2 - changeWidth;
3274
+ const keyWidth = Math.max(MIN_KEY_WIDTH2, Math.min(longest, rest));
3275
+ lines.push("");
3276
+ for (const r of rows) {
3277
+ const head = r.marker.slice(0, 1);
3278
+ const style = MARKER_STYLE[head] ?? "yellow";
3279
+ const marker = paint(head, style) + (r.marker.length > 1 ? paint(r.marker.slice(1), "red") : "");
3280
+ const pad2 = " ".repeat(markerWidth - textWidth(r.marker));
3281
+ lines.push(
3282
+ ` ${marker}${pad2} ${padEnd(truncateMiddle(r.key, keyWidth), keyWidth)} ${r.change}`.trimEnd()
3283
+ );
3284
+ }
3285
+ if (listed.length > shown.length) {
3286
+ lines.push(` \u2026 and ${listed.length - shown.length} more`);
3287
+ }
3288
+ }
3289
+ if (expired.length > 0) {
3290
+ lines.push("");
3291
+ for (const k of expired) {
3292
+ lines.push(` ${paint("!", "yellow")} ${k.key} muted (expired ${k.muted?.until ?? ""})`);
3293
+ }
3294
+ }
3295
+ const unseen = diff.counts.unseen;
3296
+ if (unseen > 0) {
3297
+ const entries = plural2(unseen, "entry", "entries");
3298
+ const verb = unseen === 1 ? "was" : "were";
3299
+ lines.push(
3300
+ "",
3301
+ opts.prune ? ` ${entries} not seen in this run ${verb} kept because ${unseen === 1 ? "it is" : "they are"} locked.` : ` ${entries} ${verb} not seen in this run and ${verb} kept. Use --prune to remove them.`
3302
+ );
3303
+ }
3304
+ return lines;
3305
+ }
3306
+ function fileStatusText(diff) {
3307
+ return diff.fileStatus === "not-written" ? "not written" : diff.fileStatus;
3308
+ }
3309
+ function mutedSuffix(k) {
3310
+ return k.muted !== void 0 && !k.muted.expired ? ` (muted until ${k.muted.until})` : "";
3311
+ }
3312
+ function formatThresholdsDiff(diffs, opts) {
3313
+ const paint = (text, style) => opts.color ? `${ANSI2[style]}${text}${RESET2}` : text;
3314
+ const lines = [];
3315
+ diffs.forEach((diff, i) => {
3316
+ lines.push(...fileLines(diff, opts.paths[i] ?? `${diff.kind} thresholds`, opts, paint));
3317
+ });
3318
+ const written = diffs.some((d) => d.fileStatus === "created" || d.fileStatus === "updated");
3319
+ lines.push("");
3320
+ lines.push(
3321
+ written ? "Review the changes and commit the thresholds files." : "The thresholds files are up to date."
3322
+ );
3323
+ if (opts.diffPath !== null) lines.push(`Diff: ${opts.diffPath}`);
3324
+ return `${lines.join("\n")}
3325
+ `;
3326
+ }
3327
+
3328
+ // src/html/escape.ts
3329
+ var SAFE = /* @__PURE__ */ Symbol("SafeHtml");
3330
+ var ESCAPES = {
3331
+ "&": "&amp;",
3332
+ "<": "&lt;",
3333
+ ">": "&gt;",
3334
+ '"': "&quot;",
3335
+ "'": "&#39;"
3336
+ };
3337
+ function escapeHtml(value) {
3338
+ return value.replace(/[&<>"']/gu, (c) => ESCAPES[c] ?? c);
3339
+ }
3340
+ function isSafe(value) {
3341
+ return typeof value === "object" && value !== null && SAFE in value;
3342
+ }
3343
+ function trustedHtml(text) {
3344
+ return { [SAFE]: true, text };
3345
+ }
3346
+ function render(value) {
3347
+ if (value === null || value === void 0 || value === false) return "";
3348
+ if (typeof value === "string") return escapeHtml(value);
3349
+ if (typeof value === "number") return escapeHtml(String(value));
3350
+ if (isSafe(value)) return value.text;
3351
+ return value.map(render).join("");
3352
+ }
3353
+ function html(strings, ...values) {
3354
+ let text = strings[0] ?? "";
3355
+ for (let i = 0; i < values.length; i++) {
3356
+ text += render(values[i]) + (strings[i + 1] ?? "");
3357
+ }
3358
+ return trustedHtml(text);
3359
+ }
3360
+
3361
+ // src/html/format.ts
3362
+ function formatMs(value) {
3363
+ if (value >= 1e4) return `${(Math.round(value / 100) / 10).toFixed(1)} s`;
3364
+ if (value < 10) return `${(Math.round(value * 10) / 10).toFixed(1)} ms`;
3365
+ return `${Math.round(value)} ms`;
3366
+ }
3367
+ function formatRatio(value) {
3368
+ return value.toFixed(3);
3369
+ }
3370
+ function pad(n) {
3371
+ return String(n).padStart(2, "0");
3372
+ }
3373
+ function formatDate(iso) {
3374
+ const time = Date.parse(iso);
3375
+ if (Number.isNaN(time)) return iso;
3376
+ const d = new Date(time);
3377
+ return `${String(d.getUTCFullYear())}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`;
3378
+ }
3379
+ function formatRunDuration(startedAt, finishedAt) {
3380
+ const ms2 = Date.parse(finishedAt) - Date.parse(startedAt);
3381
+ if (!Number.isFinite(ms2) || ms2 < 0) return "\u2014";
3382
+ const total = Math.round(ms2 / 1e3);
3383
+ const h = Math.floor(total / 3600);
3384
+ const min = Math.floor(total % 3600 / 60);
3385
+ const s = total % 60;
3386
+ if (h > 0) return `${String(h)} h ${String(min)} min ${String(s)} s`;
3387
+ if (min > 0) return `${String(min)} min ${String(s)} s`;
3388
+ return `${String(s)} s`;
3389
+ }
3390
+ function plural3(n, word, many = `${word}s`) {
3391
+ return `${String(n)} ${n === 1 ? word : many}`;
3392
+ }
3393
+ function truncateMiddle2(text, max) {
3394
+ const points = Array.from(text);
3395
+ if (points.length <= max) return text;
3396
+ const keep = max - 1;
3397
+ const head = Math.ceil(keep / 2);
3398
+ return `${points.slice(0, head).join("")}\u2026${points.slice(points.length - (keep - head)).join("")}`;
3399
+ }
3400
+
3401
+ // src/html/bar.ts
3402
+ var WIDTH = 640;
3403
+ var LEFT = 24;
3404
+ var RIGHT = 616;
3405
+ var ROW = 13;
3406
+ var CHAR = 6.2;
3407
+ var GAP = 8;
3408
+ function coordinate(value, axisMax) {
3409
+ return Math.round((LEFT + (RIGHT - LEFT) * value / axisMax) * 10) / 10;
3410
+ }
3411
+ function merge(marks) {
3412
+ const out = [];
3413
+ for (const mark of marks) {
3414
+ const same = out.find((m) => m.value === mark.value);
3415
+ if (same === void 0) out.push({ ...mark });
3416
+ else same.label = `${same.label}, ${mark.label}`;
3417
+ }
3418
+ return out;
3419
+ }
3420
+ function place(marks, axisMax) {
3421
+ const rowsEnd = [];
3422
+ return [...marks].sort((a, b) => a.value - b.value).map((mark) => {
3423
+ const x = coordinate(mark.value, axisMax);
3424
+ const text = `${mark.label} ${formatMs(mark.value)}`;
3425
+ const width = text.length * CHAR;
3426
+ const anchor = x - width / 2 < 0 ? "start" : x + width / 2 > WIDTH ? "end" : "middle";
3427
+ const from = anchor === "start" ? x : anchor === "end" ? x - width : x - width / 2;
3428
+ let row = rowsEnd.findIndex((end) => end + GAP <= from);
3429
+ if (row === -1) row = rowsEnd.length;
3430
+ rowsEnd[row] = from + width;
3431
+ return { text, x, row, anchor };
3432
+ });
3433
+ }
3434
+ function percentileBar(stats2, limits, level) {
3435
+ if (stats2 === null) return null;
3436
+ const p = stats2.percentiles;
3437
+ const markers = [];
3438
+ for (const name of ["p50", "p90", "p95", "p99"]) {
3439
+ const value = p[name];
3440
+ if (value !== void 0) markers.push({ label: name, value });
3441
+ }
3442
+ markers.push({ label: "max", value: stats2.max });
3443
+ const lines = [];
3444
+ if (limits.t !== null) lines.push({ label: "T", value: limits.t });
3445
+ lines.push({ label: "median limit", value: limits.median });
3446
+ lines.push({ label: `${level} limit`, value: limits.percentile });
3447
+ lines.push({ label: "p99 limit", value: limits.p99 });
3448
+ const axisMax = Math.max(stats2.max, limits.p99) > 0 ? Math.max(stats2.max, limits.p99) : 1;
3449
+ const top = place(merge(markers), axisMax);
3450
+ const bottom = place(merge(lines), axisMax);
3451
+ const topRows = Math.max(1, ...top.map((m) => m.row + 1));
3452
+ const bottomRows = Math.max(1, ...bottom.map((m) => m.row + 1));
3453
+ const axisY = 12 + ROW * topRows;
3454
+ const height = axisY + 22 + ROW * bottomRows + 14;
3455
+ const markerSvg = top.map((m) => {
3456
+ const y = axisY - 12 - ROW * m.row;
3457
+ return html`<line class="bar-mark" x1="${m.x}" y1="${axisY - 8}" x2="${m.x}" y2="${axisY + 8}"/><text x="${m.x}" y="${y}" text-anchor="${m.anchor}">${m.text}</text>`;
3458
+ });
3459
+ const lineSvg = bottom.map((m) => {
3460
+ const y = axisY + 24 + ROW * m.row;
3461
+ return html`<line class="bar-limit" x1="${m.x}" y1="${axisY - 4}" x2="${m.x}" y2="${y - 10}"/><text class="bar-limit-text" x="${m.x}" y="${y}" text-anchor="${m.anchor}">${m.text}</text>`;
3462
+ });
3463
+ const p50 = p["p50"];
3464
+ const p99 = p["p99"];
3465
+ let range = null;
3466
+ if (p50 !== void 0 && p99 !== void 0) {
3467
+ const x1 = coordinate(p50, axisMax);
3468
+ const width = Math.max(0, Math.round((coordinate(p99, axisMax) - x1) * 10) / 10);
3469
+ range = html`<rect class="bar-range" x="${x1}" y="${axisY - 4}" width="${width}" height="8"/>`;
3470
+ }
3471
+ const describe = [...markers, ...lines].map((m) => `${m.label} ${formatMs(m.value)}`).join(", ");
3472
+ const label = `Percentiles and limits: ${describe}`;
3473
+ return html`<svg class="bar" viewBox="0 0 ${WIDTH} ${height}" role="img" aria-label="${label}"><line class="bar-axis" x1="${LEFT}" y1="${axisY}" x2="${RIGHT}" y2="${axisY}"/>${range}${lineSvg}${markerSvg}<text class="bar-scale" x="${LEFT}" y="${height - 2}">0</text><text class="bar-scale" x="${RIGHT}" y="${height - 2}" text-anchor="end">${formatMs(axisMax)}</text></svg>`;
3474
+ }
3475
+
3476
+ // src/html/data.ts
3477
+ function withoutDurations(aggregates) {
3478
+ const out = {};
3479
+ for (const key2 of Object.keys(aggregates).sort()) {
3480
+ const { samples, ...rest } = aggregates[key2];
3481
+ out[key2] = {
3482
+ ...rest,
3483
+ samples: { retained: samples.durations.length, sampled: samples.sampled }
3484
+ };
3485
+ }
3486
+ return out;
3487
+ }
3488
+ function toHtmlReportData(report) {
3489
+ return {
3490
+ ...report,
3491
+ endpoints: withoutDurations(report.endpoints),
3492
+ custom: withoutDurations(report.custom)
3493
+ };
3494
+ }
3495
+ function stable(value, indent, depth) {
3496
+ if (value === null || typeof value !== "object") {
3497
+ return JSON.stringify(value) ?? "null";
3498
+ }
3499
+ const inner = indent === null ? "" : depth + indent;
3500
+ const open = indent === null ? "" : `
3501
+ ${inner}`;
3502
+ const close = indent === null ? "" : `
3503
+ ${depth}`;
3504
+ const sep = indent === null ? "," : `,
3505
+ ${inner}`;
3506
+ if (Array.isArray(value)) {
3507
+ if (value.length === 0) return "[]";
3508
+ return `[${open}${value.map((v) => stable(v, indent, inner)).join(sep)}${close}]`;
3509
+ }
3510
+ const record2 = value;
3511
+ const keys = Object.keys(record2).filter((k) => record2[k] !== void 0).sort();
3512
+ if (keys.length === 0) return "{}";
3513
+ const colon = indent === null ? ":" : ": ";
3514
+ const entries = keys.map(
3515
+ (k) => `${JSON.stringify(k)}${colon}${stable(record2[k], indent, inner)}`
3516
+ );
3517
+ return `{${open}${entries.join(sep)}${close}}`;
3518
+ }
3519
+ function stableJson(value, indent = null) {
3520
+ return stable(value, indent, "");
3521
+ }
3522
+ function embeddedJson(data) {
3523
+ return stableJson(data).replaceAll("<", "\\u003c");
3524
+ }
3525
+
3526
+ // src/html/generated/assets.ts
3527
+ var STYLES = ':root{color-scheme:light dark;--bg: #ffffff;--fg: #1b1f24;--muted: #57606a;--border: #d0d7de;--panel: #f6f8fa;--ok: #116329;--warn: #7d4e00;--bad: #b3261e;--link: #0550ae;--mark: #1b1f24;--range: #9fb4cc}@media(prefers-color-scheme:dark){:root{--bg: #0d1117;--fg: #e6edf3;--muted: #9da7b3;--border: #3d444d;--panel: #161b22;--ok: #56d364;--warn: #e3b341;--bad: #ff8e88;--link: #79c0ff;--mark: #e6edf3;--range: #3b5070}}*{box-sizing:border-box}html{background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}body{margin:0;overflow-x:hidden}main,footer{max-width:1280px;margin:0 auto;padding:0 16px}h1{margin:0 0 12px;font-size:24px}h2{margin:32px 0 12px;font-size:19px;border-bottom:1px solid var(--border);padding-bottom:4px}h2.sub{border:0;font-size:15px;margin:16px 0 4px}h3{margin:0 0 4px;font-size:15px}h4{margin:12px 0 4px;font-size:14px}p{margin:4px 0}a{color:var(--link)}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px}pre{background:var(--panel);border:1px solid var(--border);padding:12px;overflow-x:auto}.page-header{padding-top:24px}.tool,.muted-text,.limit,.hint{color:var(--muted)}.meta{display:flex;flex-wrap:wrap;gap:4px 24px;margin:0}.meta dt{color:var(--muted);font-size:12px}.meta dd{margin:0;overflow-wrap:anywhere}.origins,.plain{margin:0;padding-left:20px}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.verdict{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}.card{border:1px solid var(--border);border-left-width:6px;border-radius:6px;padding:12px;background:var(--panel);color:var(--fg)}.card.ok{border-left-color:var(--ok)}.card.warn{border-left-color:var(--warn)}.card.bad{border-left-color:var(--bad)}.card .status{font-size:18px;font-weight:700;text-transform:uppercase}.card.ok .status{color:var(--ok)}.card.warn .status{color:var(--warn)}.card.bad .status{color:var(--bad)}.note{font-style:italic}.toolbar{margin-top:12px}.issues{list-style:none;padding:0;margin:0}.issues li{border-left:4px solid currentColor;padding:4px 12px;margin:8px 0}.issues li p{color:var(--fg)}.issues li p.hint{color:var(--muted)}.highlight{border:2px solid var(--bad);border-radius:6px;padding:0 12px 12px}.scroll{overflow-x:auto;max-width:100%}table{border-collapse:collapse;width:100%;margin:4px 0 12px}caption{text-align:left;color:var(--muted);padding:4px 0}th,td{border-bottom:1px solid var(--border);padding:4px 8px;text-align:left;vertical-align:top}thead th{background:var(--panel);white-space:nowrap}th[scope=row]{font-weight:400}.num{text-align:right;white-space:nowrap}table.keys th.key{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px;white-space:nowrap}th button{font:inherit;font-weight:700;color:inherit;background:none;border:0;padding:0;cursor:default}.js th button{cursor:pointer;text-decoration:underline dotted}.js th[aria-sort=ascending] button:after{content:" \u25B2"}.js th[aria-sort=descending] button:after{content:" \u25BC"}table.keys tr:first-child>td:first-of-type{white-space:nowrap}.details-row>td{padding-top:0}details>summary{cursor:pointer;color:var(--link)}.details-body{padding:4px 0 12px;max-width:960px}.full-key code,.url{overflow-wrap:anywhere;word-break:break-all}.facts{display:grid;grid-template-columns:max-content 1fr;gap:2px 16px;margin:8px 0}.facts div{display:contents}.facts dt{color:var(--muted)}.facts dd{margin:0}.slowest,.top-tests{margin:0;padding-left:20px}table.checks{width:auto}.bar{width:100%;max-width:640px;height:auto;display:block;margin:8px 0}.bar text{fill:var(--fg);font-size:11px}.bar .bar-limit-text{fill:var(--bad)}.bar-axis{stroke:var(--muted);stroke-width:1}.bar-range{fill:var(--range)}.bar-mark{stroke:var(--mark);stroke-width:2}.bar-limit{stroke:var(--bad);stroke-width:1.5;stroke-dasharray:4 3}.filters{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;margin:8px 0}.filters[hidden],[hidden]{display:none!important}input[type=search]{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--border);border-radius:4px;padding:2px 6px;margin-left:4px}#download{font:inherit;color:var(--fg);background:var(--panel);border:1px solid var(--border);border-radius:6px;padding:4px 12px;cursor:pointer}button:focus-visible,input:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid var(--link);outline-offset:2px}.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}footer{margin:40px auto 24px;color:var(--muted);border-top:1px solid var(--border);padding-top:12px}@media print{:root{color-scheme:light;--bg: #ffffff;--fg: #000000;--muted: #444444;--border: #bbbbbb;--panel: #ffffff;--ok: #0b5e20;--warn: #6a4200;--bad: #a1150e;--link: #000000;--mark: #000000;--range: #c8d3e0}.filters,.toolbar,th button:after{display:none!important}.scroll{overflow:visible}tbody,tr{break-inside:avoid}details[data-violation]::details-content{content-visibility:visible;display:block}}';
3528
+ var STYLES_SHA256 = "rMj6c+jgU9bq6OVZSVVT3M4IvsOeXLSFzdizre4Z7Bc=";
3529
+ var SCRIPT = `(()=>{const D=document.getElementById("report-data"),b=D?.textContent??'{"endpoints":{},"custom":{}}',C=JSON.parse(b);document.documentElement.classList.add("js");function H(e,a,d,f){if(e===void 0)return null;switch(a){case"result":return f;case"samples":return e.successCount;case"errors":return e.errorCount;case"p50":return e.stats?.percentiles.p50??null;case"percentile":return e.stats?.percentiles[d]??null;case"p99":return e.stats?.percentiles.p99??null;case"max":return e.stats?.max??null;case"ttfb":return e.ttfb?.p50??null;case"tests":return e.testCount;default:return null}}function T(e,a){return e<a?-1:e>a?1:0}function M(e){const a=e.dataset.kind==="custom"?"custom":"endpoints",d=e.dataset.percentile??"p95",f=C[a],m=Array.from(e.tBodies),v=Array.from(e.querySelectorAll("th[data-sort]"));let u=null;function w(r,o){const s=o==="ascending"?1:-1,l=m.map(t=>{const n=t.dataset.key??"",A=Number(t.dataset.group??"3");return{body:t,key:n,value:H(f[n],r,d,A)}});l.sort((t,n)=>{if(r!=="key"){if(t.value===null||n.value===null){if(t.value!==n.value)return t.value===null?1:-1}else if(t.value!==n.value)return(t.value-n.value)*s;return T(t.key,n.key)}return T(t.key,n.key)*s});for(const t of l)e.appendChild(t.body);for(const t of v)t.dataset.sort===r?t.setAttribute("aria-sort",o):t.removeAttribute("aria-sort")}for(const r of v){const o=r.dataset.sort??"key";r.querySelector("button")?.addEventListener("click",()=>{const s=o==="key"||o==="result"?"ascending":"descending",l=u!==null&&u.column===o?u.direction==="ascending"?"descending":"ascending":s;u={column:o,direction:l},w(o,l)})}const c=document.querySelector(\`[data-filters-for="\${e.id}"]\`);if(c===null)return;const g=c.querySelector('[data-filter="text"]'),L=c.querySelector('[data-filter="violations"]'),E=c.querySelector('[data-filter="not-evaluated"]'),k=c.querySelector("[data-count]");function h(){const r=(g?.value??"").toLowerCase();let o=0;for(const s of m){const l=(s.dataset.key??"").toLowerCase(),t=s.dataset.result??"",n=l.includes(r)&&!(L?.checked===!0&&t!=="fail")&&!(E?.checked===!0&&t==="not-evaluated");s.hidden=!n,n&&o++}k!==null&&(k.textContent=\`showing \${o} of \${m.length}\`)}for(const r of[g,L,E])r?.addEventListener("input",h),r?.addEventListener("change",h);c.hidden=!1}for(const e of Array.from(document.querySelectorAll("table.keys")))M(e);const p=document.getElementById("download"),y=document.getElementById("download-link");p instanceof HTMLButtonElement&&y instanceof HTMLAnchorElement&&(p.addEventListener("click",()=>{const e=URL.createObjectURL(new Blob([b],{type:"application/json"}));y.href=e,y.click(),setTimeout(()=>URL.revokeObjectURL(e),1e3)}),p.hidden=!1);let i=[];window.addEventListener("beforeprint",()=>{i=Array.from(document.querySelectorAll("details[data-violation]:not([open])"));for(const e of i)e.open=!0});window.addEventListener("afterprint",()=>{for(const e of i)e.open=!1;i=[]});})();`;
3530
+ var SCRIPT_SHA256 = "NczooZoEwk0CPgfuEFUbnRFp9bbi8jrYYzyk+WNBTEc=";
3531
+
3532
+ // src/html/render.ts
3533
+ var KEY_COLUMN_MAX = 80;
3534
+ var DEFAULT_PERCENTILE = "p95";
3535
+ var TIME_RULES3 = /* @__PURE__ */ new Set([
3536
+ "median",
3537
+ "percentile",
3538
+ "p99"
3539
+ ]);
3540
+ var DASH = "\u2014";
3541
+ function join2(...parts) {
3542
+ return html`${parts}`;
3543
+ }
3544
+ function percentileLevel(report) {
3545
+ return report.config.checks?.time?.percentile?.level ?? DEFAULT_PERCENTILE;
3546
+ }
3547
+ function isBlocking(evaluation) {
3548
+ return evaluation.result === "fail" && evaluation.checks.some((c) => c.blocking);
3549
+ }
3550
+ function rowGroup(evaluation) {
3551
+ if (evaluation.result === "fail") return isBlocking(evaluation) ? 0 : 1;
3552
+ return evaluation.result === "pass" ? 2 : 3;
3553
+ }
3554
+ function limitRatio(agg, level) {
3555
+ const value = agg.stats?.percentiles[level];
3556
+ if (value === void 0) return -Infinity;
3557
+ const limit = agg.evaluation.limits.percentile;
3558
+ if (limit === 0) return value === 0 ? 0 : Infinity;
3559
+ return value / limit;
3560
+ }
3561
+ function defaultOrder(aggregates, level) {
3562
+ const rows = Object.keys(aggregates).map((key2) => {
3563
+ const agg = aggregates[key2];
3564
+ return { key: key2, group: rowGroup(agg.evaluation), ratio: limitRatio(agg, level) };
3565
+ });
3566
+ rows.sort((a, b) => {
3567
+ if (a.group !== b.group) return a.group - b.group;
3568
+ if (a.ratio !== b.ratio) return a.ratio > b.ratio ? -1 : 1;
3569
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
3570
+ });
3571
+ return rows.map((r) => r.key);
3572
+ }
3573
+ function reasonText(reason) {
3574
+ switch (reason) {
3575
+ case "too-few-samples":
3576
+ return "too few samples";
3577
+ case "no-rules":
3578
+ return "no applicable rules";
3579
+ case "thresholds-error":
3580
+ return "thresholds file invalid";
3581
+ default:
3582
+ return null;
3583
+ }
3584
+ }
3585
+ function resultText(evaluation) {
3586
+ if (evaluation.result === "fail") return isBlocking(evaluation) ? "fail (blocking)" : "fail";
3587
+ return evaluation.result === "pass" ? "pass" : "not evaluated";
3588
+ }
3589
+ function resultClass(evaluation) {
3590
+ if (evaluation.result === "fail") return isBlocking(evaluation) ? "bad" : "warn";
3591
+ return evaluation.result === "pass" ? "ok" : "muted-text";
3592
+ }
3593
+ function mutedText(muted) {
3594
+ if (muted === null) return null;
3595
+ const until = muted.until.slice(0, 10);
3596
+ return muted.expired ? `mute expired ${until}` : `muted until ${until}`;
3597
+ }
3598
+ function ruleName(rule, level) {
3599
+ return rule === "percentile" ? level : rule;
3600
+ }
3601
+ function checkValue(check2, value) {
3602
+ return TIME_RULES3.has(check2.rule) ? formatMs(value) : formatRatio(value);
3603
+ }
3604
+ function lowestMinSamples(report) {
3605
+ const checks = report.config.checks;
3606
+ if (checks === void 0) return null;
3607
+ const rules = [
3608
+ ["median", checks.time?.median],
3609
+ [percentileLevel(report), checks.time?.percentile],
3610
+ ["p99", checks.time?.p99],
3611
+ ["apdex", checks.slowShare?.apdex],
3612
+ ["wilson", checks.slowShare?.wilson],
3613
+ ["errors", checks.errors]
3614
+ ];
3615
+ let best = null;
3616
+ for (const [rule, cfg] of rules) {
3617
+ if (cfg?.enabled === false || cfg?.minSamples === void 0) continue;
3618
+ if (best === null || cfg.minSamples < best.n) best = { rule, n: cfg.minSamples };
3619
+ }
3620
+ return best;
3621
+ }
3622
+ function buildLink(url) {
3623
+ if (url === null) return DASH;
3624
+ return /^https?:\/\//iu.test(url.trimStart()) ? html`<a href="${url}" rel="noopener noreferrer">${url}</a>` : html`<code>${url}</code>`;
3625
+ }
3626
+ function header2(report) {
3627
+ const { ci, host } = report;
3628
+ const items = [
3629
+ ["Run ID", html`<code>${report.runId}</code>`],
3630
+ ["Started", formatDate(report.startedAt)],
3631
+ ["Duration", formatRunDuration(report.startedAt, report.finishedAt)],
3632
+ ["Mode", report.mode],
3633
+ ["Environment", report.env ?? DASH],
3634
+ ["Playwright", report.playwright.version],
3635
+ ["Node.js", host.nodeVersion],
3636
+ ["System", `${host.platform} ${host.arch}`],
3637
+ [
3638
+ "CPU",
3639
+ `${host.cpuModel === "" ? "unknown" : host.cpuModel} (${plural3(host.cpuCount, "core")})`
3640
+ ]
3641
+ ];
3642
+ if (ci !== null) {
3643
+ items.push(
3644
+ ["CI", ci.provider],
3645
+ ["Commit", ci.commit === null ? DASH : html`<code>${ci.commit}</code>`],
3646
+ ["Branch", ci.branch ?? DASH],
3647
+ ["Build", buildLink(ci.buildUrl)]
3648
+ );
3649
+ }
3650
+ const origin = (o) => join2(
3651
+ html`<li><code>${o.origin}</code> `,
3652
+ o.label === "" ? html`<span class="muted-text">(base)</span>` : html`label <code>${o.label}</code>`,
3653
+ html` · ${plural3(o.requestCount, "request")}</li>`
3654
+ );
3655
+ return join2(
3656
+ html`<header class="page-header">`,
3657
+ html`<p class="tool">${report.tool.name} v${report.tool.version}</p>`,
3658
+ html`<h1>Performance report</h1>`,
3659
+ html`<dl class="meta">${items.map(([k, v]) => html`<div><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>`,
3660
+ report.origins.length === 0 ? null : html`<h2 class="sub">Measured origins</h2><ul class="origins">${report.origins.map(origin)}</ul>`,
3661
+ html`</header>`
3662
+ );
3663
+ }
3664
+ function card(title, cls, status, ...notes) {
3665
+ return html`<div class="card ${cls}"><h3>${title}</h3><p class="status">${status}</p>${notes}</div>`;
3666
+ }
3667
+ function verdict(report) {
3668
+ const t = report.tests;
3669
+ const untrustworthy = report.toolErrors.some((i) => i.code === "TESTS_FAILED_TOO_MANY");
3670
+ const perf = report.evaluation.status;
3671
+ const errors = report.toolErrors.length;
3672
+ return join2(
3673
+ html`<section aria-labelledby="verdict-h"><h2 id="verdict-h">Verdict</h2><div class="verdict">`,
3674
+ card(
3675
+ "Tests",
3676
+ t.status === "passed" ? "ok" : "warn",
3677
+ t.status === "timedout" ? "timed out" : t.status,
3678
+ html`<p>${t.expected} expected · ${t.unexpected} unexpected · ${t.flaky} flaky · ${t.skipped} skipped</p>`,
3679
+ untrustworthy ? html`<p class="note">Too many tests failed: the performance result is not trustworthy.</p>` : t.unexpected > 0 ? html`<p class="note">Failed tests are information, not the performance verdict.</p>` : null
3680
+ ),
3681
+ card(
3682
+ "Performance",
3683
+ perf === "passed" ? "ok" : perf === "warned" ? "warn" : "bad",
3684
+ perf,
3685
+ report.evaluation.gateEnabled ? null : html`<p class="note">gate off (thresholds mode)</p>`
3686
+ ),
3687
+ card("Tool errors", errors === 0 ? "ok" : "bad", errors === 0 ? "none" : String(errors)),
3688
+ html`</div></section>`
3689
+ );
3690
+ }
3691
+ function mutedSection(report) {
3692
+ const rows = [];
3693
+ let active = 0;
3694
+ for (const [kind2, map] of [
3695
+ ["API", report.endpoints],
3696
+ ["Custom", report.custom]
3697
+ ]) {
3698
+ for (const key2 of Object.keys(map).sort()) {
3699
+ const evaluation = map[key2]?.evaluation;
3700
+ const muted = evaluation?.muted ?? null;
3701
+ if (evaluation === void 0 || muted === null) continue;
3702
+ if (!muted.expired) active++;
3703
+ rows.push(
3704
+ join2(
3705
+ html`<tr><th scope="row" class="key">${key2}</th><td>${kind2}</td><td>${muted.until}</td>`,
3706
+ html`<td>${muted.expired ? html`<span class="warn">expired</span>` : "active"}</td>`,
3707
+ html`<td>${evaluation.result === "fail" ? html`<span class="warn">yes</span>` : "no"}</td>`,
3708
+ html`<td>${muted.note}</td></tr>`
3709
+ )
3710
+ );
3711
+ }
3712
+ }
3713
+ if (rows.length === 0) return null;
3714
+ return join2(
3715
+ html`<section aria-labelledby="muted-h"><h2 id="muted-h">Muted keys</h2>`,
3716
+ html`<p>${plural3(active, "active muting")}, ${plural3(rows.length - active, "expired muting")}.</p>`,
3717
+ html`<div class="scroll"><table><caption>Keys muted in the thresholds files</caption>`,
3718
+ html`<thead><tr><th scope="col">Key</th><th scope="col">Kind</th><th scope="col">Until</th>`,
3719
+ html`<th scope="col">State</th><th scope="col">Violation</th><th scope="col">Note</th></tr></thead>`,
3720
+ html`<tbody>${rows}</tbody></table></div></section>`
3721
+ );
3722
+ }
3723
+ var COUNTERS = [
3724
+ ["keys", "Keys"],
3725
+ ["fromFile", "Evaluated with thresholds from the file"],
3726
+ ["fromDefaults", "Evaluated with default thresholds"],
3727
+ ["notEvaluated", "Not evaluated"],
3728
+ ["tooFewSamples", "Not evaluated: too few samples"],
3729
+ ["fileEntriesNotEvaluated", "File entries not evaluated (small n)"],
3730
+ ["medianOnly", "Evaluated by the median only"],
3731
+ ["unseenThresholdEntries", "File entries not seen in this run"],
3732
+ ["violations", "Violations"],
3733
+ ["blockingViolations", "Blocking violations"],
3734
+ ["muted", "Muted (active)"]
3735
+ ];
3736
+ function counters(report) {
3737
+ const { api, custom } = report.evaluation.counts;
3738
+ return join2(
3739
+ html`<section aria-labelledby="counters-h"><h2 id="counters-h">Counters</h2>`,
3740
+ html`<div class="scroll"><table class="counters"><caption>Keys per kind</caption>`,
3741
+ html`<thead><tr><th scope="col">Counter</th><th scope="col" class="num">API</th><th scope="col" class="num">Custom</th></tr></thead>`,
3742
+ html`<tbody>${COUNTERS.map(
3743
+ ([field2, label]) => html`<tr><th scope="row">${label}</th><td class="num">${api[field2]}</td><td class="num">${custom[field2]}</td></tr>`
3744
+ )}</tbody></table></div></section>`
3745
+ );
3746
+ }
3747
+ function issueList(issues, level) {
3748
+ const item = (i) => join2(
3749
+ html`<li class="${level === "error" ? "bad" : "warn"}"><p><strong>${level}</strong> <code>${i.code}</code>`,
3750
+ i.count !== void 0 && i.count > 1 ? html` <span class="count">×${i.count}</span>` : null,
3751
+ html`</p><p>${i.message}</p>`,
3752
+ i.hint === void 0 ? null : html`<p class="hint">Hint: ${i.hint}</p>`,
3753
+ html`</li>`
3754
+ );
3755
+ return html`<ul class="issues">${issues.map(item)}</ul>`;
3756
+ }
3757
+ function issuesSection(report) {
3758
+ const { warnings, toolErrors } = report;
3759
+ if (warnings.length === 0 && toolErrors.length === 0) return null;
3760
+ const cls = report.evaluation.status === "error" ? "issues-section highlight" : "issues-section";
3761
+ return join2(
3762
+ html`<section aria-labelledby="issues-h" class="${cls}"><h2 id="issues-h">Warnings and errors</h2>`,
3763
+ toolErrors.length === 0 ? null : html`<h3>Tool errors (${toolErrors.length})</h3>${issueList(toolErrors, "error")}`,
3764
+ warnings.length === 0 ? null : html`<h3>Warnings (${warnings.length})</h3>${issueList(warnings, "warning")}`,
3765
+ html`</section>`
3766
+ );
3767
+ }
3768
+ function checksTable(agg, level, report) {
3769
+ const ev = agg.evaluation;
3770
+ if (ev.result === "not-evaluated") {
3771
+ const reason = reasonText(ev.reason);
3772
+ const lowest = lowestMinSamples(report);
3773
+ return join2(
3774
+ html`<p>Not evaluated${reason === null ? "" : `: ${reason}`}.`,
3775
+ lowest === null ? null : ` The lowest rule (${lowest.rule}) needs ${plural3(lowest.n, "sample")}; this key has ${String(agg.successCount)} successful of ${plural3(agg.count, "sample")}.`,
3776
+ html`</p>`
3777
+ );
3778
+ }
3779
+ const row = (c) => join2(
3780
+ html`<tr><th scope="row">${ruleName(c.rule, level)}</th><td class="num">${c.n}</td>`,
3781
+ html`<td class="num">${checkValue(c, c.actual)}</td>`,
3782
+ html`<td class="num">${c.observed === null ? DASH : formatRatio(c.observed)}</td>`,
3783
+ html`<td class="num">${checkValue(c, c.limit)}</td>`,
3784
+ html`<td><span class="${c.passed ? "ok" : "bad"}">${c.passed ? "pass" : "fail"}</span></td>`,
3785
+ html`<td>${c.blocking ? "yes" : "no"}</td><td>${c.hardLimitExceeded ? "yes" : "no"}</td></tr>`
3786
+ );
3787
+ return join2(
3788
+ html`<table class="checks"><caption>Checks</caption><thead><tr>`,
3789
+ html`<th scope="col">Rule</th><th scope="col" class="num">n</th>`,
3790
+ html`<th scope="col" class="num">Compared value</th><th scope="col" class="num">Observed</th>`,
3791
+ html`<th scope="col" class="num">Limit</th><th scope="col">Result</th><th scope="col">Blocking</th>`,
3792
+ html`<th scope="col">Hard limit exceeded</th></tr></thead><tbody>${ev.checks.map(row)}</tbody></table>`
3793
+ );
3794
+ }
3795
+ function testRef2(t) {
3796
+ const project = t.project === "" ? "default project" : t.project;
3797
+ return html`${t.title} <span class="muted-text">(${project}, <code>${t.file}:${t.line}</code>)</span>`;
3798
+ }
3799
+ function fact(label, value) {
3800
+ return html`<div><dt>${label}</dt><dd>${value}</dd></div>`;
3801
+ }
3802
+ function details(key2, agg, kind2, report, level) {
3803
+ const statuses = Object.keys(agg.statuses).sort();
3804
+ const bar = percentileBar(agg.stats, agg.evaluation.limits, level);
3805
+ const statusList = statuses.map(
3806
+ (s, i) => html`${i > 0 ? ", " : ""}<code>${s}</code> → ${agg.statuses[s] ?? 0}`
3807
+ );
3808
+ const sampling = agg.samples.sampled ? " (sampled: the key had more successful samples than the limit)" : " (all successful samples)";
3809
+ return join2(
3810
+ html`<p class="full-key"><code>${key2}</code></p>`,
3811
+ checksTable(agg, level, report),
3812
+ bar ?? html`<p>No successful samples, so there are no time statistics.</p>`,
3813
+ html`<dl class="facts">`,
3814
+ fact("Statuses", statuses.length === 0 ? DASH : statusList),
3815
+ fact("Samples from failed tests", agg.fromFailedTests),
3816
+ agg.timeSources.node > 0 ? fact(
3817
+ "Time sources",
3818
+ `browser ${String(agg.timeSources.browser)}, node ${String(agg.timeSources.node)}`
3819
+ ) : null,
3820
+ kind2 === "endpoints" ? fact(
3821
+ "TTFB",
3822
+ agg.ttfb === null ? DASH : `p50 ${formatMs(agg.ttfb.p50)}, p95 ${formatMs(agg.ttfb.p95)}`
3823
+ ) : null,
3824
+ fact("Retained samples", `${String(agg.samples.retained)}${sampling}`),
3825
+ html`</dl>`,
3826
+ agg.slowest.length === 0 ? null : html`<h4>Slowest samples</h4><ol class="slowest">${agg.slowest.map(
3827
+ (s) => join2(
3828
+ html`<li><strong>${formatMs(s.duration)}</strong> at ${formatDate(s.startedAt)} · `,
3829
+ html`${testRef2(s.test)} · repeat ${s.test.repeatEachIndex}`,
3830
+ s.url === void 0 ? null : html`<br><span class="url">${s.url}</span>`,
3831
+ html`</li>`
3832
+ )
3833
+ )}</ol>`,
3834
+ agg.topTests.length === 0 ? null : html`<h4>Tests calling this key most often</h4><ol class="top-tests">${agg.topTests.map(
3835
+ (t) => html`<li>${testRef2(t)} · ${plural3(t.sampleCount, "sample")}</li>`
3836
+ )}</ol>`
3837
+ );
3838
+ }
3839
+ function percentileCell(value, limit) {
3840
+ return value === void 0 ? html`${DASH}` : html`${formatMs(value)} <span class="limit">/ ${formatMs(limit)}</span>`;
3841
+ }
3842
+ function keyRow(key2, agg, kind2, report, level, columns) {
3843
+ const ev = agg.evaluation;
3844
+ const s = agg.stats;
3845
+ const reason = reasonText(ev.reason);
3846
+ const muted = mutedText(ev.muted);
3847
+ const group = rowGroup(ev);
3848
+ const short = truncateMiddle2(key2, KEY_COLUMN_MAX);
3849
+ const time = (value) => value === void 0 ? DASH : formatMs(value);
3850
+ return join2(
3851
+ html`<tbody class="key-group" data-key="${key2}" data-result="${ev.result}" data-group="${group}"><tr>`,
3852
+ html`<th scope="row" class="key"${short === key2 ? null : html` title="${key2}"`}>${short}</th>`,
3853
+ html`<td><span class="${resultClass(ev)}">${resultText(ev)}</span> <span class="muted-text">· ${ev.thresholdSource}</span>`,
3854
+ reason === null ? null : html`<br><span class="muted-text">${reason}</span>`,
3855
+ muted === null ? null : html`<br><span class="${ev.muted?.expired === true ? "warn" : "muted-text"}">${muted}</span>`,
3856
+ html`</td><td class="num">${agg.successCount} / ${agg.count}</td>`,
3857
+ html`<td class="num">${agg.errorCount === 0 ? null : agg.errorCount}</td>`,
3858
+ html`<td class="num">${time(s?.percentiles["p50"])}</td>`,
3859
+ html`<td class="num">${s === null ? DASH : percentileCell(s.percentiles[level], ev.limits.percentile)}</td>`,
3860
+ html`<td class="num">${s === null ? DASH : percentileCell(s.percentiles["p99"], ev.limits.p99)}</td>`,
3861
+ html`<td class="num">${time(s?.max)}</td>`,
3862
+ kind2 === "endpoints" ? html`<td class="num">${time(agg.ttfb?.p50)}</td>` : null,
3863
+ html`<td class="num">${agg.testCount}</td></tr>`,
3864
+ html`<tr class="details-row"><td colspan="${columns}"><details${group <= 1 ? html` data-violation=""` : null}>`,
3865
+ html`<summary>Details <span class="visually-hidden">of ${short}</span></summary>`,
3866
+ html`<div class="details-body">${details(key2, agg, kind2, report, level)}</div></details></td></tr></tbody>`
3867
+ );
3868
+ }
3869
+ function keyTable(kind2, aggregates, report, level) {
3870
+ const title = kind2 === "endpoints" ? "Endpoints" : "Custom measurements";
3871
+ const id = `${kind2}-table`;
3872
+ const cols = [
3873
+ ["key", "Key", false],
3874
+ ["result", "Result", false],
3875
+ ["samples", "Samples", true],
3876
+ ["errors", "Errors", true],
3877
+ ["p50", "p50", true],
3878
+ ["percentile", `${level} / limit`, true],
3879
+ ["p99", "p99 / limit", true],
3880
+ ["max", "Max", true],
3881
+ ...kind2 === "endpoints" ? [["ttfb", "TTFB p50", true]] : [],
3882
+ ["tests", "Tests", true]
3883
+ ];
3884
+ const keys = defaultOrder(aggregates, level);
3885
+ const headerCell = ([column, label, numeric]) => html`<th scope="col" data-sort="${column}"${numeric ? html` class="num"` : null}><button type="button">${label}</button></th>`;
3886
+ return join2(
3887
+ html`<section aria-labelledby="${kind2}-h"><h2 id="${kind2}-h">${title}</h2>`,
3888
+ html`<div class="filters" data-filters-for="${id}" hidden>`,
3889
+ html`<label>Filter keys <input type="search" data-filter="text" autocomplete="off"></label>`,
3890
+ html`<label><input type="checkbox" data-filter="violations"> Only violations</label>`,
3891
+ html`<label><input type="checkbox" data-filter="not-evaluated"> Hide not evaluated</label>`,
3892
+ html`<span class="count" role="status" data-count>showing ${keys.length} of ${keys.length}</span></div>`,
3893
+ html`<div class="scroll"><table id="${id}" class="keys" data-kind="${kind2}" data-percentile="${level}">`,
3894
+ html`<caption>${title}: ${plural3(keys.length, "key")}, violations first</caption>`,
3895
+ html`<thead><tr>${cols.map(headerCell)}</tr></thead>`,
3896
+ keys.map(
3897
+ (key2) => keyRow(key2, aggregates[key2], kind2, report, level, cols.length)
3898
+ ),
3899
+ html`</table></div></section>`
3900
+ );
3901
+ }
3902
+ function field(object, name) {
3903
+ return typeof object === "object" && object !== null ? object[name] : void 0;
3904
+ }
3905
+ function textOf(value) {
3906
+ if (typeof value === "string") return value;
3907
+ return typeof value === "number" ? String(value) : null;
3908
+ }
3909
+ function generatedSource(file) {
3910
+ const generated = file.generated;
3911
+ if (generated === null) return file.status === "loaded" ? "hand-written" : DASH;
3912
+ const tool2 = field(generated, "tool");
3913
+ const run = textOf(field(generated, "sourceRunId"));
3914
+ const at2 = textOf(field(generated, "sourceRunStartedAt"));
3915
+ const count2 = field(generated, "sourceSampleCount");
3916
+ return [
3917
+ `generated by ${textOf(field(tool2, "name")) ?? "unknown"} v${textOf(field(tool2, "version")) ?? "?"}`,
3918
+ run === null ? "" : ` from run ${run}`,
3919
+ at2 === null ? "" : ` (${formatDate(at2)})`,
3920
+ typeof count2 === "number" ? `, ${plural3(count2, "sample")}` : ""
3921
+ ].join("");
3922
+ }
3923
+ function thresholdsFileRow(file, report) {
3924
+ const percentile2 = textOf(field(file.generated, "evaluatedPercentile"));
3925
+ const fingerprint2 = textOf(field(file.generated, "normalization"));
3926
+ let normalization;
3927
+ if (fingerprint2 === null) normalization = html`run <code>${report.normalization}</code>`;
3928
+ else if (fingerprint2 === report.normalization)
3929
+ normalization = html`<code>${fingerprint2}</code> <span class="ok">matches this run</span>`;
3930
+ else
3931
+ normalization = html`file <code>${fingerprint2}</code>, run <code>${report.normalization}</code> <strong class="warn">differs: keys may not match</strong>`;
3932
+ const statusClass = file.status === "loaded" ? "ok" : file.status === "invalid" ? "bad" : "muted-text";
3933
+ const unseen = file.unseenKeys;
3934
+ return join2(
3935
+ html`<tr><td>${file.kind}</td><td><code>${file.path}</code></td>`,
3936
+ html`<td><span class="${statusClass}">${file.status}</span></td><td>${percentile2 ?? DASH}</td>`,
3937
+ html`<td>${generatedSource(file)}</td><td>${normalization}</td><td>`,
3938
+ unseen.length === 0 ? "0" : html`<details><summary>${plural3(unseen.length, "key")}</summary><ul class="plain">${unseen.map((k) => html`<li><code>${k}</code></li>`)}</ul></details>`,
3939
+ html`</td></tr>`
3940
+ );
3941
+ }
3942
+ function thresholdsSection(report) {
3943
+ const files = report.thresholdFiles;
3944
+ return join2(
3945
+ html`<section aria-labelledby="thresholds-h"><h2 id="thresholds-h">Thresholds files</h2>`,
3946
+ files.length === 0 ? html`<p>No thresholds files were loaded in this run.</p>` : join2(
3947
+ html`<div class="scroll"><table><caption>Thresholds files of this run</caption><thead><tr>`,
3948
+ html`<th scope="col">Kind</th><th scope="col">Path</th><th scope="col">Status</th>`,
3949
+ html`<th scope="col">Percentile</th><th scope="col">Source</th>`,
3950
+ html`<th scope="col">Normalization fingerprint</th><th scope="col">Unseen keys</th>`,
3951
+ html`</tr></thead><tbody>${files.map((f) => thresholdsFileRow(f, report))}</tbody></table></div>`
3952
+ ),
3953
+ html`</section>`
3954
+ );
3955
+ }
3956
+ function runConditions(report) {
3957
+ const rc = report.runConditions;
3958
+ const overridden = rc.overriddenSettings.length === 0 ? "none" : rc.overriddenSettings.map((s, i) => html`${i > 0 ? ", " : ""}<code>${s}</code>`);
3959
+ const project = (p) => join2(
3960
+ html`<tr><th scope="row">${p.name === "" ? "(default)" : p.name}</th><td>${p.role}</td>`,
3961
+ html`<td>${p.browserName ?? DASH}</td><td class="num">${p.repeatEach}</td><td class="num">${p.retries}</td></tr>`
3962
+ );
3963
+ return join2(
3964
+ html`<section aria-labelledby="conditions-h"><h2 id="conditions-h">Run conditions</h2>`,
3965
+ html`<p>${plural3(rc.workers, "worker")}. Settings overridden by withPerf(): ${overridden}.</p>`,
3966
+ rc.projects.length === 0 ? null : join2(
3967
+ html`<div class="scroll"><table><caption>Projects</caption><thead><tr>`,
3968
+ html`<th scope="col">Project</th><th scope="col">Role</th><th scope="col">Browser</th>`,
3969
+ html`<th scope="col" class="num">repeatEach</th><th scope="col" class="num">retries</th>`,
3970
+ html`</tr></thead><tbody>${rc.projects.map(project)}</tbody></table></div>`
3971
+ ),
3972
+ html`</section>`
3973
+ );
3974
+ }
3975
+ function configuration(report) {
3976
+ return join2(
3977
+ html`<section aria-labelledby="config-h"><h2 id="config-h">Configuration</h2>`,
3978
+ html`<details><summary>Configuration snapshot</summary>`,
3979
+ html`<pre><code>${stableJson(report.config, " ")}</code></pre></details></section>`
3980
+ );
3981
+ }
3982
+ function footer(report) {
3983
+ return html`<footer>Generated by <a href="${chunkLV3O2BAT_cjs.REPOSITORY_URL}" rel="noopener noreferrer">${report.tool.name}</a> v${report.tool.version}</footer>`;
3984
+ }
3985
+ function keySections(data, report) {
3986
+ const level = percentileLevel(report);
3987
+ const hasEndpoints = Object.keys(data.endpoints).length > 0;
3988
+ const hasCustom = Object.keys(data.custom).length > 0;
3989
+ if (!hasEndpoints && !hasCustom) {
3990
+ return join2(
3991
+ html`<section aria-labelledby="endpoints-h"><h2 id="endpoints-h">Endpoints</h2>`,
3992
+ html`<p>No requests or custom measurements were recorded. See the `,
3993
+ html`<a href="${`${chunkLV3O2BAT_cjs.REPOSITORY_URL}#readme`}" rel="noopener noreferrer">documentation</a>`,
3994
+ html` for setting up the measured tests.</p></section>`
3995
+ );
3996
+ }
3997
+ return [
3998
+ hasEndpoints ? keyTable("endpoints", data.endpoints, report, level) : html`<section aria-labelledby="endpoints-h"><h2 id="endpoints-h">Endpoints</h2><p>No backend requests were recorded.</p></section>`,
3999
+ hasCustom ? keyTable("custom", data.custom, report, level) : null
4000
+ ];
4001
+ }
4002
+ var CONTENT_SECURITY_POLICY = `default-src 'none'; script-src 'sha256-${SCRIPT_SHA256}'; style-src 'sha256-${STYLES_SHA256}'; img-src data:`;
4003
+ function renderHtmlReport(report) {
4004
+ const data = toHtmlReportData(report);
4005
+ const head = join2(
4006
+ html`<head><meta charset="utf-8">`,
4007
+ html`<meta http-equiv="Content-Security-Policy" content="${CONTENT_SECURITY_POLICY}">`,
4008
+ html`<meta name="viewport" content="width=device-width, initial-scale=1">`,
4009
+ html`<meta name="color-scheme" content="light dark">`,
4010
+ html`<meta name="generator" content="${`${chunkLV3O2BAT_cjs.PACKAGE_NAME} ${report.tool.version}`}">`,
4011
+ html`<link rel="icon" href="data:,"><title>Performance report ${report.runId}</title>`,
4012
+ html`<style>${trustedHtml(STYLES)}</style></head>`
4013
+ );
4014
+ const download = join2(
4015
+ html`<div class="toolbar"><button type="button" id="download" hidden>Download JSON (aggregates, without raw samples)</button>`,
4016
+ html`<a id="download-link" download="report-data.json" hidden tabindex="-1"></a></div>`
4017
+ );
4018
+ const main = join2(
4019
+ header2(report),
4020
+ download,
4021
+ verdict(report),
4022
+ mutedSection(report),
4023
+ counters(report),
4024
+ issuesSection(report),
4025
+ keySections(data, report),
4026
+ thresholdsSection(report),
4027
+ runConditions(report),
4028
+ configuration(report)
4029
+ );
4030
+ const page = join2(
4031
+ html`<!doctype html>\n<html lang="en">${head}\n<body><main>${main}</main>${footer(report)}\n`,
4032
+ html`<script type="application/json" id="report-data">${trustedHtml(embeddedJson(data))}</script>\n`,
4033
+ html`<script>${trustedHtml(SCRIPT)}</script>\n</body></html>\n`
4034
+ );
4035
+ return page.text;
4036
+ }
4037
+
4038
+ // src/reporter/begin.ts
4039
+ function browserOf(project) {
4040
+ return project.use.browserName ?? project.use.defaultBrowserType ?? "chromium";
4041
+ }
4042
+ function roleOf(project, all, measured) {
4043
+ if (measured.has(project.name)) return "measured";
4044
+ return all.some((p) => p.teardown === project.name) ? "teardown" : "dependency";
4045
+ }
4046
+ function readRunConditions(config, measured, overridden) {
4047
+ return {
4048
+ workers: config.workers,
4049
+ projects: config.projects.map((project) => ({
4050
+ name: project.name,
4051
+ role: roleOf(project, config.projects, measured),
4052
+ browserName: browserOf(project),
4053
+ repeatEach: project.repeatEach,
4054
+ retries: project.retries
4055
+ })),
4056
+ overriddenSettings: [...overridden]
4057
+ };
4058
+ }
4059
+ function runConditionsWarning(conditions, repeat) {
4060
+ const diffs = [];
4061
+ if (conditions.workers !== 1) diffs.push(`workers ${conditions.workers} (expected 1)`);
4062
+ for (const project of conditions.projects) {
4063
+ const name = `project ${JSON.stringify(project.name)}`;
4064
+ const expected = project.role === "measured" ? repeat : 1;
4065
+ if (project.repeatEach !== expected) {
4066
+ diffs.push(`${name} repeatEach ${project.repeatEach} (expected ${expected})`);
4067
+ }
4068
+ if (project.retries !== 0) diffs.push(`${name} retries ${project.retries} (expected 0)`);
4069
+ }
4070
+ if (diffs.length === 0) return null;
4071
+ return {
4072
+ code: "RUN_CONDITIONS_CHANGED",
4073
+ message: `The run conditions differ from those set for perf mode: ${diffs.join("; ")}.`,
4074
+ hint: "Do not pass --workers, --retries or --repeat-each to a perf-mode run; set repetitions with run.repeat or --repeat."
4075
+ };
4076
+ }
4077
+ function duplicateBaseUrlLabels(conditions, config, keys) {
4078
+ const baseOrigins = measuredBaseOrigins(
4079
+ conditions.projects.map((p, i) => ({ role: p.role, baseURL: config.projects[i]?.use.baseURL }))
4080
+ );
4081
+ const labelled = /* @__PURE__ */ new Map();
4082
+ for (const [origin, label] of Object.entries(keys.origins)) {
4083
+ const canonical = canonicalOrigin(origin);
4084
+ if (canonical !== null) labelled.set(canonical, label);
4085
+ }
4086
+ const unlabelled = baseOrigins.filter((origin) => !labelled.has(origin));
4087
+ if (unlabelled.length === 0) return null;
4088
+ const empty = [
4089
+ ...unlabelled,
4090
+ ...[...labelled].filter(([, label]) => label === "").map(([origin]) => origin)
4091
+ ].sort();
4092
+ if (empty.length < 2) return null;
4093
+ return {
4094
+ code: "CONFIG_DUPLICATE_ORIGIN_LABEL",
4095
+ message: `${empty.map((o) => JSON.stringify(o)).join(", ")} share the empty label (use.baseURL of measured projects), so their endpoint keys are merged`,
4096
+ hint: "Give each origin its own label in keys.origins unless merging their keys is intended."
4097
+ };
4098
+ }
4099
+ function list(names) {
4100
+ return names.map((n) => n === "" ? "(default)" : n).join(", ");
4101
+ }
4102
+ function overriddenLine(conditions) {
4103
+ const parts = [];
4104
+ if (conditions.overridden.length > 0) {
4105
+ parts.push(`perf mode overrides ${conditions.overridden.join(", ")}`);
4106
+ }
4107
+ if (conditions.removedProjects.length > 0) {
4108
+ parts.push(`removed projects ${list(conditions.removedProjects)}`);
4109
+ }
4110
+ if (conditions.removedReporters.length > 0) {
4111
+ parts.push(`removed reporters ${list(conditions.removedReporters)}`);
4112
+ }
4113
+ return parts.length === 0 ? null : `${parts.join("; ")}.`;
4114
+ }
4115
+ function plural4(n, word) {
4116
+ return `${n} ${n === 1 ? word : `${word}s`}`;
4117
+ }
4118
+ function executionsLine(mode2, tests, measured, repeat, workers) {
4119
+ const inMeasured = tests.filter((t) => measured.has(t.parent.project()?.name ?? ""));
4120
+ const unique = inMeasured.filter((t) => t.repeatEachIndex === 0).length;
4121
+ const others = tests.length - inMeasured.length;
4122
+ const extra = others > 0 ? `, plus ${plural4(others, "setup or teardown execution")}` : "";
4123
+ return `perf mode "${mode2}": ${plural4(inMeasured.length, "test execution")} (${plural4(unique, "test")} \xD7 ${plural4(repeat, "repeat")}), ${plural4(workers, "worker")}${extra}.`;
4124
+ }
4125
+
4126
+ // src/reporter/samples.ts
4127
+ function testTitle(test) {
4128
+ const titles = [test.title];
4129
+ for (let suite = test.parent; suite?.type === "describe"; suite = suite.parent) {
4130
+ titles.unshift(suite.title);
4131
+ }
4132
+ return titles.join(" \u203A ");
4133
+ }
4134
+ function projectName(test) {
4135
+ return test.parent.project()?.name ?? "";
4136
+ }
4137
+ function testMeta(test, result, file) {
4138
+ const title = testTitle(test);
4139
+ const project = projectName(test);
4140
+ return {
4141
+ identity: testIdentity(project, file, title),
4142
+ resultId: resultId(test.id, test.repeatEachIndex, result.retry),
4143
+ title,
4144
+ project,
4145
+ file,
4146
+ line: test.location.line,
4147
+ repeatEachIndex: test.repeatEachIndex,
4148
+ failed: isFailedTest(result.status, test.expectedStatus)
4149
+ };
4150
+ }
4151
+ function sampleAttachments(result) {
4152
+ return result.attachments.filter((a) => a.name === chunkLV3O2BAT_cjs.SAMPLES_ATTACHMENT_NAME).map((a) => a.body === void 0 ? "" : a.body.toString("utf8"));
4153
+ }
4154
+ function hasTraceOrVideo(result) {
4155
+ return result.attachments.some((a) => a.name === "trace" || a.name === "video");
4156
+ }
4157
+
4158
+ // src/reporter/session.ts
4159
+ var PENDING_TOP_KEYS = 5;
4160
+ var DEFAULT_WIDTH = 120;
4161
+ function runSettings(registered, env, packageVersion) {
4162
+ if (registered !== void 0) {
4163
+ return {
4164
+ config: registered.config,
4165
+ snapshot: registered.snapshot,
4166
+ mode: registered.mode,
4167
+ packageVersion: registered.packageVersion,
4168
+ measuredProjects: registered.measuredProjects,
4169
+ runConditions: registered.runConditions,
4170
+ registered: true,
4171
+ warnings: [...registered.warnings],
4172
+ toolErrors: []
4173
+ };
4174
+ }
4175
+ const read2 = chunkLV3O2BAT_cjs.readModeState(env);
4176
+ if (read2.ok && read2.value === null) return null;
4177
+ const mode2 = read2.ok && read2.value !== null ? read2.value : { mode: "test" };
4178
+ const resolved = chunkGCA73FFP_cjs.resolveConfig(void 0, {
4179
+ mode: mode2.mode,
4180
+ ...mode2.repeat === void 0 ? {} : { repeat: mode2.repeat },
4181
+ ...mode2.env === void 0 ? {} : { env: mode2.env }
4182
+ });
4183
+ if (!resolved.ok) throw new Error("the default package config is not valid");
4184
+ return {
4185
+ config: resolved.value.config,
4186
+ snapshot: resolved.value.snapshot,
4187
+ mode: mode2,
4188
+ packageVersion,
4189
+ measuredProjects: null,
4190
+ runConditions: { overridden: [], removedProjects: [], removedReporters: [] },
4191
+ registered: false,
4192
+ warnings: [chunkLV3O2BAT_cjs.notWrappedWarning()],
4193
+ toolErrors: read2.ok ? [] : read2.issues
4194
+ };
4195
+ }
4196
+ function internalError(where, error) {
4197
+ const text = error instanceof Error ? error.stack ?? error.message : String(error);
4198
+ return {
4199
+ code: "REPORTER_INTERNAL_ERROR",
4200
+ message: `Unexpected error in the reporter (${where}): ${text}`,
4201
+ hint: "This is a bug in the package; please report it with the message above."
4202
+ };
4203
+ }
4204
+ function plural5(n, word, many = `${word}s`) {
4205
+ return `${n} ${n === 1 ? word : many}`;
4206
+ }
4207
+ var RunSession = class {
4208
+ host;
4209
+ settings;
4210
+ options;
4211
+ warnings;
4212
+ toolErrors;
4213
+ startedAt;
4214
+ runId;
4215
+ configDir;
4216
+ maxFailures = 0;
4217
+ measured = /* @__PURE__ */ new Set();
4218
+ conditions;
4219
+ normalization;
4220
+ aggregator;
4221
+ keyOf;
4222
+ /** onBegin failed: the evaluation is not possible. */
4223
+ fatal = false;
4224
+ testsStarted = 0;
4225
+ testsSeen = /* @__PURE__ */ new Set();
4226
+ notInstrumented = 0;
4227
+ retried = 0;
4228
+ withArtifacts = 0;
4229
+ pending = /* @__PURE__ */ new Map();
4230
+ playwrightVersion = "";
4231
+ constructor(host, settings, options = {}) {
4232
+ this.host = host;
4233
+ this.settings = settings;
4234
+ this.options = options;
4235
+ this.warnings = [...settings.warnings];
4236
+ this.toolErrors = [...settings.toolErrors];
4237
+ this.startedAt = host.now();
4238
+ this.runId = settings.mode.runId ?? chunkLV3O2BAT_cjs.generateRunId(this.startedAt, host.random);
4239
+ this.configDir = host.cwd;
4240
+ this.conditions = { workers: 1, projects: [], overriddenSettings: [] };
4241
+ const keys = settings.config.keys;
4242
+ this.normalization = normalizationFingerprint(keys, { baseOrigins: [] });
4243
+ this.aggregator = this.createAggregator();
4244
+ this.keyOf = createKeyBuilder(keys, { baseOrigins: [] });
4245
+ }
4246
+ get mode() {
4247
+ return this.settings.mode.mode;
4248
+ }
4249
+ get repeat() {
4250
+ return this.settings.config.run.repeat[this.mode];
4251
+ }
4252
+ createAggregator() {
4253
+ const cfg = this.settings.config;
4254
+ return new Aggregator({
4255
+ advanced: cfg.advanced,
4256
+ successStatuses: cfg.measure.successStatuses,
4257
+ errors: cfg.checks.errors,
4258
+ measuredProjects: this.measured,
4259
+ evaluatedPercentile: cfg.checks.time.percentile.level,
4260
+ rawUrls: cfg.report.rawUrls
4261
+ });
4262
+ }
4263
+ info(line) {
4264
+ this.host.stdout.write(`${chunkLV3O2BAT_cjs.PACKAGE_NAME}: ${line}
4265
+ `);
4266
+ }
4267
+ /** A hook threw: the error goes to the report and the outcome file (01-REQ-16). */
4268
+ recordInternalError(where, error) {
4269
+ this.toolErrors.push(internalError(where, error));
4270
+ if (where === "onBegin") this.fatal = true;
4271
+ }
4272
+ begin(config, suite) {
4273
+ this.playwrightVersion = config.version;
4274
+ this.startedAt = this.host.now();
4275
+ if (this.settings.mode.runId === void 0) {
4276
+ this.runId = chunkLV3O2BAT_cjs.generateRunId(this.startedAt, this.host.random);
4277
+ }
4278
+ const io = this.host.io;
4279
+ this.configDir = config.configFile === void 0 ? config.rootDir : io.directoryOf(config.configFile);
4280
+ this.maxFailures = config.maxFailures;
4281
+ const names = this.settings.measuredProjects ?? config.projects.map((p) => p.name);
4282
+ this.measured = new Set(names);
4283
+ this.conditions = readRunConditions(
4284
+ config,
4285
+ this.measured,
4286
+ this.settings.runConditions.overridden
4287
+ );
4288
+ const baseOrigins = measuredBaseOrigins(
4289
+ this.conditions.projects.map((p, i) => ({
4290
+ role: p.role,
4291
+ baseURL: config.projects[i]?.use.baseURL
4292
+ }))
4293
+ );
4294
+ const keys = this.settings.config.keys;
4295
+ this.normalization = normalizationFingerprint(keys, { baseOrigins });
4296
+ this.keyOf = createKeyBuilder(keys, { baseOrigins });
4297
+ this.aggregator = this.createAggregator();
4298
+ if (this.settings.registered) {
4299
+ const changed = runConditionsWarning(this.conditions, this.repeat);
4300
+ if (changed !== null) this.warnings.push(changed);
4301
+ }
4302
+ const duplicate = duplicateBaseUrlLabels(this.conditions, config, keys);
4303
+ if (duplicate !== null) this.warnings.push(duplicate);
4304
+ if (config.shard !== null) {
4305
+ this.toolErrors.push({
4306
+ code: "RUN_SHARDED",
4307
+ message: `The perf-mode run is sharded (--shard ${config.shard.current}/${config.shard.total}): each machine would evaluate only part of the keys.`,
4308
+ hint: "Run perf mode on one machine without --shard."
4309
+ });
4310
+ }
4311
+ const overridden = overriddenLine(this.settings.runConditions);
4312
+ if (overridden !== null) this.info(overridden);
4313
+ this.info(
4314
+ executionsLine(this.mode, suite.allTests(), this.measured, this.repeat, config.workers)
4315
+ );
4316
+ }
4317
+ testBegin() {
4318
+ this.testsStarted += 1;
4319
+ }
4320
+ testEnd(test, result) {
4321
+ this.testsSeen.add(test);
4322
+ if (result.retry > 0) this.retried += 1;
4323
+ if (hasTraceOrVideo(result)) this.withArtifacts += 1;
4324
+ const bodies = sampleAttachments(result);
4325
+ const measured = this.measured.has(projectName(test));
4326
+ if (bodies.length === 0) {
4327
+ if (measured && result.status !== "skipped") this.notInstrumented += 1;
4328
+ return;
4329
+ }
4330
+ const meta = testMeta(
4331
+ test,
4332
+ result,
4333
+ this.host.io.relativeSlashPath(this.configDir, test.location.file)
4334
+ );
4335
+ if (bodies.length > 1) {
4336
+ this.warnings.push({
4337
+ code: "ATTACHMENT_DUPLICATE",
4338
+ message: `Test "${meta.title}" has ${bodies.length} ${chunkLV3O2BAT_cjs.SAMPLES_ATTACHMENT_NAME} attachments; all of them were processed.`,
4339
+ hint: "Apply withPerfFixtures() once per test object."
4340
+ });
4341
+ }
4342
+ for (const body of bodies) {
4343
+ const parsed = parseSampleBatch(body, meta.title);
4344
+ if (!parsed.ok) {
4345
+ this.toolErrors.push(...parsed.issues.map(schemaIssueToIssue));
4346
+ continue;
4347
+ }
4348
+ const batch = parsed.value;
4349
+ this.warnings.push(...batch.diagnostics);
4350
+ batch.requests.forEach((sample, ordinal) => {
4351
+ const keyed = addKeyedRequest(
4352
+ this.aggregator,
4353
+ this.keyOf,
4354
+ { ...sample, test: meta, ordinal },
4355
+ batch.collector.browserName
4356
+ );
4357
+ this.warnings.push(...keyed.issues);
4358
+ if (keyed.ok && sample.status === "PENDING" && measured) {
4359
+ this.pending.set(keyed.key, (this.pending.get(keyed.key) ?? 0) + 1);
4360
+ }
4361
+ });
4362
+ batch.custom.forEach((sample, ordinal) => {
4363
+ this.aggregator.addCustom(sample.name, { ...sample, test: meta, ordinal });
4364
+ });
4365
+ }
4366
+ }
4367
+ /** Warnings known only at the end of the run (09, chapter 12.1). */
4368
+ runWarnings() {
4369
+ const issues = [];
4370
+ if (this.notInstrumented > 0) {
4371
+ issues.push({
4372
+ code: "TESTS_NOT_INSTRUMENTED",
4373
+ message: `${plural5(this.notInstrumented, "test result")} of measured projects ${this.notInstrumented === 1 ? "has" : "have"} no ${chunkLV3O2BAT_cjs.SAMPLES_ATTACHMENT_NAME} attachment, so ${this.notInstrumented === 1 ? "it was" : "they were"} not measured.`,
4374
+ hint: 'Import test from a test object wrapped with withPerfFixtures() (or from "playwright-performance-regression/test"); a crashed worker also loses the attachment.'
4375
+ });
4376
+ }
4377
+ if (this.retried > 0) {
4378
+ issues.push({
4379
+ code: "RUN_CONDITIONS_CHANGED",
4380
+ message: `${plural5(this.retried, "test result is a retry", "test results are retries")} (retry > 0), although perf mode sets retries to 0; samples of retries are counted.`,
4381
+ hint: "Remove retries set in test files (test.describe.configure({ retries })) for perf-mode runs."
4382
+ });
4383
+ }
4384
+ if (this.withArtifacts > 0) {
4385
+ issues.push({
4386
+ code: "RUN_CONDITIONS_CHANGED",
4387
+ message: `${plural5(this.withArtifacts, "test result has", "test results have")} a trace or video attachment, although perf mode turns them off; recording slows the browser down.`,
4388
+ hint: "Remove test.use({ trace, video }) from test files for perf-mode runs."
4389
+ });
4390
+ }
4391
+ return issues;
4392
+ }
4393
+ pendingWarning() {
4394
+ if (this.pending.size === 0) return null;
4395
+ let total = 0;
4396
+ for (const n of this.pending.values()) total += n;
4397
+ const top = [...this.pending].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).slice(0, PENDING_TOP_KEYS).map(([key2, n]) => `${key2} (${n})`);
4398
+ return {
4399
+ code: "COLLECTOR_REQUESTS_PENDING",
4400
+ message: `${plural5(total, "request was", "requests were")} still pending at the end of a test; most in: ${top.join(", ")}.`,
4401
+ hint: "Exclude long polling and streaming with measure.exclude, or raise measure.pendingTimeoutMs."
4402
+ };
4403
+ }
4404
+ testsResult(status) {
4405
+ const tests = { status, expected: 0, unexpected: 0, flaky: 0, skipped: 0 };
4406
+ for (const test of this.testsSeen) tests[test.outcome()] += 1;
4407
+ return tests;
4408
+ }
4409
+ source() {
4410
+ const browsers = this.conditions.projects.filter((p) => p.role === "measured" && p.browserName !== null).map((p) => p.browserName);
4411
+ const { nodeVersion: _, ...host } = this.host.host;
4412
+ return {
4413
+ browsers: [...new Set(browsers)].sort(),
4414
+ playwrightVersion: this.playwrightVersion,
4415
+ host,
4416
+ normalization: this.normalization
4417
+ };
4418
+ }
4419
+ reportInput(status, finishedAt, aggregates, evaluation, warnings, toolErrors) {
4420
+ return {
4421
+ meta: {
4422
+ tool: { name: chunkLV3O2BAT_cjs.PACKAGE_NAME, version: this.settings.packageVersion },
4423
+ runId: this.runId,
4424
+ mode: this.mode,
4425
+ startedAt: this.startedAt.toISOString(),
4426
+ finishedAt: finishedAt.toISOString(),
4427
+ env: this.settings.config.run.env,
4428
+ configDir: this.configDir,
4429
+ ci: this.host.ci,
4430
+ host: this.host.host,
4431
+ playwright: { version: this.playwrightVersion }
4432
+ },
4433
+ config: this.settings.snapshot,
4434
+ normalization: this.normalization,
4435
+ runConditions: this.conditions,
4436
+ tests: this.testsResult(status),
4437
+ aggregates,
4438
+ evaluation,
4439
+ warnings,
4440
+ toolErrors
4441
+ };
4442
+ }
4443
+ terminal() {
4444
+ const out = this.host.stdout;
4445
+ const noColor = (this.host.env.NO_COLOR ?? "") !== "";
4446
+ return {
4447
+ width: out.isTTY === true && out.columns !== void 0 && out.columns > 0 ? out.columns : DEFAULT_WIDTH,
4448
+ color: out.isTTY === true && !noColor
4449
+ };
4450
+ }
4451
+ /**
4452
+ * onEnd (01, chapter 3.3, steps 8–9). Returns the status for Playwright: `failed` when the
4453
+ * outcome exit code is not 0, otherwise nothing, so Playwright keeps its own (01-REQ-17).
4454
+ */
4455
+ async end(result) {
4456
+ if (this.testsStarted === 0) return void 0;
4457
+ let outcome;
4458
+ try {
4459
+ outcome = await this.finish(result);
4460
+ } catch (error) {
4461
+ this.recordInternalError("onEnd", error);
4462
+ outcome = this.fallbackOutcome(result);
4463
+ for (const issue2 of outcome.toolErrors) {
4464
+ this.host.stderr.write(`${chunkLV3O2BAT_cjs.PACKAGE_NAME}: ${issue2.code}: ${issue2.message}
4465
+ `);
4466
+ }
4467
+ }
4468
+ await this.writeOutcome(outcome);
4469
+ return outcome.exitCode === 0 ? void 0 : { status: "failed" };
4470
+ }
4471
+ async finish(result) {
4472
+ const cfg = this.settings.config;
4473
+ const io = this.host.io;
4474
+ const finishedAt = this.host.now();
4475
+ const warnings = [...this.warnings, ...this.runWarnings()];
4476
+ const toolErrors = [...this.toolErrors];
4477
+ const aggregates = this.aggregator.finalize();
4478
+ warnings.push(...aggregates.issues, ...detectKeyExplosion(Object.keys(aggregates.endpoints)));
4479
+ const pending = this.pendingWarning();
4480
+ if (pending !== null) warnings.push(pending);
4481
+ const tests = this.testsResult(result.status);
4482
+ const assessment = assessRun(
4483
+ { tests, maxFailures: this.maxFailures},
4484
+ cfg.gate
4485
+ );
4486
+ warnings.push(...assessment.warnings);
4487
+ toolErrors.push(...assessment.toolErrors);
4488
+ const location = {
4489
+ configDir: this.configDir,
4490
+ dir: cfg.thresholds.dir,
4491
+ filePrefix: cfg.thresholds.filePrefix,
4492
+ env: cfg.run.env
4493
+ };
4494
+ const loaded = await io.loadThresholds(location);
4495
+ const evaluation = evaluate(aggregates, loaded, cfg, {
4496
+ mode: this.mode,
4497
+ env: cfg.run.env,
4498
+ fatalToolError: this.fatal,
4499
+ source: this.source(),
4500
+ startedAt: this.startedAt.toISOString()
4501
+ });
4502
+ warnings.push(...evaluation.warnings);
4503
+ toolErrors.push(...evaluation.toolErrors);
4504
+ const build = () => buildRunReport(
4505
+ this.reportInput(result.status, finishedAt, aggregates, evaluation, warnings, toolErrors)
4506
+ );
4507
+ let report = build();
4508
+ const reportDir = io.resolvePath(this.configDir, cfg.report.dir);
4509
+ const paths = {
4510
+ reportJson: null,
4511
+ reportHtml: null,
4512
+ thresholds: [],
4513
+ thresholdsDiff: null
4514
+ };
4515
+ let diffs = [];
4516
+ let diffPaths = [];
4517
+ if (this.mode === "thresholds") {
4518
+ const derived = await this.deriveAndWrite(
4519
+ report,
4520
+ loaded,
4521
+ location,
4522
+ paths,
4523
+ warnings,
4524
+ toolErrors
4525
+ );
4526
+ diffs = derived.diffs;
4527
+ diffPaths = derived.paths;
4528
+ report = build();
4529
+ }
4530
+ const writeJson = async () => {
4531
+ try {
4532
+ const path = io.resolvePath(reportDir, "report.json");
4533
+ await io.writeJsonStable(path, report);
4534
+ paths.reportJson = path;
4535
+ return true;
4536
+ } catch (error) {
4537
+ toolErrors.push({
4538
+ code: "REPORT_WRITE_FAILED",
4539
+ message: `The run report could not be written to ${reportDir}: ${error instanceof Error ? error.message : String(error)}`,
4540
+ hint: "Check that report.dir is writable."
4541
+ });
4542
+ report = build();
4543
+ return false;
4544
+ }
4545
+ };
4546
+ await writeJson();
4547
+ if (cfg.report.html) {
4548
+ const issue2 = await this.writeHtml(report, io.resolvePath(reportDir, "report.html"), paths);
4549
+ if (issue2 !== null) {
4550
+ toolErrors.push(issue2);
4551
+ report = build();
4552
+ if (paths.reportJson !== null) await writeJson();
4553
+ }
4554
+ }
4555
+ const { width, color } = this.terminal();
4556
+ this.host.stdout.write(
4557
+ formatSummary(report, { width, color, cwd: this.host.cwd, html: paths.reportHtml !== null })
4558
+ );
4559
+ if (diffs.length > 0) {
4560
+ this.host.stdout.write(
4561
+ formatThresholdsDiff(diffs, {
4562
+ paths: diffPaths.map((p) => io.relativeSlashPath(this.host.cwd, p)),
4563
+ width,
4564
+ color,
4565
+ prune: this.settings.mode.prune === true,
4566
+ diffPath: paths.thresholdsDiff === null ? null : io.relativeSlashPath(this.host.cwd, paths.thresholdsDiff)
4567
+ })
4568
+ );
4569
+ }
4570
+ return buildOutcome(report, paths);
4571
+ }
4572
+ /**
4573
+ * Writes report.html next to report.json (11-REQ-04). The page is rendered from the report as
4574
+ * written to JSON, so `report` renders the same HTML from report.json (11-AC-10). Returns the
4575
+ * HTML_RENDER_FAILED or HTML_WRITE_FAILED tool error (11, chapter 13), or null.
4576
+ */
4577
+ async writeHtml(report, path, paths) {
4578
+ const render2 = this.options.renderHtml ?? renderHtmlReport;
4579
+ let page;
4580
+ try {
4581
+ page = render2(JSON.parse(stringifyStable(report)));
4582
+ } catch (error) {
4583
+ return {
4584
+ code: "HTML_RENDER_FAILED",
4585
+ message: `The HTML report could not be rendered: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
4586
+ hint: "This is a bug in the package; please report it with the message above. report.json is complete."
4587
+ };
4588
+ }
4589
+ try {
4590
+ await this.host.io.writeTextAtomic(path, page);
4591
+ paths.reportHtml = path;
4592
+ return null;
4593
+ } catch (error) {
4594
+ return {
4595
+ code: "HTML_WRITE_FAILED",
4596
+ message: `The HTML report could not be written to ${path}: ${error instanceof Error ? error.message : String(error)}`,
4597
+ hint: `Check that report.dir is writable; \`${chunkLV3O2BAT_cjs.CLI_COMMAND} report\` renders it again from report.json.`
4598
+ };
4599
+ }
4600
+ }
4601
+ /**
4602
+ * Derivation in thresholds mode (10, chapter 3): refusals and write errors are tool errors, so
4603
+ * nothing is written for an incomplete run (04-REQ-36); the diff file failing is a warning.
4604
+ * Returns the diffs and the absolute path of each thresholds file.
4605
+ */
4606
+ async deriveAndWrite(report, loaded, location, paths, warnings, toolErrors) {
4607
+ const cfg = this.settings.config;
4608
+ const io = this.host.io;
4609
+ const derived = deriveThresholds(report, cfg, loaded, {
4610
+ env: cfg.run.env,
4611
+ prune: this.settings.mode.prune === true,
4612
+ toolVersion: this.settings.packageVersion
4613
+ });
4614
+ if (!derived.ok) {
4615
+ toolErrors.push(...derived.issues);
4616
+ return { diffs: [], paths: [] };
4617
+ }
4618
+ warnings.push(...derived.value.warnings);
4619
+ const absolute = io.thresholdsFilePaths(location);
4620
+ for (const file of derived.value.files) {
4621
+ if (file.content === null || !file.changed) continue;
4622
+ try {
4623
+ await io.writeJsonStable(absolute[file.kind], file.content);
4624
+ paths.thresholds.push(absolute[file.kind]);
4625
+ } catch (error) {
4626
+ toolErrors.push({
4627
+ code: "THRESHOLDS_WRITE_FAILED",
4628
+ message: `The thresholds file ${loaded[file.kind].path} could not be written: ${error instanceof Error ? error.message : String(error)}`,
4629
+ hint: "Check that thresholds.dir is writable, then derive the thresholds again."
4630
+ });
4631
+ }
4632
+ }
4633
+ const diffs = derived.value.files.map(
4634
+ (file) => diffThresholds(loaded[file.kind], file, report, cfg)
4635
+ );
4636
+ const filePaths = derived.value.files.map((file) => absolute[file.kind]);
4637
+ const diffPath = io.resolvePath(
4638
+ io.resolvePath(this.configDir, cfg.report.dir),
4639
+ "thresholds-diff.md"
4640
+ );
4641
+ try {
4642
+ await io.writeTextAtomic(
4643
+ diffPath,
4644
+ formatThresholdsDiffMarkdown(
4645
+ diffs,
4646
+ derived.value.files.map((file) => loaded[file.kind].path)
4647
+ )
4648
+ );
4649
+ paths.thresholdsDiff = diffPath;
4650
+ } catch (error) {
4651
+ warnings.push({
4652
+ code: "THRESHOLDS_DIFF_WRITE_FAILED",
4653
+ message: `The thresholds diff could not be written to ${diffPath}: ${error instanceof Error ? error.message : String(error)}`,
4654
+ hint: "The thresholds files are written; check that report.dir is writable."
4655
+ });
4656
+ }
4657
+ return { diffs, paths: filePaths };
4658
+ }
4659
+ /** The outcome when building the report failed: exit code 3 with the error (02-REQ-27). */
4660
+ fallbackOutcome(result) {
4661
+ return {
4662
+ schemaVersion: SCHEMA_VERSIONS.outcome,
4663
+ runId: this.runId,
4664
+ mode: this.mode,
4665
+ exitCode: 3,
4666
+ tests: { status: result.status },
4667
+ evaluation: { status: "error", gateEnabled: this.mode === "test" },
4668
+ toolErrors: this.toolErrors.map((issue2) => ({ ...issue2 })),
4669
+ paths: { reportJson: null, reportHtml: null, thresholds: [], thresholdsDiff: null }
4670
+ };
4671
+ }
4672
+ /** Last step of onEnd (02-REQ-27); without PW_PERF_OUTCOME_FILE there is no outcome file. */
4673
+ async writeOutcome(outcome) {
4674
+ const file = this.settings.mode.outcomeFile;
4675
+ if (file === void 0) return;
4676
+ try {
4677
+ await this.host.io.writeJsonStable(file, outcome);
4678
+ } catch (error) {
4679
+ this.host.stderr.write(
4680
+ `${chunkLV3O2BAT_cjs.PACKAGE_NAME}: OUTCOME_WRITE_FAILED: the outcome file could not be written to ${file}: ${error instanceof Error ? error.message : String(error)}
4681
+ `
4682
+ );
4683
+ }
4684
+ }
4685
+ };
4686
+
4687
+ // src/reporter/perf-reporter.ts
4688
+ function processHost() {
4689
+ const env = process.env;
4690
+ return {
4691
+ env,
4692
+ io: {
4693
+ loadThresholds,
4694
+ thresholdsFilePaths,
4695
+ writeJsonStable,
4696
+ writeTextAtomic,
4697
+ resolvePath,
4698
+ directoryOf,
4699
+ relativeSlashPath
4700
+ },
4701
+ stdout: process.stdout,
4702
+ stderr: process.stderr,
4703
+ cwd: process.cwd(),
4704
+ now: () => /* @__PURE__ */ new Date(),
4705
+ random: Math.random,
4706
+ ci: readCiInfo(env),
4707
+ host: readHostInfo(env)
4708
+ };
4709
+ }
4710
+ var PerfReporter = class {
4711
+ /** Reporter options from the Playwright config; none are defined yet. */
4712
+ options;
4713
+ session;
4714
+ startError;
4715
+ constructor(options = {}) {
4716
+ this.options = options;
4717
+ let session = null;
4718
+ let startError;
4719
+ try {
4720
+ const host = processHost();
4721
+ const settings = runSettings(chunkLV3O2BAT_cjs.getRegistered(), host.env, chunkLV3O2BAT_cjs.version);
4722
+ session = settings === null ? null : new RunSession(host, settings);
4723
+ } catch (error) {
4724
+ startError = error;
4725
+ }
4726
+ this.session = session;
4727
+ this.startError = startError;
4728
+ if (startError !== void 0) {
4729
+ process.stderr.write(
4730
+ `playwright-performance-regression: REPORTER_INTERNAL_ERROR: the reporter could not start: ${startError instanceof Error ? startError.message : String(startError)}
4731
+ `
4732
+ );
4733
+ }
4734
+ }
4735
+ onBegin(config, suite) {
4736
+ const session = this.session;
4737
+ if (session === null) return;
4738
+ try {
4739
+ session.begin(config, suite);
4740
+ } catch (error) {
4741
+ session.recordInternalError("onBegin", error);
4742
+ }
4743
+ }
4744
+ onTestBegin() {
4745
+ this.session?.testBegin();
4746
+ }
4747
+ onTestEnd(test, result) {
4748
+ const session = this.session;
4749
+ if (session === null) return;
4750
+ try {
4751
+ session.testEnd(test, result);
4752
+ } catch (error) {
4753
+ session.recordInternalError("onTestEnd", error);
4754
+ }
4755
+ }
4756
+ async onEnd(result) {
4757
+ if (this.session === null) return void 0;
4758
+ return this.session.end(result);
4759
+ }
4760
+ printsToStdio() {
4761
+ return false;
4762
+ }
4763
+ };
4764
+
4765
+ // src/entries/reporter.ts
4766
+ var reporter_default = PerfReporter;
4767
+
4768
+ exports.PerfReporter = PerfReporter;
4769
+ exports.default = reporter_default;