patchright-bun-core 1.58.0 → 1.59.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.
Files changed (475) hide show
  1. package/README.md +2 -2
  2. package/ThirdPartyNotices.txt +3551 -4075
  3. package/bin/install_media_pack.ps1 +5 -5
  4. package/bin/install_webkit_wsl.ps1 +32 -32
  5. package/bin/reinstall_chrome_beta_linux.sh +42 -42
  6. package/bin/reinstall_chrome_beta_mac.sh +13 -13
  7. package/bin/reinstall_chrome_beta_win.ps1 +24 -24
  8. package/bin/reinstall_chrome_stable_linux.sh +42 -42
  9. package/bin/reinstall_chrome_stable_mac.sh +12 -12
  10. package/bin/reinstall_chrome_stable_win.ps1 +24 -24
  11. package/bin/reinstall_msedge_beta_linux.sh +48 -48
  12. package/bin/reinstall_msedge_beta_mac.sh +11 -11
  13. package/bin/reinstall_msedge_beta_win.ps1 +23 -23
  14. package/bin/reinstall_msedge_dev_linux.sh +48 -48
  15. package/bin/reinstall_msedge_dev_mac.sh +11 -11
  16. package/bin/reinstall_msedge_dev_win.ps1 +23 -23
  17. package/bin/reinstall_msedge_stable_linux.sh +48 -48
  18. package/bin/reinstall_msedge_stable_mac.sh +11 -11
  19. package/bin/reinstall_msedge_stable_win.ps1 +23 -23
  20. package/browsers.json +81 -79
  21. package/cli.js +18 -18
  22. package/index.d.ts +17 -17
  23. package/index.js +32 -32
  24. package/index.mjs +28 -28
  25. package/lib/androidServerImpl.js +65 -65
  26. package/lib/bootstrap.js +77 -0
  27. package/lib/browserServerImpl.js +120 -120
  28. package/lib/cli/browserActions.js +308 -0
  29. package/lib/cli/driver.js +98 -97
  30. package/lib/cli/installActions.js +171 -0
  31. package/lib/cli/program.js +225 -589
  32. package/lib/cli/programWithTestStub.js +74 -74
  33. package/lib/client/android.js +361 -361
  34. package/lib/client/api.js +137 -137
  35. package/lib/client/artifact.js +79 -79
  36. package/lib/client/browser.js +169 -161
  37. package/lib/client/browserContext.js +563 -582
  38. package/lib/client/browserType.js +153 -185
  39. package/lib/client/cdpSession.js +55 -51
  40. package/lib/client/channelOwner.js +194 -194
  41. package/lib/client/clientHelper.js +64 -64
  42. package/lib/client/clientInstrumentation.js +55 -55
  43. package/lib/client/clientStackTrace.js +69 -69
  44. package/lib/client/clock.js +68 -68
  45. package/lib/client/{webSocket.js → connect.js} +143 -93
  46. package/lib/client/connection.js +322 -318
  47. package/lib/client/consoleMessage.js +61 -58
  48. package/lib/client/coverage.js +44 -44
  49. package/lib/client/debugger.js +57 -0
  50. package/lib/client/dialog.js +63 -56
  51. package/lib/client/disposable.js +76 -0
  52. package/lib/client/download.js +62 -62
  53. package/lib/client/electron.js +139 -138
  54. package/lib/client/elementHandle.js +281 -284
  55. package/lib/client/errors.js +77 -77
  56. package/lib/client/eventEmitter.js +314 -314
  57. package/lib/client/events.js +103 -103
  58. package/lib/client/fetch.js +367 -368
  59. package/lib/client/fileChooser.js +46 -46
  60. package/lib/client/fileUtils.js +34 -34
  61. package/lib/client/frame.js +404 -409
  62. package/lib/client/harRouter.js +99 -87
  63. package/lib/client/input.js +84 -84
  64. package/lib/client/jsHandle.js +105 -109
  65. package/lib/client/jsonPipe.js +39 -39
  66. package/lib/client/localUtils.js +60 -60
  67. package/lib/client/locator.js +367 -369
  68. package/lib/client/network.js +750 -747
  69. package/lib/client/page.js +731 -745
  70. package/lib/client/platform.js +74 -77
  71. package/lib/client/playwright.js +71 -71
  72. package/lib/client/screencast.js +88 -0
  73. package/lib/client/selectors.js +57 -55
  74. package/lib/client/stream.js +39 -39
  75. package/lib/client/timeoutSettings.js +79 -79
  76. package/lib/client/tracing.js +126 -119
  77. package/lib/client/types.js +28 -28
  78. package/lib/client/video.js +52 -59
  79. package/lib/client/waiter.js +142 -142
  80. package/lib/client/webError.js +39 -39
  81. package/lib/client/worker.js +85 -85
  82. package/lib/client/writableStream.js +39 -39
  83. package/lib/generated/bindingsControllerSource.js +28 -28
  84. package/lib/generated/clockSource.js +28 -28
  85. package/lib/generated/injectedScriptSource.js +28 -28
  86. package/lib/generated/pollingRecorderSource.js +28 -28
  87. package/lib/generated/storageScriptSource.js +28 -28
  88. package/lib/generated/utilityScriptSource.js +28 -28
  89. package/lib/generated/webSocketMockSource.js +336 -336
  90. package/lib/inProcessFactory.js +60 -60
  91. package/lib/inprocess.js +3 -3
  92. package/lib/mcpBundle.js +78 -84
  93. package/lib/mcpBundleImpl.js +91 -0
  94. package/lib/outofprocess.js +76 -76
  95. package/lib/protocol/serializers.js +197 -197
  96. package/lib/protocol/validator.js +3067 -2969
  97. package/lib/protocol/validatorPrimitives.js +193 -193
  98. package/lib/remote/playwrightConnection.js +131 -129
  99. package/lib/remote/playwrightPipeServer.js +100 -0
  100. package/lib/remote/playwrightServer.js +339 -334
  101. package/lib/remote/playwrightWebSocketServer.js +73 -0
  102. package/lib/remote/serverTransport.js +96 -0
  103. package/lib/server/android/android.js +465 -465
  104. package/lib/server/android/backendAdb.js +177 -177
  105. package/lib/server/artifact.js +127 -127
  106. package/lib/server/bidi/bidiBrowser.js +571 -549
  107. package/lib/server/bidi/bidiChromium.js +162 -148
  108. package/lib/server/bidi/bidiConnection.js +213 -213
  109. package/lib/server/bidi/bidiDeserializer.js +116 -116
  110. package/lib/server/bidi/bidiExecutionContext.js +267 -267
  111. package/lib/server/bidi/bidiFirefox.js +128 -128
  112. package/lib/server/bidi/bidiInput.js +146 -146
  113. package/lib/server/bidi/bidiNetworkManager.js +411 -383
  114. package/lib/server/bidi/bidiOverCdp.js +102 -102
  115. package/lib/server/bidi/bidiPage.js +599 -583
  116. package/lib/server/bidi/bidiPdf.js +106 -106
  117. package/lib/server/bidi/third_party/bidiCommands.d.js +22 -22
  118. package/lib/server/bidi/third_party/bidiKeyboard.js +256 -256
  119. package/lib/server/bidi/third_party/bidiProtocol.js +24 -24
  120. package/lib/server/bidi/third_party/bidiProtocolCore.js +180 -180
  121. package/lib/server/bidi/third_party/bidiProtocolPermissions.js +42 -42
  122. package/lib/server/bidi/third_party/bidiSerializer.js +148 -148
  123. package/lib/server/bidi/third_party/firefoxPrefs.js +261 -259
  124. package/lib/server/browser.js +212 -149
  125. package/lib/server/browserContext.js +741 -702
  126. package/lib/server/browserType.js +338 -336
  127. package/lib/server/callLog.js +82 -82
  128. package/lib/server/chromium/chromium.js +399 -395
  129. package/lib/server/chromium/chromiumSwitches.js +104 -104
  130. package/lib/server/chromium/crBrowser.js +528 -511
  131. package/lib/server/chromium/crConnection.js +197 -197
  132. package/lib/server/chromium/crCoverage.js +235 -235
  133. package/lib/server/chromium/crDevTools.js +111 -111
  134. package/lib/server/chromium/crDragDrop.js +131 -131
  135. package/lib/server/chromium/crExecutionContext.js +146 -146
  136. package/lib/server/chromium/crInput.js +187 -187
  137. package/lib/server/chromium/crNetworkManager.js +707 -707
  138. package/lib/server/chromium/crPage.js +963 -1001
  139. package/lib/server/chromium/crPdf.js +121 -121
  140. package/lib/server/chromium/crProtocolHelper.js +145 -145
  141. package/lib/server/chromium/crServiceWorker.js +137 -136
  142. package/lib/server/chromium/defaultFontFamilies.js +162 -162
  143. package/lib/server/chromium/protocol.d.js +16 -16
  144. package/lib/server/clock.js +149 -149
  145. package/lib/server/codegen/csharp.js +327 -327
  146. package/lib/server/codegen/java.js +274 -274
  147. package/lib/server/codegen/javascript.js +247 -247
  148. package/lib/server/codegen/jsonl.js +52 -52
  149. package/lib/server/codegen/language.js +132 -132
  150. package/lib/server/codegen/languages.js +68 -68
  151. package/lib/server/codegen/python.js +279 -279
  152. package/lib/server/codegen/types.js +16 -16
  153. package/lib/server/console.js +61 -57
  154. package/lib/server/cookieStore.js +206 -206
  155. package/lib/server/debugController.js +197 -191
  156. package/lib/server/debugger.js +112 -119
  157. package/lib/server/deviceDescriptors.js +39 -39
  158. package/lib/server/deviceDescriptorsSource.json +1778 -1778
  159. package/lib/server/dialog.js +116 -116
  160. package/lib/server/dispatchers/androidDispatcher.js +325 -325
  161. package/lib/server/dispatchers/artifactDispatcher.js +118 -118
  162. package/lib/server/dispatchers/browserContextDispatcher.js +381 -384
  163. package/lib/server/dispatchers/browserDispatcher.js +124 -118
  164. package/lib/server/dispatchers/browserTypeDispatcher.js +71 -64
  165. package/lib/server/dispatchers/cdpSessionDispatcher.js +47 -44
  166. package/lib/server/dispatchers/debugControllerDispatcher.js +78 -78
  167. package/lib/server/dispatchers/debuggerDispatcher.js +84 -0
  168. package/lib/server/dispatchers/dialogDispatcher.js +47 -47
  169. package/lib/server/dispatchers/dispatcher.js +364 -364
  170. package/lib/server/dispatchers/disposableDispatcher.js +39 -0
  171. package/lib/server/dispatchers/electronDispatcher.js +90 -89
  172. package/lib/server/dispatchers/elementHandlerDispatcher.js +181 -181
  173. package/lib/server/dispatchers/frameDispatcher.js +227 -227
  174. package/lib/server/dispatchers/jsHandleDispatcher.js +85 -85
  175. package/lib/server/dispatchers/jsonPipeDispatcher.js +58 -58
  176. package/lib/server/dispatchers/localUtilsDispatcher.js +185 -149
  177. package/lib/server/dispatchers/networkDispatchers.js +214 -213
  178. package/lib/server/dispatchers/pageDispatcher.js +456 -393
  179. package/lib/server/dispatchers/playwrightDispatcher.js +108 -108
  180. package/lib/server/dispatchers/streamDispatcher.js +67 -67
  181. package/lib/server/dispatchers/tracingDispatcher.js +68 -68
  182. package/lib/server/dispatchers/webSocketRouteDispatcher.js +164 -165
  183. package/lib/server/dispatchers/writableStreamDispatcher.js +79 -79
  184. package/lib/server/disposable.js +41 -0
  185. package/lib/server/dom.js +833 -815
  186. package/lib/server/download.js +71 -70
  187. package/lib/server/electron/electron.js +278 -273
  188. package/lib/server/electron/loader.js +29 -29
  189. package/lib/server/errors.js +69 -69
  190. package/lib/server/fetch.js +621 -621
  191. package/lib/server/fileChooser.js +43 -43
  192. package/lib/server/fileUploadUtils.js +84 -84
  193. package/lib/server/firefox/ffBrowser.js +408 -418
  194. package/lib/server/firefox/ffConnection.js +142 -142
  195. package/lib/server/firefox/ffExecutionContext.js +150 -150
  196. package/lib/server/firefox/ffInput.js +175 -159
  197. package/lib/server/firefox/ffNetworkManager.js +256 -256
  198. package/lib/server/firefox/ffPage.js +494 -497
  199. package/lib/server/firefox/firefox.js +114 -114
  200. package/lib/server/firefox/protocol.d.js +16 -16
  201. package/lib/server/formData.js +147 -147
  202. package/lib/server/frameSelectors.js +160 -160
  203. package/lib/server/frames.js +1500 -1471
  204. package/lib/server/har/harRecorder.js +147 -147
  205. package/lib/server/har/harTracer.js +608 -607
  206. package/lib/server/harBackend.js +157 -157
  207. package/lib/server/helper.js +96 -96
  208. package/lib/server/index.js +58 -58
  209. package/lib/server/input.js +322 -277
  210. package/lib/server/instrumentation.js +77 -72
  211. package/lib/server/javascript.js +291 -291
  212. package/lib/server/launchApp.js +127 -128
  213. package/lib/server/localUtils.js +214 -214
  214. package/lib/server/macEditingCommands.js +143 -143
  215. package/lib/server/network.js +668 -667
  216. package/lib/server/overlay.js +138 -0
  217. package/lib/server/page.js +890 -830
  218. package/lib/server/pipeTransport.js +89 -89
  219. package/lib/server/playwright.js +69 -69
  220. package/lib/server/progress.js +138 -132
  221. package/lib/server/protocolError.js +52 -52
  222. package/lib/server/recorder/chat.js +161 -161
  223. package/lib/server/recorder/recorderApp.js +367 -366
  224. package/lib/server/recorder/recorderRunner.js +138 -138
  225. package/lib/server/recorder/recorderSignalProcessor.js +83 -83
  226. package/lib/server/recorder/recorderUtils.js +157 -157
  227. package/lib/server/recorder/throttledFile.js +57 -57
  228. package/lib/server/recorder.js +535 -499
  229. package/lib/server/registry/browserFetcher.js +177 -177
  230. package/lib/server/registry/dependencies.js +371 -371
  231. package/lib/server/registry/index.js +1395 -1422
  232. package/lib/server/registry/nativeDeps.js +1281 -1280
  233. package/lib/server/registry/oopDownloadBrowserMain.js +127 -127
  234. package/lib/server/screencast.js +137 -190
  235. package/lib/server/screenshotter.js +333 -333
  236. package/lib/server/selectors.js +112 -112
  237. package/lib/server/socksClientCertificatesInterceptor.js +383 -383
  238. package/lib/server/socksInterceptor.js +95 -95
  239. package/lib/server/trace/recorder/snapshotter.js +147 -147
  240. package/lib/server/trace/recorder/snapshotterInjected.js +561 -561
  241. package/lib/server/trace/recorder/tracing.js +655 -604
  242. package/lib/server/trace/viewer/traceViewer.js +244 -245
  243. package/lib/server/transport.js +254 -254
  244. package/lib/server/types.js +28 -28
  245. package/lib/server/usKeyboardLayout.js +152 -145
  246. package/lib/server/utils/ascii.js +44 -44
  247. package/lib/server/utils/comparators.js +139 -139
  248. package/lib/server/utils/crypto.js +216 -216
  249. package/lib/server/utils/debug.js +42 -42
  250. package/lib/server/utils/debugLogger.js +122 -122
  251. package/lib/server/utils/disposable.js +32 -0
  252. package/lib/server/utils/env.js +73 -73
  253. package/lib/server/utils/eventsHelper.js +41 -39
  254. package/lib/server/utils/expectUtils.js +123 -123
  255. package/lib/server/utils/fileUtils.js +205 -191
  256. package/lib/server/utils/happyEyeballs.js +210 -207
  257. package/lib/server/utils/hostPlatform.js +123 -123
  258. package/lib/server/utils/httpServer.js +205 -203
  259. package/lib/server/utils/image_tools/colorUtils.js +89 -89
  260. package/lib/server/utils/image_tools/compare.js +109 -109
  261. package/lib/server/utils/image_tools/imageChannel.js +78 -78
  262. package/lib/server/utils/image_tools/stats.js +102 -102
  263. package/lib/server/utils/linuxUtils.js +71 -71
  264. package/lib/server/utils/network.js +243 -242
  265. package/lib/server/utils/nodePlatform.js +148 -154
  266. package/lib/server/utils/pipeTransport.js +84 -84
  267. package/lib/server/utils/processLauncher.js +243 -241
  268. package/lib/server/utils/profiler.js +65 -65
  269. package/lib/server/utils/socksProxy.js +511 -511
  270. package/lib/server/utils/spawnAsync.js +41 -41
  271. package/lib/server/utils/task.js +51 -51
  272. package/lib/server/utils/userAgent.js +98 -98
  273. package/lib/server/utils/wsServer.js +121 -121
  274. package/lib/server/utils/zipFile.js +74 -74
  275. package/lib/server/utils/zones.js +57 -57
  276. package/lib/server/videoRecorder.js +194 -124
  277. package/lib/server/webkit/protocol.d.js +16 -16
  278. package/lib/server/webkit/webkit.js +108 -108
  279. package/lib/server/webkit/wkBrowser.js +330 -335
  280. package/lib/server/webkit/wkConnection.js +144 -144
  281. package/lib/server/webkit/wkExecutionContext.js +154 -154
  282. package/lib/server/webkit/wkInput.js +181 -181
  283. package/lib/server/webkit/wkInterceptableRequest.js +197 -197
  284. package/lib/server/webkit/wkPage.js +1161 -1158
  285. package/lib/server/webkit/wkProvisionalPage.js +83 -83
  286. package/lib/server/webkit/wkWorkers.js +106 -105
  287. package/lib/serverRegistry.js +156 -0
  288. package/lib/third_party/pixelmatch.js +255 -255
  289. package/lib/tools/backend/browserBackend.js +79 -0
  290. package/lib/tools/backend/common.js +63 -0
  291. package/lib/tools/backend/config.js +41 -0
  292. package/lib/tools/backend/console.js +66 -0
  293. package/lib/tools/backend/context.js +296 -0
  294. package/lib/tools/backend/cookies.js +152 -0
  295. package/lib/tools/backend/devtools.js +69 -0
  296. package/lib/tools/backend/dialogs.js +59 -0
  297. package/lib/tools/backend/evaluate.js +64 -0
  298. package/lib/tools/backend/files.js +60 -0
  299. package/lib/tools/backend/form.js +64 -0
  300. package/lib/tools/backend/keyboard.js +155 -0
  301. package/lib/tools/backend/logFile.js +95 -0
  302. package/lib/tools/backend/mouse.js +168 -0
  303. package/lib/tools/backend/navigate.js +106 -0
  304. package/lib/tools/backend/network.js +135 -0
  305. package/lib/tools/backend/pdf.js +48 -0
  306. package/lib/tools/backend/response.js +305 -0
  307. package/lib/tools/backend/route.js +140 -0
  308. package/lib/tools/backend/runCode.js +77 -0
  309. package/lib/tools/backend/screenshot.js +88 -0
  310. package/lib/tools/backend/sessionLog.js +74 -0
  311. package/lib/tools/backend/snapshot.js +208 -0
  312. package/lib/tools/backend/storage.js +68 -0
  313. package/lib/tools/backend/tab.js +445 -0
  314. package/lib/tools/backend/tabs.js +67 -0
  315. package/lib/tools/backend/tool.js +47 -0
  316. package/lib/tools/backend/tools.js +102 -0
  317. package/lib/tools/backend/tracing.js +78 -0
  318. package/lib/tools/backend/utils.js +83 -0
  319. package/lib/tools/backend/verify.js +151 -0
  320. package/lib/tools/backend/video.js +98 -0
  321. package/lib/tools/backend/wait.js +63 -0
  322. package/lib/tools/backend/webstorage.js +223 -0
  323. package/lib/tools/cli-client/cli.js +6 -0
  324. package/lib/tools/cli-client/help.json +399 -0
  325. package/lib/tools/cli-client/minimist.js +128 -0
  326. package/lib/tools/cli-client/program.js +350 -0
  327. package/lib/tools/cli-client/registry.js +176 -0
  328. package/lib/tools/cli-client/session.js +289 -0
  329. package/lib/tools/cli-client/skill/SKILL.md +328 -0
  330. package/lib/tools/cli-client/skill/references/element-attributes.md +23 -0
  331. package/lib/tools/cli-client/skill/references/playwright-tests.md +39 -0
  332. package/lib/tools/cli-client/skill/references/request-mocking.md +87 -0
  333. package/lib/tools/cli-client/skill/references/running-code.md +231 -0
  334. package/lib/tools/cli-client/skill/references/session-management.md +169 -0
  335. package/lib/tools/cli-client/skill/references/storage-state.md +275 -0
  336. package/lib/tools/cli-client/skill/references/test-generation.md +88 -0
  337. package/lib/tools/cli-client/skill/references/tracing.md +139 -0
  338. package/lib/tools/cli-client/skill/references/video-recording.md +143 -0
  339. package/lib/tools/cli-daemon/command.js +73 -0
  340. package/lib/tools/cli-daemon/commands.js +956 -0
  341. package/lib/tools/cli-daemon/daemon.js +157 -0
  342. package/lib/tools/cli-daemon/helpGenerator.js +177 -0
  343. package/lib/tools/cli-daemon/program.js +129 -0
  344. package/lib/tools/dashboard/appIcon.png +0 -0
  345. package/lib/tools/dashboard/dashboardApp.js +284 -0
  346. package/lib/tools/dashboard/dashboardController.js +296 -0
  347. package/lib/tools/exports.js +60 -0
  348. package/lib/tools/mcp/browserFactory.js +233 -0
  349. package/lib/tools/mcp/cdpRelay.js +352 -0
  350. package/lib/tools/mcp/cli-stub.js +7 -0
  351. package/lib/tools/mcp/config.d.js +16 -0
  352. package/lib/tools/mcp/config.js +446 -0
  353. package/lib/tools/mcp/configIni.js +189 -0
  354. package/lib/{server/trace/viewer/traceParser.js → tools/mcp/extensionContextFactory.js} +55 -72
  355. package/lib/tools/mcp/index.js +62 -0
  356. package/lib/tools/mcp/log.js +35 -0
  357. package/lib/tools/mcp/program.js +107 -0
  358. package/lib/tools/mcp/protocol.js +28 -0
  359. package/lib/tools/mcp/watchdog.js +44 -0
  360. package/lib/tools/trace/SKILL.md +171 -0
  361. package/lib/tools/trace/installSkill.js +48 -0
  362. package/lib/tools/trace/traceActions.js +142 -0
  363. package/lib/tools/trace/traceAttachments.js +69 -0
  364. package/lib/tools/trace/traceCli.js +87 -0
  365. package/lib/tools/trace/traceConsole.js +97 -0
  366. package/lib/tools/trace/traceErrors.js +55 -0
  367. package/lib/tools/trace/traceOpen.js +69 -0
  368. package/lib/tools/trace/traceParser.js +96 -0
  369. package/lib/tools/trace/traceRequests.js +182 -0
  370. package/lib/tools/trace/traceScreenshot.js +68 -0
  371. package/lib/tools/trace/traceSnapshot.js +149 -0
  372. package/lib/tools/trace/traceUtils.js +153 -0
  373. package/lib/tools/utils/connect.js +32 -0
  374. package/lib/tools/utils/mcp/http.js +152 -0
  375. package/lib/tools/utils/mcp/server.js +230 -0
  376. package/lib/tools/utils/mcp/tool.js +47 -0
  377. package/lib/tools/utils/socketConnection.js +108 -0
  378. package/lib/utils/isomorphic/ariaSnapshot.js +455 -455
  379. package/lib/utils/isomorphic/assert.js +31 -31
  380. package/lib/utils/isomorphic/colors.js +72 -72
  381. package/lib/utils/isomorphic/cssParser.js +245 -245
  382. package/lib/utils/isomorphic/cssTokenizer.js +1051 -1051
  383. package/lib/utils/isomorphic/formatUtils.js +64 -0
  384. package/lib/utils/isomorphic/headers.js +53 -53
  385. package/lib/{server/utils → utils/isomorphic}/imageUtils.js +141 -141
  386. package/lib/utils/isomorphic/jsonSchema.js +89 -0
  387. package/lib/utils/isomorphic/locatorGenerators.js +689 -689
  388. package/lib/utils/isomorphic/locatorParser.js +176 -176
  389. package/lib/utils/isomorphic/locatorUtils.js +81 -81
  390. package/lib/utils/isomorphic/lruCache.js +51 -51
  391. package/lib/utils/isomorphic/manualPromise.js +114 -114
  392. package/lib/utils/isomorphic/mimeType.js +464 -459
  393. package/lib/utils/isomorphic/multimap.js +80 -80
  394. package/lib/utils/isomorphic/protocolFormatter.js +81 -81
  395. package/lib/utils/isomorphic/protocolMetainfo.js +351 -330
  396. package/lib/utils/isomorphic/rtti.js +43 -43
  397. package/lib/utils/isomorphic/selectorParser.js +386 -386
  398. package/lib/utils/isomorphic/semaphore.js +54 -54
  399. package/lib/utils/isomorphic/stackTrace.js +158 -158
  400. package/lib/utils/isomorphic/stringUtils.js +204 -204
  401. package/lib/utils/isomorphic/time.js +49 -49
  402. package/lib/utils/isomorphic/timeoutRunner.js +66 -66
  403. package/lib/utils/isomorphic/trace/entries.js +16 -16
  404. package/lib/utils/isomorphic/trace/snapshotRenderer.js +492 -499
  405. package/lib/utils/isomorphic/trace/snapshotServer.js +120 -120
  406. package/lib/utils/isomorphic/trace/snapshotStorage.js +89 -89
  407. package/lib/utils/isomorphic/trace/traceLoader.js +132 -131
  408. package/lib/utils/isomorphic/trace/traceModel.js +366 -365
  409. package/lib/utils/isomorphic/trace/traceModernizer.js +401 -400
  410. package/lib/utils/isomorphic/{traceUtils.js → trace/traceUtils.js} +58 -58
  411. package/lib/utils/isomorphic/trace/versions/traceV3.js +16 -16
  412. package/lib/utils/isomorphic/trace/versions/traceV4.js +16 -16
  413. package/lib/utils/isomorphic/trace/versions/traceV5.js +16 -16
  414. package/lib/utils/isomorphic/trace/versions/traceV6.js +16 -16
  415. package/lib/utils/isomorphic/trace/versions/traceV7.js +16 -16
  416. package/lib/utils/isomorphic/trace/versions/traceV8.js +16 -16
  417. package/lib/utils/isomorphic/types.js +16 -16
  418. package/lib/utils/isomorphic/urlMatch.js +243 -190
  419. package/lib/utils/isomorphic/utilityScriptSerializers.js +262 -251
  420. package/lib/utils/isomorphic/yaml.js +84 -84
  421. package/lib/utils.js +115 -111
  422. package/lib/utilsBundle.js +91 -109
  423. package/lib/utilsBundleImpl/index.js +217 -218
  424. package/lib/utilsBundleImpl/xdg-open +1066 -1066
  425. package/lib/vite/dashboard/assets/index-BAOybkp8.js +50 -0
  426. package/lib/vite/dashboard/assets/index-CZAYOG76.css +1 -0
  427. package/lib/vite/dashboard/index.html +28 -0
  428. package/lib/vite/htmlReport/index.html +16 -84
  429. package/lib/vite/htmlReport/report.css +1 -0
  430. package/lib/vite/htmlReport/report.js +72 -0
  431. package/lib/vite/recorder/assets/{codeMirrorModule-DadYNm1I.js → codeMirrorModule-C8KMvO9L.js} +32 -32
  432. package/lib/vite/recorder/assets/codeMirrorModule-DYBRYzYX.css +1 -1
  433. package/lib/vite/recorder/assets/index-BSjZa4pk.css +1 -1
  434. package/lib/vite/recorder/assets/index-CqAYX1I3.js +193 -0
  435. package/lib/vite/recorder/index.html +29 -29
  436. package/lib/vite/recorder/playwright-logo.svg +9 -9
  437. package/lib/vite/traceViewer/assets/{codeMirrorModule-a5XoALAZ.js → codeMirrorModule-DS0FLvoc.js} +32 -32
  438. package/lib/vite/traceViewer/assets/defaultSettingsView-GTWI-W_B.js +262 -0
  439. package/lib/vite/traceViewer/assets/xtermModule-CsJ4vdCR.js +9 -9
  440. package/lib/vite/traceViewer/codeMirrorModule.DYBRYzYX.css +1 -1
  441. package/lib/vite/traceViewer/defaultSettingsView.B4dS75f0.css +1 -0
  442. package/lib/vite/traceViewer/{index.BVu7tZDe.css → index.CzXZzn5A.css} +1 -1
  443. package/lib/vite/traceViewer/{index.Bk2uYQRV.js → index.Dtstcb7U.js} +2 -2
  444. package/lib/vite/traceViewer/index.html +43 -43
  445. package/lib/vite/traceViewer/manifest.webmanifest +16 -16
  446. package/lib/vite/traceViewer/playwright-logo.svg +9 -9
  447. package/lib/vite/traceViewer/snapshot.html +21 -21
  448. package/lib/vite/traceViewer/sw.bundle.js +5 -5
  449. package/lib/vite/traceViewer/uiMode.Btcz36p_.css +1 -1
  450. package/lib/vite/traceViewer/uiMode.Vipi55dB.js +6 -0
  451. package/lib/vite/traceViewer/uiMode.html +17 -17
  452. package/lib/vite/traceViewer/xtermModule.DYP7pi_n.css +32 -32
  453. package/lib/zipBundle.js +34 -34
  454. package/lib/zipBundleImpl.js +5 -5
  455. package/lib/zodBundle.js +39 -0
  456. package/lib/zodBundleImpl.js +40 -0
  457. package/package.json +6 -1
  458. package/types/protocol.d.ts +24720 -23824
  459. package/types/structs.d.ts +45 -45
  460. package/types/types.d.ts +23623 -22843
  461. package/lib/client/pageAgent.js +0 -64
  462. package/lib/mcpBundleImpl/index.js +0 -147
  463. package/lib/server/agent/actionRunner.js +0 -335
  464. package/lib/server/agent/actions.js +0 -128
  465. package/lib/server/agent/codegen.js +0 -111
  466. package/lib/server/agent/context.js +0 -150
  467. package/lib/server/agent/expectTools.js +0 -156
  468. package/lib/server/agent/pageAgent.js +0 -204
  469. package/lib/server/agent/performTools.js +0 -262
  470. package/lib/server/agent/tool.js +0 -109
  471. package/lib/server/dispatchers/pageAgentDispatcher.js +0 -96
  472. package/lib/vite/recorder/assets/index-BhTWtUlo.js +0 -193
  473. package/lib/vite/traceViewer/assets/defaultSettingsView-CJSZINFr.js +0 -266
  474. package/lib/vite/traceViewer/defaultSettingsView.7ch9cixO.css +0 -1
  475. package/lib/vite/traceViewer/uiMode.CQJ9SCIQ.js +0 -5
