-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser-command-runners.ts
More file actions
5581 lines (5226 loc) · 239 KB
/
Copy pathbrowser-command-runners.ts
File metadata and controls
5581 lines (5226 loc) · 239 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 { createHash } from "node:crypto"
import { access, mkdir, readFile, writeFile } from "node:fs/promises"
import { dirname, join, relative } from "node:path"
import { assertRuntimeCommandAllowed, browserInteractionScriptUsesEvaluate, validateBrowserInteractionScript, type BrowserInteractionStep, type ExecutionSpec, type RuntimeCreateSpec } from "@automattic/wp-codebox-core"
import pixelmatch from "pixelmatch"
import { PNG } from "pngjs"
import { browserInteractionStepsFromArgs, browserStepTimeoutMs, durationStringMs, sanitizeScreenshotName } from "./browser-actions.js"
import type { BrowserArtifact, BrowserArtifactSummary, BrowserEditorCanvasProbeDiagnostic, BrowserEditorCanvasProbeSummary, BrowserEditorCanvasSelectorGroupSummary, BrowserEditorCanvasSelectorSummary, BrowserProbeArtifact, BrowserProbeArtifactRef, BrowserProbeAuthSummary, BrowserProbeCapabilityDiagnostics, BrowserProbeCheckpointRecord, BrowserProbeContextDetails, BrowserProbeErrorRecord, BrowserProbeLifecycleArtifact, BrowserProbeMeasuredMetric, BrowserProbeMemoryArtifact, BrowserProbeNetworkCountSummary, BrowserProbeNetworkRecord, BrowserProbeNetworkReviewSummary, BrowserProbePerformanceArtifact, BrowserProbePreviewRouting, BrowserProbeReviewSummary, BrowserProbeScriptMetadata, BrowserProbeViewport, BrowserRedirectDiagnosticsSummary, BrowserStepRecord, BrowserWordPressDiagnosticsSummary } from "./browser-artifacts.js"
import { attachBrowserCaptureListeners, chromiumBrowserMetadata, launchChromiumBrowser, settleBrowserNetworkTasks } from "./browser-capture-session.js"
import { browserAssertionsSummary, browserStepRecord, executeBrowserInteractionStep } from "./browser-interactions.js"
import { BrowserCommandLivenessError, browserCommandLivenessPolicy, withBrowserCommandLiveness, type BrowserCommandLivenessPolicy } from "./browser-liveness.js"
import { browserProbeLifecycleArtifact, browserProbeLifecycleInitScript, collectBrowserProbeLifecycle } from "./browser-lifecycle.js"
import { browserProbeBenchMetrics, jsonLines, serializeBrowserError } from "./browser-metrics.js"
import { browserPreviewNetworkPolicy, browserPreviewNetworkPolicyIsActive, browserPreviewNetworkPolicySummary, browserPreviewNeedsContextRouting, browserPreviewOrigins, browserPreviewReadinessError, browserPreviewRouting, browserPreviewSecureContextError, resolveBrowserPreviewUrl, routeBrowserPreviewContextNetwork, routeBrowserPreviewPageNetwork } from "./browser-preview-routing.js"
import { BROWSER_PROBE_CAPTURE_VALUES, BROWSER_PROBE_PERFORMANCE_INIT_SCRIPT, BROWSER_PROBE_STATE_INIT_SCRIPT, browserProbeAssertionsFromArgs, browserProbeAssertionsNeedMetrics, browserProbeAssertionsNeedNetwork, browserProbeCheckpoint, browserProbeMemoryArtifact, browserProbePendingCheckpoints, browserProbePerformanceArtifact, browserProbeReplayability, browserProbeViewport, executeBrowserProbeAssertions, navigateBrowserProbe } from "./browser-probe.js"
import { argValue, cleanWpCliOutput, commaListArg, durationArg, jsonArrayArg, strictBooleanArg, viewportArg } from "./commands.js"
import { editorActionStepsFromArgs, editorOpenTargetFromArgs, type EditorActionStep } from "./editor-actions.js"
import { bootstrapPhpCode } from "./php-bootstrap.js"
import { assertPlaygroundResponseOk, type PlaygroundRunResponse } from "./playground-command-errors.js"
import type { PlaygroundCliServer } from "./preview-server.js"
import type { Page } from "playwright"
const BROWSER_STEP_DEFAULT_TIMEOUT_MS = 15_000
const BROWSER_SCRIPT_DEFAULT_TIMEOUT_MS = 120_000
const EDITOR_CANVAS_DEFAULT_IFRAME_SELECTOR = 'iframe[name="editor-canvas"]'
const EDITOR_CANVAS_DEFAULT_LAYOUT_SELECTOR = ".block-editor-block-list__layout"
const EDITOR_CANVAS_DEFAULT_BLOCK_SELECTOR = ".block-editor-block-list__block, [data-block]"
const EDITOR_CANVAS_DEFAULT_TIMEOUT_MS = 30_000
const BROWSER_PROBE_PROFILE_OVERRIDES = new Set(["browser", "device", "locale", "permissions", "throttle", "timezone", "user-agent", "viewport"])
const VISUAL_EXPLANATION_STYLE_PROPERTIES = ["display", "position", "box-sizing", "width", "height", "margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left", "font-family", "font-size", "font-weight", "line-height", "letter-spacing", "color", "background-color", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "opacity", "transform", "visibility"] as const
const VISUAL_EXPLANATION_ATTRIBUTE_NAMES = ["id", "class", "role", "aria-label", "title", "href", "src", "type", "name"] as const
interface BrowserProbeProfileDefinition {
id: string
browser: "chromium" | "webkit"
args: string[]
}
interface BrowserProbeRunPlan {
url: string
capture: Set<string>
waitFor: string
durationMs: number
requestedViewport?: { width: number; height: number }
throttleProfile?: BrowserProbeThrottleProfileDefinition
requestedContext: BrowserProbeContextDetails["requested"]
prePageScript?: string
script?: string
authRequest?: { userId: number }
failFast: boolean
stallTimeoutMs: number
wallTimeoutMs: number
lifecycleSelectors: string[]
assertions: ReturnType<typeof browserProbeAssertionsFromArgs>
}
interface BrowserActionsRunPlan {
initialUrl?: string
steps: BrowserInteractionStep[]
capture: Set<string>
stepTimeoutMs: number
totalTimeoutMs: number
networkSettleTimeoutMs: number
requestedViewport?: { width: number; height: number }
authRequest?: { userId: number }
maxDomSnapshotElements: number
}
interface BrowserRunPlan {
profile: string
capture: string[]
probe?: BrowserProbeRunPlan
actions?: BrowserActionsRunPlan
}
interface BrowserCommandProgressEvent {
command: string
phase: "checkpoint"
checkpoint: BrowserProbeScriptCheckpoint
progress: ReturnType<ReturnType<typeof createBrowserProbeProgressTracker>["summary"]>
}
interface BrowserProbeScriptCheckpoint {
name: string
metadata?: unknown
timestamp: string
}
interface VisualCompareDomElementSnapshot {
path: string
tag: string
text: string
attributes: Record<string, string>
boundingBox: { x: number; y: number; width: number; height: number }
styles: Record<string, string>
}
interface VisualCompareSelectorSnapshot {
selector: string
matched: number
captured: number
paths: string[]
error?: string
}
interface VisualCompareDomSnapshot {
url: string
title: string
elementCount: number
capturedElements: VisualCompareDomElementSnapshot[]
selectors?: VisualCompareSelectorSnapshot[]
truncated: boolean
}
interface VisualCompareDomSnapshotArtifact {
schema: "wp-codebox/browser-dom-snapshot/v1"
command: "wordpress.browser-actions" | "wordpress.visual-compare"
screenshot: string
step?: { index: number; name?: string; kind: string }
finalUrl: string
viewport: BrowserProbeViewport | null
capturedAt: string
limits: { maxElements: number }
summary: { elementCount: number; capturedElements: number; truncated: boolean }
snapshot: VisualCompareDomSnapshot
}
interface VisualCompareElementDelta {
path: string
tag: string
changes: {
text?: { source: string; candidate: string }
boundingBox?: { source: VisualCompareDomElementSnapshot["boundingBox"]; candidate: VisualCompareDomElementSnapshot["boundingBox"]; delta: { x: number; y: number; width: number; height: number } }
attributes?: Record<string, { source: string | null; candidate: string | null }>
styles?: Record<string, { source: string; candidate: string }>
}
}
interface VisualCompareMismatchRegion {
x: number
y: number
width: number
height: number
pixels: number
}
interface VisualCompareDimensionDriftRegion extends VisualCompareMismatchRegion {
owner: "source" | "candidate"
}
interface VisualCompareDimensionDrift {
widthDelta: number
heightDelta: number
sourceOnly: VisualCompareDimensionDriftRegion[]
candidateOnly: VisualCompareDimensionDriftRegion[]
}
interface VisualCompareExplanation {
schema: "wp-codebox/visual-explanation/v1"
source: { label: string; url: string; title: string; elementCount: number; capturedElements: number; truncated: boolean }
candidate: { label: string; url: string; title: string; elementCount: number; capturedElements: number; truncated: boolean }
viewport: BrowserProbeViewport | null
mismatchRegions: VisualCompareMismatchRegion[]
selectors?: Array<{ selector: string; source: VisualCompareSelectorSnapshot; candidate: VisualCompareSelectorSnapshot }>
missingSelectors?: Array<{ selector: string; sourceMatched: boolean; candidateMatched: boolean; sourceError?: string; candidateError?: string }>
limits: { maxElements: number; maxCandidates: number }
truncation: { changed: boolean; added: boolean; removed: boolean }
summary: { changedElements: number; addedElements: number; removedElements: number; sourceCapturedElements: number; candidateCapturedElements: number }
changes: VisualCompareElementDelta[]
added: VisualCompareDomElementSnapshot[]
removed: VisualCompareDomElementSnapshot[]
limitations: string[]
}
interface VisualCompareComparisonMetrics {
status?: string
mismatchRatio?: number
mismatchPixels?: number
totalPixels?: number
dimensionMismatch?: boolean
}
interface VisualCompareComparisonSummary extends VisualCompareComparisonMetrics {
source?: { label?: string; url?: string; screenshot?: string }
candidate?: { label?: string; url?: string; screenshot?: string }
}
interface VisualCompareBaselineDelta {
ref: string
selectedIndex: number
match: "labels" | "only-comparison" | "first-comparison"
availableComparisons: number
baseline: VisualCompareComparisonSummary
delta: {
status?: { baseline?: string; current: string; changed: boolean }
mismatchRatio?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
mismatchPixels?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
totalPixels?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
dimensionMismatch?: { baseline: boolean; current: boolean; changed: boolean }
}
}
const BROWSER_PROBE_PROFILES: Record<string, BrowserProbeProfileDefinition> = {
"desktop-chrome": {
id: "desktop-chrome",
browser: "chromium",
args: ["browser=chromium", "viewport=1280x720"],
},
"mobile-chrome": {
id: "mobile-chrome",
browser: "chromium",
args: ["browser=chromium", "device=Pixel 5"],
},
"low-end-mobile-slow-4g": {
id: "low-end-mobile-slow-4g",
browser: "chromium",
args: ["browser=chromium", "device=Pixel 5", "throttle=low-end-mobile-slow-4g"],
},
"desktop-webkit": {
id: "desktop-webkit",
browser: "webkit",
args: ["browser=webkit", "viewport=1280x720"],
},
"mobile-webkit": {
id: "mobile-webkit",
browser: "webkit",
args: ["browser=webkit", "device=iPhone 13"],
},
}
interface BrowserProbeThrottleProfileDefinition {
id: string
cpuSlowdownRate: number
network: {
offline: boolean
latencyMs: number
downloadThroughputBytesPerSecond: number
uploadThroughputBytesPerSecond: number
}
}
const BROWSER_PROBE_THROTTLE_PROFILES: Record<string, BrowserProbeThrottleProfileDefinition> = {
"low-end-mobile-slow-4g": {
id: "low-end-mobile-slow-4g",
cpuSlowdownRate: 4,
network: {
offline: false,
latencyMs: 150,
downloadThroughputBytesPerSecond: 1_600_000 / 8,
uploadThroughputBytesPerSecond: 750_000 / 8,
},
},
}
export class BrowserCommandArtifactError extends Error {
constructor(message: string, readonly artifact: BrowserArtifact) {
super(message)
this.name = "BrowserCommandArtifactError"
}
}
export function isBrowserCommandArtifactError(error: unknown): error is BrowserCommandArtifactError {
return error instanceof BrowserCommandArtifactError
}
export async function runBrowserProbeCommand({
abortSignal,
artifactRoot,
command = "wordpress.browser-probe",
plan,
runtimeSpec,
runPlaygroundCommand,
server,
spec,
onProgress,
}: {
abortSignal?: AbortSignal
artifactRoot: string
command?: string
plan?: BrowserProbeRunPlan
runtimeSpec?: RuntimeCreateSpec
runPlaygroundCommand?: (command: string, server: PlaygroundCliServer, options: { code: string } | { scriptPath: string }) => Promise<PlaygroundRunResponse>
server: PlaygroundCliServer
spec: ExecutionSpec
onProgress?: (event: BrowserCommandProgressEvent) => void
}): Promise<{ artifact: BrowserProbeArtifact; artifacts?: BrowserProbeArtifact[]; output: string }> {
if (plan) {
return runSingleBrowserProbeCommand({ abortSignal, artifactRoot, command, plan, runtimeSpec, runPlaygroundCommand, server, spec, browserFilesDirectory: "files/browser", onProgress })
}
const profileIds = browserProbeProfileIds(spec.args ?? [])
if (profileIds.length === 0) {
const profileId = argValue(spec.args ?? [], "profile")?.trim()
if (profileId) {
const profile = browserProbeProfile(profileId)
if (profile.browser !== "chromium") {
throw new Error(`wordpress.browser-probe profile ${profile.id} requests ${profile.browser}, but this runner currently supports Chromium profiles only. Supported Chromium profiles: desktop-chrome, mobile-chrome, low-end-mobile-slow-4g.`)
}
return runSingleBrowserProbeCommand({
abortSignal,
artifactRoot,
command,
runtimeSpec,
runPlaygroundCommand,
server,
spec: { ...spec, args: browserProbeProfileArgs(spec.args ?? [], profile) },
browserFilesDirectory: "files/browser",
profileId: profile.id,
onProgress,
})
}
return runSingleBrowserProbeCommand({ abortSignal, artifactRoot, command, runtimeSpec, runPlaygroundCommand, server, spec, browserFilesDirectory: "files/browser", onProgress })
}
const profiles = profileIds.map((profileId) => browserProbeProfile(profileId))
for (const profile of profiles) {
if (profile.browser !== "chromium") {
throw new Error(`wordpress.browser-probe profile ${profile.id} requests ${profile.browser}, but this runner currently supports Chromium profiles only. Supported Chromium profiles: desktop-chrome, mobile-chrome, low-end-mobile-slow-4g.`)
}
}
const artifacts: BrowserProbeArtifact[] = []
const outputs: unknown[] = []
for (const profile of profiles) {
const result = await runSingleBrowserProbeCommand({
abortSignal,
artifactRoot,
command,
runtimeSpec,
runPlaygroundCommand,
server,
spec: {
...spec,
args: browserProbeProfileArgs(spec.args ?? [], profile),
},
browserFilesDirectory: `files/browser/${profile.id}`,
profileId: profile.id,
onProgress,
})
artifacts.push(result.artifact)
outputs.push(JSON.parse(result.output))
}
const artifact = artifacts[0]
if (!artifact) {
throw new Error("wordpress.browser-probe profiles requires at least one profile")
}
return {
artifact,
artifacts,
output: `${JSON.stringify({
command,
schema: "wp-codebox/browser-probe-profile-matrix/v1",
profiles: outputs,
}, null, 2)}\n`,
}
}
async function runSingleBrowserProbeCommand({
abortSignal,
artifactRoot,
command,
plan,
runtimeSpec,
runPlaygroundCommand,
server,
spec,
browserFilesDirectory,
profileId,
onProgress,
}: {
abortSignal?: AbortSignal
artifactRoot: string
command: string
plan?: BrowserProbeRunPlan
runtimeSpec?: RuntimeCreateSpec
runPlaygroundCommand?: (command: string, server: PlaygroundCliServer, options: { code: string } | { scriptPath: string }) => Promise<PlaygroundRunResponse>
server: PlaygroundCliServer
spec: ExecutionSpec
browserFilesDirectory: string
profileId?: string
onProgress?: (event: BrowserCommandProgressEvent) => void
}): Promise<{ artifact: BrowserProbeArtifact; output: string }> {
const args = spec.args ?? []
const runPlan = plan ?? browserProbeRunPlanFromArgs(args, profileId)
if (!runPlan.url) {
throw new Error("wordpress.browser-probe requires url=<path-or-url>")
}
const capture = runPlan.capture
for (const item of capture) {
if (!(BROWSER_PROBE_CAPTURE_VALUES as readonly string[]).includes(item)) {
throw new Error(`wordpress.browser-probe capture supports ${BROWSER_PROBE_CAPTURE_VALUES.join(", ")}: ${item}`)
}
}
const waitFor = runPlan.waitFor
const durationMs = runPlan.durationMs
const requestedViewport = runPlan.requestedViewport
const throttleProfile = runPlan.throttleProfile
const requestedContext = runPlan.requestedContext
const prePageScript = runPlan.prePageScript
const script = runPlan.script
const authRequest = runPlan.authRequest
const failFast = runPlan.failFast
const stallTimeoutMs = runPlan.stallTimeoutMs
const wallTimeoutMs = runPlan.wallTimeoutMs
const livenessPolicy = browserCommandLivenessPolicy({ wallTimeoutMs, idleTimeoutMs: stallTimeoutMs })
const lifecycleSelectors = runPlan.lifecycleSelectors
const routedHosts = commaListArg(args, "route-host")
const assertions = runPlan.assertions
const capturesConsoleForAssertions = assertions.some((assertion) => assertion.type === "no-console-errors" || assertion.type === "no-errors")
const capturesErrorsForAssertions = assertions.some((assertion) => assertion.type === "no-page-errors" || assertion.type === "no-errors")
const capturesNetworkForAssertions = browserProbeAssertionsNeedNetwork(assertions)
const capturesBrowserMetrics = capture.has("performance") || capture.has("memory") || browserProbeAssertionsNeedMetrics(assertions)
const prePageScriptMetadata = prePageScript ? browserProbeScriptMetadata(prePageScript) : undefined
const preview = browserPreviewRouting(args, runtimeSpec, server.serverUrl)
const networkPolicy = browserPreviewNetworkPolicy(args, routedHosts, preview)
const previewOrigins = browserPreviewOrigins(preview)
const targetUrl = resolveBrowserPreviewUrl(runPlan.url, preview.effectiveOrigin)
const browserDirectory = join(artifactRoot, browserFilesDirectory)
await mkdir(browserDirectory, { recursive: true })
const consoleMessages: Record<string, unknown>[] = []
const errors: BrowserProbeErrorRecord[] = []
const network: BrowserProbeNetworkRecord[] = []
const networkTasks: Array<Promise<void>> = []
const checkpoints: BrowserProbeCheckpointRecord[] = []
const consolePath = join(browserDirectory, "console.jsonl")
const checkpointsPath = join(browserDirectory, "checkpoints.jsonl")
const errorsPath = join(browserDirectory, "errors.jsonl")
const htmlPath = join(browserDirectory, "snapshot.html")
const memoryPath = join(browserDirectory, "memory.json")
const lifecyclePath = join(browserDirectory, "lifecycle.json")
const networkPath = join(browserDirectory, "network.jsonl")
const performancePath = join(browserDirectory, "performance.json")
const reviewPath = join(browserDirectory, "review.json")
const screenshotPath = join(browserDirectory, "screenshot.png")
const summaryPath = join(browserDirectory, "summary.json")
const redirectDiagnosticsPath = join(browserDirectory, "redirect-diagnostics.json")
const wordpressDiagnosticsPath = join(browserDirectory, "wordpress-diagnostics.json")
const startedAt = now()
const startedAtMs = Date.now()
const progress = createBrowserProbeProgressTracker(startedAt, stallTimeoutMs)
const { devices } = await import("playwright")
if (requestedContext.browser && requestedContext.browser !== "chromium") {
throw new Error(`wordpress.browser-probe browser=${requestedContext.browser} is unsupported by this runner; use browser=chromium or a Chromium profile.`)
}
const deviceProfile = requestedContext.device ? devices[requestedContext.device] : undefined
if (requestedContext.device && !deviceProfile) {
throw new Error(`wordpress.browser-probe unknown Playwright device profile: ${requestedContext.device}`)
}
const browser = await launchChromiumBrowser()
const browserMetadata = chromiumBrowserMetadata(browser)
let finalUrl = targetUrl
let windowLocationOrigin: string | undefined
let htmlSha256: string | undefined
let screenshotSha256: string | undefined
let viewport: BrowserProbeViewport | null = null
let scriptResult: unknown
let lifecycleArtifact: BrowserProbeLifecycleArtifact | undefined
let memoryArtifact: BrowserProbeMemoryArtifact | undefined
let performanceArtifact: BrowserProbePerformanceArtifact | undefined
let page: import("playwright").Page | null = null
let context: import("playwright").BrowserContext | null = null
let contextDetails: BrowserProbeContextDetails | undefined
let authSummary: BrowserProbeAuthSummary | undefined
let capabilityDiagnostics: BrowserProbeCapabilityDiagnostics | undefined
let assertionResults: import("./browser-artifacts.js").BrowserStepAssertion[] = []
let pendingError: Error | undefined
let artifact: BrowserProbeArtifact | undefined
let wordpressDiagnosticsReady = false
const abortHandler = () => {
pendingError = pendingError ?? new Error("Browser command aborted during runtime cleanup")
void page?.close().catch(() => undefined)
void context?.close().catch(() => undefined)
void browser.close().catch(() => undefined)
}
abortSignal?.addEventListener("abort", abortHandler, { once: true })
try {
if (abortSignal?.aborted) {
abortHandler()
throw pendingError
}
context = browserPreviewNeedsContextRouting(networkPolicy) || requestedContext.device || requestedContext.locale || requestedContext.timezone || requestedContext.userAgent || (requestedContext.permissions?.length ?? 0) > 0
? await browser.newContext({
...(deviceProfile ?? {}),
...(requestedContext.locale ? { locale: requestedContext.locale } : {}),
...(requestedContext.timezone ? { timezoneId: requestedContext.timezone } : {}),
...(requestedContext.userAgent ? { userAgent: requestedContext.userAgent } : {}),
})
: null
if (context && requestedContext.permissions && requestedContext.permissions.length > 0) {
await context.grantPermissions(requestedContext.permissions)
}
if (context && browserPreviewNeedsContextRouting(networkPolicy)) {
await routeBrowserPreviewContextNetwork(context, networkPolicy, preview.localOrigin)
}
page = context ? await context.newPage() : await browser.newPage()
if (onProgress) {
await page.exposeFunction("__wpCodeboxProbeCheckpointEvent", (checkpoint: unknown) => {
const normalized = normalizeBrowserProbeScriptCheckpoint(checkpoint)
if (!normalized) {
return
}
progress.mark("checkpoint", normalized.timestamp, normalized)
onProgress({ command, phase: "checkpoint", checkpoint: normalized, progress: progress.summary() })
})
}
if (authRequest) {
authSummary = await installWordPressAdminAuthCookies({ command, cookieUrls: browserAuthCookieUrls(server.serverUrl, routedHosts, [targetUrl]), page, runPlaygroundCommand, runtimeSpec, server, userId: authRequest.userId })
}
if (requestedViewport) {
await page.setViewportSize(requestedViewport)
}
if (throttleProfile) {
await applyBrowserProbeThrottleProfile(page, throttleProfile)
}
if (!context && browserPreviewNeedsContextRouting(networkPolicy)) {
await routeBrowserPreviewPageNetwork(page, networkPolicy, preview.localOrigin)
}
await page.addInitScript(BROWSER_PROBE_STATE_INIT_SCRIPT)
if (lifecycleSelectors.length > 0) {
await page.addInitScript(browserProbeLifecycleInitScript(lifecycleSelectors))
}
if (capturesBrowserMetrics) {
await page.addInitScript(BROWSER_PROBE_PERFORMANCE_INIT_SCRIPT)
}
if (prePageScript) {
await page.addInitScript(prePageScript)
}
wordpressDiagnosticsReady = await installBrowserWordPressDiagnostics(runPlaygroundCommand, server)
viewport = await browserProbeViewport(page)
contextDetails = await browserProbeContextDetails(page, requestedContext, viewport)
capabilityDiagnostics = await browserProbeCapabilityDiagnostics(page, viewport)
attachBrowserCaptureListeners({
captureConsole: capture.has("console") || capturesConsoleForAssertions,
captureErrors: capture.has("errors") || capturesErrorsForAssertions,
captureNetwork: true,
consoleMessages,
errors,
network,
networkTasks,
onConsole: () => progress.mark("console"),
onNetwork: () => progress.mark("network"),
onPageError: () => progress.mark("pageerror"),
page,
})
const previewReadinessError = browserPreviewReadinessError(preview)
if (previewReadinessError) {
throw previewReadinessError
}
await withBrowserProbeLiveness(page, progress, failFast, navigateBrowserProbe(page, targetUrl, waitFor, durationMs), livenessPolicy, "navigation")
progress.mark("navigation")
const browserLocation = await page.evaluate(() => ({ origin: window.location.origin, secureContext: window.isSecureContext })).catch(() => undefined)
windowLocationOrigin = browserLocation?.origin
preview.secureContext = browserLocation?.secureContext
const secureContextError = browserPreviewSecureContextError(preview)
if (secureContextError) {
throw secureContextError
}
if (capturesBrowserMetrics) {
checkpoints.push(await browserProbeCheckpoint(page, "after-navigation"))
}
if (script) {
scriptResult = await withBrowserProbeLiveness(page, progress, failFast, page.evaluate(async (source) => {
const run = new Function(`return (async () => {\n${source}\n})()`)
return run()
}, script), livenessPolicy, "script")
progress.mark("script")
if (capturesBrowserMetrics) {
const pendingCheckpoints = await browserProbePendingCheckpoints(page)
if (pendingCheckpoints.length > 0) {
progress.mark("checkpoint")
}
checkpoints.push(...pendingCheckpoints)
checkpoints.push(await browserProbeCheckpoint(page, "after-script"))
}
}
if (durationMs > 0 && waitFor !== "duration") {
await withBrowserProbeLiveness(page, progress, failFast, page.waitForTimeout(durationMs), livenessPolicy, "duration")
progress.mark("duration")
if (capturesBrowserMetrics) {
checkpoints.push(await browserProbeCheckpoint(page, "after-duration"))
}
}
if (assertions.length > 0) {
await settleBrowserNetworkTasks(networkTasks, livenessPolicy.networkSettleTimeoutMs)
const assertionMetrics = capturesBrowserMetrics ? browserProbeBenchMetrics(browserProbeMemoryArtifact(checkpoints), browserProbePerformanceArtifact(checkpoints)) : {}
assertionResults = await executeBrowserProbeAssertions(page, assertions, consoleMessages, errors, network, assertionMetrics)
if (capturesBrowserMetrics) {
checkpoints.push(await browserProbeCheckpoint(page, "after-assertions"))
}
const fatalFailures = assertionResults.filter((assertion) => !assertion.passed && !assertion.advisory)
if (fatalFailures.length > 0) {
pendingError = new Error(`wordpress.browser-probe assertion failed: ${fatalFailures.map((assertion) => assertion.assertion).join(", ")}`)
}
}
finalUrl = page.url()
} catch (error) {
pendingError = error instanceof Error ? error : new Error(String(error))
if (pendingError instanceof BrowserCommandLivenessError) {
await page?.close().catch(() => undefined)
page = null
}
progress.fail("probe-error", pendingError)
errors.push(serializeBrowserError("probe-error", error))
} finally {
if (abortSignal?.aborted) {
await closeBrowserBestEffort(browser)
abortSignal.removeEventListener("abort", abortHandler)
throw pendingError ?? new Error("Browser command aborted during runtime cleanup")
}
if (page) {
finalUrl = page.url()
windowLocationOrigin = windowLocationOrigin ?? await page.evaluate(() => window.location.origin).catch(() => undefined)
if (capturesBrowserMetrics) {
checkpoints.push(await browserProbeCheckpoint(page, "final"))
if (capture.has("memory")) {
memoryArtifact = browserProbeMemoryArtifact(checkpoints)
}
if (capture.has("performance")) {
performanceArtifact = browserProbePerformanceArtifact(checkpoints, { consoleMessages, errors, network, startedAt })
}
}
const lifecycle = lifecycleSelectors.length > 0 ? await collectBrowserProbeLifecycle(page) : undefined
if (lifecycle) {
lifecycleArtifact = browserProbeLifecycleArtifact(lifecycle)
}
if (capture.has("html")) {
try {
const html = await page.content()
await writeFile(htmlPath, html)
htmlSha256 = sha256(Buffer.from(html, "utf8"))
} catch (error) {
errors.push(serializeBrowserError("probe-error", error))
}
}
if (capture.has("screenshot")) {
try {
await page.screenshot({ path: screenshotPath, fullPage: true })
screenshotSha256 = await fileSha256(screenshotPath)
} catch (error) {
errors.push(serializeBrowserError("probe-error", error))
}
}
}
await settleBrowserNetworkTasks(networkTasks, livenessPolicy.networkSettleTimeoutMs)
await browser.close()
if (capture.has("console") || capturesConsoleForAssertions) {
await writeFile(consolePath, jsonLines(consoleMessages))
}
if (capture.has("errors") || capturesErrorsForAssertions) {
await writeFile(errorsPath, jsonLines(errors))
}
if (capture.has("network") || capturesNetworkForAssertions) {
await writeFile(networkPath, jsonLines(network))
}
if (checkpoints.length > 0) {
await writeFile(checkpointsPath, jsonLines(checkpoints))
}
if (memoryArtifact) {
await writeFile(memoryPath, `${JSON.stringify(memoryArtifact, null, 2)}\n`)
}
if (lifecycleArtifact) {
await writeFile(lifecyclePath, `${JSON.stringify(lifecycleArtifact, null, 2)}\n`)
}
if (performanceArtifact) {
await writeFile(performancePath, `${JSON.stringify(performanceArtifact, null, 2)}\n`)
}
const redirectDiagnostics = browserRedirectDiagnosticsArtifact({
artifactPath: `${browserFilesDirectory}/redirect-diagnostics.json`,
error: pendingError,
finalAttemptedUrl: finalUrl,
network,
requestedUrl: targetUrl,
})
if (redirectDiagnostics) {
await writeFile(redirectDiagnosticsPath, `${JSON.stringify(redirectDiagnostics, null, 2)}\n`)
}
const redirectDiagnosticsSummary = redirectDiagnostics?.summary
const wordpressDiagnostics = await browserWordPressDiagnosticsArtifact({
artifactPath: `${browserFilesDirectory}/wordpress-diagnostics.json`,
network,
ready: wordpressDiagnosticsReady,
server,
})
if (wordpressDiagnostics) {
await writeFile(wordpressDiagnosticsPath, `${JSON.stringify(wordpressDiagnostics, null, 2)}\n`)
}
const wordpressDiagnosticsSummary = wordpressDiagnostics?.summary
const assertionPassed = assertionResults.filter((assertion) => assertion.passed).length
const assertionFailed = assertionResults.filter((assertion) => !assertion.passed).length
const advisoryFailed = assertionResults.filter((assertion) => !assertion.passed && assertion.advisory).length
const assertionSummary = {
total: assertionResults.length,
passed: assertionPassed,
failed: assertionFailed,
advisoryFailed,
fatalFailed: assertionFailed - advisoryFailed,
results: assertionResults,
}
const finishedAt = now()
const review = browserProbeReviewSummary({
browser: browserMetadata,
capture,
checkpoints,
consoleMessages,
durationMs,
errors,
files: browserProbeArtifactRefs(browserFilesDirectory, capture, {
checkpoints: checkpoints.length > 0,
console: capture.has("console") || capturesConsoleForAssertions,
errors: capture.has("errors") || capturesErrorsForAssertions,
html: capture.has("html") ? htmlSha256 : undefined,
lifecycle: Boolean(lifecycleArtifact),
memory: Boolean(memoryArtifact),
network: capture.has("network") || capturesNetworkForAssertions,
performance: Boolean(performanceArtifact),
redirectDiagnostics: Boolean(redirectDiagnostics),
screenshot: capture.has("screenshot") ? screenshotSha256 : undefined,
wordpressDiagnostics: Boolean(wordpressDiagnostics),
}),
finishedAt,
network,
performanceArtifact,
startedAt,
throttle: throttleProfile?.id ?? null,
totalDurationMs: Date.now() - startedAtMs,
viewport,
waitFor,
redirectDiagnostics: redirectDiagnosticsSummary,
wordpressDiagnostics: wordpressDiagnosticsSummary,
})
await writeFile(reviewPath, `${JSON.stringify(review, null, 2)}\n`)
artifact = {
artifactType: "probe",
requestedUrl: targetUrl,
url: targetUrl,
preview,
...(browserPreviewNetworkPolicyIsActive(networkPolicy) ? { networkPolicy: browserPreviewNetworkPolicySummary(networkPolicy) } : {}),
...previewOrigins,
...(prePageScriptMetadata ? { prePageScript: prePageScriptMetadata } : {}),
files: {
...(capture.has("console") || capturesConsoleForAssertions ? { console: `${browserFilesDirectory}/console.jsonl` } : {}),
...(checkpoints.length > 0 ? { checkpoints: `${browserFilesDirectory}/checkpoints.jsonl` } : {}),
...(capture.has("errors") || capturesErrorsForAssertions ? { errors: `${browserFilesDirectory}/errors.jsonl` } : {}),
...(htmlSha256 ? { html: `${browserFilesDirectory}/snapshot.html` } : {}),
...(lifecycleArtifact ? { lifecycle: `${browserFilesDirectory}/lifecycle.json` } : {}),
...(memoryArtifact ? { memory: `${browserFilesDirectory}/memory.json` } : {}),
...(capture.has("network") || capturesNetworkForAssertions ? { network: `${browserFilesDirectory}/network.jsonl` } : {}),
...(performanceArtifact ? { performance: `${browserFilesDirectory}/performance.json` } : {}),
...(redirectDiagnostics ? { redirectDiagnostics: `${browserFilesDirectory}/redirect-diagnostics.json` } : {}),
review: `${browserFilesDirectory}/review.json`,
...(capture.has("screenshot") ? { screenshot: `${browserFilesDirectory}/screenshot.png` } : {}),
...(wordpressDiagnostics ? { wordpressDiagnostics: `${browserFilesDirectory}/wordpress-diagnostics.json` } : {}),
summary: `${browserFilesDirectory}/summary.json`,
},
summary: {
...(assertionSummary.total > 0 ? { assertions: assertionSummary } : {}),
consoleMessages: consoleMessages.length,
errors: errors.length,
finalUrl,
...(windowLocationOrigin ? { windowLocationOrigin } : {}),
htmlSnapshot: Boolean(htmlSha256),
...(browserPreviewNetworkPolicyIsActive(networkPolicy) ? { networkPolicy: browserPreviewNetworkPolicySummary(networkPolicy) } : {}),
...(lifecycleArtifact ? { lifecycle: { schema: lifecycleArtifact.schema, version: lifecycleArtifact.version, startedAtMs: lifecycleArtifact.startedAtMs, selectors: lifecycleArtifact.selectors } } : {}),
liveness: { wallTimeoutMs, stallTimeoutMs, networkSettleTimeoutMs: livenessPolicy.networkSettleTimeoutMs },
...(memoryArtifact ? { memory: memoryArtifact.peak } : {}),
...(memoryArtifact || performanceArtifact ? { metrics: browserProbeBenchMetrics(memoryArtifact, performanceArtifact) } : {}),
networkEvents: network.length,
...(performanceArtifact?.phaseMetrics ? { phaseMetrics: performanceArtifact.phaseMetrics } : {}),
...(performanceArtifact ? { performance: performanceArtifact.peak } : {}),
progress: progress.summary(),
review,
...(redirectDiagnosticsSummary ? { redirectDiagnostics: redirectDiagnosticsSummary } : {}),
...(wordpressDiagnosticsSummary ? { wordpressDiagnostics: wordpressDiagnosticsSummary } : {}),
context: contextDetails,
auth: authSummary,
capabilities: capabilityDiagnostics,
replayability: browserProbeReplayability(capture),
screenshot: capture.has("screenshot"),
...(typeof scriptResult !== "undefined" ? { scriptResult } : {}),
viewport,
},
}
await writeFile(summaryPath, `${JSON.stringify({
schema: "wp-codebox/browser-probe/v1",
requestedUrl: targetUrl,
preview,
...(browserPreviewNetworkPolicyIsActive(networkPolicy) ? { networkPolicy: browserPreviewNetworkPolicySummary(networkPolicy) } : {}),
...previewOrigins,
finalUrl,
...(windowLocationOrigin ? { windowLocationOrigin } : {}),
waitFor,
durationMs,
...(lifecycleSelectors.length > 0 ? { observe: lifecycleSelectors } : {}),
failFast,
stallTimeoutMs,
capture: [...capture].sort(),
...(assertionSummary.total > 0 ? { assertions: assertionSummary } : {}),
...(prePageScriptMetadata ? { prePageScript: prePageScriptMetadata } : {}),
startedAt,
finishedAt,
files: artifact.files,
hashes: {
...(htmlSha256 ? { html: { algorithm: "sha256", value: htmlSha256 } } : {}),
...(screenshotSha256 ? { screenshot: { algorithm: "sha256", value: screenshotSha256 } } : {}),
},
context: contextDetails,
auth: authSummary,
capabilities: capabilityDiagnostics,
review,
...(redirectDiagnosticsSummary ? { redirectDiagnostics: redirectDiagnosticsSummary } : {}),
...(wordpressDiagnosticsSummary ? { wordpressDiagnostics: wordpressDiagnosticsSummary } : {}),
viewport,
summary: artifact.summary,
}, null, 2)}\n`)
}
abortSignal?.removeEventListener("abort", abortHandler)
if (pendingError) {
if (!artifact) {
throw pendingError
}
throw new BrowserCommandArtifactError(pendingError.message, artifact)
}
if (!artifact) {
throw new Error("wordpress.browser-probe did not produce a browser artifact")
}
return {
artifact,
output: `${JSON.stringify({
command,
requestedUrl: targetUrl,
preview,
...(browserPreviewNetworkPolicyIsActive(networkPolicy) ? { networkPolicy: browserPreviewNetworkPolicySummary(networkPolicy) } : {}),
...previewOrigins,
finalUrl: artifact.summary.finalUrl ?? targetUrl,
files: artifact.files,
summary: artifact.summary,
}, null, 2)}\n`,
}
}
async function closeBrowserBestEffort(browser: import("playwright").Browser): Promise<void> {
await Promise.race([
browser.close().catch(() => undefined),
new Promise<void>((resolve) => {
const timeout = setTimeout(resolve, 1_000)
timeout.unref()
}),
])
}
function browserProbeProfileIds(args: string[]): string[] {
const raw = argValue(args, "profiles")?.trim()
if (!raw) {
return []
}
return raw.split(",").map((profile) => profile.trim()).filter(Boolean)
}
function browserProbeProfile(profileId: string): BrowserProbeProfileDefinition {
const profile = BROWSER_PROBE_PROFILES[profileId]
if (!profile) {
throw new Error(`wordpress.browser-probe unknown profile: ${profileId}. Supported profiles: ${Object.keys(BROWSER_PROBE_PROFILES).join(", ")}`)
}
return profile
}
function browserProbeRunPlanFromArgs(args: string[], profileId?: string): BrowserProbeRunPlan {
const capture = new Set(commaListArg(args, "capture"))
if (capture.size === 0) {
capture.add("console")
capture.add("errors")
capture.add("html")
capture.add("network")
capture.add("screenshot")
}
const requestedViewport = viewportArg(args, "viewport")
const throttleProfile = browserProbeThrottleProfile(args)
return {
url: argValue(args, "url")?.trim() ?? "",
capture,
waitFor: argValue(args, "wait-for")?.trim() || "domcontentloaded",
durationMs: durationArg(args, "duration", 0),
requestedViewport,
throttleProfile,
requestedContext: browserProbeContextRequest(args, requestedViewport, profileId, throttleProfile?.id),
prePageScript: argValue(args, "pre-page-script"),
script: argValue(args, "script"),
authRequest: browserAuthRequest(args),
failFast: strictBooleanArg(args, "fail-fast", false),
stallTimeoutMs: durationArg(args, "stall-timeout", 0),
wallTimeoutMs: durationArg(args, "timeout", browserCommandLivenessPolicy().wallTimeoutMs),
lifecycleSelectors: commaListArg(args, "observe"),
assertions: browserProbeAssertionsFromArgs(args),
}
}
function browserProbeProfileArgs(args: string[], profile: BrowserProbeProfileDefinition): string[] {
const explicitOverrideKeys = new Set(args.map((arg) => arg.match(/^([^=]+)=/)?.[1]).filter((key): key is string => typeof key === "string" && BROWSER_PROBE_PROFILE_OVERRIDES.has(key)))
return [
...args.filter((arg) => !arg.startsWith("profiles=") && !arg.startsWith("profile=")),
`profile=${profile.id}`,
...profile.args.filter((arg) => {
const key = arg.match(/^([^=]+)=/)?.[1]
return !key || !explicitOverrideKeys.has(key)
}),
]
}
function browserProbeThrottleProfile(args: string[]): BrowserProbeThrottleProfileDefinition | undefined {
const profileId = argValue(args, "throttle")?.trim()
if (!profileId || profileId === "none") {
return undefined
}
const profile = BROWSER_PROBE_THROTTLE_PROFILES[profileId]
if (!profile) {
throw new Error(`wordpress.browser-probe unknown throttle profile: ${profileId}. Supported profiles: ${Object.keys(BROWSER_PROBE_THROTTLE_PROFILES).join(", ")}`)
}
return profile
}
async function applyBrowserProbeThrottleProfile(page: import("playwright").Page, profile: BrowserProbeThrottleProfileDefinition): Promise<void> {
const session = await page.context().newCDPSession(page)
try {
await Promise.all([
session.send("Network.enable").catch(() => undefined),
session.send("Emulation.setCPUThrottlingRate", { rate: profile.cpuSlowdownRate }).catch(() => undefined),
])
await session.send("Network.emulateNetworkConditions", {
offline: profile.network.offline,
latency: profile.network.latencyMs,
downloadThroughput: profile.network.downloadThroughputBytesPerSecond,
uploadThroughput: profile.network.uploadThroughputBytesPerSecond,
}).catch(() => undefined)
} finally {
await session.detach().catch(() => undefined)
}
}
function browserProbeScriptMetadata(source: string): BrowserProbeScriptMetadata {
return {
sha256: sha256(Buffer.from(source, "utf8")),
bytes: Buffer.byteLength(source, "utf8"),
}
}
function browserProbeContextRequest(args: string[], viewport: { width: number; height: number } | undefined, profileId?: string, throttleProfileId?: string): BrowserProbeContextDetails["requested"] {
const browser = argValue(args, "browser")?.trim()
const device = argValue(args, "device")?.trim()
const locale = argValue(args, "locale")?.trim()
const permissions = commaListArg(args, "permissions")
const timezone = argValue(args, "timezone")?.trim()
const userAgent = argValue(args, "user-agent")?.trim()
return {
...(browser ? { browser } : {}),
...(device ? { device } : {}),
...(locale ? { locale } : {}),
...(permissions.length > 0 ? { permissions } : {}),
...(profileId ? { profile: profileId } : {}),
...(throttleProfileId ? { throttle: throttleProfileId } : {}),
...(timezone ? { timezone } : {}),
...(userAgent ? { userAgent } : {}),
...(viewport ? { viewport } : {}),
}
}
async function browserProbeContextDetails(page: import("playwright").Page, requested: BrowserProbeContextDetails["requested"], viewport: BrowserProbeViewport | null): Promise<BrowserProbeContextDetails> {
const effective = await page.evaluate(() => ({
locale: navigator.language || undefined,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || undefined,
})).catch(() => ({ locale: undefined, timezone: undefined }))
return {
requested,
effective: {
...(requested.browser ? { browser: requested.browser } : {}),
...(requested.device ? { device: requested.device } : {}),
...(effective.locale ? { locale: effective.locale } : {}),
...(requested.permissions ? { permissions: requested.permissions } : {}),
...(requested.profile ? { profile: requested.profile } : {}),
...(requested.throttle ? { throttle: requested.throttle } : {}),
...(effective.timezone ? { timezone: effective.timezone } : {}),
...(viewport?.userAgent ? { userAgent: viewport.userAgent } : {}),