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.
Files changed (142) hide show
  1. patchright/__init__.py +5 -0
  2. patchright/__main__.py +18 -0
  3. patchright/_impl/__init__.py +0 -0
  4. patchright/_impl/__pyinstaller/__init__.py +20 -0
  5. patchright/_impl/__pyinstaller/hook-playwright.async_api.py +3 -0
  6. patchright/_impl/__pyinstaller/hook-playwright.sync_api.py +3 -0
  7. patchright/_impl/_api_structures.py +343 -0
  8. patchright/_impl/_artifact.py +46 -0
  9. patchright/_impl/_assertions.py +1014 -0
  10. patchright/_impl/_async_base.py +88 -0
  11. patchright/_impl/_browser.py +267 -0
  12. patchright/_impl/_browser_context.py +759 -0
  13. patchright/_impl/_browser_type.py +336 -0
  14. patchright/_impl/_cdp_session.py +25 -0
  15. patchright/_impl/_clock.py +62 -0
  16. patchright/_impl/_connection.py +686 -0
  17. patchright/_impl/_console_message.py +83 -0
  18. patchright/_impl/_credentials.py +38 -0
  19. patchright/_impl/_debugger.py +37 -0
  20. patchright/_impl/_dialog.py +45 -0
  21. patchright/_impl/_disposable.py +71 -0
  22. patchright/_impl/_download.py +49 -0
  23. patchright/_impl/_driver.py +24 -0
  24. patchright/_impl/_element_handle.py +446 -0
  25. patchright/_impl/_errors.py +46 -0
  26. patchright/_impl/_event_context_manager.py +19 -0
  27. patchright/_impl/_fetch.py +592 -0
  28. patchright/_impl/_file_chooser.py +42 -0
  29. patchright/_impl/_form_data.py +19 -0
  30. patchright/_impl/_frame.py +959 -0
  31. patchright/_impl/_glob.py +47 -0
  32. patchright/_impl/_greenlets.py +35 -0
  33. patchright/_impl/_har_router.py +98 -0
  34. patchright/_impl/_helper.py +551 -0
  35. patchright/_impl/_impl_to_api_mapping.py +141 -0
  36. patchright/_impl/_input.py +85 -0
  37. patchright/_impl/_js_handle.py +297 -0
  38. patchright/_impl/_json_pipe.py +55 -0
  39. patchright/_impl/_local_utils.py +73 -0
  40. patchright/_impl/_locator.py +894 -0
  41. patchright/_impl/_map.py +18 -0
  42. patchright/_impl/_network.py +953 -0
  43. patchright/_impl/_object_factory.py +93 -0
  44. patchright/_impl/_page.py +1601 -0
  45. patchright/_impl/_path_utils.py +13 -0
  46. patchright/_impl/_playwright.py +43 -0
  47. patchright/_impl/_screencast.py +149 -0
  48. patchright/_impl/_selectors.py +48 -0
  49. patchright/_impl/_set_input_files_helpers.py +134 -0
  50. patchright/_impl/_str_utils.py +59 -0
  51. patchright/_impl/_stream.py +31 -0
  52. patchright/_impl/_sync_base.py +130 -0
  53. patchright/_impl/_tracing.py +243 -0
  54. patchright/_impl/_transport.py +151 -0
  55. patchright/_impl/_video.py +41 -0
  56. patchright/_impl/_waiter.py +168 -0
  57. patchright/_impl/_web_error.py +33 -0
  58. patchright/_impl/_web_storage.py +41 -0
  59. patchright/_impl/_writable_stream.py +26 -0
  60. patchright/_repo_version.py +1 -0
  61. patchright/async_api/__init__.py +234 -0
  62. patchright/async_api/_context_manager.py +38 -0
  63. patchright/async_api/_generated.py +23396 -0
  64. patchright/driver/README.md +1 -0
  65. patchright/driver/package/README.md +3 -0
  66. patchright/driver/package/ThirdPartyNotices.txt +13 -0
  67. patchright/driver/package/bin/install_media_pack.ps1 +5 -0
  68. patchright/driver/package/bin/install_webkit_wsl.ps1 +33 -0
  69. patchright/driver/package/bin/reinstall_chrome_beta_linux.sh +42 -0
  70. patchright/driver/package/bin/reinstall_chrome_beta_mac.sh +13 -0
  71. patchright/driver/package/bin/reinstall_chrome_beta_win.ps1 +24 -0
  72. patchright/driver/package/bin/reinstall_chrome_stable_linux.sh +42 -0
  73. patchright/driver/package/bin/reinstall_chrome_stable_mac.sh +12 -0
  74. patchright/driver/package/bin/reinstall_chrome_stable_win.ps1 +24 -0
  75. patchright/driver/package/bin/reinstall_msedge_beta_linux.sh +48 -0
  76. patchright/driver/package/bin/reinstall_msedge_beta_mac.sh +11 -0
  77. patchright/driver/package/bin/reinstall_msedge_beta_win.ps1 +23 -0
  78. patchright/driver/package/bin/reinstall_msedge_dev_linux.sh +48 -0
  79. patchright/driver/package/bin/reinstall_msedge_dev_mac.sh +11 -0
  80. patchright/driver/package/bin/reinstall_msedge_dev_win.ps1 +23 -0
  81. patchright/driver/package/bin/reinstall_msedge_stable_linux.sh +48 -0
  82. patchright/driver/package/bin/reinstall_msedge_stable_mac.sh +11 -0
  83. patchright/driver/package/bin/reinstall_msedge_stable_win.ps1 +24 -0
  84. patchright/driver/package/browsers.json +75 -0
  85. patchright/driver/package/cli.js +21 -0
  86. patchright/driver/package/index.js +17 -0
  87. patchright/driver/package/index.mjs +28 -0
  88. patchright/driver/package/lib/bootstrap.js +88 -0
  89. patchright/driver/package/lib/coreBundle.js +77498 -0
  90. patchright/driver/package/lib/entry/cliDaemon.js +5 -0
  91. patchright/driver/package/lib/entry/dashboardApp.js +3 -0
  92. patchright/driver/package/lib/entry/mcp.js +10 -0
  93. patchright/driver/package/lib/entry/oopBrowserDownload.js +3 -0
  94. patchright/driver/package/lib/package.js +50 -0
  95. patchright/driver/package/lib/server/chromium/appIcon.png +0 -0
  96. patchright/driver/package/lib/server/electron/loader.js +107 -0
  97. patchright/driver/package/lib/serverRegistry.js +7347 -0
  98. patchright/driver/package/lib/serverRegistry.js.LICENSE +354 -0
  99. patchright/driver/package/lib/tools/cli-client/channelSessions.js +141 -0
  100. patchright/driver/package/lib/tools/cli-client/cli.js +6 -0
  101. patchright/driver/package/lib/tools/cli-client/help.json +708 -0
  102. patchright/driver/package/lib/tools/cli-client/minimist.js +128 -0
  103. patchright/driver/package/lib/tools/cli-client/output.js +343 -0
  104. patchright/driver/package/lib/tools/cli-client/program.js +404 -0
  105. patchright/driver/package/lib/tools/cli-client/registry.js +176 -0
  106. patchright/driver/package/lib/tools/cli-client/session.js +258 -0
  107. patchright/driver/package/lib/tools/dashboard/appIcon.png +0 -0
  108. patchright/driver/package/lib/tools/skills/playwright-cli/SKILL.md +420 -0
  109. patchright/driver/package/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
  110. patchright/driver/package/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
  111. patchright/driver/package/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
  112. patchright/driver/package/lib/tools/skills/playwright-cli/references/running-code.md +241 -0
  113. patchright/driver/package/lib/tools/skills/playwright-cli/references/session-management.md +225 -0
  114. patchright/driver/package/lib/tools/skills/playwright-cli/references/storage-state.md +275 -0
  115. patchright/driver/package/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
  116. patchright/driver/package/lib/tools/skills/playwright-cli/references/tracing.md +139 -0
  117. patchright/driver/package/lib/tools/skills/playwright-cli/references/video-recording.md +143 -0
  118. patchright/driver/package/lib/tools/skills/playwright-component-testing/SKILL.md +143 -0
  119. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
  120. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/migration.md +85 -0
  121. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/react.md +67 -0
  122. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/vue.md +75 -0
  123. patchright/driver/package/lib/tools/skills/playwright-trace/SKILL.md +171 -0
  124. patchright/driver/package/lib/tools/utils/extension.js +101 -0
  125. patchright/driver/package/lib/tools/utils/socketConnection.js +108 -0
  126. patchright/driver/package/lib/utilsBundle.js +90764 -0
  127. patchright/driver/package/lib/utilsBundle.js.LICENSE +2179 -0
  128. patchright/driver/package/lib/webp_codec.LICENSE +173 -0
  129. patchright/driver/package/lib/webp_codec.wasm +0 -0
  130. patchright/driver/package/lib/xdg-open +1267 -0
  131. patchright/driver/package/package.json +34 -0
  132. patchright/py.typed +0 -0
  133. patchright/sync_api/__init__.py +234 -0
  134. patchright/sync_api/_context_manager.py +73 -0
  135. patchright/sync_api/_generated.py +23590 -0
  136. pure_patchright-1.62.3.dist-info/LICENSE +201 -0
  137. pure_patchright-1.62.3.dist-info/METADATA +96 -0
  138. pure_patchright-1.62.3.dist-info/RECORD +142 -0
  139. pure_patchright-1.62.3.dist-info/WHEEL +4 -0
  140. pure_patchright-1.62.3.dist-info/entry_points.txt +5 -0
  141. pure_patchright-1.62.3.dist-info/licenses/LICENSE +202 -0
  142. pure_patchright-1.62.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,592 @@