@@ -1,1001 +1,963 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var crPage_exports = {};
30
- __export(crPage_exports, {
31
- CRPage: () => CRPage
32
- });
33
- module.exports = __toCommonJS(crPage_exports);
34
- var import_assert = require("../../utils/isomorphic/assert");
35
- var import_eventsHelper = require("../utils/eventsHelper");
36
- var import_stackTrace = require("../../utils/isomorphic/stackTrace");
37
- var dialog = __toESM(require("../dialog"));
38
- var dom = __toESM(require("../dom"));
39
- var frames = __toESM(require("../frames"));
40
- var import_helper = require("../helper");
41
- var network = __toESM(require("../network"));
42
- var import_page = require("../page");
43
- var import_crCoverage = require("./crCoverage");
44
- var import_crDragDrop = require("./crDragDrop");
45
- var import_crExecutionContext = require("./crExecutionContext");
46
- var import_crInput = require("./crInput");
47
- var import_crNetworkManager = require("./crNetworkManager");
48
- var import_crPdf = require("./crPdf");
49
- var import_crProtocolHelper = require("./crProtocolHelper");
50
- var import_defaultFontFamilies = require("./defaultFontFamilies");
51
- var import_errors = require("../errors");
52
- var import_protocolError = require("../protocolError");
53
- class CRPage {
54
- constructor(client, targetId, browserContext, opener, bits) {
55
- this._sessions = /* @__PURE__ */ new Map();
56
- // Holds window features for the next popup being opened via window.open,
57
- // until the popup target arrives. This could be racy if two oopifs
58
- // simultaneously call window.open with window features: the order
59
- // of their Page.windowOpen events is not guaranteed to match the order
60
- // of new popup targets.
61
- this._nextWindowOpenPopupFeatures = [];
62
- this._targetId = targetId;
63
- this._opener = opener;
64
- const dragManager = new import_crDragDrop.DragManager(this);
65
- this.rawKeyboard = new import_crInput.RawKeyboardImpl(client, browserContext._browser._platform() === "mac", dragManager);
66
- this.rawMouse = new import_crInput.RawMouseImpl(this, client, dragManager);
67
- this.rawTouchscreen = new import_crInput.RawTouchscreenImpl(client);
68
- this._pdf = new import_crPdf.CRPDF(client);
69
- this._coverage = new import_crCoverage.CRCoverage(client);
70
- this._browserContext = browserContext;
71
- this._page = new import_page.Page(this, browserContext);
72
- this.utilityWorldName = `__playwright_utility_world_${this._page.guid}`;
73
- this._networkManager = new import_crNetworkManager.CRNetworkManager(this._page, null);
74
- this.updateOffline();
75
- this.updateExtraHTTPHeaders();
76
- this.updateHttpCredentials();
77
- this.updateRequestInterception();
78
- this._mainFrameSession = new FrameSession(this, client, targetId, null);
79
- this._sessions.set(targetId, this._mainFrameSession);
80
- if (opener && !browserContext._options.noDefaultViewport) {
81
- const features = opener._nextWindowOpenPopupFeatures.shift() || [];
82
- const viewportSize = import_helper.helper.getViewportSizeFromWindowFeatures(features);
83
- if (viewportSize)
84
- this._page.setEmulatedSizeFromWindowOpen({ viewport: viewportSize, screen: viewportSize });
85
- }
86
- this._mainFrameSession._initialize(bits.hasUIWindow).then(
87
- () => this._page.reportAsNew(this._opener?._page, void 0),
88
- (error) => this._page.reportAsNew(this._opener?._page, error)
89
- );
90
- }
91
- static mainFrameSession(page) {
92
- const crPage = page.delegate;
93
- return crPage._mainFrameSession;
94
- }
95
- async _forAllFrameSessions(cb) {
96
- const frameSessions = Array.from(this._sessions.values());
97
- await Promise.all(frameSessions.map((frameSession) => {
98
- if (frameSession._isMainFrame())
99
- return cb(frameSession);
100
- return cb(frameSession).catch((e) => {
101
- if ((0, import_protocolError.isSessionClosedError)(e))
102
- return;
103
- throw e;
104
- });
105
- }));
106
- }
107
- _sessionForFrame(frame) {
108
- while (!this._sessions.has(frame._id)) {
109
- const parent = frame.parentFrame();
110
- if (!parent)
111
- throw new Error(`Frame has been detached.`);
112
- frame = parent;
113
- }
114
- return this._sessions.get(frame._id);
115
- }
116
- _sessionForHandle(handle) {
117
- const frame = handle._context.frame;
118
- return this._sessionForFrame(frame);
119
- }
120
- willBeginDownload() {
121
- this._mainFrameSession._willBeginDownload();
122
- }
123
- didClose() {
124
- for (const session of this._sessions.values())
125
- session.dispose();
126
- this._page._didClose();
127
- }
128
- async navigateFrame(frame, url, referrer) {
129
- return this._sessionForFrame(frame)._navigate(frame, url, referrer);
130
- }
131
- async updateExtraHTTPHeaders() {
132
- const headers = network.mergeHeaders([
133
- this._browserContext._options.extraHTTPHeaders,
134
- this._page.extraHTTPHeaders()
135
- ]);
136
- await this._networkManager.setExtraHTTPHeaders(headers);
137
- }
138
- async updateGeolocation() {
139
- await this._forAllFrameSessions((frame) => frame._updateGeolocation(false));
140
- }
141
- async updateOffline() {
142
- await this._networkManager.setOffline(!!this._browserContext._options.offline);
143
- }
144
- async updateHttpCredentials() {
145
- await this._networkManager.authenticate(this._browserContext._options.httpCredentials || null);
146
- }
147
- async updateEmulatedViewportSize(preserveWindowBoundaries) {
148
- await this._mainFrameSession._updateViewport(preserveWindowBoundaries);
149
- }
150
- async bringToFront() {
151
- await this._mainFrameSession._client.send("Page.bringToFront");
152
- }
153
- async updateEmulateMedia() {
154
- await this._forAllFrameSessions((frame) => frame._updateEmulateMedia());
155
- }
156
- async updateUserAgent() {
157
- await this._forAllFrameSessions((frame) => frame._updateUserAgent());
158
- }
159
- async updateRequestInterception() {
160
- await this._networkManager.setRequestInterception(this._page.needsRequestInterception());
161
- }
162
- async updateFileChooserInterception() {
163
- await this._forAllFrameSessions((frame) => frame._updateFileChooserInterception(false));
164
- }
165
- async reload() {
166
- await this._mainFrameSession._client.send("Page.reload");
167
- }
168
- async _go(delta) {
169
- const history = await this._mainFrameSession._client.send("Page.getNavigationHistory");
170
- const entry = history.entries[history.currentIndex + delta];
171
- if (!entry)
172
- return false;
173
- await this._mainFrameSession._client.send("Page.navigateToHistoryEntry", { entryId: entry.id });
174
- return true;
175
- }
176
- goBack() {
177
- return this._go(-1);
178
- }
179
- goForward() {
180
- return this._go(1);
181
- }
182
- async requestGC() {
183
- await this._mainFrameSession._client.send("HeapProfiler.collectGarbage");
184
- }
185
- async addInitScript(initScript, world = "main") {
186
- await this._forAllFrameSessions((frame) => frame._evaluateOnNewDocument(initScript, world));
187
- }
188
- async exposePlaywrightBinding() {
189
- await this._forAllFrameSessions((frame) => frame.exposePlaywrightBinding());
190
- }
191
- async removeInitScripts(initScripts) {
192
- await this._forAllFrameSessions((frame) => frame._removeEvaluatesOnNewDocument(initScripts));
193
- }
194
- async closePage(runBeforeUnload) {
195
- if (runBeforeUnload)
196
- await this._mainFrameSession._client.send("Page.close");
197
- else
198
- await this._browserContext._browser._closePage(this);
199
- }
200
- async setBackgroundColor(color) {
201
- await this._mainFrameSession._client.send("Emulation.setDefaultBackgroundColorOverride", { color });
202
- }
203
- async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {
204
- const { visualViewport } = await progress.race(this._mainFrameSession._client.send("Page.getLayoutMetrics"));
205
- if (!documentRect) {
206
- documentRect = {
207
- x: visualViewport.pageX + viewportRect.x,
208
- y: visualViewport.pageY + viewportRect.y,
209
- ...import_helper.helper.enclosingIntSize({
210
- width: viewportRect.width / visualViewport.scale,
211
- height: viewportRect.height / visualViewport.scale
212
- })
213
- };
214
- }
215
- const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 };
216
- if (scale === "css") {
217
- const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1;
218
- clip.scale /= deviceScaleFactor;
219
- }
220
- const result = await progress.race(this._mainFrameSession._client.send("Page.captureScreenshot", { format, quality, clip, captureBeyondViewport: !fitsViewport }));
221
- return Buffer.from(result.data, "base64");
222
- }
223
- async getContentFrame(handle) {
224
- return this._sessionForHandle(handle)._getContentFrame(handle);
225
- }
226
- async getOwnerFrame(handle) {
227
- return this._sessionForHandle(handle)._getOwnerFrame(handle);
228
- }
229
- async getBoundingBox(handle) {
230
- return this._sessionForHandle(handle)._getBoundingBox(handle);
231
- }
232
- async scrollRectIntoViewIfNeeded(handle, rect) {
233
- return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);
234
- }
235
- async startScreencast(options) {
236
- await this._mainFrameSession._client.send("Page.startScreencast", {
237
- format: "jpeg",
238
- quality: options.quality,
239
- maxWidth: options.width,
240
- maxHeight: options.height
241
- });
242
- }
243
- async stopScreencast() {
244
- await this._mainFrameSession._client._sendMayFail("Page.stopScreencast");
245
- }
246
- rafCountForStablePosition() {
247
- return 1;
248
- }
249
- async getContentQuads(handle) {
250
- return this._sessionForHandle(handle)._getContentQuads(handle);
251
- }
252
- async setInputFilePaths(handle, files) {
253
- const frame = await handle.ownerFrame();
254
- if (!frame)
255
- throw new Error("Cannot set input files to detached input element");
256
- const parentSession = this._sessionForFrame(frame);
257
- await parentSession._client.send("DOM.setFileInputFiles", {
258
- objectId: handle._objectId,
259
- files
260
- });
261
- }
262
- async adoptElementHandle(handle, to) {
263
- return this._sessionForHandle(handle)._adoptElementHandle(handle, to);
264
- }
265
- async inputActionEpilogue() {
266
- await this._mainFrameSession._client.send("Page.enable").catch((e) => {
267
- });
268
- }
269
- async resetForReuse(progress) {
270
- await this.rawMouse.move(progress, -1, -1, "none", /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), true);
271
- }
272
- async pdf(options) {
273
- return this._pdf.generate(options);
274
- }
275
- coverage() {
276
- return this._coverage;
277
- }
278
- async getFrameElement(frame) {
279
- let parent = frame.parentFrame();
280
- if (!parent)
281
- throw new Error("Frame has been detached.");
282
- const parentSession = this._sessionForFrame(parent);
283
- const { backendNodeId } = await parentSession._client.send("DOM.getFrameOwner", { frameId: frame._id }).catch((e) => {
284
- if (e instanceof Error && e.message.includes("Frame with the given id was not found."))
285
- (0, import_stackTrace.rewriteErrorMessage)(e, "Frame has been detached.");
286
- throw e;
287
- });
288
- parent = frame.parentFrame();
289
- if (!parent)
290
- throw new Error("Frame has been detached.");
291
- return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());
292
- }
293
- shouldToggleStyleSheetToSyncAnimations() {
294
- return false;
295
- }
296
- }
297
- class FrameSession {
298
- constructor(crPage, client, targetId, parentSession) {
299
- this._childSessions = /* @__PURE__ */ new Set();
300
- this._contextIdToContext = /* @__PURE__ */ new Map();
301
- this._eventListeners = [];
302
- this._firstNonInitialNavigationCommittedFulfill = () => {
303
- };
304
- this._firstNonInitialNavigationCommittedReject = (e) => {
305
- };
306
- // Marks the oopif session that remote -> local transition has happened in the parent.
307
- // See Target.detachedFromTarget handler for details.
308
- this._swappedIn = false;
309
- this._workerSessions = /* @__PURE__ */ new Map();
310
- this._initScriptIds = /* @__PURE__ */ new Map();
311
- this._client = client;
312
- this._crPage = crPage;
313
- this._page = crPage._page;
314
- this._targetId = targetId;
315
- this._parentSession = parentSession;
316
- if (parentSession)
317
- parentSession._childSessions.add(this);
318
- this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {
319
- this._firstNonInitialNavigationCommittedFulfill = f;
320
- this._firstNonInitialNavigationCommittedReject = r;
321
- });
322
- this._firstNonInitialNavigationCommittedPromise.catch(() => {
323
- });
324
- }
325
- _isMainFrame() {
326
- return this._targetId === this._crPage._targetId;
327
- }
328
- _addRendererListeners() {
329
- this._eventListeners.push(...[
330
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Log.entryAdded", (event) => this._onLogEntryAdded(event)),
331
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.fileChooserOpened", (event) => this._onFileChooserOpened(event)),
332
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameAttached", (event) => this._onFrameAttached(event.frameId, event.parentFrameId)),
333
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameDetached", (event) => this._onFrameDetached(event.frameId, event.reason)),
334
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameNavigated", (event) => this._onFrameNavigated(event.frame, false)),
335
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameRequestedNavigation", (event) => this._onFrameRequestedNavigation(event)),
336
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.javascriptDialogOpening", (event) => this._onDialog(event)),
337
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.navigatedWithinDocument", (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
338
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.bindingCalled", (event) => this._onBindingCalled(event)),
339
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)),
340
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.exceptionThrown", (exception) => this._handleException(exception.exceptionDetails)),
341
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextCreated", (event) => this._onExecutionContextCreated(event.context)),
342
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextDestroyed", (event) => this._onExecutionContextDestroyed(event.executionContextId)),
343
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", (event) => this._onExecutionContextsCleared())
344
- ]);
345
- }
346
- _addBrowserListeners() {
347
- this._eventListeners.push(...[
348
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.attachedToTarget", (event) => this._onAttachedToTarget(event)),
349
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.detachedFromTarget", (event) => this._onDetachedFromTarget(event)),
350
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Inspector.targetCrashed", (event) => this._onTargetCrashed()),
351
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.screencastFrame", (event) => this._onScreencastFrame(event)),
352
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.windowOpen", (event) => this._onWindowOpen(event))
353
- ]);
354
- }
355
- async _initialize(hasUIWindow) {
356
- if (!this._page.isStorageStatePage && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {
357
- const { windowId } = await this._client.send("Browser.getWindowForTarget");
358
- this._windowId = windowId;
359
- }
360
- let videoOptions;
361
- if (!this._page.isStorageStatePage && this._isMainFrame() && hasUIWindow)
362
- videoOptions = this._crPage._page.screencast.launchVideoRecorder();
363
- let lifecycleEventsEnabled;
364
- if (!this._isMainFrame())
365
- this._addRendererListeners();
366
- this._addBrowserListeners();
367
- this._bufferedAttachedToTargetEvents = [];
368
- const promises = [
369
- this._client.send("Page.enable"),
370
- this._client.send("Page.getFrameTree").then(({ frameTree }) => {
371
- if (this._isMainFrame()) {
372
- this._handleFrameTree(frameTree);
373
- this._addRendererListeners();
374
- }
375
- const attachedToTargetEvents = this._bufferedAttachedToTargetEvents || [];
376
- this._bufferedAttachedToTargetEvents = void 0;
377
- for (const event of attachedToTargetEvents)
378
- this._onAttachedToTarget(event);
379
- const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)];
380
- for (const frame of localFrames) {
381
- this._client._sendMayFail("Page.createIsolatedWorld", {
382
- frameId: frame._id,
383
- grantUniveralAccess: true,
384
- worldName: this._crPage.utilityWorldName
385
- });
386
- }
387
- const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ":";
388
- if (isInitialEmptyPage) {
389
- lifecycleEventsEnabled.catch((e) => {
390
- }).then(() => {
391
- this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
392
- });
393
- } else {
394
- this._firstNonInitialNavigationCommittedFulfill();
395
- this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
396
- }
397
- }),
398
- this._client.send("Log.enable", {}),
399
- lifecycleEventsEnabled = this._client.send("Page.setLifecycleEventsEnabled", { enabled: true }),
400
- this._client.send("Runtime.enable", {}),
401
- this._client.send("Page.addScriptToEvaluateOnNewDocument", {
402
- source: "",
403
- worldName: this._crPage.utilityWorldName
404
- }),
405
- this._crPage._networkManager.addSession(this._client, void 0, this._isMainFrame()),
406
- this._client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true })
407
- ];
408
- if (!this._page.isStorageStatePage) {
409
- if (this._crPage._browserContext.needsPlaywrightBinding())
410
- promises.push(this.exposePlaywrightBinding());
411
- if (this._isMainFrame())
412
- promises.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true }));
413
- const options = this._crPage._browserContext._options;
414
- if (options.bypassCSP)
415
- promises.push(this._client.send("Page.setBypassCSP", { enabled: true }));
416
- if (options.ignoreHTTPSErrors || options.internalIgnoreHTTPSErrors)
417
- promises.push(this._client.send("Security.setIgnoreCertificateErrors", { ignore: true }));
418
- if (this._isMainFrame())
419
- promises.push(this._updateViewport());
420
- if (options.hasTouch)
421
- promises.push(this._client.send("Emulation.setTouchEmulationEnabled", { enabled: true }));
422
- if (options.javaScriptEnabled === false)
423
- promises.push(this._client.send("Emulation.setScriptExecutionDisabled", { value: true }));
424
- if (options.userAgent || options.locale)
425
- promises.push(this._updateUserAgent());
426
- if (options.locale)
427
- promises.push(emulateLocale(this._client, options.locale));
428
- if (options.timezoneId)
429
- promises.push(emulateTimezone(this._client, options.timezoneId));
430
- if (!this._crPage._browserContext._browser.options.headful)
431
- promises.push(this._setDefaultFontFamilies(this._client));
432
- promises.push(this._updateGeolocation(true));
433
- promises.push(this._updateEmulateMedia());
434
- promises.push(this._updateFileChooserInterception(true));
435
- for (const initScript of this._crPage._page.allInitScripts())
436
- promises.push(this._evaluateOnNewDocument(
437
- initScript,
438
- "main",
439
- true
440
- /* runImmediately */
441
- ));
442
- if (videoOptions)
443
- promises.push(this._crPage._page.screencast.startVideoRecording(videoOptions));
444
- }
445
- promises.push(this._client.send("Runtime.runIfWaitingForDebugger"));
446
- promises.push(this._firstNonInitialNavigationCommittedPromise);
447
- await Promise.all(promises);
448
- }
449
- dispose() {
450
- this._firstNonInitialNavigationCommittedReject(new import_errors.TargetClosedError(this._page.closeReason()));
451
- for (const childSession of this._childSessions)
452
- childSession.dispose();
453
- if (this._parentSession)
454
- this._parentSession._childSessions.delete(this);
455
- import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
456
- this._crPage._networkManager.removeSession(this._client);
457
- this._crPage._sessions.delete(this._targetId);
458
- this._client.dispose();
459
- }
460
- async _navigate(frame, url, referrer) {
461
- const response = await this._client.send("Page.navigate", { url, referrer, frameId: frame._id, referrerPolicy: "unsafeUrl" });
462
- if (response.isDownload)
463
- throw new frames.NavigationAbortedError(response.loaderId, "Download is starting");
464
- if (response.errorText)
465
- throw new frames.NavigationAbortedError(response.loaderId, `${response.errorText} at ${url}`);
466
- return { newDocumentId: response.loaderId };
467
- }
468
- _onLifecycleEvent(event) {
469
- if (this._eventBelongsToStaleFrame(event.frameId))
470
- return;
471
- if (event.name === "load")
472
- this._page.frameManager.frameLifecycleEvent(event.frameId, "load");
473
- else if (event.name === "DOMContentLoaded")
474
- this._page.frameManager.frameLifecycleEvent(event.frameId, "domcontentloaded");
475
- }
476
- _handleFrameTree(frameTree) {
477
- this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
478
- this._onFrameNavigated(frameTree.frame, true);
479
- if (!frameTree.childFrames)
480
- return;
481
- for (const child of frameTree.childFrames)
482
- this._handleFrameTree(child);
483
- }
484
- _eventBelongsToStaleFrame(frameId) {
485
- const frame = this._page.frameManager.frame(frameId);
486
- if (!frame)
487
- return true;
488
- const session = this._crPage._sessionForFrame(frame);
489
- return session && session !== this && !session._swappedIn;
490
- }
491
- _onFrameAttached(frameId, parentFrameId) {
492
- const frameSession = this._crPage._sessions.get(frameId);
493
- if (frameSession && frameId !== this._targetId) {
494
- frameSession._swappedIn = true;
495
- const frame = this._page.frameManager.frame(frameId);
496
- if (frame)
497
- this._page.frameManager.removeChildFramesRecursively(frame);
498
- return;
499
- }
500
- if (parentFrameId && !this._page.frameManager.frame(parentFrameId)) {
501
- return;
502
- }
503
- this._page.frameManager.frameAttached(frameId, parentFrameId);
504
- }
505
- _onFrameNavigated(framePayload, initial) {
506
- if (this._eventBelongsToStaleFrame(framePayload.id))
507
- return;
508
- this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ""), framePayload.name || "", framePayload.loaderId, initial);
509
- if (!initial)
510
- this._firstNonInitialNavigationCommittedFulfill();
511
- }
512
- _onFrameRequestedNavigation(payload) {
513
- if (this._eventBelongsToStaleFrame(payload.frameId))
514
- return;
515
- if (payload.disposition === "currentTab")
516
- this._page.frameManager.frameRequestedNavigation(payload.frameId);
517
- }
518
- _onFrameNavigatedWithinDocument(frameId, url) {
519
- if (this._eventBelongsToStaleFrame(frameId))
520
- return;
521
- this._page.frameManager.frameCommittedSameDocumentNavigation(frameId, url);
522
- }
523
- _onFrameDetached(frameId, reason) {
524
- if (this._crPage._sessions.has(frameId)) {
525
- return;
526
- }
527
- if (reason === "swap") {
528
- const frame = this._page.frameManager.frame(frameId);
529
- if (frame)
530
- this._page.frameManager.removeChildFramesRecursively(frame);
531
- return;
532
- }
533
- this._page.frameManager.frameDetached(frameId);
534
- }
535
- _onExecutionContextCreated(contextPayload) {
536
- const frame = contextPayload.auxData ? this._page.frameManager.frame(contextPayload.auxData.frameId) : null;
537
- if (!frame || this._eventBelongsToStaleFrame(frame._id))
538
- return;
539
- const delegate = new import_crExecutionContext.CRExecutionContext(this._client, contextPayload);
540
- let worldName = null;
541
- if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
542
- worldName = "main";
543
- else if (contextPayload.name === this._crPage.utilityWorldName)
544
- worldName = "utility";
545
- const context = new dom.FrameExecutionContext(delegate, frame, worldName);
546
- if (worldName)
547
- frame._contextCreated(worldName, context);
548
- this._contextIdToContext.set(contextPayload.id, context);
549
- }
550
- _onExecutionContextDestroyed(executionContextId) {
551
- const context = this._contextIdToContext.get(executionContextId);
552
- if (!context)
553
- return;
554
- this._contextIdToContext.delete(executionContextId);
555
- context.frame._contextDestroyed(context);
556
- }
557
- _onExecutionContextsCleared() {
558
- for (const contextId of Array.from(this._contextIdToContext.keys()))
559
- this._onExecutionContextDestroyed(contextId);
560
- }
561
- _onAttachedToTarget(event) {
562
- if (this._bufferedAttachedToTargetEvents) {
563
- this._bufferedAttachedToTargetEvents.push(event);
564
- return;
565
- }
566
- const session = this._client.createChildSession(event.sessionId);
567
- if (event.targetInfo.type === "iframe") {
568
- const targetId = event.targetInfo.targetId;
569
- let frame = this._page.frameManager.frame(targetId);
570
- if (!frame && event.targetInfo.parentFrameId) {
571
- frame = this._page.frameManager.frameAttached(targetId, event.targetInfo.parentFrameId);
572
- }
573
- if (!frame)
574
- return;
575
- this._page.frameManager.removeChildFramesRecursively(frame);
576
- for (const [contextId, context] of this._contextIdToContext) {
577
- if (context.frame === frame)
578
- this._onExecutionContextDestroyed(contextId);
579
- }
580
- const frameSession = new FrameSession(this._crPage, session, targetId, this);
581
- this._crPage._sessions.set(targetId, frameSession);
582
- frameSession._initialize(false).catch((e) => e);
583
- return;
584
- }
585
- if (event.targetInfo.type !== "worker") {
586
- session.detach().catch(() => {
587
- });
588
- return;
589
- }
590
- const url = event.targetInfo.url;
591
- const worker = new import_page.Worker(this._page, url);
592
- this._page.addWorker(event.sessionId, worker);
593
- this._workerSessions.set(event.sessionId, session);
594
- session.once("Runtime.executionContextCreated", async (event2) => {
595
- worker.createExecutionContext(new import_crExecutionContext.CRExecutionContext(session, event2.context));
596
- });
597
- if (this._crPage._browserContext._browser.majorVersion() >= 143)
598
- session.on("Inspector.workerScriptLoaded", () => worker.workerScriptLoaded());
599
- else
600
- worker.workerScriptLoaded();
601
- session._sendMayFail("Runtime.enable");
602
- this._crPage._networkManager.addSession(session, this._page.frameManager.frame(this._targetId) ?? void 0).catch(() => {
603
- });
604
- session._sendMayFail("Runtime.runIfWaitingForDebugger");
605
- session._sendMayFail("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
606
- session.on("Target.attachedToTarget", (event2) => this._onAttachedToTarget(event2));
607
- session.on("Target.detachedFromTarget", (event2) => this._onDetachedFromTarget(event2));
608
- session.on("Runtime.consoleAPICalled", (event2) => {
609
- const args = event2.args.map((o) => (0, import_crExecutionContext.createHandle)(worker.existingExecutionContext, o));
610
- this._page.addConsoleMessage(worker, event2.type, args, (0, import_crProtocolHelper.toConsoleMessageLocation)(event2.stackTrace));
611
- });
612
- session.on("Runtime.exceptionThrown", (exception) => this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exception.exceptionDetails)));
613
- }
614
- _onDetachedFromTarget(event) {
615
- const workerSession = this._workerSessions.get(event.sessionId);
616
- if (workerSession) {
617
- workerSession.dispose();
618
- this._page.removeWorker(event.sessionId);
619
- return;
620
- }
621
- const childFrameSession = this._crPage._sessions.get(event.targetId);
622
- if (!childFrameSession)
623
- return;
624
- if (childFrameSession._swappedIn) {
625
- childFrameSession.dispose();
626
- return;
627
- }
628
- this._client.send("Page.enable").catch((e) => null).then(() => {
629
- if (!childFrameSession._swappedIn)
630
- this._page.frameManager.frameDetached(event.targetId);
631
- childFrameSession.dispose();
632
- });
633
- }
634
- _onWindowOpen(event) {
635
- this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);
636
- }
637
- async _onConsoleAPI(event) {
638
- if (event.executionContextId === 0) {
639
- return;
640
- }
641
- const context = this._contextIdToContext.get(event.executionContextId);
642
- if (!context)
643
- return;
644
- const values = event.args.map((arg) => (0, import_crExecutionContext.createHandle)(context, arg));
645
- this._page.addConsoleMessage(null, event.type, values, (0, import_crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));
646
- }
647
- async _onBindingCalled(event) {
648
- const pageOrError = await this._crPage._page.waitForInitializedOrError();
649
- if (!(pageOrError instanceof Error)) {
650
- const context = this._contextIdToContext.get(event.executionContextId);
651
- if (context)
652
- await this._page.onBindingCalled(event.payload, context);
653
- }
654
- }
655
- _onDialog(event) {
656
- if (!this._page.frameManager.frame(this._targetId))
657
- return;
658
- this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(
659
- this._page,
660
- event.type,
661
- event.message,
662
- async (accept, promptText) => {
663
- if (this._isMainFrame() && event.type === "beforeunload" && !accept)
664
- this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, "navigation cancelled by beforeunload dialog");
665
- await this._client.send("Page.handleJavaScriptDialog", { accept, promptText });
666
- },
667
- event.defaultPrompt
668
- ));
669
- }
670
- _handleException(exceptionDetails) {
671
- this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exceptionDetails));
672
- }
673
- async _onTargetCrashed() {
674
- this._client._markAsCrashed();
675
- this._page._didCrash();
676
- }
677
- _onLogEntryAdded(event) {
678
- const { level, text, args, source, url, lineNumber } = event.entry;
679
- if (args)
680
- args.map((arg) => (0, import_crProtocolHelper.releaseObject)(this._client, arg.objectId));
681
- if (source !== "worker") {
682
- const location = {
683
- url: url || "",
684
- lineNumber: lineNumber || 0,
685
- columnNumber: 0
686
- };
687
- this._page.addConsoleMessage(null, level, [], location, text);
688
- }
689
- }
690
- async _onFileChooserOpened(event) {
691
- if (!event.backendNodeId)
692
- return;
693
- const frame = this._page.frameManager.frame(event.frameId);
694
- if (!frame)
695
- return;
696
- let handle;
697
- try {
698
- const utilityContext = await frame._utilityContext();
699
- handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);
700
- } catch (e) {
701
- return;
702
- }
703
- await this._page._onFileChooserOpened(handle);
704
- }
705
- _willBeginDownload() {
706
- if (!this._crPage._page.initializedOrUndefined()) {
707
- this._firstNonInitialNavigationCommittedReject(new Error("Starting new page download"));
708
- }
709
- }
710
- _onScreencastFrame(payload) {
711
- this._page.screencast.throttleFrameAck(() => {
712
- this._client._sendMayFail("Page.screencastFrameAck", { sessionId: payload.sessionId });
713
- });
714
- const buffer = Buffer.from(payload.data, "base64");
715
- this._page.emit(import_page.Page.Events.ScreencastFrame, {
716
- buffer,
717
- frameSwapWallTime: payload.metadata.timestamp ? payload.metadata.timestamp * 1e3 : Date.now(),
718
- width: payload.metadata.deviceWidth,
719
- height: payload.metadata.deviceHeight
720
- });
721
- }
722
- async _updateGeolocation(initial) {
723
- const geolocation = this._crPage._browserContext._options.geolocation;
724
- if (!initial || geolocation)
725
- await this._client.send("Emulation.setGeolocationOverride", geolocation || {});
726
- }
727
- async _updateViewport(preserveWindowBoundaries) {
728
- if (this._crPage._browserContext._browser.isClank())
729
- return;
730
- (0, import_assert.assert)(this._isMainFrame());
731
- const options = this._crPage._browserContext._options;
732
- const emulatedSize = this._page.emulatedSize();
733
- if (!emulatedSize)
734
- return;
735
- const viewportSize = emulatedSize.viewport;
736
- const screenSize = emulatedSize.screen;
737
- const isLandscape = screenSize.width > screenSize.height;
738
- const metricsOverride = {
739
- mobile: !!options.isMobile,
740
- width: viewportSize.width,
741
- height: viewportSize.height,
742
- screenWidth: screenSize.width,
743
- screenHeight: screenSize.height,
744
- deviceScaleFactor: options.deviceScaleFactor || 1,
745
- screenOrientation: !!options.isMobile ? isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" } : { angle: 0, type: "landscapePrimary" },
746
- dontSetVisibleSize: preserveWindowBoundaries
747
- };
748
- if (JSON.stringify(this._metricsOverride) === JSON.stringify(metricsOverride))
749
- return;
750
- const promises = [];
751
- if (!preserveWindowBoundaries && this._windowId) {
752
- let insets = { width: 0, height: 0 };
753
- if (this._crPage._browserContext._browser.options.headful) {
754
- insets = { width: 24, height: 88 };
755
- if (process.platform === "win32")
756
- insets = { width: 16, height: 88 };
757
- else if (process.platform === "linux")
758
- insets = { width: 8, height: 85 };
759
- else if (process.platform === "darwin")
760
- insets = { width: 2, height: 80 };
761
- if (this._crPage._browserContext.isPersistentContext()) {
762
- insets.height += 46;
763
- }
764
- }
765
- promises.push(this.setWindowBounds({
766
- width: viewportSize.width + insets.width,
767
- height: viewportSize.height + insets.height
768
- }));
769
- }
770
- promises.push(this._client.send("Emulation.setDeviceMetricsOverride", metricsOverride));
771
- await Promise.all(promises);
772
- this._metricsOverride = metricsOverride;
773
- }
774
- async windowBounds() {
775
- const { bounds } = await this._client.send("Browser.getWindowBounds", {
776
- windowId: this._windowId
777
- });
778
- return bounds;
779
- }
780
- async setWindowBounds(bounds) {
781
- return await this._client.send("Browser.setWindowBounds", {
782
- windowId: this._windowId,
783
- bounds
784
- });
785
- }
786
- async _updateEmulateMedia() {
787
- const emulatedMedia = this._page.emulatedMedia();
788
- const media = emulatedMedia.media === "no-override" ? "" : emulatedMedia.media;
789
- const colorScheme = emulatedMedia.colorScheme === "no-override" ? "" : emulatedMedia.colorScheme;
790
- const reducedMotion = emulatedMedia.reducedMotion === "no-override" ? "" : emulatedMedia.reducedMotion;
791
- const forcedColors = emulatedMedia.forcedColors === "no-override" ? "" : emulatedMedia.forcedColors;
792
- const contrast = emulatedMedia.contrast === "no-override" ? "" : emulatedMedia.contrast;
793
- const features = [
794
- { name: "prefers-color-scheme", value: colorScheme },
795
- { name: "prefers-reduced-motion", value: reducedMotion },
796
- { name: "forced-colors", value: forcedColors },
797
- { name: "prefers-contrast", value: contrast }
798
- ];
799
- await this._client.send("Emulation.setEmulatedMedia", { media, features });
800
- }
801
- async _updateUserAgent() {
802
- const options = this._crPage._browserContext._options;
803
- await this._client.send("Emulation.setUserAgentOverride", {
804
- userAgent: options.userAgent || "",
805
- acceptLanguage: options.locale,
806
- userAgentMetadata: calculateUserAgentMetadata(options)
807
- });
808
- }
809
- async _setDefaultFontFamilies(session) {
810
- const fontFamilies = import_defaultFontFamilies.platformToFontFamilies[this._crPage._browserContext._browser._platform()];
811
- await session.send("Page.setFontFamilies", fontFamilies);
812
- }
813
- async _updateFileChooserInterception(initial) {
814
- const enabled = this._page.fileChooserIntercepted();
815
- if (initial && !enabled)
816
- return;
817
- await this._client.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => {
818
- });
819
- }
820
- async _evaluateOnNewDocument(initScript, world, runImmediately) {
821
- const worldName = world === "utility" ? this._crPage.utilityWorldName : void 0;
822
- const { identifier } = await this._client.send("Page.addScriptToEvaluateOnNewDocument", { source: initScript.source, worldName, runImmediately });
823
- this._initScriptIds.set(initScript, identifier);
824
- }
825
- async _removeEvaluatesOnNewDocument(initScripts) {
826
- const ids = [];
827
- for (const script of initScripts) {
828
- const id = this._initScriptIds.get(script);
829
- if (id)
830
- ids.push(id);
831
- this._initScriptIds.delete(script);
832
- }
833
- await Promise.all(ids.map((identifier) => this._client.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => {
834
- })));
835
- }
836
- async exposePlaywrightBinding() {
837
- await this._client.send("Runtime.addBinding", { name: import_page.PageBinding.kBindingName });
838
- }
839
- async _getContentFrame(handle) {
840
- const nodeInfo = await this._client.send("DOM.describeNode", {
841
- objectId: handle._objectId
842
- });
843
- if (!nodeInfo || typeof nodeInfo.node.frameId !== "string")
844
- return null;
845
- return this._page.frameManager.frame(nodeInfo.node.frameId);
846
- }
847
- async _getOwnerFrame(handle) {
848
- const documentElement = await handle.evaluateHandle((node) => {
849
- const doc = node;
850
- if (doc.documentElement && doc.documentElement.ownerDocument === doc)
851
- return doc.documentElement;
852
- return node.ownerDocument ? node.ownerDocument.documentElement : null;
853
- });
854
- if (!documentElement)
855
- return null;
856
- if (!documentElement._objectId)
857
- return null;
858
- const nodeInfo = await this._client.send("DOM.describeNode", {
859
- objectId: documentElement._objectId
860
- });
861
- const frameId = nodeInfo && typeof nodeInfo.node.frameId === "string" ? nodeInfo.node.frameId : null;
862
- documentElement.dispose();
863
- return frameId;
864
- }
865
- async _getBoundingBox(handle) {
866
- const result = await this._client._sendMayFail("DOM.getBoxModel", {
867
- objectId: handle._objectId
868
- });
869
- if (!result)
870
- return null;
871
- const quad = result.model.border;
872
- const x = Math.min(quad[0], quad[2], quad[4], quad[6]);
873
- const y = Math.min(quad[1], quad[3], quad[5], quad[7]);
874
- const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;
875
- const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;
876
- const position = await this._framePosition();
877
- if (!position)
878
- return null;
879
- return { x: x + position.x, y: y + position.y, width, height };
880
- }
881
- async _framePosition() {
882
- const frame = this._page.frameManager.frame(this._targetId);
883
- if (!frame)
884
- return null;
885
- if (frame === this._page.mainFrame())
886
- return { x: 0, y: 0 };
887
- const element = await frame.frameElement();
888
- const box = await element.boundingBox();
889
- return box;
890
- }
891
- async _scrollRectIntoViewIfNeeded(handle, rect) {
892
- return await this._client.send("DOM.scrollIntoViewIfNeeded", {
893
- objectId: handle._objectId,
894
- rect
895
- }).then(() => "done").catch((e) => {
896
- if (e instanceof Error && e.message.includes("Node does not have a layout object"))
897
- return "error:notvisible";
898
- if (e instanceof Error && e.message.includes("Node is detached from document"))
899
- return "error:notconnected";
900
- throw e;
901
- });
902
- }
903
- async _getContentQuads(handle) {
904
- const result = await this._client._sendMayFail("DOM.getContentQuads", {
905
- objectId: handle._objectId
906
- });
907
- if (!result)
908
- return null;
909
- const position = await this._framePosition();
910
- if (!position)
911
- return null;
912
- return result.quads.map((quad) => [
913
- { x: quad[0] + position.x, y: quad[1] + position.y },
914
- { x: quad[2] + position.x, y: quad[3] + position.y },
915
- { x: quad[4] + position.x, y: quad[5] + position.y },
916
- { x: quad[6] + position.x, y: quad[7] + position.y }
917
- ]);
918
- }
919
- async _adoptElementHandle(handle, to) {
920
- const nodeInfo = await this._client.send("DOM.describeNode", {
921
- objectId: handle._objectId
922
- });
923
- return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to);
924
- }
925
- async _adoptBackendNodeId(backendNodeId, to) {
926
- const result = await this._client._sendMayFail("DOM.resolveNode", {
927
- backendNodeId,
928
- executionContextId: to.delegate._contextId
929
- });
930
- if (!result || result.object.subtype === "null")
931
- throw new Error(dom.kUnableToAdoptErrorMessage);
932
- return (0, import_crExecutionContext.createHandle)(to, result.object).asElement();
933
- }
934
- }
935
- async function emulateLocale(session, locale) {
936
- try {
937
- await session.send("Emulation.setLocaleOverride", { locale });
938
- } catch (exception) {
939
- if (exception.message.includes("Another locale override is already in effect"))
940
- return;
941
- throw exception;
942
- }
943
- }
944
- async function emulateTimezone(session, timezoneId) {
945
- try {
946
- await session.send("Emulation.setTimezoneOverride", { timezoneId });
947
- } catch (exception) {
948
- if (exception.message.includes("Timezone override is already in effect"))
949
- return;
950
- if (exception.message.includes("Invalid timezone"))
951
- throw new Error(`Invalid timezone ID: ${timezoneId}`);
952
- throw exception;
953
- }
954
- }
955
- function calculateUserAgentMetadata(options) {
956
- const ua = options.userAgent;
957
- if (!ua)
958
- return void 0;
959
- const metadata = {
960
- mobile: !!options.isMobile,
961
- model: "",
962
- architecture: "x86",
963
- platform: "Windows",
964
- platformVersion: ""
965
- };
966
- const androidMatch = ua.match(/Android (\d+(\.\d+)?(\.\d+)?)/);
967
- const iPhoneMatch = ua.match(/iPhone OS (\d+(_\d+)?)/);
968
- const iPadMatch = ua.match(/iPad; CPU OS (\d+(_\d+)?)/);
969
- const macOSMatch = ua.match(/Mac OS X (\d+(_\d+)?(_\d+)?)/);
970
- const windowsMatch = ua.match(/Windows\D+(\d+(\.\d+)?(\.\d+)?)/);
971
- if (androidMatch) {
972
- metadata.platform = "Android";
973
- metadata.platformVersion = androidMatch[1];
974
- metadata.architecture = "arm";
975
- } else if (iPhoneMatch) {
976
- metadata.platform = "iOS";
977
- metadata.platformVersion = iPhoneMatch[1];
978
- metadata.architecture = "arm";
979
- } else if (iPadMatch) {
980
- metadata.platform = "iOS";
981
- metadata.platformVersion = iPadMatch[1];
982
- metadata.architecture = "arm";
983
- } else if (macOSMatch) {
984
- metadata.platform = "macOS";
985
- metadata.platformVersion = macOSMatch[1];
986
- if (!ua.includes("Intel"))
987
- metadata.architecture = "arm";
988
- } else if (windowsMatch) {
989
- metadata.platform = "Windows";
990
- metadata.platformVersion = windowsMatch[1];
991
- } else if (ua.toLowerCase().includes("linux")) {
992
- metadata.platform = "Linux";
993
- }
994
- if (ua.includes("ARM"))
995
- metadata.architecture = "arm";
996
- return metadata;
997
- }
998
- // Annotate the CommonJS export names for ESM import in node:
999
- 0 && (module.exports = {
1000
- CRPage
1001
- });
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var crPage_exports = {};
30
+ __export(crPage_exports, {
31
+ CRPage: () => CRPage
32
+ });
33
+ module.exports = __toCommonJS(crPage_exports);
34
+ var import_assert = require("../../utils/isomorphic/assert");
35
+ var import_eventsHelper = require("../utils/eventsHelper");
36
+ var import_stackTrace = require("../../utils/isomorphic/stackTrace");
37
+ var dialog = __toESM(require("../dialog"));
38
+ var dom = __toESM(require("../dom"));
39
+ var frames = __toESM(require("../frames"));
40
+ var import_helper = require("../helper");
41
+ var network = __toESM(require("../network"));
42
+ var import_page = require("../page");
43
+ var import_browserContext = require("../browserContext");
44
+ var import_crCoverage = require("./crCoverage");
45
+ var import_crDragDrop = require("./crDragDrop");
46
+ var import_crExecutionContext = require("./crExecutionContext");
47
+ var import_crInput = require("./crInput");
48
+ var import_crNetworkManager = require("./crNetworkManager");
49
+ var import_crPdf = require("./crPdf");
50
+ var import_crProtocolHelper = require("./crProtocolHelper");
51
+ var import_defaultFontFamilies = require("./defaultFontFamilies");
52
+ var import_errors = require("../errors");
53
+ var import_protocolError = require("../protocolError");
54
+ var import_videoRecorder = require("../videoRecorder");
55
+ class CRPage {
56
+ constructor(client, targetId, browserContext, opener, bits) {
57
+ this._sessions = /* @__PURE__ */ new Map();
58
+ // Holds window features for the next popup being opened via window.open,
59
+ // until the popup target arrives. This could be racy if two oopifs
60
+ // simultaneously call window.open with window features: the order
61
+ // of their Page.windowOpen events is not guaranteed to match the order
62
+ // of new popup targets.
63
+ this._nextWindowOpenPopupFeatures = [];
64
+ this._targetId = targetId;
65
+ this._opener = opener;
66
+ const dragManager = new import_crDragDrop.DragManager(this);
67
+ this.rawKeyboard = new import_crInput.RawKeyboardImpl(client, browserContext._browser._platform() === "mac", dragManager);
68
+ this.rawMouse = new import_crInput.RawMouseImpl(this, client, dragManager);
69
+ this.rawTouchscreen = new import_crInput.RawTouchscreenImpl(client);
70
+ this._pdf = new import_crPdf.CRPDF(client);
71
+ this._coverage = new import_crCoverage.CRCoverage(client);
72
+ this._browserContext = browserContext;
73
+ this._page = new import_page.Page(this, browserContext);
74
+ this.utilityWorldName = `__playwright_utility_world_${this._page.guid}`;
75
+ this._networkManager = new import_crNetworkManager.CRNetworkManager(this._page, null);
76
+ this.updateOffline();
77
+ this.updateExtraHTTPHeaders();
78
+ this.updateHttpCredentials();
79
+ this.updateRequestInterception();
80
+ this._mainFrameSession = new FrameSession(this, client, targetId, null);
81
+ this._sessions.set(targetId, this._mainFrameSession);
82
+ if (opener && !browserContext._options.noDefaultViewport) {
83
+ const features = opener._nextWindowOpenPopupFeatures.shift() || [];
84
+ const viewportSize = import_helper.helper.getViewportSizeFromWindowFeatures(features);
85
+ if (viewportSize)
86
+ this._page.setEmulatedSizeFromWindowOpen({ viewport: viewportSize, screen: viewportSize });
87
+ }
88
+ this._mainFrameSession._initialize(bits.hasUIWindow).then(
89
+ () => this._page.reportAsNew(this._opener?._page, void 0),
90
+ (error) => this._page.reportAsNew(this._opener?._page, error)
91
+ );
92
+ }
93
+ static mainFrameSession(page) {
94
+ const crPage = page.delegate;
95
+ return crPage._mainFrameSession;
96
+ }
97
+ async _forAllFrameSessions(cb) {
98
+ const frameSessions = Array.from(this._sessions.values());
99
+ await Promise.all(frameSessions.map((frameSession) => {
100
+ if (frameSession._isMainFrame())
101
+ return cb(frameSession);
102
+ return cb(frameSession).catch((e) => {
103
+ if ((0, import_protocolError.isSessionClosedError)(e))
104
+ return;
105
+ throw e;
106
+ });
107
+ }));
108
+ }
109
+ _sessionForFrame(frame) {
110
+ while (!this._sessions.has(frame._id)) {
111
+ const parent = frame.parentFrame();
112
+ if (!parent)
113
+ throw new Error(`Frame has been detached.`);
114
+ frame = parent;
115
+ }
116
+ return this._sessions.get(frame._id);
117
+ }
118
+ _sessionForHandle(handle) {
119
+ const frame = handle._context.frame;
120
+ return this._sessionForFrame(frame);
121
+ }
122
+ willBeginDownload() {
123
+ this._mainFrameSession._willBeginDownload();
124
+ }
125
+ didClose() {
126
+ for (const session of this._sessions.values())
127
+ session.dispose();
128
+ this._page._didClose();
129
+ }
130
+ async navigateFrame(frame, url, referrer) {
131
+ return this._sessionForFrame(frame)._navigate(frame, url, referrer);
132
+ }
133
+ async updateExtraHTTPHeaders() {
134
+ const headers = network.mergeHeaders([
135
+ this._browserContext._options.extraHTTPHeaders,
136
+ this._page.extraHTTPHeaders()
137
+ ]);
138
+ await this._networkManager.setExtraHTTPHeaders(headers);
139
+ }
140
+ async updateGeolocation() {
141
+ await this._forAllFrameSessions((frame) => frame._updateGeolocation(false));
142
+ }
143
+ async updateOffline() {
144
+ await this._networkManager.setOffline(!!this._browserContext._options.offline);
145
+ }
146
+ async updateHttpCredentials() {
147
+ await this._networkManager.authenticate(this._browserContext._options.httpCredentials || null);
148
+ }
149
+ async updateEmulatedViewportSize(preserveWindowBoundaries) {
150
+ await this._mainFrameSession._updateViewport(preserveWindowBoundaries);
151
+ }
152
+ async bringToFront() {
153
+ await this._mainFrameSession._client.send("Page.bringToFront");
154
+ }
155
+ async updateEmulateMedia() {
156
+ await this._forAllFrameSessions((frame) => frame._updateEmulateMedia());
157
+ }
158
+ async updateUserAgent() {
159
+ await this._forAllFrameSessions((frame) => frame._updateUserAgent());
160
+ }
161
+ async updateRequestInterception() {
162
+ await this._networkManager.setRequestInterception(this._page.needsRequestInterception());
163
+ }
164
+ async updateFileChooserInterception() {
165
+ await this._forAllFrameSessions((frame) => frame._updateFileChooserInterception(false));
166
+ }
167
+ async reload() {
168
+ await this._mainFrameSession._client.send("Page.reload");
169
+ }
170
+ async _go(delta) {
171
+ const history = await this._mainFrameSession._client.send("Page.getNavigationHistory");
172
+ const entry = history.entries[history.currentIndex + delta];
173
+ if (!entry)
174
+ return false;
175
+ await this._mainFrameSession._client.send("Page.navigateToHistoryEntry", { entryId: entry.id });
176
+ return true;
177
+ }
178
+ goBack() {
179
+ return this._go(-1);
180
+ }
181
+ goForward() {
182
+ return this._go(1);
183
+ }
184
+ async requestGC() {
185
+ await this._mainFrameSession._client.send("HeapProfiler.collectGarbage");
186
+ }
187
+ async addInitScript(initScript, world = "main") {
188
+ await this._forAllFrameSessions((frame) => frame._evaluateOnNewDocument(initScript, world));
189
+ }
190
+ async exposePlaywrightBinding() {
191
+ await this._forAllFrameSessions((frame) => frame.exposePlaywrightBinding());
192
+ }
193
+ async removeInitScripts(initScripts) {
194
+ await this._forAllFrameSessions((frame) => frame._removeEvaluatesOnNewDocument(initScripts));
195
+ }
196
+ async closePage(runBeforeUnload) {
197
+ if (runBeforeUnload)
198
+ await this._mainFrameSession._client.send("Page.close");
199
+ else
200
+ await this._browserContext._browser._closePage(this);
201
+ }
202
+ async setBackgroundColor(color) {
203
+ await this._mainFrameSession._client.send("Emulation.setDefaultBackgroundColorOverride", { color });
204
+ }
205
+ async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {
206
+ const { visualViewport, contentSize, cssContentSize } = await progress.race(this._mainFrameSession._client.send("Page.getLayoutMetrics"));
207
+ if (!documentRect) {
208
+ documentRect = {
209
+ x: visualViewport.pageX + viewportRect.x,
210
+ y: visualViewport.pageY + viewportRect.y,
211
+ ...import_helper.helper.enclosingIntSize({
212
+ width: viewportRect.width / visualViewport.scale,
213
+ height: viewportRect.height / visualViewport.scale
214
+ })
215
+ };
216
+ }
217
+ const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 };
218
+ if (scale === "css") {
219
+ const deviceScaleFactor = this._mainFrameSession._metricsOverride?.deviceScaleFactor || contentSize.width / cssContentSize.width || 1;
220
+ clip.scale /= deviceScaleFactor;
221
+ }
222
+ const result = await progress.race(this._mainFrameSession._client.send("Page.captureScreenshot", { format, quality, clip, captureBeyondViewport: !fitsViewport }));
223
+ return Buffer.from(result.data, "base64");
224
+ }
225
+ async getContentFrame(handle) {
226
+ return this._sessionForHandle(handle)._getContentFrame(handle);
227
+ }
228
+ async getOwnerFrame(handle) {
229
+ return this._sessionForHandle(handle)._getOwnerFrame(handle);
230
+ }
231
+ async getBoundingBox(handle) {
232
+ return this._sessionForHandle(handle)._getBoundingBox(handle);
233
+ }
234
+ async scrollRectIntoViewIfNeeded(handle, rect) {
235
+ return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);
236
+ }
237
+ startScreencast(options) {
238
+ this._mainFrameSession._client.send("Page.startScreencast", {
239
+ format: "jpeg",
240
+ quality: options.quality,
241
+ maxWidth: options.width,
242
+ maxHeight: options.height
243
+ }).catch(() => {
244
+ });
245
+ }
246
+ stopScreencast() {
247
+ this._mainFrameSession._client._sendMayFail("Page.stopScreencast").catch(() => {
248
+ });
249
+ }
250
+ rafCountForStablePosition() {
251
+ return 1;
252
+ }
253
+ async getContentQuads(handle) {
254
+ return this._sessionForHandle(handle)._getContentQuads(handle);
255
+ }
256
+ async setInputFilePaths(handle, files) {
257
+ const frame = await handle.ownerFrame();
258
+ if (!frame)
259
+ throw new Error("Cannot set input files to detached input element");
260
+ const parentSession = this._sessionForFrame(frame);
261
+ await parentSession._client.send("DOM.setFileInputFiles", {
262
+ objectId: handle._objectId,
263
+ files
264
+ });
265
+ }
266
+ async adoptElementHandle(handle, to) {
267
+ return this._sessionForHandle(handle)._adoptElementHandle(handle, to);
268
+ }
269
+ async inputActionEpilogue() {
270
+ await this._mainFrameSession._client.send("Page.enable").catch((e) => {
271
+ });
272
+ }
273
+ async resetForReuse(progress) {
274
+ await this.rawMouse.move(progress, -1, -1, "none", /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), true);
275
+ }
276
+ async pdf(options) {
277
+ return this._pdf.generate(options);
278
+ }
279
+ coverage() {
280
+ return this._coverage;
281
+ }
282
+ async getFrameElement(frame) {
283
+ let parent = frame.parentFrame();
284
+ if (!parent)
285
+ throw new Error("Frame has been detached.");
286
+ const parentSession = this._sessionForFrame(parent);
287
+ const { backendNodeId } = await parentSession._client.send("DOM.getFrameOwner", { frameId: frame._id }).catch((e) => {
288
+ if (e instanceof Error && e.message.includes("Frame with the given id was not found."))
289
+ (0, import_stackTrace.rewriteErrorMessage)(e, "Frame has been detached.");
290
+ throw e;
291
+ });
292
+ parent = frame.parentFrame();
293
+ if (!parent)
294
+ throw new Error("Frame has been detached.");
295
+ return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());
296
+ }
297
+ shouldToggleStyleSheetToSyncAnimations() {
298
+ return false;
299
+ }
300
+ async setDockTile(image) {
301
+ await this._mainFrameSession._client.send("Browser.setDockTile", { image: image.toString("base64") });
302
+ }
303
+ }
304
+ class FrameSession {
305
+ constructor(crPage, client, targetId, parentSession) {
306
+ this._childSessions = /* @__PURE__ */ new Set();
307
+ this._contextIdToContext = /* @__PURE__ */ new Map();
308
+ this._eventListeners = [];
309
+ this._firstNonInitialNavigationCommittedFulfill = () => {
310
+ };
311
+ this._firstNonInitialNavigationCommittedReject = (e) => {
312
+ };
313
+ // Marks the oopif session that remote -> local transition has happened in the parent.
314
+ // See Target.detachedFromTarget handler for details.
315
+ this._swappedIn = false;
316
+ this._workerSessions = /* @__PURE__ */ new Map();
317
+ this._initScriptIds = /* @__PURE__ */ new Map();
318
+ this._client = client;
319
+ this._crPage = crPage;
320
+ this._page = crPage._page;
321
+ this._targetId = targetId;
322
+ this._parentSession = parentSession;
323
+ if (parentSession)
324
+ parentSession._childSessions.add(this);
325
+ this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {
326
+ this._firstNonInitialNavigationCommittedFulfill = f;
327
+ this._firstNonInitialNavigationCommittedReject = r;
328
+ });
329
+ this._firstNonInitialNavigationCommittedPromise.catch(() => {
330
+ });
331
+ }
332
+ _isMainFrame() {
333
+ return this._targetId === this._crPage._targetId;
334
+ }
335
+ _addRendererListeners() {
336
+ this._eventListeners.push(...[
337
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Log.entryAdded", (event) => this._onLogEntryAdded(event)),
338
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.fileChooserOpened", (event) => this._onFileChooserOpened(event)),
339
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameAttached", (event) => this._onFrameAttached(event.frameId, event.parentFrameId)),
340
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameDetached", (event) => this._onFrameDetached(event.frameId, event.reason)),
341
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameNavigated", (event) => this._onFrameNavigated(event.frame, false)),
342
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameRequestedNavigation", (event) => this._onFrameRequestedNavigation(event)),
343
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.javascriptDialogOpening", (event) => this._onDialog(event)),
344
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.navigatedWithinDocument", (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
345
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.bindingCalled", (event) => this._onBindingCalled(event)),
346
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)),
347
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.exceptionThrown", (exception) => this._handleException(exception.exceptionDetails)),
348
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextCreated", (event) => this._onExecutionContextCreated(event.context)),
349
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextDestroyed", (event) => this._onExecutionContextDestroyed(event.executionContextId)),
350
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", (event) => this._onExecutionContextsCleared())
351
+ ]);
352
+ }
353
+ _addBrowserListeners() {
354
+ this._eventListeners.push(...[
355
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.attachedToTarget", (event) => this._onAttachedToTarget(event)),
356
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.detachedFromTarget", (event) => this._onDetachedFromTarget(event)),
357
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Inspector.targetCrashed", (event) => this._onTargetCrashed()),
358
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.screencastFrame", (event) => this._onScreencastFrame(event)),
359
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.windowOpen", (event) => this._onWindowOpen(event))
360
+ ]);
361
+ }
362
+ async _initialize(hasUIWindow) {
363
+ if (!this._page.isStorageStatePage && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {
364
+ const { windowId } = await this._client.send("Browser.getWindowForTarget");
365
+ this._windowId = windowId;
366
+ }
367
+ if (this._isMainFrame() && hasUIWindow && !this._page.isStorageStatePage)
368
+ (0, import_videoRecorder.startAutomaticVideoRecording)(this._crPage._page);
369
+ let lifecycleEventsEnabled;
370
+ if (!this._isMainFrame())
371
+ this._addRendererListeners();
372
+ this._addBrowserListeners();
373
+ this._bufferedAttachedToTargetEvents = [];
374
+ const promises = [
375
+ this._client.send("Page.enable"),
376
+ this._client.send("Page.getFrameTree").then(({ frameTree }) => {
377
+ if (this._isMainFrame()) {
378
+ this._handleFrameTree(frameTree);
379
+ this._addRendererListeners();
380
+ }
381
+ const attachedToTargetEvents = this._bufferedAttachedToTargetEvents || [];
382
+ this._bufferedAttachedToTargetEvents = void 0;
383
+ for (const event of attachedToTargetEvents)
384
+ this._onAttachedToTarget(event);
385
+ const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)];
386
+ for (const frame of localFrames) {
387
+ this._client._sendMayFail("Page.createIsolatedWorld", {
388
+ frameId: frame._id,
389
+ grantUniveralAccess: true,
390
+ worldName: this._crPage.utilityWorldName
391
+ });
392
+ }
393
+ const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ":";
394
+ if (isInitialEmptyPage) {
395
+ lifecycleEventsEnabled.catch((e) => {
396
+ }).then(() => {
397
+ this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
398
+ });
399
+ } else {
400
+ this._firstNonInitialNavigationCommittedFulfill();
401
+ this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
402
+ }
403
+ }),
404
+ this._client.send("Log.enable", {}),
405
+ lifecycleEventsEnabled = this._client.send("Page.setLifecycleEventsEnabled", { enabled: true }),
406
+ this._client.send("Runtime.enable", {}),
407
+ this._client.send("Page.addScriptToEvaluateOnNewDocument", {
408
+ source: "",
409
+ worldName: this._crPage.utilityWorldName
410
+ }),
411
+ this._crPage._networkManager.addSession(this._client, void 0, this._isMainFrame()),
412
+ this._client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true })
413
+ ];
414
+ if (!this._page.isStorageStatePage) {
415
+ if (this._crPage._browserContext.needsPlaywrightBinding())
416
+ promises.push(this.exposePlaywrightBinding());
417
+ if (this._isMainFrame())
418
+ promises.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true }));
419
+ const options = this._crPage._browserContext._options;
420
+ if (options.bypassCSP)
421
+ promises.push(this._client.send("Page.setBypassCSP", { enabled: true }));
422
+ if (options.ignoreHTTPSErrors || options.internalIgnoreHTTPSErrors)
423
+ promises.push(this._client.send("Security.setIgnoreCertificateErrors", { ignore: true }));
424
+ if (this._isMainFrame())
425
+ promises.push(this._updateViewport());
426
+ if (options.hasTouch)
427
+ promises.push(this._client.send("Emulation.setTouchEmulationEnabled", { enabled: true }));
428
+ if (options.javaScriptEnabled === false)
429
+ promises.push(this._client.send("Emulation.setScriptExecutionDisabled", { value: true }));
430
+ if (options.userAgent || options.locale)
431
+ promises.push(this._updateUserAgent());
432
+ if (options.locale)
433
+ promises.push(emulateLocale(this._client, options.locale));
434
+ if (options.timezoneId)
435
+ promises.push(emulateTimezone(this._client, options.timezoneId));
436
+ if (!this._crPage._browserContext._browser.options.headful)
437
+ promises.push(this._setDefaultFontFamilies(this._client));
438
+ promises.push(this._updateGeolocation(true));
439
+ promises.push(this._updateEmulateMedia());
440
+ promises.push(this._updateFileChooserInterception(true));
441
+ for (const initScript of this._crPage._page.allInitScripts())
442
+ promises.push(this._evaluateOnNewDocument(
443
+ initScript,
444
+ "main",
445
+ true
446
+ /* runImmediately */
447
+ ));
448
+ }
449
+ promises.push(this._client.send("Runtime.runIfWaitingForDebugger"));
450
+ promises.push(this._firstNonInitialNavigationCommittedPromise);
451
+ await Promise.all(promises);
452
+ }
453
+ dispose() {
454
+ this._firstNonInitialNavigationCommittedReject(new import_errors.TargetClosedError(this._page.closeReason()));
455
+ for (const childSession of this._childSessions)
456
+ childSession.dispose();
457
+ if (this._parentSession)
458
+ this._parentSession._childSessions.delete(this);
459
+ import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
460
+ this._crPage._networkManager.removeSession(this._client);
461
+ this._crPage._sessions.delete(this._targetId);
462
+ this._client.dispose();
463
+ }
464
+ async _navigate(frame, url, referrer) {
465
+ const response = await this._client.send("Page.navigate", { url, referrer, frameId: frame._id, referrerPolicy: "unsafeUrl" });
466
+ if (response.isDownload)
467
+ throw new frames.NavigationAbortedError(response.loaderId, "Download is starting");
468
+ if (response.errorText)
469
+ throw new frames.NavigationAbortedError(response.loaderId, `${response.errorText} at ${url}`);
470
+ return { newDocumentId: response.loaderId };
471
+ }
472
+ _onLifecycleEvent(event) {
473
+ if (this._eventBelongsToStaleFrame(event.frameId))
474
+ return;
475
+ if (event.name === "load")
476
+ this._page.frameManager.frameLifecycleEvent(event.frameId, "load");
477
+ else if (event.name === "DOMContentLoaded")
478
+ this._page.frameManager.frameLifecycleEvent(event.frameId, "domcontentloaded");
479
+ }
480
+ _handleFrameTree(frameTree) {
481
+ this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
482
+ this._onFrameNavigated(frameTree.frame, true);
483
+ if (!frameTree.childFrames)
484
+ return;
485
+ for (const child of frameTree.childFrames)
486
+ this._handleFrameTree(child);
487
+ }
488
+ _eventBelongsToStaleFrame(frameId) {
489
+ const frame = this._page.frameManager.frame(frameId);
490
+ if (!frame)
491
+ return true;
492
+ const session = this._crPage._sessionForFrame(frame);
493
+ return session && session !== this && !session._swappedIn;
494
+ }
495
+ _onFrameAttached(frameId, parentFrameId) {
496
+ const frameSession = this._crPage._sessions.get(frameId);
497
+ if (frameSession && frameId !== this._targetId) {
498
+ frameSession._swappedIn = true;
499
+ const frame = this._page.frameManager.frame(frameId);
500
+ if (frame)
501
+ this._page.frameManager.removeChildFramesRecursively(frame);
502
+ return;
503
+ }
504
+ if (parentFrameId && !this._page.frameManager.frame(parentFrameId)) {
505
+ return;
506
+ }
507
+ this._page.frameManager.frameAttached(frameId, parentFrameId);
508
+ }
509
+ _onFrameNavigated(framePayload, initial) {
510
+ if (this._eventBelongsToStaleFrame(framePayload.id))
511
+ return;
512
+ this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ""), framePayload.name || "", framePayload.loaderId, initial);
513
+ if (!initial)
514
+ this._firstNonInitialNavigationCommittedFulfill();
515
+ }
516
+ _onFrameRequestedNavigation(payload) {
517
+ if (this._eventBelongsToStaleFrame(payload.frameId))
518
+ return;
519
+ if (payload.disposition === "currentTab")
520
+ this._page.frameManager.frameRequestedNavigation(payload.frameId);
521
+ }
522
+ _onFrameNavigatedWithinDocument(frameId, url) {
523
+ if (this._eventBelongsToStaleFrame(frameId))
524
+ return;
525
+ this._page.frameManager.frameCommittedSameDocumentNavigation(frameId, url);
526
+ }
527
+ _onFrameDetached(frameId, reason) {
528
+ if (this._crPage._sessions.has(frameId)) {
529
+ return;
530
+ }
531
+ if (reason === "swap") {
532
+ const frame = this._page.frameManager.frame(frameId);
533
+ if (frame)
534
+ this._page.frameManager.removeChildFramesRecursively(frame);
535
+ return;
536
+ }
537
+ this._page.frameManager.frameDetached(frameId);
538
+ }
539
+ _onExecutionContextCreated(contextPayload) {
540
+ const frame = contextPayload.auxData ? this._page.frameManager.frame(contextPayload.auxData.frameId) : null;
541
+ if (!frame || this._eventBelongsToStaleFrame(frame._id))
542
+ return;
543
+ const delegate = new import_crExecutionContext.CRExecutionContext(this._client, contextPayload);
544
+ let worldName = null;
545
+ if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
546
+ worldName = "main";
547
+ else if (contextPayload.name === this._crPage.utilityWorldName)
548
+ worldName = "utility";
549
+ const context = new dom.FrameExecutionContext(delegate, frame, worldName);
550
+ if (worldName)
551
+ frame._contextCreated(worldName, context);
552
+ this._contextIdToContext.set(contextPayload.id, context);
553
+ }
554
+ _onExecutionContextDestroyed(executionContextId) {
555
+ const context = this._contextIdToContext.get(executionContextId);
556
+ if (!context)
557
+ return;
558
+ this._contextIdToContext.delete(executionContextId);
559
+ context.frame._contextDestroyed(context);
560
+ }
561
+ _onExecutionContextsCleared() {
562
+ for (const contextId of Array.from(this._contextIdToContext.keys()))
563
+ this._onExecutionContextDestroyed(contextId);
564
+ }
565
+ _onAttachedToTarget(event) {
566
+ if (this._bufferedAttachedToTargetEvents) {
567
+ this._bufferedAttachedToTargetEvents.push(event);
568
+ return;
569
+ }
570
+ const session = this._client.createChildSession(event.sessionId);
571
+ if (event.targetInfo.type === "iframe") {
572
+ const targetId = event.targetInfo.targetId;
573
+ let frame = this._page.frameManager.frame(targetId);
574
+ if (!frame && event.targetInfo.parentFrameId) {
575
+ frame = this._page.frameManager.frameAttached(targetId, event.targetInfo.parentFrameId);
576
+ }
577
+ if (!frame)
578
+ return;
579
+ this._page.frameManager.removeChildFramesRecursively(frame);
580
+ for (const [contextId, context] of this._contextIdToContext) {
581
+ if (context.frame === frame)
582
+ this._onExecutionContextDestroyed(contextId);
583
+ }
584
+ const frameSession = new FrameSession(this._crPage, session, targetId, this);
585
+ this._crPage._sessions.set(targetId, frameSession);
586
+ frameSession._initialize(false).catch((e) => e);
587
+ return;
588
+ }
589
+ if (event.targetInfo.type !== "worker") {
590
+ session.detach().catch(() => {
591
+ });
592
+ return;
593
+ }
594
+ const url = event.targetInfo.url;
595
+ const worker = new import_page.Worker(this._page, url);
596
+ this._page.addWorker(event.sessionId, worker);
597
+ this._workerSessions.set(event.sessionId, session);
598
+ session.once("Runtime.executionContextCreated", async (event2) => {
599
+ worker.createExecutionContext(new import_crExecutionContext.CRExecutionContext(session, event2.context));
600
+ });
601
+ if (this._crPage._browserContext._browser.majorVersion() >= 143)
602
+ session.on("Inspector.workerScriptLoaded", () => worker.workerScriptLoaded());
603
+ else
604
+ worker.workerScriptLoaded();
605
+ session._sendMayFail("Runtime.enable");
606
+ this._crPage._networkManager.addSession(session, this._page.frameManager.frame(this._targetId) ?? void 0).catch(() => {
607
+ });
608
+ session._sendMayFail("Runtime.runIfWaitingForDebugger");
609
+ session._sendMayFail("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
610
+ session.on("Target.attachedToTarget", (event2) => this._onAttachedToTarget(event2));
611
+ session.on("Target.detachedFromTarget", (event2) => this._onDetachedFromTarget(event2));
612
+ session.on("Runtime.consoleAPICalled", (event2) => {
613
+ const args = event2.args.map((o) => (0, import_crExecutionContext.createHandle)(worker.existingExecutionContext, o));
614
+ this._page.addConsoleMessage(worker, event2.type, args, (0, import_crProtocolHelper.toConsoleMessageLocation)(event2.stackTrace), void 0, event2.timestamp);
615
+ });
616
+ session.on("Runtime.exceptionThrown", (exception) => this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exception.exceptionDetails)));
617
+ }
618
+ _onDetachedFromTarget(event) {
619
+ const workerSession = this._workerSessions.get(event.sessionId);
620
+ if (workerSession) {
621
+ workerSession.dispose();
622
+ this._page.removeWorker(event.sessionId);
623
+ return;
624
+ }
625
+ const childFrameSession = this._crPage._sessions.get(event.targetId);
626
+ if (!childFrameSession)
627
+ return;
628
+ if (childFrameSession._swappedIn) {
629
+ childFrameSession.dispose();
630
+ return;
631
+ }
632
+ this._client.send("Page.enable").catch((e) => null).then(() => {
633
+ if (!childFrameSession._swappedIn)
634
+ this._page.frameManager.frameDetached(event.targetId);
635
+ childFrameSession.dispose();
636
+ });
637
+ }
638
+ _onWindowOpen(event) {
639
+ this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);
640
+ }
641
+ async _onConsoleAPI(event) {
642
+ if (event.executionContextId === 0) {
643
+ return;
644
+ }
645
+ const context = this._contextIdToContext.get(event.executionContextId);
646
+ if (!context)
647
+ return;
648
+ const values = event.args.map((arg) => (0, import_crExecutionContext.createHandle)(context, arg));
649
+ this._page.addConsoleMessage(null, event.type, values, (0, import_crProtocolHelper.toConsoleMessageLocation)(event.stackTrace), void 0, event.timestamp);
650
+ }
651
+ async _onBindingCalled(event) {
652
+ const pageOrError = await this._crPage._page.waitForInitializedOrError();
653
+ if (!(pageOrError instanceof Error)) {
654
+ const context = this._contextIdToContext.get(event.executionContextId);
655
+ if (context)
656
+ await this._page.onBindingCalled(event.payload, context);
657
+ }
658
+ }
659
+ _onDialog(event) {
660
+ if (!this._page.frameManager.frame(this._targetId))
661
+ return;
662
+ this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(
663
+ this._page,
664
+ event.type,
665
+ event.message,
666
+ async (accept, promptText) => {
667
+ if (this._isMainFrame() && event.type === "beforeunload" && !accept)
668
+ this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, "navigation cancelled by beforeunload dialog");
669
+ await this._client.send("Page.handleJavaScriptDialog", { accept, promptText });
670
+ },
671
+ event.defaultPrompt
672
+ ));
673
+ }
674
+ _handleException(exceptionDetails) {
675
+ this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exceptionDetails));
676
+ }
677
+ async _onTargetCrashed() {
678
+ this._client._markAsCrashed();
679
+ this._page._didCrash();
680
+ }
681
+ _onLogEntryAdded(event) {
682
+ const { level, text, args, source, url, lineNumber } = event.entry;
683
+ if (args)
684
+ args.map((arg) => (0, import_crProtocolHelper.releaseObject)(this._client, arg.objectId));
685
+ if (source !== "worker") {
686
+ const location = {
687
+ url: url || "",
688
+ lineNumber: lineNumber || 0,
689
+ columnNumber: 0
690
+ };
691
+ this._page.addConsoleMessage(null, level, [], location, text, event.entry.timestamp);
692
+ }
693
+ }
694
+ async _onFileChooserOpened(event) {
695
+ if (!event.backendNodeId)
696
+ return;
697
+ const frame = this._page.frameManager.frame(event.frameId);
698
+ if (!frame)
699
+ return;
700
+ let handle;
701
+ try {
702
+ const utilityContext = await frame._utilityContext();
703
+ handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);
704
+ } catch (e) {
705
+ return;
706
+ }
707
+ await this._page._onFileChooserOpened(handle);
708
+ }
709
+ _willBeginDownload() {
710
+ if (!this._crPage._page.initializedOrUndefined()) {
711
+ this._firstNonInitialNavigationCommittedReject(new Error("Starting new page download"));
712
+ }
713
+ }
714
+ _onScreencastFrame(payload) {
715
+ const buffer = Buffer.from(payload.data, "base64");
716
+ this._page.screencast.onScreencastFrame({
717
+ buffer,
718
+ frameSwapWallTime: payload.metadata.timestamp ? payload.metadata.timestamp * 1e3 : Date.now(),
719
+ viewportWidth: payload.metadata.deviceWidth,
720
+ viewportHeight: payload.metadata.deviceHeight
721
+ }, () => {
722
+ this._client._sendMayFail("Page.screencastFrameAck", { sessionId: payload.sessionId });
723
+ });
724
+ }
725
+ async _updateGeolocation(initial) {
726
+ const geolocation = this._crPage._browserContext._options.geolocation;
727
+ if (!initial || geolocation)
728
+ await this._client.send("Emulation.setGeolocationOverride", geolocation || {});
729
+ }
730
+ async _updateViewport(preserveWindowBoundaries) {
731
+ if (this._crPage._browserContext._browser.isClank())
732
+ return;
733
+ (0, import_assert.assert)(this._isMainFrame());
734
+ const options = this._crPage._browserContext._options;
735
+ const emulatedSize = this._page.emulatedSize();
736
+ if (!emulatedSize)
737
+ return;
738
+ const viewportSize = emulatedSize.viewport;
739
+ const screenSize = emulatedSize.screen;
740
+ const isLandscape = screenSize.width > screenSize.height;
741
+ const metricsOverride = {
742
+ mobile: !!options.isMobile,
743
+ width: viewportSize.width,
744
+ height: viewportSize.height,
745
+ screenWidth: screenSize.width,
746
+ screenHeight: screenSize.height,
747
+ deviceScaleFactor: options.deviceScaleFactor || 1,
748
+ screenOrientation: !!options.isMobile ? isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" } : { angle: 0, type: "landscapePrimary" },
749
+ dontSetVisibleSize: preserveWindowBoundaries
750
+ };
751
+ if (JSON.stringify(this._metricsOverride) === JSON.stringify(metricsOverride))
752
+ return;
753
+ const promises = [];
754
+ if (!preserveWindowBoundaries && this._windowId) {
755
+ let insets = { width: 0, height: 0 };
756
+ if (this._crPage._browserContext._browser.options.headful) {
757
+ insets = { width: 24, height: 88 };
758
+ if (process.platform === "win32")
759
+ insets = { width: 16, height: 88 };
760
+ else if (process.platform === "linux")
761
+ insets = { width: 8, height: 85 };
762
+ else if (process.platform === "darwin")
763
+ insets = { width: 2, height: 80 };
764
+ if (this._crPage._browserContext.isPersistentContext()) {
765
+ insets.height += 46;
766
+ }
767
+ }
768
+ promises.push(this.setWindowBounds({
769
+ width: viewportSize.width + insets.width,
770
+ height: viewportSize.height + insets.height
771
+ }));
772
+ }
773
+ promises.push(this._client.send("Emulation.setDeviceMetricsOverride", metricsOverride));
774
+ await Promise.all(promises);
775
+ this._metricsOverride = metricsOverride;
776
+ }
777
+ async windowBounds() {
778
+ const { bounds } = await this._client.send("Browser.getWindowBounds", {
779
+ windowId: this._windowId
780
+ });
781
+ return bounds;
782
+ }
783
+ async setWindowBounds(bounds) {
784
+ return await this._client.send("Browser.setWindowBounds", {
785
+ windowId: this._windowId,
786
+ bounds
787
+ });
788
+ }
789
+ async _updateEmulateMedia() {
790
+ const emulatedMedia = this._page.emulatedMedia();
791
+ const media = emulatedMedia.media === "no-override" ? "" : emulatedMedia.media;
792
+ const colorScheme = emulatedMedia.colorScheme === "no-override" ? "" : emulatedMedia.colorScheme;
793
+ const reducedMotion = emulatedMedia.reducedMotion === "no-override" ? "" : emulatedMedia.reducedMotion;
794
+ const forcedColors = emulatedMedia.forcedColors === "no-override" ? "" : emulatedMedia.forcedColors;
795
+ const contrast = emulatedMedia.contrast === "no-override" ? "" : emulatedMedia.contrast;
796
+ const features = [
797
+ { name: "prefers-color-scheme", value: colorScheme },
798
+ { name: "prefers-reduced-motion", value: reducedMotion },
799
+ { name: "forced-colors", value: forcedColors },
800
+ { name: "prefers-contrast", value: contrast }
801
+ ];
802
+ await this._client.send("Emulation.setEmulatedMedia", { media, features });
803
+ }
804
+ async _updateUserAgent() {
805
+ const options = this._crPage._browserContext._options;
806
+ const { navigatorPlatform, userAgentMetadata } = (0, import_browserContext.calculateUserAgentEmulation)(options);
807
+ await this._client.send("Emulation.setUserAgentOverride", {
808
+ userAgent: options.userAgent || "",
809
+ acceptLanguage: options.locale,
810
+ platform: navigatorPlatform,
811
+ userAgentMetadata
812
+ });
813
+ }
814
+ async _setDefaultFontFamilies(session) {
815
+ const fontFamilies = import_defaultFontFamilies.platformToFontFamilies[this._crPage._browserContext._browser._platform()];
816
+ await session.send("Page.setFontFamilies", fontFamilies);
817
+ }
818
+ async _updateFileChooserInterception(initial) {
819
+ const enabled = this._page.fileChooserIntercepted();
820
+ if (initial && !enabled)
821
+ return;
822
+ await this._client.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => {
823
+ });
824
+ }
825
+ async _evaluateOnNewDocument(initScript, world, runImmediately) {
826
+ const worldName = world === "utility" ? this._crPage.utilityWorldName : void 0;
827
+ const { identifier } = await this._client.send("Page.addScriptToEvaluateOnNewDocument", { source: initScript.source, worldName, runImmediately });
828
+ this._initScriptIds.set(initScript, identifier);
829
+ }
830
+ async _removeEvaluatesOnNewDocument(initScripts) {
831
+ const ids = [];
832
+ for (const script of initScripts) {
833
+ const id = this._initScriptIds.get(script);
834
+ if (id)
835
+ ids.push(id);
836
+ this._initScriptIds.delete(script);
837
+ }
838
+ await Promise.all(ids.map((identifier) => this._client.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => {
839
+ })));
840
+ }
841
+ async exposePlaywrightBinding() {
842
+ await this._client.send("Runtime.addBinding", { name: import_page.PageBinding.kBindingName });
843
+ }
844
+ async _getContentFrame(handle) {
845
+ const nodeInfo = await this._client.send("DOM.describeNode", {
846
+ objectId: handle._objectId
847
+ });
848
+ if (!nodeInfo || typeof nodeInfo.node.frameId !== "string")
849
+ return null;
850
+ return this._page.frameManager.frame(nodeInfo.node.frameId);
851
+ }
852
+ async _getOwnerFrame(handle) {
853
+ const documentElement = await handle.evaluateHandle((node) => {
854
+ const doc = node;
855
+ if (doc.documentElement && doc.documentElement.ownerDocument === doc)
856
+ return doc.documentElement;
857
+ return node.ownerDocument ? node.ownerDocument.documentElement : null;
858
+ });
859
+ if (!documentElement)
860
+ return null;
861
+ if (!documentElement._objectId)
862
+ return null;
863
+ const nodeInfo = await this._client.send("DOM.describeNode", {
864
+ objectId: documentElement._objectId
865
+ });
866
+ const frameId = nodeInfo && typeof nodeInfo.node.frameId === "string" ? nodeInfo.node.frameId : null;
867
+ documentElement.dispose();
868
+ return frameId;
869
+ }
870
+ async _getBoundingBox(handle) {
871
+ const result = await this._client._sendMayFail("DOM.getBoxModel", {
872
+ objectId: handle._objectId
873
+ });
874
+ if (!result)
875
+ return null;
876
+ const quad = result.model.border;
877
+ const x = Math.min(quad[0], quad[2], quad[4], quad[6]);
878
+ const y = Math.min(quad[1], quad[3], quad[5], quad[7]);
879
+ const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;
880
+ const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;
881
+ const position = await this._framePosition();
882
+ if (!position)
883
+ return null;
884
+ return { x: x + position.x, y: y + position.y, width, height };
885
+ }
886
+ async _framePosition() {
887
+ const frame = this._page.frameManager.frame(this._targetId);
888
+ if (!frame)
889
+ return null;
890
+ if (frame === this._page.mainFrame())
891
+ return { x: 0, y: 0 };
892
+ const element = await frame.frameElement();
893
+ const box = await element.boundingBox();
894
+ return box;
895
+ }
896
+ async _scrollRectIntoViewIfNeeded(handle, rect) {
897
+ return await this._client.send("DOM.scrollIntoViewIfNeeded", {
898
+ objectId: handle._objectId,
899
+ rect
900
+ }).then(() => "done").catch((e) => {
901
+ if (e instanceof Error && e.message.includes("Node does not have a layout object"))
902
+ return "error:notvisible";
903
+ if (e instanceof Error && e.message.includes("Node is detached from document"))
904
+ return "error:notconnected";
905
+ throw e;
906
+ });
907
+ }
908
+ async _getContentQuads(handle) {
909
+ const result = await this._client._sendMayFail("DOM.getContentQuads", {
910
+ objectId: handle._objectId
911
+ });
912
+ if (!result)
913
+ return null;
914
+ const position = await this._framePosition();
915
+ if (!position)
916
+ return null;
917
+ return result.quads.map((quad) => [
918
+ { x: quad[0] + position.x, y: quad[1] + position.y },
919
+ { x: quad[2] + position.x, y: quad[3] + position.y },
920
+ { x: quad[4] + position.x, y: quad[5] + position.y },
921
+ { x: quad[6] + position.x, y: quad[7] + position.y }
922
+ ]);
923
+ }
924
+ async _adoptElementHandle(handle, to) {
925
+ const nodeInfo = await this._client.send("DOM.describeNode", {
926
+ objectId: handle._objectId
927
+ });
928
+ return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to);
929
+ }
930
+ async _adoptBackendNodeId(backendNodeId, to) {
931
+ const result = await this._client._sendMayFail("DOM.resolveNode", {
932
+ backendNodeId,
933
+ executionContextId: to.delegate._contextId
934
+ });
935
+ if (!result || result.object.subtype === "null")
936
+ throw new Error(dom.kUnableToAdoptErrorMessage);
937
+ return (0, import_crExecutionContext.createHandle)(to, result.object).asElement();
938
+ }
939
+ }
940
+ async function emulateLocale(session, locale) {
941
+ try {
942
+ await session.send("Emulation.setLocaleOverride", { locale });
943
+ } catch (exception) {
944
+ if (exception.message.includes("Another locale override is already in effect"))
945
+ return;
946
+ throw exception;
947
+ }
948
+ }
949
+ async function emulateTimezone(session, timezoneId) {
950
+ try {
951
+ await session.send("Emulation.setTimezoneOverride", { timezoneId });
952
+ } catch (exception) {
953
+ if (exception.message.includes("Timezone override is already in effect"))
954
+ return;
955
+ if (exception.message.includes("Invalid timezone"))
956
+ throw new Error(`Invalid timezone ID: ${timezoneId}`);
957
+ throw exception;
958
+ }
959
+ }
960
+ // Annotate the CommonJS export names for ESM import in node:
961
+ 0 && (module.exports = {
962
+ CRPage
963
+ });