Repository navigation
Expand file tree
/
Copy pathbenchmark-readiness.ts
More file actions
1406 lines (1385 loc) · 51.5 KB
/
Copy pathbenchmark-readiness.ts
File metadata and controls
1406 lines (1385 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execFile } from 'node:child_process'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { promisify } from 'node:util'
import {
type Browser,
type BrowserContext,
chromium,
expect,
type Locator,
type Page,
type Request,
} from '@playwright/test'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { sleep } from '@sim/utils/helpers'
import { isRecordLike } from '@sim/utils/object'
import { escapeRegExp } from '@sim/utils/string'
/** Bounded production measurements: no builds, writes to services, or corpus crawling. */
const logger = createLogger('DocsReadinessBenchmark', { logLevel: 'INFO' })
const exec = promisify(execFile)
const LIGHTHOUSE_VERSION = '13.6.0'
const DEFAULT_ROUTES = [
'/introduction',
'/getting-started',
'/files/editor',
'/search/find-content',
'/integrations/cloudflare',
'/api-reference/logs/getLog',
'/workflows',
] as const
const PROFILES = [
{ name: 'desktop', width: 1440, height: 1000, dpr: 1, mobile: false, cpu: 1 },
{ name: 'mobile', width: 390, height: 844, dpr: 3, mobile: true, cpu: 4 },
] as const
type Profile = (typeof PROFILES)[number]
interface NetworkRecord {
url: string
type: string
method: string
prefetch: boolean
status?: number
headers?: Record<string, string>
sizes?: Awaited<ReturnType<Request['sizes']>>
timing?: ReturnType<Request['timing']>
failure?: string
}
interface BrowserObservations {
longTasks: Array<{ startTime: number; duration: number }>
shifts: Array<{ startTime: number; value: number; hadRecentInput: boolean }>
events: Array<{ name: string; startTime: number; duration: number }>
lcp: Array<{ startTime: number; size?: number; url?: string; element?: string }>
shell?: Element | null
}
interface BrowserWindow extends Window {
docsBenchmark?: BrowserObservations
}
interface Measurement {
profile: string
route: string
repetition: number
scenario: string
status: 'completed' | 'failed' | 'unavailable' | 'unverified'
durationMs: number
meaningfulPaintMs?: number
feedbackMs?: number
mediaReadyMs?: number
data?: unknown
error?: string
}
const baseSetting = process.env.DOCS_BENCHMARK_BASE_URL
const revision = process.env.DOCS_BENCHMARK_REVISION
const reportSetting = process.env.DOCS_BENCHMARK_REPORT_PATH
if (!baseSetting || !revision || !reportSetting)
throw new Error(
'DOCS_BENCHMARK_BASE_URL, DOCS_BENCHMARK_REVISION and DOCS_BENCHMARK_REPORT_PATH are required'
)
const reportPath: string = reportSetting
const base = new URL(baseSetting)
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password)
throw new Error('Use a public HTTP(S) docs URL without credentials')
const mode = process.env.DOCS_BENCHMARK_MODE ?? 'navigation'
if (!['navigation', 'lighthouse'].includes(mode))
throw new Error('Mode must be navigation or lighthouse')
const repetitions = Number(process.env.DOCS_BENCHMARK_REPETITIONS ?? 3)
if (!Number.isInteger(repetitions) || repetitions < 1 || repetitions > 5)
throw new Error('Repetitions must be an integer from 1 through 5')
const routes = process.env.DOCS_BENCHMARK_ROUTES?.split(',') ?? [...DEFAULT_ROUTES]
if (
routes.length > 8 ||
routes.some((route) => !route.startsWith('/') || new URL(route, base).origin !== base.origin)
)
throw new Error('Provide at most eight same-origin route paths')
const profiles = PROFILES.filter((profile) =>
(process.env.DOCS_BENCHMARK_PROFILES?.split(',') ?? ['desktop', 'mobile']).includes(profile.name)
)
if (!profiles.length) throw new Error('No valid benchmark profile selected')
const directory = dirname(reportPath)
const results: Measurement[] = []
const titles = new Map<string, string>()
const startedAt = new Date().toISOString()
let originBlocked: { url: string; status: 403; observedAt: string } | undefined
const scenarios = new Set(
process.env.DOCS_BENCHMARK_SCENARIOS?.split(',') ?? ['cold', 'warm', 'navigation', 'interactions']
)
await mkdir(directory, { recursive: true })
const nodeRuntime = (await exec('node', ['--version'], { timeout: 5000 })).stdout.trim()
function stats(values: number[]) {
if (!values.length) return { count: 0, median: null, min: null, max: null, raw: values }
const sorted = [...values].sort((left, right) => left - right)
const middle = Math.floor(sorted.length / 2)
return {
count: sorted.length,
median:
sorted.length % 2 ? sorted[middle] : ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2,
min: sorted[0],
max: sorted.at(-1),
raw: values,
}
}
async function save() {
const groups = new Map<string, Measurement[]>()
for (const result of results) {
const key = `${result.profile}:${result.scenario}:${result.route}`
groups.set(key, [...(groups.get(key) ?? []), result])
}
const summary = [...groups].map(([key, samples]) => ({
key,
completed: samples.filter((sample) => sample.status === 'completed').length,
meaningfulPaintMs: stats(
samples.flatMap((sample) =>
sample.meaningfulPaintMs === undefined ? [] : [sample.meaningfulPaintMs]
)
),
feedbackMs: stats(
samples.flatMap((sample) => (sample.feedbackMs === undefined ? [] : [sample.feedbackMs]))
),
mediaReadyMs: stats(
samples.flatMap((sample) => (sample.mediaReadyMs === undefined ? [] : [sample.mediaReadyMs]))
),
}))
await writeFile(
reportPath,
`${JSON.stringify(
{
baseUrl: base.href,
revision,
startedAt,
updatedAt: new Date().toISOString(),
mode,
originBlocked,
runtime: {
node: nodeRuntime,
bunNodeCompatibilityVersion: process.version,
bun: process.versions.bun,
platform: process.platform,
architecture: process.arch,
},
profiles,
repetitions,
routes,
lighthouseVersion: LIGHTHOUSE_VERSION,
methodology: {
concurrency: 1,
viewportPaint:
'Visible destination h1 and nonempty article, followed by two animation frames; URL alone is insufficient.',
feedback:
'Input action to observable UI state followed by two animation frames; automation overhead is included.',
media:
'Visible article images have decoded; measured separately from useful article paint.',
navigation:
'Existing site links only. No-hover case aborts prefetch requests and has HTTP cache disabled by Playwright routing. Intent case preserves normal caching and allows 500ms hover/focus dwell.',
documentLcp:
'LCP entries belong to their recorded document URL, not a subsequent client-side destination. Use meaningfulPaintMs for client-side navigation.',
mobileNetwork:
'Chromium CDP: 150ms latency, 1.6Mbps download, 750Kbps upload, 4x CPU slowdown.',
lighthouse:
'Desktop uses provided/unthrottled conditions; mobile uses Lighthouse default simulated throttling. Read each raw report configSettings for exact values.',
limits:
'Lab observations, not field Core Web Vitals; three repetitions are reported as median/range, never p95. Performance targets are observations, not brittle pass/fail timing assertions.',
},
summary,
results,
},
null,
2
)}\n`
)
}
async function measure(
profile: Profile,
route: string,
repetition: number,
scenario: string,
action: () => Promise<
Omit<Measurement, 'profile' | 'route' | 'repetition' | 'scenario' | 'durationMs'>
>
) {
if (originBlocked) {
results.push({
profile: profile.name,
route,
repetition,
scenario,
status: 'unverified',
durationMs: 0,
error: 'Origin returned HTTP 403; no further requests were attempted.',
data: originBlocked,
})
await save()
return
}
const start = performance.now()
logger.info('Measuring', { profile: profile.name, route, repetition, scenario })
try {
const observation = await action()
results.push({
profile: profile.name,
route,
repetition,
scenario,
durationMs: performance.now() - start,
...observation,
})
} catch (error) {
results.push({
profile: profile.name,
route,
repetition,
scenario,
status: 'failed',
durationMs: performance.now() - start,
error: getErrorMessage(error),
})
logger.error('Measurement failed', { route, scenario, error: getErrorMessage(error) })
}
await save()
}
async function instrument(context: BrowserContext) {
await context.addInitScript(() => {
const state: BrowserObservations = { longTasks: [], shifts: [], events: [], lcp: [] }
;(window as BrowserWindow).docsBenchmark = state
performance.setResourceTimingBufferSize(5000)
for (const type of ['longtask', 'layout-shift', 'event', 'largest-contentful-paint']) {
if (!PerformanceObserver.supportedEntryTypes.includes(type)) continue
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (type === 'longtask' && state.longTasks.length < 2000)
state.longTasks.push({ startTime: entry.startTime, duration: entry.duration })
else if (type === 'layout-shift' && state.shifts.length < 2000) {
const shift = entry as PerformanceEntry & { value: number; hadRecentInput: boolean }
state.shifts.push({
startTime: entry.startTime,
value: shift.value,
hadRecentInput: shift.hadRecentInput,
})
} else if (type === 'event' && state.events.length < 2000)
state.events.push({
name: entry.name,
startTime: entry.startTime,
duration: entry.duration,
})
else if (type === 'largest-contentful-paint') {
const paint = entry as PerformanceEntry & {
size?: number
url?: string
element?: Element
}
state.lcp.push({
startTime: entry.startTime,
size: paint.size,
url: paint.url,
element: paint.element?.tagName,
})
}
}
}).observe({ type, buffered: true, ...(type === 'event' ? { durationThreshold: 16 } : {}) })
}
})
}
async function contextFor(browser: Browser, profile: Profile, disablePrefetch = false) {
const context = await browser.newContext({
viewport: { width: profile.width, height: profile.height },
deviceScaleFactor: profile.dpr,
isMobile: profile.mobile,
hasTouch: profile.mobile,
colorScheme: 'light',
reducedMotion: 'reduce',
serviceWorkers: 'block',
})
if (disablePrefetch)
await context.route('**/*', async (route) => {
const headers = route.request().headers()
if (
headers['next-router-prefetch'] ||
headers['next-router-segment-prefetch'] ||
headers.purpose === 'prefetch'
)
await route.abort()
else await route.continue()
})
await instrument(context)
const page = await context.newPage()
page.setDefaultTimeout(30_000)
page.setDefaultNavigationTimeout(60_000)
const cdp = await context.newCDPSession(page)
await cdp.send('Performance.enable')
if (profile.mobile) {
await cdp.send('Network.enable')
await cdp.send('Network.emulateNetworkConditions', {
offline: false,
latency: 150,
downloadThroughput: 1_600_000 / 8,
uploadThroughput: 750_000 / 8,
})
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
}
const network: NetworkRecord[] = []
const requests = new Map<Request, NetworkRecord>()
const pending: Promise<void>[] = []
page.on('request', (request) => {
if (network.length >= 5000) return
const headers = request.headers()
const record = {
url: request.url(),
type: request.resourceType(),
method: request.method(),
prefetch: Boolean(
headers['next-router-prefetch'] ||
headers['next-router-segment-prefetch'] ||
headers.purpose === 'prefetch'
),
}
requests.set(request, record)
network.push(record)
})
page.on('response', (response) => {
const request = response.request()
if (
response.status() === 403 &&
new URL(response.url()).origin === base.origin &&
request.isNavigationRequest() &&
request.frame() === page.mainFrame()
) {
originBlocked = { url: response.url(), status: 403, observedAt: new Date().toISOString() }
void context.close().catch(() => {})
}
const record = requests.get(request)
if (!record) return
record.status = response.status()
const headers = response.headers()
record.headers = Object.fromEntries(
[
'content-type',
'content-encoding',
'content-length',
'cache-control',
'etag',
'last-modified',
'age',
'vary',
'x-vercel-cache',
'cf-cache-status',
].flatMap((key) => (headers[key] ? [[key, headers[key]]] : []))
)
})
page.on('requestfinished', (request) => {
const record = requests.get(request)
if (record)
pending.push(
request
.sizes()
.then((sizes) => {
record.sizes = sizes
record.timing = request.timing()
})
.catch(() => {})
)
})
page.on('requestfailed', (request) => {
const record = requests.get(request)
if (record) record.failure = request.failure()?.errorText
})
return { context, page, network, pending, cdp }
}
async function painted(page: Page) {
await page.evaluate(
() =>
new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
)
)
}
async function meaningful(page: Page, path: string, title?: string, previousTitle?: string) {
await page.waitForFunction(
({ expectedPath, expectedTitle, previous }) => {
const heading = document.querySelector('main h1') ?? document.querySelector('h1')
const article =
document.querySelector('main article') ??
document.querySelector('article') ??
document.querySelector('main')
return (
location.pathname.replace(/\/$/, '') === expectedPath.replace(/\/$/, '') &&
heading instanceof HTMLElement &&
heading.getClientRects().length > 0 &&
(!expectedTitle || heading.textContent?.trim() === expectedTitle) &&
(!previous || Boolean(expectedTitle) || heading.textContent?.trim() !== previous) &&
article instanceof HTMLElement &&
article.getClientRects().length > 0 &&
(article.textContent?.trim().length ?? 0) > 80
)
},
{ expectedPath: path, expectedTitle: title, previous: previousTitle }
)
await painted(page)
}
async function visibleMedia(page: Page) {
return page.evaluate(async () => {
const images = [...document.querySelectorAll<HTMLImageElement>('main img, article img')].filter(
(image) => {
const bounds = image.getBoundingClientRect()
return (
bounds.width > 0 && bounds.height > 0 && bounds.top < innerHeight && bounds.bottom > 0
)
}
)
await Promise.race([
Promise.all(images.map((image) => image.decode().catch(() => {}))),
new Promise<void>((_, reject) =>
setTimeout(
() => reject(new Error('Visible media did not decode within 20 seconds')),
20_000
)
),
])
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
return images.map((image) => ({
src: image.currentSrc,
loaded: image.complete && image.naturalWidth > 0,
}))
})
}
async function snapshot(page: Page, since = 0) {
return page.evaluate((start) => {
const state = (window as BrowserWindow).docsBenchmark
const resources = performance
.getEntriesByType('resource')
.filter((entry) => entry.startTime >= start)
.map((entry) => entry.toJSON())
return {
url: location.href,
title: document.querySelector('h1')?.textContent?.trim(),
now: performance.now(),
timeOrigin: performance.timeOrigin,
domElements: document.getElementsByTagName('*').length,
horizontalOverflow: document.documentElement.scrollWidth - innerWidth,
shellPreserved: state?.shell
? state.shell === document.querySelector('body header')
: undefined,
activeElement:
document.activeElement?.getAttribute('aria-label') ?? document.activeElement?.tagName,
navigation: performance.getEntriesByType('navigation').map((entry) => entry.toJSON()),
resources,
longTasks: state?.longTasks.filter((entry) => entry.startTime >= start),
eventTimings: state?.events.filter((entry) => entry.startTime >= start),
layoutShifts: state?.shifts.filter((entry) => entry.startTime >= start),
documentLcp: {
url: performance.getEntriesByType('navigation')[0]?.name,
entries: state?.lcp,
},
images: [...document.images].slice(0, 100).map((image) => {
const bounds = image.getBoundingClientRect()
return {
src: image.src,
currentSrc: image.currentSrc,
srcset: image.srcset,
sizes: image.sizes,
alt: image.alt,
naturalWidth: image.naturalWidth,
naturalHeight: image.naturalHeight,
width: bounds.width,
height: bounds.height,
dpr: devicePixelRatio,
loading: image.loading,
fetchPriority: image.fetchPriority,
complete: image.complete,
objectFit: getComputedStyle(image).objectFit,
objectPosition: getComputedStyle(image).objectPosition,
}
}),
}
}, since)
}
async function existingLink(page: Page, route: string): Promise<Locator | null> {
await page.waitForLoadState('load')
const exact = page.locator(`a[href="${route}"]`)
const visited = new Set<string>()
const folders = route.split('/').filter(Boolean).slice(0, -1)
for (let attempt = 0; attempt < 14; attempt++) {
const visible = exact.filter({ visible: true }).first()
if (await visible.count()) return visible
const menu = page
.getByRole('button', { name: /^(Menu|Open menu|Open navigation|Open sidebar)$/i })
.filter({ visible: true })
.first()
if (!visited.has('menu') && (await menu.count())) {
visited.add('menu')
await menu.click()
await painted(page)
continue
}
if (await exact.count()) {
const dialogTarget = page
.getByRole('dialog')
.filter({ visible: true })
.locator(`a[href="${route}"]`)
.first()
const hiddenTarget = (await dialogTarget.count()) ? dialogTarget : exact.first()
const controls = await hiddenTarget.evaluate((element) => {
const labels: string[] = []
let parent = element.parentElement
while (parent) {
if (parent.matches('aside, [role=dialog]')) break
if (getComputedStyle(parent).display === 'none' || parent.hidden) {
const trigger = parent.id
? document.querySelector<HTMLButtonElement>(
`button[aria-controls="${CSS.escape(parent.id)}"]`
)
: null
const candidate =
trigger ??
parent.parentElement?.querySelector<HTMLButtonElement>(
'button[aria-expanded="false"]'
)
const label = candidate?.getAttribute('aria-label') ?? candidate?.textContent?.trim()
if (label) labels.unshift(label)
}
parent = parent.parentElement
}
return labels
})
let opened = false
for (const control of controls) {
const button = page
.getByRole('button', { name: control, exact: true })
.filter({ visible: true })
.first()
if (await button.count()) {
await button.click()
await painted(page)
opened = true
break
}
}
if (opened) continue
}
let opened = false
for (const folder of folders) {
const label =
folder === 'api-reference' ? 'API(?: reference)?' : folder.replaceAll('-', '[ -]')
const branch = page
.getByRole('button', { name: new RegExp(`^(?:Expand )?${label}$`, 'i') })
.filter({ visible: true })
.first()
if ((await branch.count()) && (await branch.getAttribute('aria-expanded')) === 'false') {
await branch.click()
await painted(page)
opened = true
break
}
const path = `/${folders.slice(0, folders.indexOf(folder) + 1).join('/')}`
const ancestor = page.locator(`a[href="${path}"]`).filter({ visible: true }).first()
if (!visited.has(path) && (await ancestor.count())) {
visited.add(path)
await ancestor.click()
await meaningful(page, path)
opened = true
break
}
}
if (opened) continue
const section = route.startsWith('/api-reference/')
? /^API(?: reference)?$/i
: route.startsWith('/mcp/')
? /^MCP$/i
: route.startsWith('/cli')
? /^CLI$/i
: /^Documentation$/i
const sectionLink = page.getByRole('link', { name: section }).filter({ visible: true }).first()
const closeNavigation = page
.getByRole('button', { name: /^(Close navigation|Close sidebar)$/i })
.filter({ visible: true })
.first()
if (!(await sectionLink.count()) && (await closeNavigation.count())) {
await closeNavigation.click()
await painted(page)
continue
}
const sectionHref = (await sectionLink.count()) ? await sectionLink.getAttribute('href') : null
if (sectionHref && !visited.has(`section:${sectionHref}`)) {
visited.add(`section:${sectionHref}`)
const previousTitle = (await page.locator('h1').first().textContent())?.trim()
await sectionLink.click()
await meaningful(page, new URL(sectionHref, base).pathname, undefined, previousTitle)
visited.delete('menu')
continue
}
return null
}
return null
}
function searchInput(page: Page) {
return page
.getByRole('combobox', { name: /Search/i })
.or(page.getByRole('searchbox', { name: /Search/i }))
.or(page.getByPlaceholder(/Search/))
.filter({ visible: true })
.first()
}
async function readyForControls(page: Page) {
await page.waitForLoadState('load')
const input = searchInput(page)
if (!(await input.isVisible())) {
await page
.getByRole('button', {
name: /^(Search docs|Search documentation|Open Search|Search(?:\.\.\.)?(?:.*))$/i,
})
.filter({ visible: true })
.first()
.click()
}
await input.waitFor()
await expect(input).toBeFocused()
await page.keyboard.press('Escape')
await input.waitFor({ state: 'hidden' })
}
async function directSamples(
browser: Browser,
profile: Profile,
route: string,
repetition: number
) {
const run = await contextFor(browser, profile)
try {
for (const scenario of ['cold', 'warm']) {
if (!scenarios.has(scenario)) continue
await measure(profile, route, repetition, scenario, async () => {
const networkStart = run.network.length
const response =
scenario === 'cold' || run.page.url() === 'about:blank'
? await run.page.goto(new URL(route, base).href, { waitUntil: 'commit' })
: await run.page.reload({ waitUntil: 'commit' })
if (!response?.ok()) throw new Error(`Document returned ${response?.status()}`)
await meaningful(run.page, new URL(route, base).pathname)
const meaningfulPaintMs = await run.page.evaluate(() => performance.now())
const media = await visibleMedia(run.page)
const mediaReadyMs = await run.page.evaluate(() => performance.now())
await run.page.waitForLoadState('load')
await sleep(500)
const data = await snapshot(run.page)
if (data.title) titles.set(route, data.title)
await Promise.allSettled(run.pending)
const metrics = await run.cdp.send('Performance.getMetrics')
if (repetition === 1 && scenario === 'cold')
await run.page.screenshot({
path: join(directory, `${profile.name}-${route.replaceAll('/', '_')}.png`),
})
return {
status: 'completed',
meaningfulPaintMs,
mediaReadyMs,
data: {
...data,
media,
network: run.network.slice(networkStart),
chromiumMetrics: metrics,
},
}
})
}
} finally {
await run.context.close()
}
}
async function navigationSample(
browser: Browser,
profile: Profile,
route: string,
repetition: number,
intent: boolean
) {
const run = await contextFor(browser, profile, !intent)
try {
await measure(
profile,
route,
repetition,
intent ? 'intent-navigation' : 'uncached-navigation',
async () => {
const source = route === '/introduction' ? '/getting-started' : '/introduction'
await run.page.goto(new URL(source, base).href, { waitUntil: 'domcontentloaded' })
await meaningful(run.page, new URL(source, base).pathname)
const link = await existingLink(run.page, route)
if (!link)
return {
status: 'unavailable',
error:
'No reachable existing navigation link found; do not substitute an injected link or router call.',
}
await link.scrollIntoViewIfNeeded()
const beforeIntent = run.network.length
if (intent) {
if (profile.mobile) await link.focus()
else await link.hover()
await sleep(500)
}
const beforeClick = run.network.length
const previousTitle = (await run.page.locator('h1').first().textContent())?.trim()
const start = await run.page.evaluate(() => {
const state = (window as BrowserWindow).docsBenchmark
if (state) state.shell = document.querySelector('body header')
return performance.now()
})
await link.click()
await meaningful(run.page, new URL(route, base).pathname, titles.get(route), previousTitle)
const meaningfulPaintMs = await run.page.evaluate((then) => performance.now() - then, start)
const media = await visibleMedia(run.page)
const mediaReadyMs = await run.page.evaluate((then) => performance.now() - then, start)
await sleep(500)
const data = await snapshot(run.page, start)
await Promise.allSettled(run.pending)
const network = run.network.slice(beforeClick)
const documentReload = network.some((request) => request.type === 'document')
return {
status: 'completed',
meaningfulPaintMs: documentReload ? undefined : meaningfulPaintMs,
mediaReadyMs: documentReload ? undefined : mediaReadyMs,
data: {
...data,
documentReload,
media,
prefetchDuringIntent: run.network.slice(beforeIntent, beforeClick),
network,
},
}
}
)
} finally {
await run.context.close()
}
}
async function interactions(browser: Browser, profile: Profile, repetition: number) {
if (originBlocked) {
await measure(profile, '/introduction', repetition, 'interactions-suite', async () => ({
status: 'unverified',
}))
return
}
const run = await contextFor(browser, profile)
try {
await measure(profile, '/introduction', repetition, 'interaction-page', async () => {
const response = await run.page.goto(new URL('/introduction', base).href, {
waitUntil: 'domcontentloaded',
})
if (!response?.ok()) throw new Error(`Document returned ${response?.status()}`)
await meaningful(run.page, new URL('/introduction', base).pathname)
return { status: 'completed' }
})
await measure(profile, '/introduction', repetition, 'cold-shortcut-observation', async () => {
const at = await run.page.evaluate(() => ({
readyState: document.readyState,
time: performance.now(),
}))
await run.page.keyboard.press('ControlOrMeta+k')
await painted(run.page)
return {
status: 'completed',
data: {
...at,
openedAfterTwoFrames: await searchInput(run.page).isVisible(),
interpretation:
'Early input observation, before control readiness. Not included in warm search timing.',
},
}
})
await measure(profile, '/introduction', repetition, 'control-readiness', async () => {
await readyForControls(run.page)
return { status: 'completed', data: { searchOpenedFocusedAndClosed: true } }
})
await measure(profile, '/introduction', repetition, 'search-open', async () => {
const start = performance.now()
await run.page.keyboard.press('ControlOrMeta+k')
const input = run.page
.getByRole('combobox')
.or(run.page.getByRole('searchbox'))
.or(run.page.getByPlaceholder(/Search/))
.filter({ visible: true })
.first()
await input.waitFor()
await painted(run.page)
const feedbackMs = performance.now() - start
return {
status: 'completed',
feedbackMs,
data: { focused: await input.evaluate((element) => document.activeElement === element) },
}
})
await measure(profile, '/introduction', repetition, 'search-result-navigation', async () => {
const input = run.page
.getByRole('combobox')
.or(run.page.getByRole('searchbox'))
.or(run.page.getByPlaceholder(/Search/))
.filter({ visible: true })
.first()
const start = performance.now()
await input.fill('Slack')
const result = run.page
.getByRole('dialog')
.locator('[role=option], button[aria-selected]')
.filter({ hasText: /Slack/i })
.first()
await result.waitFor()
await painted(run.page)
const feedbackMs = performance.now() - start
const navigationStart = performance.now()
await result.click()
await run.page.waitForURL((url) => url.pathname !== '/introduction')
await meaningful(run.page, new URL(run.page.url()).pathname, undefined, 'Introduction')
return {
status: 'completed',
feedbackMs,
meaningfulPaintMs: performance.now() - navigationStart,
data: {
destination: run.page.url(),
openDialogs: await run.page.getByRole('dialog').count(),
...(await snapshot(run.page)),
},
}
})
await measure(profile, '/introduction', repetition, 'media-dialog', async () => {
await run.page.goto(new URL('/introduction', base).href, { waitUntil: 'domcontentloaded' })
await meaningful(run.page, new URL('/introduction', base).pathname)
await readyForControls(run.page)
const trigger = run.page.getByRole('button', { name: /Open .*in media viewer/i }).first()
if (!(await trigger.count()))
return { status: 'unavailable', error: 'No media viewer trigger on this baseline.' }
const before = run.network.length
const start = performance.now()
await trigger.click()
const dialog = run.page.getByRole('dialog').first()
await dialog.waitFor()
await painted(run.page)
const feedbackMs = performance.now() - start
const data = await snapshot(run.page)
await run.page.keyboard.press('Escape')
await dialog.waitFor({ state: 'hidden' })
await run.page.waitForFunction(() =>
document.activeElement?.getAttribute('aria-label')?.includes('media viewer')
)
await Promise.allSettled(run.pending)
return {
status: 'completed',
feedbackMs,
data: {
...data,
focusRestored: await trigger.evaluate((element) => element === document.activeElement),
viewerRequests: run.network.slice(before),
},
}
})
await measure(profile, '/introduction', repetition, 'history-and-footer', async () => {
const link = await existingLink(run.page, '/getting-started')
if (!link) return { status: 'unavailable', error: 'Getting-started link unavailable' }
await run.page.evaluate(() => window.scrollTo(0, 500))
const scrollBefore = await run.page.evaluate(() => window.scrollY)
await link.click()
await meaningful(run.page, new URL('/getting-started', base).pathname)
await run.page.goBack({ waitUntil: 'commit' })
await meaningful(run.page, new URL('/introduction', base).pathname)
const scrollAfter = await run.page.evaluate(() => window.scrollY)
await run.page.goForward({ waitUntil: 'commit' })
await meaningful(run.page, new URL('/getting-started', base).pathname)
const footer = run.page.locator('footer a[href="/introduction"]').first()
const before = run.network.length
if (await footer.count()) {
await footer.click()
await meaningful(run.page, new URL('/introduction', base).pathname)
}
return {
status: 'completed',
data: {
scrollBefore,
scrollAfter,
footerPresent: (await footer.count()) > 0,
footerDocumentReload: run.network
.slice(before)
.some((request) => request.type === 'document'),
network: run.network.slice(before),
},
}
})
await measure(profile, '/introduction', repetition, 'theme-control', async () => {
const control = run.page
.getByRole('button', { name: 'Dark', exact: true })
.or(run.page.getByRole('button', { name: /^Toggle theme$/i }))
.filter({ visible: true })
.first()
if (!(await control.count()))
return { status: 'unavailable', error: 'No named theme control found on this baseline.' }
await control.scrollIntoViewIfNeeded()
const before = await run.page.locator('html').getAttribute('class')
const start = performance.now()
await control.click()
await run.page.waitForFunction(
(previous) => document.documentElement.className !== previous,
before
)
await painted(run.page)
const feedbackMs = performance.now() - start
const selectedTheme = await run.page.locator('html').getAttribute('class')
await run.page.reload({ waitUntil: 'domcontentloaded' })
await meaningful(run.page, new URL(run.page.url()).pathname)
return {
status: 'completed',
feedbackMs,
data: {
selectedTheme,
afterReload: await run.page.locator('html').getAttribute('class'),
limitation:
'Final theme persistence only; this does not establish flash-free first paint.',
},
}
})
await apiControls(run, profile, repetition)
await measure(profile, '/workflows', repetition, 'workflow-canvas-control', async () => {
await run.page.goto(new URL('/workflows', base).href, { waitUntil: 'domcontentloaded' })
await meaningful(run.page, new URL('/workflows', base).pathname)
const trigger = run.page
.getByRole('button', { name: /^(Expand .*workflow preview|Inspect workflow: .*)$/i })
.first()
await trigger.waitFor({ state: 'visible', timeout: 15_000 })
await trigger.click({ trial: true })
const start = performance.now()
await trigger.click()
const dialog = run.page.getByRole('dialog').first()
await dialog.waitFor()
await painted(run.page)
const feedbackMs = performance.now() - start
const canvas = dialog.locator('.react-flow__pane')
const viewport = dialog.locator('.react-flow__viewport')
const node = dialog.locator('.react-flow__node').first()
await expect(node).toBeVisible()
await painted(run.page)
const bounds = await canvas.boundingBox()
if (!bounds) throw new Error('Workflow canvas has no visible bounds')
const transform = (element: Locator) =>
element.evaluate((element) => {
const matrix = new DOMMatrixReadOnly(getComputedStyle(element).transform)
return { x: matrix.e, y: matrix.f, scale: matrix.a }
})
const beforePan = await transform(viewport)
const x = bounds.x + bounds.width / 2
const y = bounds.y + bounds.height - 24
await run.page.mouse.move(x, y)
await run.page.mouse.down()
await run.page.mouse.move(x + 24, y - 24, { steps: 5 })
await run.page.mouse.up()
await expect.poll(async () => (await transform(viewport)).x).not.toBe(beforePan.x)
const afterPan = await transform(viewport)
expect(afterPan.scale).toBe(beforePan.scale)
const beforeZoom = afterPan.scale
await run.page.mouse.wheel(0, -80)
await expect
.poll(() =>
viewport.evaluate(
(element) => new DOMMatrixReadOnly(getComputedStyle(element).transform).a
)
)
.toBeGreaterThan(beforeZoom)
await node.click({ trial: true, position: { x: 8, y: 8 } })
const afterZoom = await transform(viewport)
const nodeBefore = await transform(node)
const nodeBounds = await node.boundingBox()