patchright-bun-core 1.58.0 → 1.58.2

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 (358) hide show
  1. package/README.md +2 -2
  2. package/ThirdPartyNotices.txt +4075 -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 +79 -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/browserServerImpl.js +120 -120
  27. package/lib/cli/driver.js +97 -97
  28. package/lib/cli/program.js +589 -589
  29. package/lib/cli/programWithTestStub.js +74 -74
  30. package/lib/client/android.js +361 -361
  31. package/lib/client/api.js +137 -137
  32. package/lib/client/artifact.js +79 -79
  33. package/lib/client/browser.js +161 -161
  34. package/lib/client/browserContext.js +582 -582
  35. package/lib/client/browserType.js +185 -185
  36. package/lib/client/cdpSession.js +51 -51
  37. package/lib/client/channelOwner.js +194 -194
  38. package/lib/client/clientHelper.js +64 -64
  39. package/lib/client/clientInstrumentation.js +55 -55
  40. package/lib/client/clientStackTrace.js +69 -69
  41. package/lib/client/clock.js +68 -68
  42. package/lib/client/connection.js +318 -318
  43. package/lib/client/consoleMessage.js +58 -58
  44. package/lib/client/coverage.js +44 -44
  45. package/lib/client/dialog.js +56 -56
  46. package/lib/client/download.js +62 -62
  47. package/lib/client/electron.js +138 -138
  48. package/lib/client/elementHandle.js +284 -284
  49. package/lib/client/errors.js +77 -77
  50. package/lib/client/eventEmitter.js +314 -314
  51. package/lib/client/events.js +103 -103
  52. package/lib/client/fetch.js +368 -368
  53. package/lib/client/fileChooser.js +46 -46
  54. package/lib/client/fileUtils.js +34 -34
  55. package/lib/client/frame.js +409 -409
  56. package/lib/client/harRouter.js +87 -87
  57. package/lib/client/input.js +84 -84
  58. package/lib/client/jsHandle.js +109 -109
  59. package/lib/client/jsonPipe.js +39 -39
  60. package/lib/client/localUtils.js +60 -60
  61. package/lib/client/locator.js +369 -369
  62. package/lib/client/network.js +747 -747
  63. package/lib/client/page.js +745 -745
  64. package/lib/client/pageAgent.js +64 -64
  65. package/lib/client/platform.js +77 -77
  66. package/lib/client/playwright.js +71 -71
  67. package/lib/client/selectors.js +55 -55
  68. package/lib/client/stream.js +39 -39
  69. package/lib/client/timeoutSettings.js +79 -79
  70. package/lib/client/tracing.js +119 -119
  71. package/lib/client/types.js +28 -28
  72. package/lib/client/video.js +59 -59
  73. package/lib/client/waiter.js +142 -142
  74. package/lib/client/webError.js +39 -39
  75. package/lib/client/webSocket.js +93 -93
  76. package/lib/client/worker.js +85 -85
  77. package/lib/client/writableStream.js +39 -39
  78. package/lib/generated/bindingsControllerSource.js +28 -28
  79. package/lib/generated/clockSource.js +28 -28
  80. package/lib/generated/injectedScriptSource.js +28 -28
  81. package/lib/generated/pollingRecorderSource.js +28 -28
  82. package/lib/generated/storageScriptSource.js +28 -28
  83. package/lib/generated/utilityScriptSource.js +28 -28
  84. package/lib/generated/webSocketMockSource.js +336 -336
  85. package/lib/inProcessFactory.js +60 -60
  86. package/lib/inprocess.js +3 -3
  87. package/lib/mcpBundle.js +84 -84
  88. package/lib/mcpBundleImpl/index.js +147 -147
  89. package/lib/outofprocess.js +76 -76
  90. package/lib/protocol/serializers.js +197 -197
  91. package/lib/protocol/validator.js +2969 -2969
  92. package/lib/protocol/validatorPrimitives.js +193 -193
  93. package/lib/remote/playwrightConnection.js +129 -129
  94. package/lib/remote/playwrightServer.js +334 -334
  95. package/lib/server/agent/actionRunner.js +335 -335
  96. package/lib/server/agent/actions.js +128 -128
  97. package/lib/server/agent/codegen.js +111 -111
  98. package/lib/server/agent/context.js +150 -150
  99. package/lib/server/agent/expectTools.js +156 -156
  100. package/lib/server/agent/pageAgent.js +204 -204
  101. package/lib/server/agent/performTools.js +262 -262
  102. package/lib/server/agent/tool.js +109 -109
  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 +549 -549
  107. package/lib/server/bidi/bidiChromium.js +149 -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 +383 -383
  114. package/lib/server/bidi/bidiOverCdp.js +102 -102
  115. package/lib/server/bidi/bidiPage.js +583 -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 +259 -259
  124. package/lib/server/browser.js +149 -149
  125. package/lib/server/browserContext.js +702 -702
  126. package/lib/server/browserType.js +336 -336
  127. package/lib/server/callLog.js +82 -82
  128. package/lib/server/chromium/chromium.js +397 -395
  129. package/lib/server/chromium/chromiumSwitches.js +104 -104
  130. package/lib/server/chromium/crBrowser.js +520 -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 +1001 -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 +136 -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 +57 -57
  154. package/lib/server/cookieStore.js +206 -206
  155. package/lib/server/debugController.js +191 -191
  156. package/lib/server/debugger.js +119 -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 +384 -384
  163. package/lib/server/dispatchers/browserDispatcher.js +118 -118
  164. package/lib/server/dispatchers/browserTypeDispatcher.js +64 -64
  165. package/lib/server/dispatchers/cdpSessionDispatcher.js +44 -44
  166. package/lib/server/dispatchers/debugControllerDispatcher.js +78 -78
  167. package/lib/server/dispatchers/dialogDispatcher.js +47 -47
  168. package/lib/server/dispatchers/dispatcher.js +364 -364
  169. package/lib/server/dispatchers/electronDispatcher.js +89 -89
  170. package/lib/server/dispatchers/elementHandlerDispatcher.js +181 -181
  171. package/lib/server/dispatchers/frameDispatcher.js +227 -227
  172. package/lib/server/dispatchers/jsHandleDispatcher.js +85 -85
  173. package/lib/server/dispatchers/jsonPipeDispatcher.js +58 -58
  174. package/lib/server/dispatchers/localUtilsDispatcher.js +149 -149
  175. package/lib/server/dispatchers/networkDispatchers.js +213 -213
  176. package/lib/server/dispatchers/pageAgentDispatcher.js +96 -96
  177. package/lib/server/dispatchers/pageDispatcher.js +393 -393
  178. package/lib/server/dispatchers/playwrightDispatcher.js +108 -108
  179. package/lib/server/dispatchers/streamDispatcher.js +67 -67
  180. package/lib/server/dispatchers/tracingDispatcher.js +68 -68
  181. package/lib/server/dispatchers/webSocketRouteDispatcher.js +165 -165
  182. package/lib/server/dispatchers/writableStreamDispatcher.js +79 -79
  183. package/lib/server/dom.js +815 -815
  184. package/lib/server/download.js +70 -70
  185. package/lib/server/electron/electron.js +273 -273
  186. package/lib/server/electron/loader.js +29 -29
  187. package/lib/server/errors.js +69 -69
  188. package/lib/server/fetch.js +621 -621
  189. package/lib/server/fileChooser.js +43 -43
  190. package/lib/server/fileUploadUtils.js +84 -84
  191. package/lib/server/firefox/ffBrowser.js +418 -418
  192. package/lib/server/firefox/ffConnection.js +142 -142
  193. package/lib/server/firefox/ffExecutionContext.js +150 -150
  194. package/lib/server/firefox/ffInput.js +159 -159
  195. package/lib/server/firefox/ffNetworkManager.js +256 -256
  196. package/lib/server/firefox/ffPage.js +497 -497
  197. package/lib/server/firefox/firefox.js +114 -114
  198. package/lib/server/firefox/protocol.d.js +16 -16
  199. package/lib/server/formData.js +147 -147
  200. package/lib/server/frameSelectors.js +160 -160
  201. package/lib/server/frames.js +1471 -1471
  202. package/lib/server/har/harRecorder.js +147 -147
  203. package/lib/server/har/harTracer.js +607 -607
  204. package/lib/server/harBackend.js +157 -157
  205. package/lib/server/helper.js +96 -96
  206. package/lib/server/index.js +58 -58
  207. package/lib/server/input.js +277 -277
  208. package/lib/server/instrumentation.js +72 -72
  209. package/lib/server/javascript.js +291 -291
  210. package/lib/server/launchApp.js +128 -128
  211. package/lib/server/localUtils.js +214 -214
  212. package/lib/server/macEditingCommands.js +143 -143
  213. package/lib/server/network.js +667 -667
  214. package/lib/server/page.js +830 -830
  215. package/lib/server/pipeTransport.js +89 -89
  216. package/lib/server/playwright.js +69 -69
  217. package/lib/server/progress.js +132 -132
  218. package/lib/server/protocolError.js +52 -52
  219. package/lib/server/recorder/chat.js +161 -161
  220. package/lib/server/recorder/recorderApp.js +366 -366
  221. package/lib/server/recorder/recorderRunner.js +138 -138
  222. package/lib/server/recorder/recorderSignalProcessor.js +83 -83
  223. package/lib/server/recorder/recorderUtils.js +157 -157
  224. package/lib/server/recorder/throttledFile.js +57 -57
  225. package/lib/server/recorder.js +499 -499
  226. package/lib/server/registry/browserFetcher.js +177 -177
  227. package/lib/server/registry/dependencies.js +371 -371
  228. package/lib/server/registry/index.js +1422 -1422
  229. package/lib/server/registry/nativeDeps.js +1280 -1280
  230. package/lib/server/registry/oopDownloadBrowserMain.js +127 -127
  231. package/lib/server/screencast.js +190 -190
  232. package/lib/server/screenshotter.js +333 -333
  233. package/lib/server/selectors.js +112 -112
  234. package/lib/server/socksClientCertificatesInterceptor.js +383 -383
  235. package/lib/server/socksInterceptor.js +95 -95
  236. package/lib/server/trace/recorder/snapshotter.js +147 -147
  237. package/lib/server/trace/recorder/snapshotterInjected.js +561 -561
  238. package/lib/server/trace/recorder/tracing.js +604 -604
  239. package/lib/server/trace/viewer/traceParser.js +72 -72
  240. package/lib/server/trace/viewer/traceViewer.js +245 -245
  241. package/lib/server/transport.js +254 -254
  242. package/lib/server/types.js +28 -28
  243. package/lib/server/usKeyboardLayout.js +145 -145
  244. package/lib/server/utils/ascii.js +44 -44
  245. package/lib/server/utils/comparators.js +139 -139
  246. package/lib/server/utils/crypto.js +216 -216
  247. package/lib/server/utils/debug.js +42 -42
  248. package/lib/server/utils/debugLogger.js +122 -122
  249. package/lib/server/utils/env.js +73 -73
  250. package/lib/server/utils/eventsHelper.js +39 -39
  251. package/lib/server/utils/expectUtils.js +123 -123
  252. package/lib/server/utils/fileUtils.js +191 -191
  253. package/lib/server/utils/happyEyeballs.js +207 -207
  254. package/lib/server/utils/hostPlatform.js +138 -123
  255. package/lib/server/utils/httpServer.js +203 -203
  256. package/lib/server/utils/imageUtils.js +141 -141
  257. package/lib/server/utils/image_tools/colorUtils.js +89 -89
  258. package/lib/server/utils/image_tools/compare.js +109 -109
  259. package/lib/server/utils/image_tools/imageChannel.js +78 -78
  260. package/lib/server/utils/image_tools/stats.js +102 -102
  261. package/lib/server/utils/linuxUtils.js +71 -71
  262. package/lib/server/utils/network.js +242 -242
  263. package/lib/server/utils/nodePlatform.js +154 -154
  264. package/lib/server/utils/pipeTransport.js +84 -84
  265. package/lib/server/utils/processLauncher.js +241 -241
  266. package/lib/server/utils/profiler.js +65 -65
  267. package/lib/server/utils/socksProxy.js +511 -511
  268. package/lib/server/utils/spawnAsync.js +41 -41
  269. package/lib/server/utils/task.js +51 -51
  270. package/lib/server/utils/userAgent.js +98 -98
  271. package/lib/server/utils/wsServer.js +121 -121
  272. package/lib/server/utils/zipFile.js +74 -74
  273. package/lib/server/utils/zones.js +57 -57
  274. package/lib/server/videoRecorder.js +124 -124
  275. package/lib/server/webkit/protocol.d.js +16 -16
  276. package/lib/server/webkit/webkit.js +108 -108
  277. package/lib/server/webkit/wkBrowser.js +335 -335
  278. package/lib/server/webkit/wkConnection.js +144 -144
  279. package/lib/server/webkit/wkExecutionContext.js +154 -154
  280. package/lib/server/webkit/wkInput.js +181 -181
  281. package/lib/server/webkit/wkInterceptableRequest.js +197 -197
  282. package/lib/server/webkit/wkPage.js +1159 -1158
  283. package/lib/server/webkit/wkProvisionalPage.js +83 -83
  284. package/lib/server/webkit/wkWorkers.js +105 -105
  285. package/lib/third_party/pixelmatch.js +255 -255
  286. package/lib/utils/isomorphic/ariaSnapshot.js +455 -455
  287. package/lib/utils/isomorphic/assert.js +31 -31
  288. package/lib/utils/isomorphic/colors.js +72 -72
  289. package/lib/utils/isomorphic/cssParser.js +245 -245
  290. package/lib/utils/isomorphic/cssTokenizer.js +1051 -1051
  291. package/lib/utils/isomorphic/headers.js +53 -53
  292. package/lib/utils/isomorphic/locatorGenerators.js +689 -689
  293. package/lib/utils/isomorphic/locatorParser.js +176 -176
  294. package/lib/utils/isomorphic/locatorUtils.js +81 -81
  295. package/lib/utils/isomorphic/lruCache.js +51 -51
  296. package/lib/utils/isomorphic/manualPromise.js +114 -114
  297. package/lib/utils/isomorphic/mimeType.js +459 -459
  298. package/lib/utils/isomorphic/multimap.js +80 -80
  299. package/lib/utils/isomorphic/protocolFormatter.js +81 -81
  300. package/lib/utils/isomorphic/protocolMetainfo.js +330 -330
  301. package/lib/utils/isomorphic/rtti.js +43 -43
  302. package/lib/utils/isomorphic/selectorParser.js +386 -386
  303. package/lib/utils/isomorphic/semaphore.js +54 -54
  304. package/lib/utils/isomorphic/stackTrace.js +158 -158
  305. package/lib/utils/isomorphic/stringUtils.js +204 -204
  306. package/lib/utils/isomorphic/time.js +49 -49
  307. package/lib/utils/isomorphic/timeoutRunner.js +66 -66
  308. package/lib/utils/isomorphic/trace/entries.js +16 -16
  309. package/lib/utils/isomorphic/trace/snapshotRenderer.js +499 -499
  310. package/lib/utils/isomorphic/trace/snapshotServer.js +120 -120
  311. package/lib/utils/isomorphic/trace/snapshotStorage.js +89 -89
  312. package/lib/utils/isomorphic/trace/traceLoader.js +131 -131
  313. package/lib/utils/isomorphic/trace/traceModel.js +365 -365
  314. package/lib/utils/isomorphic/trace/traceModernizer.js +400 -400
  315. package/lib/utils/isomorphic/trace/versions/traceV3.js +16 -16
  316. package/lib/utils/isomorphic/trace/versions/traceV4.js +16 -16
  317. package/lib/utils/isomorphic/trace/versions/traceV5.js +16 -16
  318. package/lib/utils/isomorphic/trace/versions/traceV6.js +16 -16
  319. package/lib/utils/isomorphic/trace/versions/traceV7.js +16 -16
  320. package/lib/utils/isomorphic/trace/versions/traceV8.js +16 -16
  321. package/lib/utils/isomorphic/traceUtils.js +58 -58
  322. package/lib/utils/isomorphic/types.js +16 -16
  323. package/lib/utils/isomorphic/urlMatch.js +190 -190
  324. package/lib/utils/isomorphic/utilityScriptSerializers.js +251 -251
  325. package/lib/utils/isomorphic/yaml.js +84 -84
  326. package/lib/utils.js +111 -111
  327. package/lib/utilsBundle.js +109 -109
  328. package/lib/utilsBundleImpl/index.js +218 -218
  329. package/lib/utilsBundleImpl/xdg-open +1066 -1066
  330. package/lib/vite/htmlReport/index.html +84 -84
  331. package/lib/vite/recorder/assets/codeMirrorModule-DYBRYzYX.css +1 -1
  332. package/lib/vite/recorder/assets/codeMirrorModule-DadYNm1I.js +32 -32
  333. package/lib/vite/recorder/assets/index-BSjZa4pk.css +1 -1
  334. package/lib/vite/recorder/assets/index-BhTWtUlo.js +193 -193
  335. package/lib/vite/recorder/index.html +29 -29
  336. package/lib/vite/recorder/playwright-logo.svg +9 -9
  337. package/lib/vite/traceViewer/assets/codeMirrorModule-a5XoALAZ.js +32 -32
  338. package/lib/vite/traceViewer/assets/defaultSettingsView-CJSZINFr.js +266 -266
  339. package/lib/vite/traceViewer/assets/xtermModule-CsJ4vdCR.js +9 -9
  340. package/lib/vite/traceViewer/codeMirrorModule.DYBRYzYX.css +1 -1
  341. package/lib/vite/traceViewer/defaultSettingsView.7ch9cixO.css +1 -1
  342. package/lib/vite/traceViewer/{index.Bk2uYQRV.js → index.BDwrLSGN.js} +2 -2
  343. package/lib/vite/traceViewer/index.BVu7tZDe.css +1 -1
  344. package/lib/vite/traceViewer/index.html +43 -43
  345. package/lib/vite/traceViewer/manifest.webmanifest +16 -16
  346. package/lib/vite/traceViewer/playwright-logo.svg +9 -9
  347. package/lib/vite/traceViewer/snapshot.html +21 -21
  348. package/lib/vite/traceViewer/sw.bundle.js +5 -5
  349. package/lib/vite/traceViewer/uiMode.Btcz36p_.css +1 -1
  350. package/lib/vite/traceViewer/uiMode.CQJ9SCIQ.js +5 -5
  351. package/lib/vite/traceViewer/uiMode.html +17 -17
  352. package/lib/vite/traceViewer/xtermModule.DYP7pi_n.css +32 -32
  353. package/lib/zipBundle.js +34 -34
  354. package/lib/zipBundleImpl.js +5 -5
  355. package/package.json +1 -1
  356. package/types/protocol.d.ts +23824 -23824
  357. package/types/structs.d.ts +45 -45
  358. package/types/types.d.ts +22843 -22843