1
+ import base64
2
+ import json
3
+ import mimetypes
4
+ import pathlib
5
+ import typing
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional, Union, cast
8
+ import patchright._impl._network as network
9
+ from patchright._impl._api_structures import (
10
+ ClientCertificate,
11
+ FilePayload,
12
+ FormField,
13
+ Headers,
14
+ HttpCredentials,
15
+ ProxySettings,
16
+ RemoteAddr,
17
+ ResourceTiming,
18
+ SecurityDetails,
19
+ ServerFilePayload,
20
+ StorageState,
21
+ )
22
+ from patchright._impl._connection import ChannelOwner, from_channel
23
+ from patchright._impl._errors import is_target_closed_error
24
+ from patchright._impl._form_data import FormData
25
+ from patchright._impl._helper import (
26
+ Error,
27
+ NameValue,
28
+ TargetClosedError,
29
+ TimeoutSettings,
30
+ async_readfile,
31
+ async_writefile,
32
+ is_file_payload,
33
+ locals_to_params,
34
+ object_to_array,
35
+ to_impl,
36
+ )
37
+ from patchright._impl._network import serialize_headers, to_client_certificates_protocol
38
+ from patchright._impl._tracing import Tracing
39
+
40
+ if typing.TYPE_CHECKING:
41
+ from patchright._impl._playwright import Playwright
42
+ FormType = Union[Dict[str, Union[bool, float, str]], FormData]
43
+ DataType = Union[Any, bytes, str]
44
+ MultipartType = Union[Dict[str, Union[bytes, bool, float, str, FilePayload]], FormData]
45
+ ParamsType = Union[Dict[str, Union[bool, float, str]], str]
46
+
47
+
48
+ class APIRequest:
49
+ def __init__(self, playwright: "Playwright") -> None:
50
+ self.playwright = playwright
51
+ self._loop = playwright._loop
52
+ self._dispatcher_fiber = playwright._connection._dispatcher_fiber
53
+
54
+ async def new_context(
55
+ self,
56
+ baseURL: str = None,
57
+ extraHTTPHeaders: Dict[str, str] = None,
58
+ httpCredentials: HttpCredentials = None,
59
+ ignoreHTTPSErrors: bool = None,
60
+ proxy: ProxySettings = None,
61
+ userAgent: str = None,
62
+ timeout: float = None,
63
+ storageState: Union[StorageState, str, Path] = None,
64
+ clientCertificates: List[ClientCertificate] = None,
65
+ failOnStatusCode: bool = None,
66
+ maxRedirects: int = None,
67
+ ) -> "APIRequestContext":
68
+ params = locals_to_params(locals())
69
+ if "storageState" in params:
70
+ storage_state = params["storageState"]
71
+ if not isinstance(storage_state, dict) and storage_state:
72
+ params["storageState"] = json.loads(
73
+ (await async_readfile(storage_state)).decode()
74
+ )
75
+ if "extraHTTPHeaders" in params:
76
+ params["extraHTTPHeaders"] = serialize_headers(params["extraHTTPHeaders"])
77
+ params["clientCertificates"] = await to_client_certificates_protocol(
78
+ params.get("clientCertificates")
79
+ )
80
+ context = cast(
81
+ APIRequestContext,
82
+ from_channel(
83
+ await self.playwright._channel.send("newRequest", None, params)
84
+ ),
85
+ )
86
+ context._timeout_settings.set_default_timeout(timeout)
87
+ return context
88
+
89
+
90
+ class APIRequestContext(ChannelOwner):
91
+ def __init__(
92
+ self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
93
+ ) -> None:
94
+ super().__init__(parent, type, guid, initializer)
95
+ self._tracing: Tracing = from_channel(initializer["tracing"])
96
+ self._close_reason: Optional[str] = None
97
+ self._timeout_settings = TimeoutSettings(None)
98
+
99
+ async def dispose(self, reason: str = None) -> None:
100
+ self._close_reason = reason
101
+ await self._tracing._export_all_hars()
102
+ try:
103
+ await self._channel.send("dispose", None, {"reason": reason})
104
+ except Error as e:
105
+ if is_target_closed_error(e):
106
+ return
107
+ raise e
108
+ self._tracing._reset_stack_counter()
109
+
110
+ @property
111
+ def tracing(self) -> Tracing:
112
+ return self._tracing
113
+
114
+ async def delete(
115
+ self,
116
+ url: str,
117
+ params: ParamsType = None,
118
+ headers: Headers = None,
119
+ data: DataType = None,
120
+ form: FormType = None,
121
+ multipart: MultipartType = None,
122
+ timeout: float = None,
123
+ failOnStatusCode: bool = None,
124
+ ignoreHTTPSErrors: bool = None,
125
+ maxRedirects: int = None,
126
+ maxRetries: int = None,
127
+ ) -> "APIResponse":
128
+ return await self.fetch(
129
+ url,
130
+ method="DELETE",
131
+ params=params,
132
+ headers=headers,
133
+ data=data,
134
+ form=form,
135
+ multipart=multipart,
136
+ timeout=timeout,
137
+ failOnStatusCode=failOnStatusCode,
138
+ ignoreHTTPSErrors=ignoreHTTPSErrors,
139
+ maxRedirects=maxRedirects,
140
+ maxRetries=maxRetries,
141
+ )
142
+
143
+ async def head(
144
+ self,
145
+ url: str,
146
+ params: ParamsType = None,
147
+ headers: Headers = None,
148
+ data: DataType = None,
149
+ form: FormType = None,
150
+ multipart: MultipartType = None,
151
+ timeout: float = None,
152
+ failOnStatusCode: bool = None,
153
+ ignoreHTTPSErrors: bool = None,
154
+ maxRedirects: int = None,
155
+ maxRetries: int = None,
156
+ ) -> "APIResponse":
157
+ return await self.fetch(
158
+ url,
159
+ method="HEAD",
160
+ params=params,
161
+ headers=headers,
162
+ data=data,
163
+ form=form,
164
+ multipart=multipart,
165
+ timeout=timeout,
166
+ failOnStatusCode=failOnStatusCode,
167
+ ignoreHTTPSErrors=ignoreHTTPSErrors,
168
+ maxRedirects=maxRedirects,
169
+ maxRetries=maxRetries,
170
+ )
171
+
172
+ async def get(
173
+ self,
174
+ url: str,
175
+ params: ParamsType = None,
176
+ headers: Headers = None,
177
+ data: DataType = None,
178
+ form: FormType = None,
179
+ multipart: MultipartType = None,
180
+ timeout: float = None,
181
+ failOnStatusCode: bool = None,
182
+ ignoreHTTPSErrors: bool = None,
183
+ maxRedirects: int = None,
184
+ maxRetries: int = None,
185
+ ) -> "APIResponse":
186
+ return await self.fetch(
187
+ url,
188
+ method="GET",
189
+ params=params,
190
+ headers=headers,
191
+ data=data,
192
+ form=form,
193
+ multipart=multipart,
194
+ timeout=timeout,
195
+ failOnStatusCode=failOnStatusCode,
196
+ ignoreHTTPSErrors=ignoreHTTPSErrors,
197
+ maxRedirects=maxRedirects,
198
+ maxRetries=maxRetries,
199
+ )
200
+
201
+ async def patch(
202
+ self,
203
+ url: str,
204
+ params: ParamsType = None,
205
+ headers: Headers = None,
206
+ data: DataType = None,
207
+ form: FormType = None,
208
+ multipart: MultipartType = None,
209
+ timeout: float = None,
210
+ failOnStatusCode: bool = None,
211
+ ignoreHTTPSErrors: bool = None,
212
+ maxRedirects: int = None,
213
+ maxRetries: int = None,
214
+ ) -> "APIResponse":
215
+ return await self.fetch(
216
+ url,
217
+ method="PATCH",
218
+ params=params,
219
+ headers=headers,
220
+ data=data,
221
+ form=form,
222
+ multipart=multipart,
223
+ timeout=timeout,
224
+ failOnStatusCode=failOnStatusCode,
225
+ ignoreHTTPSErrors=ignoreHTTPSErrors,
226
+ maxRedirects=maxRedirects,
227
+ maxRetries=maxRetries,
228
+ )
229
+
230
+ async def put(
231
+ self,
232
+ url: str,
233
+ params: ParamsType = None,
234
+ headers: Headers = None,
235
+ data: DataType = None,
236
+ form: FormType = None,
237
+ multipart: MultipartType = None,
238
+ timeout: float = None,
239
+ failOnStatusCode: bool = None,
240
+ ignoreHTTPSErrors: bool = None,
241
+ maxRedirects: int = None,
242
+ maxRetries: int = None,
243
+ ) -> "APIResponse":
244
+ return await self.fetch(
245
+ url,
246
+ method="PUT",
247
+ params=params,
248
+ headers=headers,
249
+ data=data,
250
+ form=form,
251
+ multipart=multipart,
252
+ timeout=timeout,
253
+ failOnStatusCode=failOnStatusCode,
254
+ ignoreHTTPSErrors=ignoreHTTPSErrors,
255
+ maxRedirects=maxRedirects,
256
+ maxRetries=maxRetries,
257
+ )
258
+
259
+ async def post(
260
+ self,
261
+ url: str,
262
+ params: ParamsType = None,
263
+ headers: Headers = None,
264
+ data: DataType = None,
265
+ form: FormType = None,
266
+ multipart: MultipartType = None,
267
+ timeout: float = None,
268
+ failOnStatusCode: bool = None,
269
+ ignoreHTTPSErrors: bool = None,
270
+ maxRedirects: int = None,
271
+ maxRetries: int = None,
272
+ ) -> "APIResponse":
273
+ return await self.fetch(
274
+ url,
275
+ method="POST",
276
+ params=params,
277
+ headers=headers,
278
+ data=data,
279
+ form=form,
280
+ multipart=multipart,
281
+ timeout=timeout,
282
+ failOnStatusCode=failOnStatusCode,
283
+ ignoreHTTPSErrors=ignoreHTTPSErrors,
284
+ maxRedirects=maxRedirects,
285
+ maxRetries=maxRetries,
286
+ )
287
+
288
+ async def fetch(
289
+ self,
290
+ urlOrRequest: Union[str, network.Request],
291
+ params: ParamsType = None,
292
+ method: str = None,
293
+ headers: Headers = None,
294
+ data: DataType = None,
295
+ form: FormType = None,
296
+ multipart: MultipartType = None,
297
+ timeout: float = None,
298
+ failOnStatusCode: bool = None,
299
+ ignoreHTTPSErrors: bool = None,
300
+ maxRedirects: int = None,
301
+ maxRetries: int = None,
302
+ ) -> "APIResponse":
303
+ url = urlOrRequest if isinstance(urlOrRequest, str) else None
304
+ request = (
305
+ cast(network.Request, to_impl(urlOrRequest))
306
+ if isinstance(to_impl(urlOrRequest), network.Request)
307
+ else None
308
+ )
309
+ assert request or isinstance(urlOrRequest, str), (
310
+ "First argument must be either URL string or Request"
311
+ )
312
+ return await self._inner_fetch(
313
+ request,
314
+ url,
315
+ method,
316
+ headers,
317
+ data,
318
+ params,
319
+ form,
320
+ multipart,
321
+ timeout,
322
+ failOnStatusCode,
323
+ ignoreHTTPSErrors,
324
+ maxRedirects,
325
+ maxRetries,
326
+ )
327
+
328
+ async def _inner_fetch(
329
+ self,
330
+ request: Optional[network.Request],
331
+ url: Optional[str],
332
+ method: str = None,
333
+ headers: Headers = None,
334
+ data: DataType = None,
335
+ params: ParamsType = None,
336
+ form: FormType = None,
337
+ multipart: MultipartType = None,
338
+ timeout: float = None,
339
+ failOnStatusCode: bool = None,
340
+ ignoreHTTPSErrors: bool = None,
341
+ maxRedirects: int = None,
342
+ maxRetries: int = None,
343
+ ) -> "APIResponse":
344
+ if self._close_reason:
345
+ raise TargetClosedError(self._close_reason)
346
+ assert (1 if data else 0) + (1 if form else 0) + (1 if multipart else 0) <= 1, (
347
+ "Only one of 'data', 'form' or 'multipart' can be specified"
348
+ )
349
+ assert maxRedirects is None or maxRedirects >= 0, (
350
+ "'max_redirects' must be greater than or equal to '0'"
351
+ )
352
+ assert maxRetries is None or maxRetries >= 0, (
353
+ "'max_retries' must be greater than or equal to '0'"
354
+ )
355
+ url = url or (request.url if request else url)
356
+ method = method or (request.method if request else "GET")
357
+ headers_obj = headers or (request.headers if request else None)
358
+ serialized_headers = serialize_headers(headers_obj) if headers_obj else None
359
+ json_data: Any = None
360
+ form_data: Optional[List[NameValue]] = None
361
+ multipart_data: Optional[List[FormField]] = None
362
+ post_data_buffer: Optional[bytes] = None
363
+ if data is not None:
364
+ if isinstance(data, str):
365
+ if is_json_content_type(serialized_headers):
366
+ json_data = data if is_json_parsable(data) else json.dumps(data)
367
+ else:
368
+ post_data_buffer = data.encode()
369
+ elif isinstance(data, bytes):
370
+ post_data_buffer = data
371
+ elif isinstance(data, (dict, list, int, bool)):
372
+ json_data = json.dumps(data)
373
+ else:
374
+ raise Error(f"Unsupported 'data' type: {type(data)}")
375
+ elif form:
376
+ if isinstance(form, FormData):
377
+ form_data = []
378
+ for fd_name, fd_value in form._fields:
379
+ if isinstance(fd_value, (pathlib.Path, dict)):
380
+ raise Error(
381
+ f"Form field {fd_name!r} must be a string, number or boolean. Use 'multipart' for file uploads."
382
+ )
383
+ form_data.append(NameValue(name=fd_name, value=str(fd_value)))
384
+ else:
385
+ form_data = object_to_array(form)
386
+ elif multipart:
387
+ multipart_data = []
388
+ if isinstance(multipart, FormData):
389
+ for fd_name, fd_value in multipart._fields:
390
+ multipart_data.append(
391
+ await _form_data_field_to_form_field(fd_name, fd_value)
392
+ )
393
+ else:
394
+ for name, value in multipart.items():
395
+ if is_file_payload(value):
396
+ payload = cast(FilePayload, value)
397
+ assert isinstance(payload["buffer"], bytes), (
398
+ f"Unexpected buffer type of 'data.{name}'"
399
+ )
400
+ multipart_data.append(
401
+ FormField(name=name, file=file_payload_to_json(payload))
402
+ )
403
+ elif isinstance(value, str):
404
+ multipart_data.append(FormField(name=name, value=value))
405
+ if (
406
+ post_data_buffer is None
407
+ and json_data is None
408
+ and (form_data is None)
409
+ and (multipart_data is None)
410
+ ):
411
+ post_data_buffer = request.post_data_buffer if request else None
412
+ post_data = (
413
+ base64.b64encode(post_data_buffer).decode() if post_data_buffer else None
414
+ )
415
+ response = await self._channel.send(
416
+ "fetch",
417
+ self._timeout_settings.timeout,
418
+ {
419
+ "url": url,
420
+ "timeout": timeout,
421
+ "params": object_to_array(params) if isinstance(params, dict) else None,
422
+ "encodedParams": params if isinstance(params, str) else None,
423
+ "method": method,
424
+ "headers": serialized_headers,
425
+ "postData": post_data,
426
+ "jsonData": json_data,
427
+ "formData": form_data,
428
+ "multipartData": multipart_data,
429
+ "failOnStatusCode": failOnStatusCode,
430
+ "ignoreHTTPSErrors": ignoreHTTPSErrors,
431
+ "maxRedirects": maxRedirects,
432
+ "maxRetries": maxRetries,
433
+ },
434
+ )
435
+ return APIResponse(self, response)
436
+
437
+ async def storage_state(
438
+ self, path: Union[pathlib.Path, str] = None, indexedDB: bool = None
439
+ ) -> StorageState:
440
+ result = await self._channel.send_return_as_dict(
441
+ "storageState", None, {"indexedDB": indexedDB}
442
+ )
443
+ if path:
444
+ await async_writefile(path, json.dumps(result))
445
+ return result
446
+
447
+
448
+ def file_payload_to_json(payload: FilePayload) -> ServerFilePayload:
449
+ return ServerFilePayload(
450
+ name=payload["name"],
451
+ mimeType=payload["mimeType"],
452
+ buffer=base64.b64encode(payload["buffer"]).decode(),
453
+ )
454
+
455
+
456
+ async def _form_data_field_to_form_field(name: str, value: Any) -> FormField:
457
+ if isinstance(value, pathlib.Path):
458
+ mime_type, _ = mimetypes.guess_type(str(value))
459
+ return FormField(
460
+ name=name,
461
+ file=ServerFilePayload(
462
+ name=value.name,
463
+ mimeType=mime_type or "application/octet-stream",
464
+ buffer=base64.b64encode(await async_readfile(str(value))).decode(),
465
+ ),
466
+ )
467
+ if is_file_payload(value):
468
+ payload = cast(FilePayload, value)
469
+ assert isinstance(payload["buffer"], bytes), (
470
+ f"Unexpected buffer type of form field {name!r}"
471
+ )
472
+ return FormField(name=name, file=file_payload_to_json(payload))
473
+ if isinstance(value, (str, int, float, bool)):
474
+ return FormField(name=name, value=str(value))
475
+ raise Error(f"Unsupported form field {name!r} value type: {type(value).__name__}")
476
+
477
+
478
+ class APIResponse:
479
+ def __init__(self, context: APIRequestContext, initializer: Dict) -> None:
480
+ self._loop = context._loop
481
+ self._dispatcher_fiber = context._connection._dispatcher_fiber
482
+ self._request = context
483
+ self._initializer = initializer
484
+ self._headers = network.RawHeaders(initializer["headers"])
485
+
486
+ def __repr__(self) -> str:
487
+ return f"<APIResponse url={self.url!r} status={self.status!r} status_text={self.status_text!r}>"
488
+
489
+ @property
490
+ def ok(self) -> bool:
491
+ return self.status >= 200 and self.status <= 299
492
+
493
+ @property
494
+ def url(self) -> str:
495
+ return self._initializer["url"]
496
+
497
+ @property
498
+ def status(self) -> int:
499
+ return self._initializer["status"]
500
+
501
+ @property
502
+ def status_text(self) -> str:
503
+ return self._initializer["statusText"]
504
+
505
+ @property
506
+ def headers(self) -> Headers:
507
+ return self._headers.headers()
508
+
509
+ @property
510
+ def headers_array(self) -> network.HeadersArray:
511
+ return self._headers.headers_array()
512
+
513
+ @property
514
+ def timing(self) -> ResourceTiming:
515
+ return cast(
516
+ ResourceTiming,
517
+ {
518
+ "startTime": -1,
519
+ "domainLookupStart": -1,
520
+ "domainLookupEnd": -1,
521
+ "connectStart": -1,
522
+ "secureConnectionStart": -1,
523
+ "connectEnd": -1,
524
+ "requestStart": -1,
525
+ "responseStart": -1,
526
+ **self._initializer.get("timing", {}),
527
+ "responseEnd": self._initializer.get("responseEndTiming", -1),
528
+ },
529
+ )
530
+
531
+ async def body(self) -> bytes:
532
+ try:
533
+ result = await self._request._connection.wrap_api_call(
534
+ lambda: self._request._channel.send_return_as_dict(
535
+ "fetchResponseBody", None, {"fetchUid": self._fetch_uid}
536
+ ),
537
+ True,
538
+ )
539
+ if result is None:
540
+ raise Error("Response has been disposed")
541
+ return base64.b64decode(result["binary"])
542
+ except Error as exc:
543
+ if is_target_closed_error(exc):
544
+ raise Error("Response has been disposed")
545
+ raise exc
546
+
547
+ async def text(self) -> str:
548
+ content = await self.body()
549
+ return content.decode()
550
+
551
+ async def json(self) -> Any:
552
+ content = await self.text()
553
+ return json.loads(content)
554
+
555
+ async def security_details(self) -> Optional[SecurityDetails]:
556
+ return self._initializer.get("securityDetails") or None
557
+
558
+ async def server_addr(self) -> Optional[RemoteAddr]:
559
+ return self._initializer.get("serverAddr") or None
560
+
561
+ async def dispose(self) -> None:
562
+ await self._request._channel.send(
563
+ "disposeAPIResponse", None, {"fetchUid": self._fetch_uid}
564
+ )
565
+
566
+ @property
567
+ def _fetch_uid(self) -> str:
568
+ return self._initializer["fetchUid"]
569
+
570
+ async def _fetch_log(self) -> List[str]:
571
+ return await self._request._channel.send(
572
+ "fetchLog", None, {"fetchUid": self._fetch_uid}
573
+ )
574
+
575
+
576
+ def is_json_content_type(headers: network.HeadersArray = None) -> bool:
577
+ if not headers:
578
+ return False
579
+ for header in headers:
580
+ if header["name"] == "Content-Type":
581
+ return header["value"].startswith("application/json")
582
+ return False
583
+
584
+
585
+ def is_json_parsable(value: Any) -> bool:
586
+ if not isinstance(value, str):
587
+ return False
588
+ try:
589
+ json.loads(value)
590
+ return True
591
+ except json.JSONDecodeError:
592
+ return False
@@ -0,0 +1,42 @@
1
+ from pathlib import Path
2
+ from typing import TYPE_CHECKING, Sequence, Union
3
+ from patchright._impl._api_structures import FilePayload
4
+
5
+ if TYPE_CHECKING:
6
+ from patchright._impl._element_handle import ElementHandle
7
+ from patchright._impl._page import Page
8
+
9
+
10
+ class FileChooser:
11
+ def __init__(
12
+ self, page: "Page", element_handle: "ElementHandle", is_multiple: bool
13
+ ) -> None:
14
+ self._page = page
15
+ self._loop = page._loop
16
+ self._dispatcher_fiber = page._dispatcher_fiber
17
+ self._element_handle = element_handle
18
+ self._is_multiple = is_multiple
19
+
20
+ def __repr__(self) -> str:
21
+ return f"<FileChooser page={self._page} element={self._element_handle}>"
22
+
23
+ @property
24
+ def page(self) -> "Page":
25
+ return self._page
26
+
27
+ @property
28
+ def element(self) -> "ElementHandle":
29
+ return self._element_handle
30
+
31
+ def is_multiple(self) -> bool:
32
+ return self._is_multiple
33
+
34
+ async def set_files(
35
+ self,
36
+ files: Union[
37
+ str, Path, FilePayload, Sequence[Union[str, Path]], Sequence[FilePayload]
38
+ ],
39
+ timeout: float = None,
40
+ noWaitAfter: bool = None,
41
+ ) -> None:
42
+ await self._element_handle.set_input_files(files, timeout, noWaitAfter)
@@ -0,0 +1,19 @@
1
+ import pathlib
2
+ from typing import List, Tuple, Union
3
+ from patchright._impl._api_structures import FilePayload
4
+
5
+ FormDataValue = Union[bool, float, str, pathlib.Path, FilePayload]
6
+
7
+
8
+ class FormData:
9
+ def __init__(self) -> None:
10
+ self._fields: List[Tuple[str, FormDataValue]] = []
11
+
12
+ def set(self, name: str, value: FormDataValue) -> "FormData":
13
+ self._fields = [(n, v) for n, v in self._fields if n != name]
14
+ self._fields.append((name, value))
15
+ return self
16
+
17
+ def append(self, name: str, value: FormDataValue) -> "FormData":
18
+ self._fields.append((name, value))
19
+ return self