pure-patchright 1.62.3__py3-none-any.whl
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.
- patchright/__init__.py +5 -0
- patchright/__main__.py +18 -0
- patchright/_impl/__init__.py +0 -0
- patchright/_impl/__pyinstaller/__init__.py +20 -0
- patchright/_impl/__pyinstaller/hook-playwright.async_api.py +3 -0
- patchright/_impl/__pyinstaller/hook-playwright.sync_api.py +3 -0
- patchright/_impl/_api_structures.py +343 -0
- patchright/_impl/_artifact.py +46 -0
- patchright/_impl/_assertions.py +1014 -0
- patchright/_impl/_async_base.py +88 -0
- patchright/_impl/_browser.py +267 -0
- patchright/_impl/_browser_context.py +759 -0
- patchright/_impl/_browser_type.py +336 -0
- patchright/_impl/_cdp_session.py +25 -0
- patchright/_impl/_clock.py +62 -0
- patchright/_impl/_connection.py +686 -0
- patchright/_impl/_console_message.py +83 -0
- patchright/_impl/_credentials.py +38 -0
- patchright/_impl/_debugger.py +37 -0
- patchright/_impl/_dialog.py +45 -0
- patchright/_impl/_disposable.py +71 -0
- patchright/_impl/_download.py +49 -0
- patchright/_impl/_driver.py +24 -0
- patchright/_impl/_element_handle.py +446 -0
- patchright/_impl/_errors.py +46 -0
- patchright/_impl/_event_context_manager.py +19 -0
- patchright/_impl/_fetch.py +592 -0
- patchright/_impl/_file_chooser.py +42 -0
- patchright/_impl/_form_data.py +19 -0
- patchright/_impl/_frame.py +959 -0
- patchright/_impl/_glob.py +47 -0
- patchright/_impl/_greenlets.py +35 -0
- patchright/_impl/_har_router.py +98 -0
- patchright/_impl/_helper.py +551 -0
- patchright/_impl/_impl_to_api_mapping.py +141 -0
- patchright/_impl/_input.py +85 -0
- patchright/_impl/_js_handle.py +297 -0
- patchright/_impl/_json_pipe.py +55 -0
- patchright/_impl/_local_utils.py +73 -0
- patchright/_impl/_locator.py +894 -0
- patchright/_impl/_map.py +18 -0
- patchright/_impl/_network.py +953 -0
- patchright/_impl/_object_factory.py +93 -0
- patchright/_impl/_page.py +1601 -0
- patchright/_impl/_path_utils.py +13 -0
- patchright/_impl/_playwright.py +43 -0
- patchright/_impl/_screencast.py +149 -0
- patchright/_impl/_selectors.py +48 -0
- patchright/_impl/_set_input_files_helpers.py +134 -0
- patchright/_impl/_str_utils.py +59 -0
- patchright/_impl/_stream.py +31 -0
- patchright/_impl/_sync_base.py +130 -0
- patchright/_impl/_tracing.py +243 -0
- patchright/_impl/_transport.py +151 -0
- patchright/_impl/_video.py +41 -0
- patchright/_impl/_waiter.py +168 -0
- patchright/_impl/_web_error.py +33 -0
- patchright/_impl/_web_storage.py +41 -0
- patchright/_impl/_writable_stream.py +26 -0
- patchright/_repo_version.py +1 -0
- patchright/async_api/__init__.py +234 -0
- patchright/async_api/_context_manager.py +38 -0
- patchright/async_api/_generated.py +23396 -0
- patchright/driver/README.md +1 -0
- patchright/driver/package/README.md +3 -0
- patchright/driver/package/ThirdPartyNotices.txt +13 -0
- patchright/driver/package/bin/install_media_pack.ps1 +5 -0
- patchright/driver/package/bin/install_webkit_wsl.ps1 +33 -0
- patchright/driver/package/bin/reinstall_chrome_beta_linux.sh +42 -0
- patchright/driver/package/bin/reinstall_chrome_beta_mac.sh +13 -0
- patchright/driver/package/bin/reinstall_chrome_beta_win.ps1 +24 -0
- patchright/driver/package/bin/reinstall_chrome_stable_linux.sh +42 -0
- patchright/driver/package/bin/reinstall_chrome_stable_mac.sh +12 -0
- patchright/driver/package/bin/reinstall_chrome_stable_win.ps1 +24 -0
- patchright/driver/package/bin/reinstall_msedge_beta_linux.sh +48 -0
- patchright/driver/package/bin/reinstall_msedge_beta_mac.sh +11 -0
- patchright/driver/package/bin/reinstall_msedge_beta_win.ps1 +23 -0
- patchright/driver/package/bin/reinstall_msedge_dev_linux.sh +48 -0
- patchright/driver/package/bin/reinstall_msedge_dev_mac.sh +11 -0
- patchright/driver/package/bin/reinstall_msedge_dev_win.ps1 +23 -0
- patchright/driver/package/bin/reinstall_msedge_stable_linux.sh +48 -0
- patchright/driver/package/bin/reinstall_msedge_stable_mac.sh +11 -0
- patchright/driver/package/bin/reinstall_msedge_stable_win.ps1 +24 -0
- patchright/driver/package/browsers.json +75 -0
- patchright/driver/package/cli.js +21 -0
- patchright/driver/package/index.js +17 -0
- patchright/driver/package/index.mjs +28 -0
- patchright/driver/package/lib/bootstrap.js +88 -0
- patchright/driver/package/lib/coreBundle.js +77498 -0
- patchright/driver/package/lib/entry/cliDaemon.js +5 -0
- patchright/driver/package/lib/entry/dashboardApp.js +3 -0
- patchright/driver/package/lib/entry/mcp.js +10 -0
- patchright/driver/package/lib/entry/oopBrowserDownload.js +3 -0
- patchright/driver/package/lib/package.js +50 -0
- patchright/driver/package/lib/server/chromium/appIcon.png +0 -0
- patchright/driver/package/lib/server/electron/loader.js +107 -0
- patchright/driver/package/lib/serverRegistry.js +7347 -0
- patchright/driver/package/lib/serverRegistry.js.LICENSE +354 -0
- patchright/driver/package/lib/tools/cli-client/channelSessions.js +141 -0
- patchright/driver/package/lib/tools/cli-client/cli.js +6 -0
- patchright/driver/package/lib/tools/cli-client/help.json +708 -0
- patchright/driver/package/lib/tools/cli-client/minimist.js +128 -0
- patchright/driver/package/lib/tools/cli-client/output.js +343 -0
- patchright/driver/package/lib/tools/cli-client/program.js +404 -0
- patchright/driver/package/lib/tools/cli-client/registry.js +176 -0
- patchright/driver/package/lib/tools/cli-client/session.js +258 -0
- patchright/driver/package/lib/tools/dashboard/appIcon.png +0 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/SKILL.md +420 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/running-code.md +241 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/session-management.md +225 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/storage-state.md +275 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/tracing.md +139 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/video-recording.md +143 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/SKILL.md +143 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/migration.md +85 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/react.md +67 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/vue.md +75 -0
- patchright/driver/package/lib/tools/skills/playwright-trace/SKILL.md +171 -0
- patchright/driver/package/lib/tools/utils/extension.js +101 -0
- patchright/driver/package/lib/tools/utils/socketConnection.js +108 -0
- patchright/driver/package/lib/utilsBundle.js +90764 -0
- patchright/driver/package/lib/utilsBundle.js.LICENSE +2179 -0
- patchright/driver/package/lib/webp_codec.LICENSE +173 -0
- patchright/driver/package/lib/webp_codec.wasm +0 -0
- patchright/driver/package/lib/xdg-open +1267 -0
- patchright/driver/package/package.json +34 -0
- patchright/py.typed +0 -0
- patchright/sync_api/__init__.py +234 -0
- patchright/sync_api/_context_manager.py +73 -0
- patchright/sync_api/_generated.py +23590 -0
- pure_patchright-1.62.3.dist-info/LICENSE +201 -0
- pure_patchright-1.62.3.dist-info/METADATA +96 -0
- pure_patchright-1.62.3.dist-info/RECORD +142 -0
- pure_patchright-1.62.3.dist-info/WHEEL +4 -0
- pure_patchright-1.62.3.dist-info/entry_points.txt +5 -0
- pure_patchright-1.62.3.dist-info/licenses/LICENSE +202 -0
- pure_patchright-1.62.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
from typing import Any, Dict, Literal, Optional, Pattern, Union, cast
|
|
3
|
+
from patchright._impl._api_structures import TracingGroupLocation
|
|
4
|
+
from patchright._impl._artifact import Artifact
|
|
5
|
+
from patchright._impl._connection import (
|
|
6
|
+
ChannelOwner,
|
|
7
|
+
from_channel,
|
|
8
|
+
from_nullable_channel,
|
|
9
|
+
)
|
|
10
|
+
from patchright._impl._disposable import DisposableStub
|
|
11
|
+
from patchright._impl._helper import Error, locals_to_params
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Tracing(ChannelOwner):
|
|
15
|
+
def __init__(
|
|
16
|
+
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
|
|
17
|
+
) -> None:
|
|
18
|
+
super().__init__(parent, type, guid, initializer)
|
|
19
|
+
self._include_sources: bool = False
|
|
20
|
+
self._is_live: bool = False
|
|
21
|
+
self._stacks_id: Optional[str] = None
|
|
22
|
+
self._is_tracing: bool = False
|
|
23
|
+
self._traces_dir: Optional[str] = None
|
|
24
|
+
self._har_id: Optional[str] = None
|
|
25
|
+
self._har_recorders: Dict[str, Dict[str, str]] = {}
|
|
26
|
+
|
|
27
|
+
async def start(
|
|
28
|
+
self,
|
|
29
|
+
name: str = None,
|
|
30
|
+
title: str = None,
|
|
31
|
+
snapshots: bool = None,
|
|
32
|
+
screenshots: bool = None,
|
|
33
|
+
sources: bool = None,
|
|
34
|
+
live: bool = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
if hasattr(self._parent, "install_inject_route"):
|
|
37
|
+
await self._parent.install_inject_route()
|
|
38
|
+
params = locals_to_params(locals())
|
|
39
|
+
self._include_sources = bool(sources)
|
|
40
|
+
self._is_live = bool(live)
|
|
41
|
+
await self._channel.send(
|
|
42
|
+
"tracingStart",
|
|
43
|
+
None,
|
|
44
|
+
{
|
|
45
|
+
"name": name,
|
|
46
|
+
"snapshots": snapshots,
|
|
47
|
+
"screenshots": screenshots,
|
|
48
|
+
"live": live,
|
|
49
|
+
},
|
|
50
|
+
)
|
|
51
|
+
trace_name = await self._channel.send(
|
|
52
|
+
"tracingStartChunk", None, {"title": title, "name": name}
|
|
53
|
+
)
|
|
54
|
+
await self._start_collecting_stacks(trace_name)
|
|
55
|
+
|
|
56
|
+
async def start_chunk(self, title: str = None, name: str = None) -> None:
|
|
57
|
+
params = locals_to_params(locals())
|
|
58
|
+
trace_name = await self._channel.send("tracingStartChunk", None, params)
|
|
59
|
+
await self._start_collecting_stacks(trace_name)
|
|
60
|
+
|
|
61
|
+
async def _start_collecting_stacks(self, trace_name: str) -> None:
|
|
62
|
+
if not self._is_tracing:
|
|
63
|
+
self._is_tracing = True
|
|
64
|
+
self._connection.set_is_tracing(True)
|
|
65
|
+
self._stacks_id = await self._connection.local_utils.tracing_started(
|
|
66
|
+
self._traces_dir, trace_name, self._is_live
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
async def stop_chunk(self, path: Union[pathlib.Path, str] = None) -> None:
|
|
70
|
+
await self._do_stop_chunk(path)
|
|
71
|
+
|
|
72
|
+
async def stop(self, path: Union[pathlib.Path, str] = None) -> None:
|
|
73
|
+
await self._do_stop_chunk(path)
|
|
74
|
+
await self._channel.send("tracingStop", None)
|
|
75
|
+
|
|
76
|
+
async def _do_stop_chunk(self, file_path: Union[pathlib.Path, str] = None) -> None:
|
|
77
|
+
self._reset_stack_counter()
|
|
78
|
+
if not file_path:
|
|
79
|
+
await self._channel.send("tracingStopChunk", None, {"mode": "discard"})
|
|
80
|
+
if self._stacks_id:
|
|
81
|
+
await self._connection.local_utils.trace_discarded(self._stacks_id)
|
|
82
|
+
return
|
|
83
|
+
is_local = not self._connection.is_remote
|
|
84
|
+
if is_local:
|
|
85
|
+
result = await self._channel.send_return_as_dict(
|
|
86
|
+
"tracingStopChunk", None, {"mode": "entries"}
|
|
87
|
+
)
|
|
88
|
+
await self._connection.local_utils.zip(
|
|
89
|
+
{
|
|
90
|
+
"zipFile": str(file_path),
|
|
91
|
+
"entries": result["entries"],
|
|
92
|
+
"stacksId": self._stacks_id,
|
|
93
|
+
"mode": "write",
|
|
94
|
+
"includeSources": self._include_sources,
|
|
95
|
+
}
|
|
96
|
+
)
|
|
97
|
+
return
|
|
98
|
+
result = await self._channel.send_return_as_dict(
|
|
99
|
+
"tracingStopChunk", None, {"mode": "archive"}
|
|
100
|
+
)
|
|
101
|
+
artifact = cast(
|
|
102
|
+
Optional[Artifact], from_nullable_channel(result.get("artifact"))
|
|
103
|
+
)
|
|
104
|
+
if not artifact:
|
|
105
|
+
if self._stacks_id:
|
|
106
|
+
await self._connection.local_utils.trace_discarded(self._stacks_id)
|
|
107
|
+
return
|
|
108
|
+
await artifact.save_as(file_path)
|
|
109
|
+
await artifact.delete()
|
|
110
|
+
await self._connection.local_utils.zip(
|
|
111
|
+
{
|
|
112
|
+
"zipFile": str(file_path),
|
|
113
|
+
"entries": [],
|
|
114
|
+
"stacksId": self._stacks_id,
|
|
115
|
+
"mode": "append",
|
|
116
|
+
"includeSources": self._include_sources,
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def _reset_stack_counter(self) -> None:
|
|
121
|
+
if self._is_tracing:
|
|
122
|
+
self._is_tracing = False
|
|
123
|
+
self._connection.set_is_tracing(False)
|
|
124
|
+
|
|
125
|
+
async def group(
|
|
126
|
+
self, name: str, location: TracingGroupLocation = None
|
|
127
|
+
) -> DisposableStub:
|
|
128
|
+
await self._channel.send("tracingGroup", None, locals_to_params(locals()))
|
|
129
|
+
return DisposableStub(lambda: self.group_end(), self)
|
|
130
|
+
|
|
131
|
+
async def group_end(self) -> None:
|
|
132
|
+
await self._channel.send("tracingGroupEnd", None)
|
|
133
|
+
|
|
134
|
+
async def start_har(
|
|
135
|
+
self,
|
|
136
|
+
path: Union[pathlib.Path, str],
|
|
137
|
+
content: Literal["attach", "embed", "omit"] = None,
|
|
138
|
+
mode: Literal["full", "minimal"] = None,
|
|
139
|
+
urlFilter: Union[str, Pattern[str]] = None,
|
|
140
|
+
) -> DisposableStub:
|
|
141
|
+
if self._har_id:
|
|
142
|
+
raise Error("HAR recording has already been started")
|
|
143
|
+
is_zip = str(path).endswith(".zip")
|
|
144
|
+
default_content: Literal["attach", "embed", "omit"] = (
|
|
145
|
+
"attach" if is_zip else "embed"
|
|
146
|
+
)
|
|
147
|
+
self._har_id = await self._record_into_har(
|
|
148
|
+
har=path,
|
|
149
|
+
page=None,
|
|
150
|
+
url=urlFilter,
|
|
151
|
+
update_content=content or default_content,
|
|
152
|
+
update_mode=mode or "full",
|
|
153
|
+
)
|
|
154
|
+
return DisposableStub(lambda: self.stop_har(), self)
|
|
155
|
+
|
|
156
|
+
async def _record_into_har(
|
|
157
|
+
self,
|
|
158
|
+
har: Union[pathlib.Path, str],
|
|
159
|
+
page: Optional[ChannelOwner],
|
|
160
|
+
url: Union[str, Pattern[str]] = None,
|
|
161
|
+
update_content: Literal["attach", "embed", "omit"] = None,
|
|
162
|
+
update_mode: Literal["full", "minimal"] = None,
|
|
163
|
+
resourcesDir: Optional[str] = None,
|
|
164
|
+
) -> str:
|
|
165
|
+
is_zip = str(har).endswith(".zip")
|
|
166
|
+
url_glob: Optional[str] = None
|
|
167
|
+
url_regex_source: Optional[str] = None
|
|
168
|
+
url_regex_flags: Optional[str] = None
|
|
169
|
+
if isinstance(url, str):
|
|
170
|
+
url_glob = url
|
|
171
|
+
elif url is not None:
|
|
172
|
+
url_regex_source = url.pattern
|
|
173
|
+
url_regex_flags = "".join(
|
|
174
|
+
(
|
|
175
|
+
flag
|
|
176
|
+
for flag, mask in (("i", 2), ("m", 8), ("s", 16))
|
|
177
|
+
if url.flags & mask
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
options: Dict[str, object] = {
|
|
181
|
+
"content": update_content or "attach",
|
|
182
|
+
"mode": update_mode or "minimal",
|
|
183
|
+
"harPath": None if is_zip else str(har),
|
|
184
|
+
}
|
|
185
|
+
if url_glob is not None:
|
|
186
|
+
options["urlGlob"] = url_glob
|
|
187
|
+
if url_regex_source is not None:
|
|
188
|
+
options["urlRegexSource"] = url_regex_source
|
|
189
|
+
if url_regex_flags is not None:
|
|
190
|
+
options["urlRegexFlags"] = url_regex_flags
|
|
191
|
+
if resourcesDir is not None:
|
|
192
|
+
options["resourcesDir"] = resourcesDir
|
|
193
|
+
params: Dict[str, Any] = {"options": options}
|
|
194
|
+
if page is not None:
|
|
195
|
+
params["page"] = page._channel
|
|
196
|
+
result = await self._channel.send_return_as_dict("harStart", None, params)
|
|
197
|
+
har_id = result["harId"]
|
|
198
|
+
self._har_recorders[har_id] = {"path": str(har)}
|
|
199
|
+
return har_id
|
|
200
|
+
|
|
201
|
+
async def _export_all_hars(self) -> None:
|
|
202
|
+
for har_id in list(self._har_recorders.keys()):
|
|
203
|
+
await self._export_har(har_id)
|
|
204
|
+
self._har_id = None
|
|
205
|
+
|
|
206
|
+
async def stop_har(self) -> None:
|
|
207
|
+
har_id = self._har_id
|
|
208
|
+
if not har_id:
|
|
209
|
+
return
|
|
210
|
+
self._har_id = None
|
|
211
|
+
await self._export_har(har_id)
|
|
212
|
+
|
|
213
|
+
async def _export_har(self, har_id: str) -> None:
|
|
214
|
+
params = self._har_recorders.pop(har_id, None)
|
|
215
|
+
if not params:
|
|
216
|
+
return
|
|
217
|
+
is_local = not self._connection.is_remote
|
|
218
|
+
is_zip = params["path"].endswith(".zip")
|
|
219
|
+
if is_local:
|
|
220
|
+
result = await self._channel.send_return_as_dict(
|
|
221
|
+
"harExport", None, {"harId": har_id, "mode": "entries"}
|
|
222
|
+
)
|
|
223
|
+
if not is_zip:
|
|
224
|
+
return
|
|
225
|
+
await self._connection.local_utils.zip(
|
|
226
|
+
{
|
|
227
|
+
"zipFile": params["path"],
|
|
228
|
+
"entries": result["entries"],
|
|
229
|
+
"mode": "write",
|
|
230
|
+
"includeSources": False,
|
|
231
|
+
}
|
|
232
|
+
)
|
|
233
|
+
return
|
|
234
|
+
result = await self._channel.send_return_as_dict(
|
|
235
|
+
"harExport", None, {"harId": har_id, "mode": "archive"}
|
|
236
|
+
)
|
|
237
|
+
artifact = cast(Artifact, from_channel(result["artifact"]))
|
|
238
|
+
if is_zip:
|
|
239
|
+
await artifact.save_as(params["path"])
|
|
240
|
+
await artifact.delete()
|
|
241
|
+
return
|
|
242
|
+
await artifact.save_as(params["path"] + ".tmp")
|
|
243
|
+
await artifact.delete()
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from typing import Callable, Dict, Optional, Union
|
|
9
|
+
from patchright._impl._driver import compute_driver_executable, get_driver_env
|
|
10
|
+
from patchright._impl._helper import ParsedMessagePayload
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _get_stderr_fileno() -> Optional[int]:
|
|
14
|
+
try:
|
|
15
|
+
if sys.stderr is None or not hasattr(sys.stderr, "closed"):
|
|
16
|
+
return None
|
|
17
|
+
if sys.stderr.closed:
|
|
18
|
+
return None
|
|
19
|
+
return sys.stderr.fileno()
|
|
20
|
+
except (NotImplementedError, AttributeError, io.UnsupportedOperation):
|
|
21
|
+
if not hasattr(sys, "__stderr__") or not sys.__stderr__:
|
|
22
|
+
return None
|
|
23
|
+
return sys.__stderr__.fileno()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Transport(ABC):
|
|
27
|
+
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
28
|
+
self._loop = loop
|
|
29
|
+
self.on_message: Callable[[ParsedMessagePayload], None] = lambda _: None
|
|
30
|
+
self.on_error_future: asyncio.Future = loop.create_future()
|
|
31
|
+
|
|
32
|
+
@abstractmethod
|
|
33
|
+
def request_stop(self) -> None:
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
def dispose(self) -> None:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
async def wait_until_stopped(self) -> None:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
async def connect(self) -> None:
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
async def run(self) -> None:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
@abstractmethod
|
|
52
|
+
def send(self, message: Dict) -> None:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
def serialize_message(self, message: Dict) -> bytes:
|
|
56
|
+
msg = json.dumps(message)
|
|
57
|
+
if "DEBUGP" in os.environ:
|
|
58
|
+
print("\x1b[32mSEND>\x1b[0m", json.dumps(message, indent=2))
|
|
59
|
+
return msg.encode()
|
|
60
|
+
|
|
61
|
+
def deserialize_message(self, data: Union[str, bytes]) -> ParsedMessagePayload:
|
|
62
|
+
obj = json.loads(data)
|
|
63
|
+
if "DEBUGP" in os.environ:
|
|
64
|
+
print("\x1b[33mRECV>\x1b[0m", json.dumps(obj, indent=2))
|
|
65
|
+
return obj
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class PipeTransport(Transport):
|
|
69
|
+
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
70
|
+
super().__init__(loop)
|
|
71
|
+
self._stopped = False
|
|
72
|
+
|
|
73
|
+
def request_stop(self) -> None:
|
|
74
|
+
assert self._output
|
|
75
|
+
self._stopped = True
|
|
76
|
+
self._output.close()
|
|
77
|
+
|
|
78
|
+
async def wait_until_stopped(self) -> None:
|
|
79
|
+
await self._stopped_future
|
|
80
|
+
|
|
81
|
+
async def connect(self) -> None:
|
|
82
|
+
self._stopped_future: asyncio.Future = asyncio.Future()
|
|
83
|
+
try:
|
|
84
|
+
env = get_driver_env()
|
|
85
|
+
if getattr(sys, "frozen", False) or globals().get("__compiled__"):
|
|
86
|
+
env.setdefault("PLAYWRIGHT_BROWSERS_PATH", "0")
|
|
87
|
+
startupinfo = None
|
|
88
|
+
if sys.platform == "win32":
|
|
89
|
+
startupinfo = subprocess.STARTUPINFO()
|
|
90
|
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
91
|
+
startupinfo.wShowWindow = subprocess.SW_HIDE
|
|
92
|
+
executable_path, entrypoint_path = compute_driver_executable()
|
|
93
|
+
self._proc = await asyncio.create_subprocess_exec(
|
|
94
|
+
executable_path,
|
|
95
|
+
entrypoint_path,
|
|
96
|
+
"run-driver",
|
|
97
|
+
stdin=asyncio.subprocess.PIPE,
|
|
98
|
+
stdout=asyncio.subprocess.PIPE,
|
|
99
|
+
stderr=_get_stderr_fileno(),
|
|
100
|
+
limit=32768,
|
|
101
|
+
env=env,
|
|
102
|
+
startupinfo=startupinfo,
|
|
103
|
+
)
|
|
104
|
+
except Exception as exc:
|
|
105
|
+
self.on_error_future.set_exception(exc)
|
|
106
|
+
raise exc
|
|
107
|
+
self._output = self._proc.stdin
|
|
108
|
+
|
|
109
|
+
async def run(self) -> None:
|
|
110
|
+
assert self._proc.stdout
|
|
111
|
+
assert self._proc.stdin
|
|
112
|
+
try:
|
|
113
|
+
while not self._stopped:
|
|
114
|
+
try:
|
|
115
|
+
buffer = await self._proc.stdout.readexactly(4)
|
|
116
|
+
if self._stopped:
|
|
117
|
+
break
|
|
118
|
+
length = int.from_bytes(buffer, byteorder="little", signed=False)
|
|
119
|
+
buffer = bytes(0)
|
|
120
|
+
while length:
|
|
121
|
+
to_read = min(length, 32768)
|
|
122
|
+
data = await self._proc.stdout.readexactly(to_read)
|
|
123
|
+
if self._stopped:
|
|
124
|
+
break
|
|
125
|
+
length -= to_read
|
|
126
|
+
if len(buffer):
|
|
127
|
+
buffer = buffer + data
|
|
128
|
+
else:
|
|
129
|
+
buffer = data
|
|
130
|
+
if self._stopped:
|
|
131
|
+
break
|
|
132
|
+
obj = self.deserialize_message(buffer)
|
|
133
|
+
self.on_message(obj)
|
|
134
|
+
except asyncio.IncompleteReadError:
|
|
135
|
+
if not self._stopped:
|
|
136
|
+
self.on_error_future.set_exception(
|
|
137
|
+
Exception("Connection closed while reading from the driver")
|
|
138
|
+
)
|
|
139
|
+
break
|
|
140
|
+
await asyncio.sleep(0)
|
|
141
|
+
await self._proc.communicate()
|
|
142
|
+
finally:
|
|
143
|
+
if not self._stopped_future.done():
|
|
144
|
+
self._stopped_future.set_result(None)
|
|
145
|
+
|
|
146
|
+
def send(self, message: Dict) -> None:
|
|
147
|
+
assert self._output
|
|
148
|
+
data = self.serialize_message(message)
|
|
149
|
+
self._output.write(
|
|
150
|
+
len(data).to_bytes(4, byteorder="little", signed=False) + data
|
|
151
|
+
)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
from typing import TYPE_CHECKING, Optional, Union
|
|
3
|
+
from patchright._impl._artifact import Artifact
|
|
4
|
+
from patchright._impl._helper import Error
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from patchright._impl._page import Page
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Video:
|
|
11
|
+
def __init__(self, page: "Page", artifact: Optional[Artifact]) -> None:
|
|
12
|
+
self._loop = page._loop
|
|
13
|
+
self._dispatcher_fiber = page._dispatcher_fiber
|
|
14
|
+
self._page = page
|
|
15
|
+
self._is_remote = page._connection.is_remote
|
|
16
|
+
self._artifact = artifact
|
|
17
|
+
|
|
18
|
+
def __repr__(self) -> str:
|
|
19
|
+
return f"<Video page={self._page}>"
|
|
20
|
+
|
|
21
|
+
async def path(self) -> pathlib.Path:
|
|
22
|
+
if self._is_remote:
|
|
23
|
+
raise Error(
|
|
24
|
+
"Path is not available when using browserType.connect(). Use save_as() to save a local copy."
|
|
25
|
+
)
|
|
26
|
+
if not self._artifact:
|
|
27
|
+
raise Error("Video recording has not been started.")
|
|
28
|
+
return self._artifact.absolute_path
|
|
29
|
+
|
|
30
|
+
async def save_as(self, path: Union[str, pathlib.Path]) -> None:
|
|
31
|
+
if self._page._connection._is_sync and (not self._page._is_closed):
|
|
32
|
+
raise Error(
|
|
33
|
+
"Page is not yet closed. Close the page prior to calling save_as"
|
|
34
|
+
)
|
|
35
|
+
if not self._artifact:
|
|
36
|
+
raise Error("Video recording has not been started.")
|
|
37
|
+
await self._artifact.save_as(path)
|
|
38
|
+
|
|
39
|
+
async def delete(self) -> None:
|
|
40
|
+
if self._artifact:
|
|
41
|
+
await self._artifact.delete()
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import math
|
|
4
|
+
import uuid
|
|
5
|
+
from asyncio.tasks import Task
|
|
6
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
|
7
|
+
from pyee import EventEmitter
|
|
8
|
+
from patchright._impl._connection import ChannelOwner
|
|
9
|
+
from patchright._impl._errors import Error, TimeoutError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Waiter:
|
|
13
|
+
def __init__(self, channel_owner: ChannelOwner, event: str) -> None:
|
|
14
|
+
self._result: asyncio.Future = asyncio.Future()
|
|
15
|
+
self._wait_id = uuid.uuid4().hex
|
|
16
|
+
self._loop = channel_owner._loop
|
|
17
|
+
self._pending_tasks: List[Task] = []
|
|
18
|
+
self._channel = channel_owner._channel
|
|
19
|
+
self._registered_listeners: List[Tuple[EventEmitter, str, Callable]] = []
|
|
20
|
+
self._logs: List[str] = []
|
|
21
|
+
self._wait_for_event_info_before(self._wait_id, event)
|
|
22
|
+
|
|
23
|
+
def _wait_for_event_info_before(self, wait_id: str, event: str) -> None:
|
|
24
|
+
self._send_wait_for_event_info(
|
|
25
|
+
{"waitId": wait_id, "phase": "before", "event": event},
|
|
26
|
+
title=f'Wait for event "{event}"',
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def _wait_for_event_info_after(self, wait_id: str, error: Exception = None) -> None:
|
|
30
|
+
self._send_wait_for_event_info(
|
|
31
|
+
{
|
|
32
|
+
"waitId": wait_id,
|
|
33
|
+
"phase": "after",
|
|
34
|
+
**({"error": str(error)} if error else {}),
|
|
35
|
+
},
|
|
36
|
+
is_internal=True,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def _send_wait_for_event_info(
|
|
40
|
+
self, params: Dict[str, Any], is_internal: bool = False, title: str = None
|
|
41
|
+
) -> None:
|
|
42
|
+
try:
|
|
43
|
+
self._channel.send_no_reply(
|
|
44
|
+
"__waitInfo__", None, params, is_internal=is_internal, title=title
|
|
45
|
+
)
|
|
46
|
+
except Error:
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
def reject_on_event(
|
|
50
|
+
self,
|
|
51
|
+
emitter: EventEmitter,
|
|
52
|
+
event: str,
|
|
53
|
+
error: Union[Error, Callable[..., Error]],
|
|
54
|
+
predicate: Callable = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
|
|
57
|
+
def on_match() -> None:
|
|
58
|
+
self._reject(error() if callable(error) else error)
|
|
59
|
+
|
|
60
|
+
def listener(event_data: Any = None) -> None:
|
|
61
|
+
self._evaluate_predicate(predicate, event_data, on_match)
|
|
62
|
+
|
|
63
|
+
emitter.on(event, listener)
|
|
64
|
+
self._registered_listeners.append((emitter, event, listener))
|
|
65
|
+
|
|
66
|
+
def reject_on_timeout(self, timeout: float, message: str) -> None:
|
|
67
|
+
if timeout == 0:
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
async def reject() -> None:
|
|
71
|
+
await asyncio.sleep(timeout / 1000)
|
|
72
|
+
self._reject(TimeoutError(message))
|
|
73
|
+
|
|
74
|
+
self._pending_tasks.append(self._loop.create_task(reject()))
|
|
75
|
+
|
|
76
|
+
def _cleanup(self) -> None:
|
|
77
|
+
for task in self._pending_tasks:
|
|
78
|
+
if not task.done():
|
|
79
|
+
task.cancel()
|
|
80
|
+
for listener in self._registered_listeners:
|
|
81
|
+
listener[0].remove_listener(listener[1], listener[2])
|
|
82
|
+
|
|
83
|
+
def _fulfill(self, result: Any) -> None:
|
|
84
|
+
self._cleanup()
|
|
85
|
+
if not self._result.done():
|
|
86
|
+
self._result.set_result(result)
|
|
87
|
+
self._wait_for_event_info_after(self._wait_id)
|
|
88
|
+
|
|
89
|
+
def _reject(self, exception: Exception) -> None:
|
|
90
|
+
self._cleanup()
|
|
91
|
+
if exception:
|
|
92
|
+
base_class = TimeoutError if isinstance(exception, TimeoutError) else Error
|
|
93
|
+
exception = base_class(str(exception) + format_log_recording(self._logs))
|
|
94
|
+
if not self._result.done():
|
|
95
|
+
self._result.set_exception(exception)
|
|
96
|
+
self._wait_for_event_info_after(self._wait_id, exception)
|
|
97
|
+
|
|
98
|
+
def wait_for_event(
|
|
99
|
+
self, emitter: EventEmitter, event: str, predicate: Callable = None
|
|
100
|
+
) -> None:
|
|
101
|
+
|
|
102
|
+
def listener(event_data: Any = None) -> None:
|
|
103
|
+
self._evaluate_predicate(
|
|
104
|
+
predicate, event_data, lambda: self._fulfill(event_data)
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
emitter.on(event, listener)
|
|
108
|
+
self._registered_listeners.append((emitter, event, listener))
|
|
109
|
+
|
|
110
|
+
def _evaluate_predicate(
|
|
111
|
+
self,
|
|
112
|
+
predicate: Optional[Callable],
|
|
113
|
+
event_data: Any,
|
|
114
|
+
on_match: Callable[[], None],
|
|
115
|
+
) -> None:
|
|
116
|
+
if predicate is None:
|
|
117
|
+
on_match()
|
|
118
|
+
return
|
|
119
|
+
try:
|
|
120
|
+
result = predicate(event_data)
|
|
121
|
+
except Exception as e:
|
|
122
|
+
self._reject(e)
|
|
123
|
+
return
|
|
124
|
+
if inspect.iscoroutine(result):
|
|
125
|
+
|
|
126
|
+
async def _await_predicate(coro: Any) -> None:
|
|
127
|
+
try:
|
|
128
|
+
matched = await coro
|
|
129
|
+
except Exception as e:
|
|
130
|
+
self._reject(e)
|
|
131
|
+
return
|
|
132
|
+
if matched and (not self._result.done()):
|
|
133
|
+
on_match()
|
|
134
|
+
|
|
135
|
+
self._pending_tasks.append(self._loop.create_task(_await_predicate(result)))
|
|
136
|
+
return
|
|
137
|
+
if result:
|
|
138
|
+
on_match()
|
|
139
|
+
|
|
140
|
+
def result(self) -> asyncio.Future:
|
|
141
|
+
return self._result
|
|
142
|
+
|
|
143
|
+
def log(self, message: str) -> None:
|
|
144
|
+
self._logs.append(message)
|
|
145
|
+
self._send_wait_for_event_info(
|
|
146
|
+
{"waitId": self._wait_id, "phase": "log", "message": message},
|
|
147
|
+
is_internal=True,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def throw_on_timeout(timeout: float, exception: Exception) -> asyncio.Task:
|
|
152
|
+
|
|
153
|
+
async def throw() -> None:
|
|
154
|
+
await asyncio.sleep(timeout / 1000)
|
|
155
|
+
raise exception
|
|
156
|
+
|
|
157
|
+
return asyncio.create_task(throw())
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def format_log_recording(log: List[str]) -> str:
|
|
161
|
+
if not log:
|
|
162
|
+
return ""
|
|
163
|
+
header = " logs "
|
|
164
|
+
header_length = 60
|
|
165
|
+
left_length = math.floor((header_length - len(header)) / 2)
|
|
166
|
+
right_length = header_length - len(header) - left_length
|
|
167
|
+
new_line = "\n"
|
|
168
|
+
return f"{new_line}{'=' * left_length}{header}{'=' * right_length}{new_line}{new_line.join(log)}{new_line}{'=' * header_length}"
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from asyncio import AbstractEventLoop
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
from patchright._impl._api_structures import WebErrorLocation
|
|
4
|
+
from patchright._impl._helper import Error
|
|
5
|
+
from patchright._impl._page import Page
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class WebError:
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
loop: AbstractEventLoop,
|
|
12
|
+
dispatcher_fiber: Any,
|
|
13
|
+
page: Optional[Page],
|
|
14
|
+
error: Error,
|
|
15
|
+
location: WebErrorLocation,
|
|
16
|
+
) -> None:
|
|
17
|
+
self._loop = loop
|
|
18
|
+
self._dispatcher_fiber = dispatcher_fiber
|
|
19
|
+
self._page = page
|
|
20
|
+
self._error = error
|
|
21
|
+
self._location = location
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def page(self) -> Optional[Page]:
|
|
25
|
+
return self._page
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def error(self) -> Error:
|
|
29
|
+
return self._error
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def location(self) -> WebErrorLocation:
|
|
33
|
+
return self._location
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, List, Literal, Optional
|
|
2
|
+
from patchright._impl._api_structures import NameValue
|
|
3
|
+
|
|
4
|
+
if TYPE_CHECKING:
|
|
5
|
+
from patchright._impl._page import Page
|
|
6
|
+
WebStorageKind = Literal["local", "session"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class WebStorage:
|
|
10
|
+
def __init__(self, page: "Page", kind: WebStorageKind) -> None:
|
|
11
|
+
self._page = page
|
|
12
|
+
self._kind = kind
|
|
13
|
+
self._loop = page._loop
|
|
14
|
+
self._dispatcher_fiber = page._dispatcher_fiber
|
|
15
|
+
|
|
16
|
+
async def items(self) -> List[NameValue]:
|
|
17
|
+
result = await self._page._channel.send_return_as_dict(
|
|
18
|
+
"webStorageItems", None, {"kind": self._kind}
|
|
19
|
+
)
|
|
20
|
+
return (result or {}).get("items", [])
|
|
21
|
+
|
|
22
|
+
async def get_item(self, name: str) -> Optional[str]:
|
|
23
|
+
result = await self._page._channel.send_return_as_dict(
|
|
24
|
+
"webStorageGetItem", None, {"kind": self._kind, "name": name}
|
|
25
|
+
)
|
|
26
|
+
return (result or {}).get("value")
|
|
27
|
+
|
|
28
|
+
async def set_item(self, name: str, value: str) -> None:
|
|
29
|
+
await self._page._channel.send(
|
|
30
|
+
"webStorageSetItem",
|
|
31
|
+
None,
|
|
32
|
+
{"kind": self._kind, "name": name, "value": value},
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
async def remove_item(self, name: str) -> None:
|
|
36
|
+
await self._page._channel.send(
|
|
37
|
+
"webStorageRemoveItem", None, {"kind": self._kind, "name": name}
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
async def clear(self) -> None:
|
|
41
|
+
await self._page._channel.send("webStorageClear", None, {"kind": self._kind})
|