@@ -1,830 +1,830 @@
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 page_exports = {};
30
- __export(page_exports, {
31
- InitScript: () => InitScript,
32
- Page: () => Page,
33
- PageBinding: () => PageBinding,
34
- Worker: () => Worker,
35
- WorkerEvent: () => WorkerEvent
36
- });
37
- module.exports = __toCommonJS(page_exports);
38
- var import_browserContext = require("./browserContext");
39
- var import_console = require("./console");
40
- var import_errors = require("./errors");
41
- var import_fileChooser = require("./fileChooser");
42
- var frames = __toESM(require("./frames"));
43
- var import_helper = require("./helper");
44
- var input = __toESM(require("./input"));
45
- var import_instrumentation = require("./instrumentation");
46
- var js = __toESM(require("./javascript"));
47
- var import_screenshotter = require("./screenshotter");
48
- var import_utils = require("../utils");
49
- var import_utils2 = require("../utils");
50
- var import_comparators = require("./utils/comparators");
51
- var import_debugLogger = require("./utils/debugLogger");
52
- var import_selectorParser = require("../utils/isomorphic/selectorParser");
53
- var import_manualPromise = require("../utils/isomorphic/manualPromise");
54
- var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");
55
- var import_callLog = require("./callLog");
56
- var rawBindingsControllerSource = __toESM(require("../generated/bindingsControllerSource"));
57
- var import_screencast = require("./screencast");
58
- const PageEvent = {
59
- Close: "close",
60
- Crash: "crash",
61
- Download: "download",
62
- EmulatedSizeChanged: "emulatedsizechanged",
63
- FileChooser: "filechooser",
64
- FrameAttached: "frameattached",
65
- FrameDetached: "framedetached",
66
- InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument",
67
- LocatorHandlerTriggered: "locatorhandlertriggered",
68
- ScreencastFrame: "screencastframe",
69
- Video: "video",
70
- WebSocket: "websocket",
71
- Worker: "worker"
72
- };
73
- class Page extends import_instrumentation.SdkObject {
74
- constructor(delegate, browserContext) {
75
- super(browserContext, "page");
76
- this._closedState = "open";
77
- this._closedPromise = new import_manualPromise.ManualPromise();
78
- this._initializedPromise = new import_manualPromise.ManualPromise();
79
- this._consoleMessages = [];
80
- this._pageErrors = [];
81
- this._crashed = false;
82
- this.openScope = new import_utils.LongStandingScope();
83
- this._emulatedMedia = {};
84
- this._fileChooserInterceptedBy = /* @__PURE__ */ new Set();
85
- this._pageBindings = /* @__PURE__ */ new Map();
86
- this.initScripts = [];
87
- this._workers = /* @__PURE__ */ new Map();
88
- this.requestInterceptors = [];
89
- this.video = null;
90
- this._locatorHandlers = /* @__PURE__ */ new Map();
91
- this._lastLocatorHandlerUid = 0;
92
- this._locatorHandlerRunningCounter = 0;
93
- this._networkRequests = [];
94
- this.attribution.page = this;
95
- this.delegate = delegate;
96
- this.browserContext = browserContext;
97
- this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);
98
- this.mouse = new input.Mouse(delegate.rawMouse, this);
99
- this.touchscreen = new input.Touchscreen(delegate.rawTouchscreen, this);
100
- this.screenshotter = new import_screenshotter.Screenshotter(this);
101
- this.frameManager = new frames.FrameManager(this);
102
- this.screencast = new import_screencast.Screencast(this);
103
- if (delegate.pdf)
104
- this.pdf = delegate.pdf.bind(delegate);
105
- this.coverage = delegate.coverage ? delegate.coverage() : null;
106
- this.isStorageStatePage = browserContext.isCreatingStorageStatePage();
107
- }
108
- static {
109
- this.Events = PageEvent;
110
- }
111
- async reportAsNew(opener, error) {
112
- if (opener) {
113
- const openerPageOrError = await opener.waitForInitializedOrError();
114
- if (openerPageOrError instanceof Page && !openerPageOrError.isClosed())
115
- this._opener = openerPageOrError;
116
- }
117
- this._markInitialized(error);
118
- }
119
- _markInitialized(error = void 0) {
120
- if (error) {
121
- if (this.browserContext.isClosingOrClosed())
122
- return;
123
- this.frameManager.createDummyMainFrameIfNeeded();
124
- }
125
- this._initialized = error || this;
126
- this.emitOnContext(import_browserContext.BrowserContext.Events.Page, this);
127
- for (const pageError of this._pageErrors)
128
- this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);
129
- for (const message of this._consoleMessages)
130
- this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);
131
- if (this.isClosed())
132
- this.emit(Page.Events.Close);
133
- else
134
- this.instrumentation.onPageOpen(this);
135
- this._initializedPromise.resolve(this._initialized);
136
- }
137
- initializedOrUndefined() {
138
- return this._initialized ? this : void 0;
139
- }
140
- waitForInitializedOrError() {
141
- return this._initializedPromise;
142
- }
143
- emitOnContext(event, ...args) {
144
- if (this.isStorageStatePage)
145
- return;
146
- this.browserContext.emit(event, ...args);
147
- }
148
- async resetForReuse(progress) {
149
- await this.mainFrame().gotoImpl(progress, "about:blank", {});
150
- this._emulatedSize = void 0;
151
- this._emulatedMedia = {};
152
- this._extraHTTPHeaders = void 0;
153
- await Promise.all([
154
- this.delegate.updateEmulatedViewportSize(),
155
- this.delegate.updateEmulateMedia(),
156
- this.delegate.updateExtraHTTPHeaders()
157
- ]);
158
- await this.delegate.resetForReuse(progress);
159
- }
160
- _didClose() {
161
- this.frameManager.dispose();
162
- this.screencast.stopFrameThrottler();
163
- (0, import_utils.assert)(this._closedState !== "closed", "Page closed twice");
164
- this._closedState = "closed";
165
- this.emit(Page.Events.Close);
166
- this._closedPromise.resolve();
167
- this.instrumentation.onPageClose(this);
168
- this.openScope.close(new import_errors.TargetClosedError(this.closeReason()));
169
- }
170
- _didCrash() {
171
- this.frameManager.dispose();
172
- this.screencast.stopFrameThrottler();
173
- this.emit(Page.Events.Crash);
174
- this._crashed = true;
175
- this.instrumentation.onPageClose(this);
176
- this.openScope.close(new Error("Page crashed"));
177
- }
178
- async _onFileChooserOpened(handle) {
179
- let multiple;
180
- try {
181
- multiple = await handle.evaluate((element) => !!element.multiple);
182
- } catch (e) {
183
- return;
184
- }
185
- if (!this.listenerCount(Page.Events.FileChooser)) {
186
- handle.dispose();
187
- return;
188
- }
189
- const fileChooser = new import_fileChooser.FileChooser(this, handle, multiple);
190
- this.emit(Page.Events.FileChooser, fileChooser);
191
- }
192
- opener() {
193
- return this._opener;
194
- }
195
- mainFrame() {
196
- return this.frameManager.mainFrame();
197
- }
198
- frames() {
199
- return this.frameManager.frames();
200
- }
201
- async exposeBinding(progress, name, needsHandle, playwrightBinding) {
202
- if (this._pageBindings.has(name))
203
- throw new Error(`Function "${name}" has been already registered`);
204
- if (this.browserContext._pageBindings.has(name))
205
- throw new Error(`Function "${name}" has been already registered in the browser context`);
206
- await progress.race(this.browserContext.exposePlaywrightBindingIfNeeded());
207
- const binding = new PageBinding(name, playwrightBinding, needsHandle);
208
- this._pageBindings.set(name, binding);
209
- try {
210
- await progress.race(this.delegate.addInitScript(binding.initScript));
211
- await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));
212
- return binding;
213
- } catch (error) {
214
- this._pageBindings.delete(name);
215
- throw error;
216
- }
217
- }
218
- async removeExposedBindings(bindings) {
219
- bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);
220
- for (const binding of bindings)
221
- this._pageBindings.delete(binding.name);
222
- await this.delegate.removeInitScripts(bindings.map((binding) => binding.initScript));
223
- const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };
224
- `).join("");
225
- await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");
226
- }
227
- async setExtraHTTPHeaders(progress, headers) {
228
- const oldHeaders = this._extraHTTPHeaders;
229
- try {
230
- this._extraHTTPHeaders = headers;
231
- await progress.race(this.delegate.updateExtraHTTPHeaders());
232
- } catch (error) {
233
- this._extraHTTPHeaders = oldHeaders;
234
- this.delegate.updateExtraHTTPHeaders().catch(() => {
235
- });
236
- throw error;
237
- }
238
- }
239
- extraHTTPHeaders() {
240
- return this._extraHTTPHeaders;
241
- }
242
- addNetworkRequest(request) {
243
- this._networkRequests.push(request);
244
- ensureArrayLimit(this._networkRequests, 100);
245
- }
246
- networkRequests() {
247
- return this._networkRequests;
248
- }
249
- async onBindingCalled(payload, context) {
250
- if (this._closedState === "closed")
251
- return;
252
- await PageBinding.dispatch(this, payload, context);
253
- }
254
- addConsoleMessage(worker, type, args, location, text) {
255
- const message = new import_console.ConsoleMessage(this, worker, type, text, args, location);
256
- const intercepted = this.frameManager.interceptConsoleMessage(message);
257
- if (intercepted) {
258
- args.forEach((arg) => arg.dispose());
259
- return;
260
- }
261
- this._consoleMessages.push(message);
262
- ensureArrayLimit(this._consoleMessages, 200);
263
- if (this._initialized)
264
- this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);
265
- }
266
- consoleMessages() {
267
- return this._consoleMessages;
268
- }
269
- addPageError(pageError) {
270
- this._pageErrors.push(pageError);
271
- ensureArrayLimit(this._pageErrors, 200);
272
- if (this._initialized)
273
- this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);
274
- }
275
- pageErrors() {
276
- return this._pageErrors;
277
- }
278
- async reload(progress, options) {
279
- return this.mainFrame().raceNavigationAction(progress, async () => {
280
- const [response] = await Promise.all([
281
- // Reload must be a new document, and should not be confused with a stray pushState.
282
- this.mainFrame()._waitForNavigation(progress, true, options),
283
- progress.race(this.delegate.reload())
284
- ]);
285
- return response;
286
- });
287
- }
288
- async goBack(progress, options) {
289
- return this.mainFrame().raceNavigationAction(progress, async () => {
290
- let error;
291
- const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
292
- error = e;
293
- return null;
294
- });
295
- const result = await progress.race(this.delegate.goBack());
296
- if (!result) {
297
- waitPromise.catch(() => {
298
- });
299
- return null;
300
- }
301
- const response = await waitPromise;
302
- if (error)
303
- throw error;
304
- return response;
305
- });
306
- }
307
- async goForward(progress, options) {
308
- return this.mainFrame().raceNavigationAction(progress, async () => {
309
- let error;
310
- const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
311
- error = e;
312
- return null;
313
- });
314
- const result = await progress.race(this.delegate.goForward());
315
- if (!result) {
316
- waitPromise.catch(() => {
317
- });
318
- return null;
319
- }
320
- const response = await waitPromise;
321
- if (error)
322
- throw error;
323
- return response;
324
- });
325
- }
326
- requestGC() {
327
- return this.delegate.requestGC();
328
- }
329
- registerLocatorHandler(selector, noWaitAfter) {
330
- const uid = ++this._lastLocatorHandlerUid;
331
- this._locatorHandlers.set(uid, { selector, noWaitAfter });
332
- return uid;
333
- }
334
- resolveLocatorHandler(uid, remove) {
335
- const handler = this._locatorHandlers.get(uid);
336
- if (remove)
337
- this._locatorHandlers.delete(uid);
338
- if (handler) {
339
- handler.resolved?.resolve();
340
- handler.resolved = void 0;
341
- }
342
- }
343
- unregisterLocatorHandler(uid) {
344
- this._locatorHandlers.delete(uid);
345
- }
346
- async performActionPreChecks(progress) {
347
- await this._performWaitForNavigationCheck(progress);
348
- await this._performLocatorHandlersCheckpoint(progress);
349
- await this._performWaitForNavigationCheck(progress);
350
- }
351
- async _performWaitForNavigationCheck(progress) {
352
- if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK)
353
- return;
354
- const mainFrame = this.frameManager.mainFrame();
355
- if (!mainFrame || !mainFrame.pendingDocument())
356
- return;
357
- const url = mainFrame.pendingDocument()?.request?.url();
358
- const toUrl = url ? `" ${(0, import_utils.trimStringWithEllipsis)(url, 200)}"` : "";
359
- progress.log(` waiting for${toUrl} navigation to finish...`);
360
- await import_helper.helper.waitForEvent(progress, mainFrame, frames.Frame.Events.InternalNavigation, (e) => {
361
- if (!e.isPublic)
362
- return false;
363
- if (!e.error)
364
- progress.log(` navigated to "${(0, import_utils.trimStringWithEllipsis)(mainFrame.url(), 200)}"`);
365
- return true;
366
- }).promise;
367
- }
368
- async _performLocatorHandlersCheckpoint(progress) {
369
- if (this._locatorHandlerRunningCounter)
370
- return;
371
- for (const [uid, handler] of this._locatorHandlers) {
372
- if (!handler.resolved) {
373
- if (await this.mainFrame().isVisibleInternal(progress, handler.selector, { strict: true })) {
374
- handler.resolved = new import_manualPromise.ManualPromise();
375
- this.emit(Page.Events.LocatorHandlerTriggered, uid);
376
- }
377
- }
378
- if (handler.resolved) {
379
- ++this._locatorHandlerRunningCounter;
380
- progress.log(` found ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`);
381
- const promise = handler.resolved.then(async () => {
382
- if (!handler.noWaitAfter) {
383
- progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`);
384
- await this.mainFrame().waitForSelector(progress, handler.selector, false, { state: "hidden" });
385
- } else {
386
- progress.log(` locator handler has finished`);
387
- }
388
- });
389
- await progress.race(this.openScope.race(promise)).finally(() => --this._locatorHandlerRunningCounter);
390
- progress.log(` interception handler has finished, continuing`);
391
- }
392
- }
393
- }
394
- async emulateMedia(progress, options) {
395
- const oldEmulatedMedia = { ...this._emulatedMedia };
396
- if (options.media !== void 0)
397
- this._emulatedMedia.media = options.media;
398
- if (options.colorScheme !== void 0)
399
- this._emulatedMedia.colorScheme = options.colorScheme;
400
- if (options.reducedMotion !== void 0)
401
- this._emulatedMedia.reducedMotion = options.reducedMotion;
402
- if (options.forcedColors !== void 0)
403
- this._emulatedMedia.forcedColors = options.forcedColors;
404
- if (options.contrast !== void 0)
405
- this._emulatedMedia.contrast = options.contrast;
406
- try {
407
- await progress.race(this.delegate.updateEmulateMedia());
408
- } catch (error) {
409
- this._emulatedMedia = oldEmulatedMedia;
410
- this.delegate.updateEmulateMedia().catch(() => {
411
- });
412
- throw error;
413
- }
414
- }
415
- emulatedMedia() {
416
- const contextOptions = this.browserContext._options;
417
- return {
418
- media: this._emulatedMedia.media || "no-override",
419
- colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light",
420
- reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference",
421
- forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none",
422
- contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference"
423
- };
424
- }
425
- async setViewportSize(progress, viewportSize) {
426
- const oldEmulatedSize = this._emulatedSize;
427
- try {
428
- this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
429
- await progress.race(this.delegate.updateEmulatedViewportSize());
430
- } catch (error) {
431
- this._emulatedSize = oldEmulatedSize;
432
- this.delegate.updateEmulatedViewportSize().catch(() => {
433
- });
434
- throw error;
435
- }
436
- }
437
- setEmulatedSizeFromWindowOpen(emulatedSize) {
438
- this._setEmulatedSize(emulatedSize);
439
- }
440
- _setEmulatedSize(emulatedSize) {
441
- this._emulatedSize = emulatedSize;
442
- this.emit(Page.Events.EmulatedSizeChanged);
443
- }
444
- emulatedSize() {
445
- if (this._emulatedSize)
446
- return this._emulatedSize;
447
- const contextOptions = this.browserContext._options;
448
- return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0;
449
- }
450
- async bringToFront() {
451
- await this.delegate.bringToFront();
452
- }
453
- async addInitScript(progress, source) {
454
- const initScript = new InitScript(source);
455
- this.initScripts.push(initScript);
456
- try {
457
- await progress.race(this.delegate.addInitScript(initScript));
458
- } catch (error) {
459
- this.removeInitScripts([initScript]).catch(() => {
460
- });
461
- throw error;
462
- }
463
- return initScript;
464
- }
465
- async removeInitScripts(initScripts) {
466
- const set = new Set(initScripts);
467
- this.initScripts = this.initScripts.filter((script) => !set.has(script));
468
- await this.delegate.removeInitScripts(initScripts);
469
- }
470
- needsRequestInterception() {
471
- return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0;
472
- }
473
- async addRequestInterceptor(progress, handler, prepend) {
474
- if (prepend)
475
- this.requestInterceptors.unshift(handler);
476
- else
477
- this.requestInterceptors.push(handler);
478
- await this.delegate.updateRequestInterception();
479
- }
480
- async removeRequestInterceptor(handler) {
481
- const index = this.requestInterceptors.indexOf(handler);
482
- if (index === -1)
483
- return;
484
- this.requestInterceptors.splice(index, 1);
485
- await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler);
486
- await this.delegate.updateRequestInterception();
487
- }
488
- async expectScreenshot(progress, options) {
489
- const locator = options.locator;
490
- const rafrafScreenshot = locator ? async (timeout) => {
491
- return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});
492
- } : async (timeout) => {
493
- await this.performActionPreChecks(progress);
494
- await this.mainFrame().rafrafTimeout(progress, timeout);
495
- return await this.screenshotter.screenshotPage(progress, options || {});
496
- };
497
- const comparator = (0, import_comparators.getComparator)("image/png");
498
- if (!options.expected && options.isNot)
499
- return { errorMessage: '"not" matcher requires expected result' };
500
- try {
501
- const format = (0, import_screenshotter.validateScreenshotOptions)(options || {});
502
- if (format !== "png")
503
- throw new Error("Only PNG screenshots are supported");
504
- } catch (error) {
505
- return { errorMessage: error.message };
506
- }
507
- let intermediateResult;
508
- const areEqualScreenshots = (actual, expected, previous) => {
509
- const comparatorResult = actual && expected ? comparator(actual, expected, options) : void 0;
510
- if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot)
511
- return true;
512
- if (comparatorResult)
513
- intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous };
514
- return false;
515
- };
516
- try {
517
- let actual;
518
- let previous;
519
- const pollIntervals = [0, 100, 250, 500];
520
- progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeout ? ` with timeout ${options.timeout}ms` : ""}`);
521
- if (options.expected)
522
- progress.log(` verifying given screenshot expectation`);
523
- else
524
- progress.log(` generating new stable screenshot expectation`);
525
- let isFirstIteration = true;
526
- while (true) {
527
- if (this.isClosed())
528
- throw new Error("The page has closed");
529
- const screenshotTimeout = pollIntervals.shift() ?? 1e3;
530
- if (screenshotTimeout)
531
- progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
532
- previous = actual;
533
- actual = await rafrafScreenshot(screenshotTimeout).catch((e) => {
534
- if (this.mainFrame().isNonRetriableError(e))
535
- throw e;
536
- progress.log(`failed to take screenshot - ` + e.message);
537
- return void 0;
538
- });
539
- if (!actual)
540
- continue;
541
- const expectation = options.expected && isFirstIteration ? options.expected : previous;
542
- if (areEqualScreenshots(actual, expectation, previous))
543
- break;
544
- if (intermediateResult)
545
- progress.log(intermediateResult.errorMessage);
546
- isFirstIteration = false;
547
- }
548
- if (!isFirstIteration)
549
- progress.log(`captured a stable screenshot`);
550
- if (!options.expected)
551
- return { actual };
552
- if (isFirstIteration) {
553
- progress.log(`screenshot matched expectation`);
554
- return {};
555
- }
556
- if (areEqualScreenshots(actual, options.expected, void 0)) {
557
- progress.log(`screenshot matched expectation`);
558
- return {};
559
- }
560
- throw new Error(intermediateResult.errorMessage);
561
- } catch (e) {
562
- if (js.isJavaScriptErrorInEvaluate(e) || (0, import_selectorParser.isInvalidSelectorError)(e))
563
- throw e;
564
- let errorMessage = e.message;
565
- if (e instanceof import_errors.TimeoutError && intermediateResult?.previous)
566
- errorMessage = `Failed to take two consecutive stable screenshots.`;
567
- return {
568
- log: (0, import_callLog.compressCallLog)(e.message ? [...progress.metadata.log, e.message] : progress.metadata.log),
569
- ...intermediateResult,
570
- errorMessage,
571
- timedOut: e instanceof import_errors.TimeoutError
572
- };
573
- }
574
- }
575
- async screenshot(progress, options) {
576
- return await this.screenshotter.screenshotPage(progress, options);
577
- }
578
- async close(options = {}) {
579
- if (this._closedState === "closed")
580
- return;
581
- if (options.reason)
582
- this._closeReason = options.reason;
583
- const runBeforeUnload = !!options.runBeforeUnload;
584
- if (this._closedState !== "closing") {
585
- if (!runBeforeUnload)
586
- this._closedState = "closing";
587
- await this.delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));
588
- }
589
- if (!runBeforeUnload)
590
- await this._closedPromise;
591
- }
592
- isClosed() {
593
- return this._closedState === "closed";
594
- }
595
- hasCrashed() {
596
- return this._crashed;
597
- }
598
- isClosedOrClosingOrCrashed() {
599
- return this._closedState !== "open" || this._crashed;
600
- }
601
- addWorker(workerId, worker) {
602
- this._workers.set(workerId, worker);
603
- this.emit(Page.Events.Worker, worker);
604
- }
605
- removeWorker(workerId) {
606
- const worker = this._workers.get(workerId);
607
- if (!worker)
608
- return;
609
- worker.didClose();
610
- this._workers.delete(workerId);
611
- }
612
- clearWorkers() {
613
- for (const [workerId, worker] of this._workers) {
614
- worker.didClose();
615
- this._workers.delete(workerId);
616
- }
617
- }
618
- async setFileChooserInterceptedBy(enabled, by) {
619
- const wasIntercepted = this.fileChooserIntercepted();
620
- if (enabled)
621
- this._fileChooserInterceptedBy.add(by);
622
- else
623
- this._fileChooserInterceptedBy.delete(by);
624
- if (wasIntercepted !== this.fileChooserIntercepted())
625
- await this.delegate.updateFileChooserInterception();
626
- }
627
- fileChooserIntercepted() {
628
- return this._fileChooserInterceptedBy.size > 0;
629
- }
630
- frameNavigatedToNewDocument(frame) {
631
- this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);
632
- const origin = frame.origin();
633
- if (origin)
634
- this.browserContext.addVisitedOrigin(origin);
635
- }
636
- allInitScripts() {
637
- const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript);
638
- if (this.browserContext.bindingsInitScript)
639
- bindings.unshift(this.browserContext.bindingsInitScript);
640
- return [...bindings, ...this.browserContext.initScripts, ...this.initScripts];
641
- }
642
- getBinding(name) {
643
- return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name);
644
- }
645
- async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
646
- await Promise.all(this.frames().map(async (frame) => {
647
- try {
648
- await frame.nonStallingEvaluateInExistingContext(expression, world);
649
- } catch (e) {
650
- if (options.throwOnJSErrors && js.isJavaScriptErrorInEvaluate(e))
651
- throw e;
652
- }
653
- }));
654
- }
655
- async hideHighlight() {
656
- await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => {
657
- })));
658
- }
659
- async snapshotForAI(progress, options = {}) {
660
- const snapshot = await snapshotFrameForAI(progress, this.mainFrame(), options);
661
- return { full: snapshot.full.join("\n"), incremental: snapshot.incremental?.join("\n") };
662
- }
663
- }
664
- const WorkerEvent = {
665
- Close: "close"
666
- };
667
- class Worker extends import_instrumentation.SdkObject {
668
- constructor(parent, url) {
669
- super(parent, "worker");
670
- this._executionContextPromise = new import_manualPromise.ManualPromise();
671
- this._workerScriptLoaded = false;
672
- this.existingExecutionContext = null;
673
- this.openScope = new import_utils.LongStandingScope();
674
- this.url = url;
675
- }
676
- static {
677
- this.Events = WorkerEvent;
678
- }
679
- createExecutionContext(delegate) {
680
- this.existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");
681
- if (this._workerScriptLoaded)
682
- this._executionContextPromise.resolve(this.existingExecutionContext);
683
- return this.existingExecutionContext;
684
- }
685
- workerScriptLoaded() {
686
- this._workerScriptLoaded = true;
687
- if (this.existingExecutionContext)
688
- this._executionContextPromise.resolve(this.existingExecutionContext);
689
- }
690
- didClose() {
691
- if (this.existingExecutionContext)
692
- this.existingExecutionContext.contextDestroyed("Worker was closed");
693
- this.emit(Worker.Events.Close, this);
694
- this.openScope.close(new Error("Worker closed"));
695
- }
696
- async evaluateExpression(expression, isFunction, arg) {
697
- return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg);
698
- }
699
- async evaluateExpressionHandle(expression, isFunction, arg) {
700
- return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg);
701
- }
702
- }
703
- class PageBinding {
704
- static {
705
- this.kController = "__playwright__binding__controller__";
706
- }
707
- static {
708
- this.kBindingName = "__playwright__binding__";
709
- }
710
- static createInitScript() {
711
- return new InitScript(`
712
- (() => {
713
- const module = {};
714
- ${rawBindingsControllerSource.source}
715
- const property = '${PageBinding.kController}';
716
- if (!globalThis[property])
717
- globalThis[property] = new (module.exports.BindingsController())(globalThis, '${PageBinding.kBindingName}');
718
- })();
719
- `);
720
- }
721
- constructor(name, playwrightFunction, needsHandle) {
722
- this.name = name;
723
- this.playwrightFunction = playwrightFunction;
724
- this.initScript = new InitScript(`globalThis['${PageBinding.kController}'].addBinding(${JSON.stringify(name)}, ${needsHandle})`);
725
- this.needsHandle = needsHandle;
726
- this.cleanupScript = `globalThis['${PageBinding.kController}'].removeBinding(${JSON.stringify(name)})`;
727
- }
728
- static async dispatch(page, payload, context) {
729
- const { name, seq, serializedArgs } = JSON.parse(payload);
730
- try {
731
- (0, import_utils.assert)(context.world);
732
- const binding = page.getBinding(name);
733
- if (!binding)
734
- throw new Error(`Function "${name}" is not exposed`);
735
- let result;
736
- if (binding.needsHandle) {
737
- const handle = await context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].takeBindingHandle(arg)`, { isFunction: true }, { name, seq }).catch((e) => null);
738
- result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, handle);
739
- } else {
740
- if (!Array.isArray(serializedArgs))
741
- throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);
742
- const args = serializedArgs.map((a) => (0, import_utilityScriptSerializers.parseEvaluationResultValue)(a));
743
- result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args);
744
- }
745
- context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result }).catch((e) => import_debugLogger.debugLogger.log("error", e));
746
- } catch (error) {
747
- context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => import_debugLogger.debugLogger.log("error", e));
748
- }
749
- }
750
- }
751
- class InitScript {
752
- constructor(source) {
753
- this.source = `(() => {
754
- ${source}
755
- })();`;
756
- }
757
- }
758
- async function snapshotFrameForAI(progress, frame, options = {}) {
759
- const snapshot = await frame.retryWithProgressAndTimeouts(progress, [1e3, 2e3, 4e3, 8e3], async (continuePolling) => {
760
- try {
761
- const context = await progress.race(frame._utilityContext());
762
- const injectedScript = await progress.race(context.injectedScript());
763
- const snapshotOrRetry = await progress.race(injectedScript.evaluate((injected, options2) => {
764
- const node = injected.document.body;
765
- if (!node)
766
- return true;
767
- return injected.incrementalAriaSnapshot(node, { mode: "ai", ...options2 });
768
- }, { refPrefix: frame.seq ? "f" + frame.seq : "", track: options.track, doNotRenderActive: options.doNotRenderActive }));
769
- if (snapshotOrRetry === true)
770
- return continuePolling;
771
- return snapshotOrRetry;
772
- } catch (e) {
773
- if (frame.isNonRetriableError(e))
774
- throw e;
775
- return continuePolling;
776
- }
777
- });
778
- const childSnapshotPromises = snapshot.iframeRefs.map((ref) => snapshotFrameRefForAI(progress, frame, ref, options));
779
- const childSnapshots = await Promise.all(childSnapshotPromises);
780
- const full = [];
781
- let incremental;
782
- if (snapshot.incremental !== void 0) {
783
- incremental = snapshot.incremental.split("\n");
784
- for (let i = 0; i < snapshot.iframeRefs.length; i++) {
785
- const childSnapshot = childSnapshots[i];
786
- if (childSnapshot.incremental)
787
- incremental.push(...childSnapshot.incremental);
788
- else if (childSnapshot.full.length)
789
- incremental.push("- <changed> iframe [ref=" + snapshot.iframeRefs[i] + "]:", ...childSnapshot.full.map((l) => " " + l));
790
- }
791
- }
792
- for (const line of snapshot.full.split("\n")) {
793
- const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=([^\]]*)\]/);
794
- if (!match) {
795
- full.push(line);
796
- continue;
797
- }
798
- const leadingSpace = match[1];
799
- const ref = match[2];
800
- const childSnapshot = childSnapshots[snapshot.iframeRefs.indexOf(ref)] ?? { full: [] };
801
- full.push(childSnapshot.full.length ? line + ":" : line);
802
- full.push(...childSnapshot.full.map((l) => leadingSpace + " " + l));
803
- }
804
- return { full, incremental };
805
- }
806
- async function snapshotFrameRefForAI(progress, parentFrame, frameRef, options) {
807
- const frameSelector = `aria-ref=${frameRef} >> internal:control=enter-frame`;
808
- const frameBodySelector = `${frameSelector} >> body`;
809
- const child = await progress.race(parentFrame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true }));
810
- if (!child)
811
- return { full: [] };
812
- try {
813
- return await snapshotFrameForAI(progress, child.frame, options);
814
- } catch {
815
- return { full: [] };
816
- }
817
- }
818
- function ensureArrayLimit(array, limit) {
819
- if (array.length > limit)
820
- return array.splice(0, limit / 10);
821
- return [];
822
- }
823
- // Annotate the CommonJS export names for ESM import in node:
824
- 0 && (module.exports = {
825
- InitScript,
826
- Page,
827
- PageBinding,
828
- Worker,
829
- WorkerEvent
830
- });
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 page_exports = {};
30
+ __export(page_exports, {
31
+ InitScript: () => InitScript,
32
+ Page: () => Page,
33
+ PageBinding: () => PageBinding,
34
+ Worker: () => Worker,
35
+ WorkerEvent: () => WorkerEvent
36
+ });
37
+ module.exports = __toCommonJS(page_exports);
38
+ var import_browserContext = require("./browserContext");
39
+ var import_console = require("./console");
40
+ var import_errors = require("./errors");
41
+ var import_fileChooser = require("./fileChooser");
42
+ var frames = __toESM(require("./frames"));
43
+ var import_helper = require("./helper");
44
+ var input = __toESM(require("./input"));
45
+ var import_instrumentation = require("./instrumentation");
46
+ var js = __toESM(require("./javascript"));
47
+ var import_screenshotter = require("./screenshotter");
48
+ var import_utils = require("../utils");
49
+ var import_utils2 = require("../utils");
50
+ var import_comparators = require("./utils/comparators");
51
+ var import_debugLogger = require("./utils/debugLogger");
52
+ var import_selectorParser = require("../utils/isomorphic/selectorParser");
53
+ var import_manualPromise = require("../utils/isomorphic/manualPromise");
54
+ var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");
55
+ var import_callLog = require("./callLog");
56
+ var rawBindingsControllerSource = __toESM(require("../generated/bindingsControllerSource"));
57
+ var import_screencast = require("./screencast");
58
+ const PageEvent = {
59
+ Close: "close",
60
+ Crash: "crash",
61
+ Download: "download",
62
+ EmulatedSizeChanged: "emulatedsizechanged",
63
+ FileChooser: "filechooser",
64
+ FrameAttached: "frameattached",
65
+ FrameDetached: "framedetached",
66
+ InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument",
67
+ LocatorHandlerTriggered: "locatorhandlertriggered",
68
+ ScreencastFrame: "screencastframe",
69
+ Video: "video",
70
+ WebSocket: "websocket",
71
+ Worker: "worker"
72
+ };
73
+ class Page extends import_instrumentation.SdkObject {
74
+ constructor(delegate, browserContext) {
75
+ super(browserContext, "page");
76
+ this._closedState = "open";
77
+ this._closedPromise = new import_manualPromise.ManualPromise();
78
+ this._initializedPromise = new import_manualPromise.ManualPromise();
79
+ this._consoleMessages = [];
80
+ this._pageErrors = [];
81
+ this._crashed = false;
82
+ this.openScope = new import_utils.LongStandingScope();
83
+ this._emulatedMedia = {};
84
+ this._fileChooserInterceptedBy = /* @__PURE__ */ new Set();
85
+ this._pageBindings = /* @__PURE__ */ new Map();
86
+ this.initScripts = [];
87
+ this._workers = /* @__PURE__ */ new Map();
88
+ this.requestInterceptors = [];
89
+ this.video = null;
90
+ this._locatorHandlers = /* @__PURE__ */ new Map();
91
+ this._lastLocatorHandlerUid = 0;
92
+ this._locatorHandlerRunningCounter = 0;
93
+ this._networkRequests = [];
94
+ this.attribution.page = this;
95
+ this.delegate = delegate;
96
+ this.browserContext = browserContext;
97
+ this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);
98
+ this.mouse = new input.Mouse(delegate.rawMouse, this);
99
+ this.touchscreen = new input.Touchscreen(delegate.rawTouchscreen, this);
100
+ this.screenshotter = new import_screenshotter.Screenshotter(this);
101
+ this.frameManager = new frames.FrameManager(this);
102
+ this.screencast = new import_screencast.Screencast(this);
103
+ if (delegate.pdf)
104
+ this.pdf = delegate.pdf.bind(delegate);
105
+ this.coverage = delegate.coverage ? delegate.coverage() : null;
106
+ this.isStorageStatePage = browserContext.isCreatingStorageStatePage();
107
+ }
108
+ static {
109
+ this.Events = PageEvent;
110
+ }
111
+ async reportAsNew(opener, error) {
112
+ if (opener) {
113
+ const openerPageOrError = await opener.waitForInitializedOrError();
114
+ if (openerPageOrError instanceof Page && !openerPageOrError.isClosed())
115
+ this._opener = openerPageOrError;
116
+ }
117
+ this._markInitialized(error);
118
+ }
119
+ _markInitialized(error = void 0) {
120
+ if (error) {
121
+ if (this.browserContext.isClosingOrClosed())
122
+ return;
123
+ this.frameManager.createDummyMainFrameIfNeeded();
124
+ }
125
+ this._initialized = error || this;
126
+ this.emitOnContext(import_browserContext.BrowserContext.Events.Page, this);
127
+ for (const pageError of this._pageErrors)
128
+ this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);
129
+ for (const message of this._consoleMessages)
130
+ this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);
131
+ if (this.isClosed())
132
+ this.emit(Page.Events.Close);
133
+ else
134
+ this.instrumentation.onPageOpen(this);
135
+ this._initializedPromise.resolve(this._initialized);
136
+ }
137
+ initializedOrUndefined() {
138
+ return this._initialized ? this : void 0;
139
+ }
140
+ waitForInitializedOrError() {
141
+ return this._initializedPromise;
142
+ }
143
+ emitOnContext(event, ...args) {
144
+ if (this.isStorageStatePage)
145
+ return;
146
+ this.browserContext.emit(event, ...args);
147
+ }
148
+ async resetForReuse(progress) {
149
+ await this.mainFrame().gotoImpl(progress, "about:blank", {});
150
+ this._emulatedSize = void 0;
151
+ this._emulatedMedia = {};
152
+ this._extraHTTPHeaders = void 0;
153
+ await Promise.all([
154
+ this.delegate.updateEmulatedViewportSize(),
155
+ this.delegate.updateEmulateMedia(),
156
+ this.delegate.updateExtraHTTPHeaders()
157
+ ]);
158
+ await this.delegate.resetForReuse(progress);
159
+ }
160
+ _didClose() {
161
+ this.frameManager.dispose();
162
+ this.screencast.stopFrameThrottler();
163
+ (0, import_utils.assert)(this._closedState !== "closed", "Page closed twice");
164
+ this._closedState = "closed";
165
+ this.emit(Page.Events.Close);
166
+ this._closedPromise.resolve();
167
+ this.instrumentation.onPageClose(this);
168
+ this.openScope.close(new import_errors.TargetClosedError(this.closeReason()));
169
+ }
170
+ _didCrash() {
171
+ this.frameManager.dispose();
172
+ this.screencast.stopFrameThrottler();
173
+ this.emit(Page.Events.Crash);
174
+ this._crashed = true;
175
+ this.instrumentation.onPageClose(this);
176
+ this.openScope.close(new Error("Page crashed"));
177
+ }
178
+ async _onFileChooserOpened(handle) {
179
+ let multiple;
180
+ try {
181
+ multiple = await handle.evaluate((element) => !!element.multiple);
182
+ } catch (e) {
183
+ return;
184
+ }
185
+ if (!this.listenerCount(Page.Events.FileChooser)) {
186
+ handle.dispose();
187
+ return;
188
+ }
189
+ const fileChooser = new import_fileChooser.FileChooser(this, handle, multiple);
190
+ this.emit(Page.Events.FileChooser, fileChooser);
191
+ }
192
+ opener() {
193
+ return this._opener;
194
+ }
195
+ mainFrame() {
196
+ return this.frameManager.mainFrame();
197
+ }
198
+ frames() {
199
+ return this.frameManager.frames();
200
+ }
201
+ async exposeBinding(progress, name, needsHandle, playwrightBinding) {
202
+ if (this._pageBindings.has(name))
203
+ throw new Error(`Function "${name}" has been already registered`);
204
+ if (this.browserContext._pageBindings.has(name))
205
+ throw new Error(`Function "${name}" has been already registered in the browser context`);
206
+ await progress.race(this.browserContext.exposePlaywrightBindingIfNeeded());
207
+ const binding = new PageBinding(name, playwrightBinding, needsHandle);
208
+ this._pageBindings.set(name, binding);
209
+ try {
210
+ await progress.race(this.delegate.addInitScript(binding.initScript));
211
+ await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));
212
+ return binding;
213
+ } catch (error) {
214
+ this._pageBindings.delete(name);
215
+ throw error;
216
+ }
217
+ }
218
+ async removeExposedBindings(bindings) {
219
+ bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);
220
+ for (const binding of bindings)
221
+ this._pageBindings.delete(binding.name);
222
+ await this.delegate.removeInitScripts(bindings.map((binding) => binding.initScript));
223
+ const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };
224
+ `).join("");
225
+ await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");
226
+ }
227
+ async setExtraHTTPHeaders(progress, headers) {
228
+ const oldHeaders = this._extraHTTPHeaders;
229
+ try {
230
+ this._extraHTTPHeaders = headers;
231
+ await progress.race(this.delegate.updateExtraHTTPHeaders());
232
+ } catch (error) {
233
+ this._extraHTTPHeaders = oldHeaders;
234
+ this.delegate.updateExtraHTTPHeaders().catch(() => {
235
+ });
236
+ throw error;
237
+ }
238
+ }
239
+ extraHTTPHeaders() {
240
+ return this._extraHTTPHeaders;
241
+ }
242
+ addNetworkRequest(request) {
243
+ this._networkRequests.push(request);
244
+ ensureArrayLimit(this._networkRequests, 100);
245
+ }
246
+ networkRequests() {
247
+ return this._networkRequests;
248
+ }
249
+ async onBindingCalled(payload, context) {
250
+ if (this._closedState === "closed")
251
+ return;
252
+ await PageBinding.dispatch(this, payload, context);
253
+ }
254
+ addConsoleMessage(worker, type, args, location, text) {
255
+ const message = new import_console.ConsoleMessage(this, worker, type, text, args, location);
256
+ const intercepted = this.frameManager.interceptConsoleMessage(message);
257
+ if (intercepted) {
258
+ args.forEach((arg) => arg.dispose());
259
+ return;
260
+ }
261
+ this._consoleMessages.push(message);
262
+ ensureArrayLimit(this._consoleMessages, 200);
263
+ if (this._initialized)
264
+ this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);
265
+ }
266
+ consoleMessages() {
267
+ return this._consoleMessages;
268
+ }
269
+ addPageError(pageError) {
270
+ this._pageErrors.push(pageError);
271
+ ensureArrayLimit(this._pageErrors, 200);
272
+ if (this._initialized)
273
+ this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);
274
+ }
275
+ pageErrors() {
276
+ return this._pageErrors;
277
+ }
278
+ async reload(progress, options) {
279
+ return this.mainFrame().raceNavigationAction(progress, async () => {
280
+ const [response] = await Promise.all([
281
+ // Reload must be a new document, and should not be confused with a stray pushState.
282
+ this.mainFrame()._waitForNavigation(progress, true, options),
283
+ progress.race(this.delegate.reload())
284
+ ]);
285
+ return response;
286
+ });
287
+ }
288
+ async goBack(progress, options) {
289
+ return this.mainFrame().raceNavigationAction(progress, async () => {
290
+ let error;
291
+ const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
292
+ error = e;
293
+ return null;
294
+ });
295
+ const result = await progress.race(this.delegate.goBack());
296
+ if (!result) {
297
+ waitPromise.catch(() => {
298
+ });
299
+ return null;
300
+ }
301
+ const response = await waitPromise;
302
+ if (error)
303
+ throw error;
304
+ return response;
305
+ });
306
+ }
307
+ async goForward(progress, options) {
308
+ return this.mainFrame().raceNavigationAction(progress, async () => {
309
+ let error;
310
+ const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
311
+ error = e;
312
+ return null;
313
+ });
314
+ const result = await progress.race(this.delegate.goForward());
315
+ if (!result) {
316
+ waitPromise.catch(() => {
317
+ });
318
+ return null;
319
+ }
320
+ const response = await waitPromise;
321
+ if (error)
322
+ throw error;
323
+ return response;
324
+ });
325
+ }
326
+ requestGC() {
327
+ return this.delegate.requestGC();
328
+ }
329
+ registerLocatorHandler(selector, noWaitAfter) {
330
+ const uid = ++this._lastLocatorHandlerUid;
331
+ this._locatorHandlers.set(uid, { selector, noWaitAfter });
332
+ return uid;
333
+ }
334
+ resolveLocatorHandler(uid, remove) {
335
+ const handler = this._locatorHandlers.get(uid);
336
+ if (remove)
337
+ this._locatorHandlers.delete(uid);
338
+ if (handler) {
339
+ handler.resolved?.resolve();
340
+ handler.resolved = void 0;
341
+ }
342
+ }
343
+ unregisterLocatorHandler(uid) {
344
+ this._locatorHandlers.delete(uid);
345
+ }
346
+ async performActionPreChecks(progress) {
347
+ await this._performWaitForNavigationCheck(progress);
348
+ await this._performLocatorHandlersCheckpoint(progress);
349
+ await this._performWaitForNavigationCheck(progress);
350
+ }
351
+ async _performWaitForNavigationCheck(progress) {
352
+ if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK)
353
+ return;
354
+ const mainFrame = this.frameManager.mainFrame();
355
+ if (!mainFrame || !mainFrame.pendingDocument())
356
+ return;
357
+ const url = mainFrame.pendingDocument()?.request?.url();
358
+ const toUrl = url ? `" ${(0, import_utils.trimStringWithEllipsis)(url, 200)}"` : "";
359
+ progress.log(` waiting for${toUrl} navigation to finish...`);
360
+ await import_helper.helper.waitForEvent(progress, mainFrame, frames.Frame.Events.InternalNavigation, (e) => {
361
+ if (!e.isPublic)
362
+ return false;
363
+ if (!e.error)
364
+ progress.log(` navigated to "${(0, import_utils.trimStringWithEllipsis)(mainFrame.url(), 200)}"`);
365
+ return true;
366
+ }).promise;
367
+ }
368
+ async _performLocatorHandlersCheckpoint(progress) {
369
+ if (this._locatorHandlerRunningCounter)
370
+ return;
371
+ for (const [uid, handler] of this._locatorHandlers) {
372
+ if (!handler.resolved) {
373
+ if (await this.mainFrame().isVisibleInternal(progress, handler.selector, { strict: true })) {
374
+ handler.resolved = new import_manualPromise.ManualPromise();
375
+ this.emit(Page.Events.LocatorHandlerTriggered, uid);
376
+ }
377
+ }
378
+ if (handler.resolved) {
379
+ ++this._locatorHandlerRunningCounter;
380
+ progress.log(` found ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`);
381
+ const promise = handler.resolved.then(async () => {
382
+ if (!handler.noWaitAfter) {
383
+ progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`);
384
+ await this.mainFrame().waitForSelector(progress, handler.selector, false, { state: "hidden" });
385
+ } else {
386
+ progress.log(` locator handler has finished`);
387
+ }
388
+ });
389
+ await progress.race(this.openScope.race(promise)).finally(() => --this._locatorHandlerRunningCounter);
390
+ progress.log(` interception handler has finished, continuing`);
391
+ }
392
+ }
393
+ }
394
+ async emulateMedia(progress, options) {
395
+ const oldEmulatedMedia = { ...this._emulatedMedia };
396
+ if (options.media !== void 0)
397
+ this._emulatedMedia.media = options.media;
398
+ if (options.colorScheme !== void 0)
399
+ this._emulatedMedia.colorScheme = options.colorScheme;
400
+ if (options.reducedMotion !== void 0)
401
+ this._emulatedMedia.reducedMotion = options.reducedMotion;
402
+ if (options.forcedColors !== void 0)
403
+ this._emulatedMedia.forcedColors = options.forcedColors;
404
+ if (options.contrast !== void 0)
405
+ this._emulatedMedia.contrast = options.contrast;
406
+ try {
407
+ await progress.race(this.delegate.updateEmulateMedia());
408
+ } catch (error) {
409
+ this._emulatedMedia = oldEmulatedMedia;
410
+ this.delegate.updateEmulateMedia().catch(() => {
411
+ });
412
+ throw error;
413
+ }
414
+ }
415
+ emulatedMedia() {
416
+ const contextOptions = this.browserContext._options;
417
+ return {
418
+ media: this._emulatedMedia.media || "no-override",
419
+ colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light",
420
+ reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference",
421
+ forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none",
422
+ contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference"
423
+ };
424
+ }
425
+ async setViewportSize(progress, viewportSize) {
426
+ const oldEmulatedSize = this._emulatedSize;
427
+ try {
428
+ this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
429
+ await progress.race(this.delegate.updateEmulatedViewportSize());
430
+ } catch (error) {
431
+ this._emulatedSize = oldEmulatedSize;
432
+ this.delegate.updateEmulatedViewportSize().catch(() => {
433
+ });
434
+ throw error;
435
+ }
436
+ }
437
+ setEmulatedSizeFromWindowOpen(emulatedSize) {
438
+ this._setEmulatedSize(emulatedSize);
439
+ }
440
+ _setEmulatedSize(emulatedSize) {
441
+ this._emulatedSize = emulatedSize;
442
+ this.emit(Page.Events.EmulatedSizeChanged);
443
+ }
444
+ emulatedSize() {
445
+ if (this._emulatedSize)
446
+ return this._emulatedSize;
447
+ const contextOptions = this.browserContext._options;
448
+ return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0;
449
+ }
450
+ async bringToFront() {
451
+ await this.delegate.bringToFront();
452
+ }
453
+ async addInitScript(progress, source) {
454
+ const initScript = new InitScript(source);
455
+ this.initScripts.push(initScript);
456
+ try {
457
+ await progress.race(this.delegate.addInitScript(initScript));
458
+ } catch (error) {
459
+ this.removeInitScripts([initScript]).catch(() => {
460
+ });
461
+ throw error;
462
+ }
463
+ return initScript;
464
+ }
465
+ async removeInitScripts(initScripts) {
466
+ const set = new Set(initScripts);
467
+ this.initScripts = this.initScripts.filter((script) => !set.has(script));
468
+ await this.delegate.removeInitScripts(initScripts);
469
+ }
470
+ needsRequestInterception() {
471
+ return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0;
472
+ }
473
+ async addRequestInterceptor(progress, handler, prepend) {
474
+ if (prepend)
475
+ this.requestInterceptors.unshift(handler);
476
+ else
477
+ this.requestInterceptors.push(handler);
478
+ await this.delegate.updateRequestInterception();
479
+ }
480
+ async removeRequestInterceptor(handler) {
481
+ const index = this.requestInterceptors.indexOf(handler);
482
+ if (index === -1)
483
+ return;
484
+ this.requestInterceptors.splice(index, 1);
485
+ await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler);
486
+ await this.delegate.updateRequestInterception();
487
+ }
488
+ async expectScreenshot(progress, options) {
489
+ const locator = options.locator;
490
+ const rafrafScreenshot = locator ? async (timeout) => {
491
+ return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});
492
+ } : async (timeout) => {
493
+ await this.performActionPreChecks(progress);
494
+ await this.mainFrame().rafrafTimeout(progress, timeout);
495
+ return await this.screenshotter.screenshotPage(progress, options || {});
496
+ };
497
+ const comparator = (0, import_comparators.getComparator)("image/png");
498
+ if (!options.expected && options.isNot)
499
+ return { errorMessage: '"not" matcher requires expected result' };
500
+ try {
501
+ const format = (0, import_screenshotter.validateScreenshotOptions)(options || {});
502
+ if (format !== "png")
503
+ throw new Error("Only PNG screenshots are supported");
504
+ } catch (error) {
505
+ return { errorMessage: error.message };
506
+ }
507
+ let intermediateResult;
508
+ const areEqualScreenshots = (actual, expected, previous) => {
509
+ const comparatorResult = actual && expected ? comparator(actual, expected, options) : void 0;
510
+ if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot)
511
+ return true;
512
+ if (comparatorResult)
513
+ intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous };
514
+ return false;
515
+ };
516
+ try {
517
+ let actual;
518
+ let previous;
519
+ const pollIntervals = [0, 100, 250, 500];
520
+ progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeout ? ` with timeout ${options.timeout}ms` : ""}`);
521
+ if (options.expected)
522
+ progress.log(` verifying given screenshot expectation`);
523
+ else
524
+ progress.log(` generating new stable screenshot expectation`);
525
+ let isFirstIteration = true;
526
+ while (true) {
527
+ if (this.isClosed())
528
+ throw new Error("The page has closed");
529
+ const screenshotTimeout = pollIntervals.shift() ?? 1e3;
530
+ if (screenshotTimeout)
531
+ progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
532
+ previous = actual;
533
+ actual = await rafrafScreenshot(screenshotTimeout).catch((e) => {
534
+ if (this.mainFrame().isNonRetriableError(e))
535
+ throw e;
536
+ progress.log(`failed to take screenshot - ` + e.message);
537
+ return void 0;
538
+ });
539
+ if (!actual)
540
+ continue;
541
+ const expectation = options.expected && isFirstIteration ? options.expected : previous;
542
+ if (areEqualScreenshots(actual, expectation, previous))
543
+ break;
544
+ if (intermediateResult)
545
+ progress.log(intermediateResult.errorMessage);
546
+ isFirstIteration = false;
547
+ }
548
+ if (!isFirstIteration)
549
+ progress.log(`captured a stable screenshot`);
550
+ if (!options.expected)
551
+ return { actual };
552
+ if (isFirstIteration) {
553
+ progress.log(`screenshot matched expectation`);
554
+ return {};
555
+ }
556
+ if (areEqualScreenshots(actual, options.expected, void 0)) {
557
+ progress.log(`screenshot matched expectation`);
558
+ return {};
559
+ }
560
+ throw new Error(intermediateResult.errorMessage);
561
+ } catch (e) {
562
+ if (js.isJavaScriptErrorInEvaluate(e) || (0, import_selectorParser.isInvalidSelectorError)(e))
563
+ throw e;
564
+ let errorMessage = e.message;
565
+ if (e instanceof import_errors.TimeoutError && intermediateResult?.previous)
566
+ errorMessage = `Failed to take two consecutive stable screenshots.`;
567
+ return {
568
+ log: (0, import_callLog.compressCallLog)(e.message ? [...progress.metadata.log, e.message] : progress.metadata.log),
569
+ ...intermediateResult,
570
+ errorMessage,
571
+ timedOut: e instanceof import_errors.TimeoutError
572
+ };
573
+ }
574
+ }
575
+ async screenshot(progress, options) {
576
+ return await this.screenshotter.screenshotPage(progress, options);
577
+ }
578
+ async close(options = {}) {
579
+ if (this._closedState === "closed")
580
+ return;
581
+ if (options.reason)
582
+ this._closeReason = options.reason;
583
+ const runBeforeUnload = !!options.runBeforeUnload;
584
+ if (this._closedState !== "closing") {
585
+ if (!runBeforeUnload)
586
+ this._closedState = "closing";
587
+ await this.delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));
588
+ }
589
+ if (!runBeforeUnload)
590
+ await this._closedPromise;
591
+ }
592
+ isClosed() {
593
+ return this._closedState === "closed";
594
+ }
595
+ hasCrashed() {
596
+ return this._crashed;
597
+ }
598
+ isClosedOrClosingOrCrashed() {
599
+ return this._closedState !== "open" || this._crashed;
600
+ }
601
+ addWorker(workerId, worker) {
602
+ this._workers.set(workerId, worker);
603
+ this.emit(Page.Events.Worker, worker);
604
+ }
605
+ removeWorker(workerId) {
606
+ const worker = this._workers.get(workerId);
607
+ if (!worker)
608
+ return;
609
+ worker.didClose();
610
+ this._workers.delete(workerId);
611
+ }
612
+ clearWorkers() {
613
+ for (const [workerId, worker] of this._workers) {
614
+ worker.didClose();
615
+ this._workers.delete(workerId);
616
+ }
617
+ }
618
+ async setFileChooserInterceptedBy(enabled, by) {
619
+ const wasIntercepted = this.fileChooserIntercepted();
620
+ if (enabled)
621
+ this._fileChooserInterceptedBy.add(by);
622
+ else
623
+ this._fileChooserInterceptedBy.delete(by);
624
+ if (wasIntercepted !== this.fileChooserIntercepted())
625
+ await this.delegate.updateFileChooserInterception();
626
+ }
627
+ fileChooserIntercepted() {
628
+ return this._fileChooserInterceptedBy.size > 0;
629
+ }
630
+ frameNavigatedToNewDocument(frame) {
631
+ this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);
632
+ const origin = frame.origin();
633
+ if (origin)
634
+ this.browserContext.addVisitedOrigin(origin);
635
+ }
636
+ allInitScripts() {
637
+ const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript);
638
+ if (this.browserContext.bindingsInitScript)
639
+ bindings.unshift(this.browserContext.bindingsInitScript);
640
+ return [...bindings, ...this.browserContext.initScripts, ...this.initScripts];
641
+ }
642
+ getBinding(name) {
643
+ return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name);
644
+ }
645
+ async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
646
+ await Promise.all(this.frames().map(async (frame) => {
647
+ try {
648
+ await frame.nonStallingEvaluateInExistingContext(expression, world);
649
+ } catch (e) {
650
+ if (options.throwOnJSErrors && js.isJavaScriptErrorInEvaluate(e))
651
+ throw e;
652
+ }
653
+ }));
654
+ }
655
+ async hideHighlight() {
656
+ await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => {
657
+ })));
658
+ }
659
+ async snapshotForAI(progress, options = {}) {
660
+ const snapshot = await snapshotFrameForAI(progress, this.mainFrame(), options);
661
+ return { full: snapshot.full.join("\n"), incremental: snapshot.incremental?.join("\n") };
662
+ }
663
+ }
664
+ const WorkerEvent = {
665
+ Close: "close"
666
+ };
667
+ class Worker extends import_instrumentation.SdkObject {
668
+ constructor(parent, url) {
669
+ super(parent, "worker");
670
+ this._executionContextPromise = new import_manualPromise.ManualPromise();
671
+ this._workerScriptLoaded = false;
672
+ this.existingExecutionContext = null;
673
+ this.openScope = new import_utils.LongStandingScope();
674
+ this.url = url;
675
+ }
676
+ static {
677
+ this.Events = WorkerEvent;
678
+ }
679
+ createExecutionContext(delegate) {
680
+ this.existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");
681
+ if (this._workerScriptLoaded)
682
+ this._executionContextPromise.resolve(this.existingExecutionContext);
683
+ return this.existingExecutionContext;
684
+ }
685
+ workerScriptLoaded() {
686
+ this._workerScriptLoaded = true;
687
+ if (this.existingExecutionContext)
688
+ this._executionContextPromise.resolve(this.existingExecutionContext);
689
+ }
690
+ didClose() {
691
+ if (this.existingExecutionContext)
692
+ this.existingExecutionContext.contextDestroyed("Worker was closed");
693
+ this.emit(Worker.Events.Close, this);
694
+ this.openScope.close(new Error("Worker closed"));
695
+ }
696
+ async evaluateExpression(expression, isFunction, arg) {
697
+ return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg);
698
+ }
699
+ async evaluateExpressionHandle(expression, isFunction, arg) {
700
+ return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg);
701
+ }
702
+ }
703
+ class PageBinding {
704
+ static {
705
+ this.kController = "__playwright__binding__controller__";
706
+ }
707
+ static {
708
+ this.kBindingName = "__playwright__binding__";
709
+ }
710
+ static createInitScript() {
711
+ return new InitScript(`
712
+ (() => {
713
+ const module = {};
714
+ ${rawBindingsControllerSource.source}
715
+ const property = '${PageBinding.kController}';
716
+ if (!globalThis[property])
717
+ globalThis[property] = new (module.exports.BindingsController())(globalThis, '${PageBinding.kBindingName}');
718
+ })();
719
+ `);
720
+ }
721
+ constructor(name, playwrightFunction, needsHandle) {
722
+ this.name = name;
723
+ this.playwrightFunction = playwrightFunction;
724
+ this.initScript = new InitScript(`globalThis['${PageBinding.kController}'].addBinding(${JSON.stringify(name)}, ${needsHandle})`);
725
+ this.needsHandle = needsHandle;
726
+ this.cleanupScript = `globalThis['${PageBinding.kController}'].removeBinding(${JSON.stringify(name)})`;
727
+ }
728
+ static async dispatch(page, payload, context) {
729
+ const { name, seq, serializedArgs } = JSON.parse(payload);
730
+ try {
731
+ (0, import_utils.assert)(context.world);
732
+ const binding = page.getBinding(name);
733
+ if (!binding)
734
+ throw new Error(`Function "${name}" is not exposed`);
735
+ let result;
736
+ if (binding.needsHandle) {
737
+ const handle = await context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].takeBindingHandle(arg)`, { isFunction: true }, { name, seq }).catch((e) => null);
738
+ result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, handle);
739
+ } else {
740
+ if (!Array.isArray(serializedArgs))
741
+ throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);
742
+ const args = serializedArgs.map((a) => (0, import_utilityScriptSerializers.parseEvaluationResultValue)(a));
743
+ result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args);
744
+ }
745
+ context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result }).catch((e) => import_debugLogger.debugLogger.log("error", e));
746
+ } catch (error) {
747
+ context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => import_debugLogger.debugLogger.log("error", e));
748
+ }
749
+ }
750
+ }
751
+ class InitScript {
752
+ constructor(source) {
753
+ this.source = `(() => {
754
+ ${source}
755
+ })();`;
756
+ }
757
+ }
758
+ async function snapshotFrameForAI(progress, frame, options = {}) {
759
+ const snapshot = await frame.retryWithProgressAndTimeouts(progress, [1e3, 2e3, 4e3, 8e3], async (continuePolling) => {
760
+ try {
761
+ const context = await progress.race(frame._utilityContext());
762
+ const injectedScript = await progress.race(context.injectedScript());
763
+ const snapshotOrRetry = await progress.race(injectedScript.evaluate((injected, options2) => {
764
+ const node = injected.document.body;
765
+ if (!node)
766
+ return true;
767
+ return injected.incrementalAriaSnapshot(node, { mode: "ai", ...options2 });
768
+ }, { refPrefix: frame.seq ? "f" + frame.seq : "", track: options.track, doNotRenderActive: options.doNotRenderActive }));
769
+ if (snapshotOrRetry === true)
770
+ return continuePolling;
771
+ return snapshotOrRetry;
772
+ } catch (e) {
773
+ if (frame.isNonRetriableError(e))
774
+ throw e;
775
+ return continuePolling;
776
+ }
777
+ });
778
+ const childSnapshotPromises = snapshot.iframeRefs.map((ref) => snapshotFrameRefForAI(progress, frame, ref, options));
779
+ const childSnapshots = await Promise.all(childSnapshotPromises);
780
+ const full = [];
781
+ let incremental;
782
+ if (snapshot.incremental !== void 0) {
783
+ incremental = snapshot.incremental.split("\n");
784
+ for (let i = 0; i < snapshot.iframeRefs.length; i++) {
785
+ const childSnapshot = childSnapshots[i];
786
+ if (childSnapshot.incremental)
787
+ incremental.push(...childSnapshot.incremental);
788
+ else if (childSnapshot.full.length)
789
+ incremental.push("- <changed> iframe [ref=" + snapshot.iframeRefs[i] + "]:", ...childSnapshot.full.map((l) => " " + l));
790
+ }
791
+ }
792
+ for (const line of snapshot.full.split("\n")) {
793
+ const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=([^\]]*)\]/);
794
+ if (!match) {
795
+ full.push(line);
796
+ continue;
797
+ }
798
+ const leadingSpace = match[1];
799
+ const ref = match[2];
800
+ const childSnapshot = childSnapshots[snapshot.iframeRefs.indexOf(ref)] ?? { full: [] };
801
+ full.push(childSnapshot.full.length ? line + ":" : line);
802
+ full.push(...childSnapshot.full.map((l) => leadingSpace + " " + l));
803
+ }
804
+ return { full, incremental };
805
+ }
806
+ async function snapshotFrameRefForAI(progress, parentFrame, frameRef, options) {
807
+ const frameSelector = `aria-ref=${frameRef} >> internal:control=enter-frame`;
808
+ const frameBodySelector = `${frameSelector} >> body`;
809
+ const child = await progress.race(parentFrame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true }));
810
+ if (!child)
811
+ return { full: [] };
812
+ try {
813
+ return await snapshotFrameForAI(progress, child.frame, options);
814
+ } catch {
815
+ return { full: [] };
816
+ }
817
+ }
818
+ function ensureArrayLimit(array, limit) {
819
+ if (array.length > limit)
820
+ return array.splice(0, limit / 10);
821
+ return [];
822
+ }
823
+ // Annotate the CommonJS export names for ESM import in node:
824
+ 0 && (module.exports = {
825
+ InitScript,
826
+ Page,
827
+ PageBinding,
828
+ Worker,
829
+ WorkerEvent
830
+ });