node-mantis 0.1.0__py3-none-win_amd64.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.
- node_mantis-0.1.0.dist-info/METADATA +296 -0
- node_mantis-0.1.0.dist-info/RECORD +31 -0
- node_mantis-0.1.0.dist-info/WHEEL +5 -0
- node_mantis-0.1.0.dist-info/entry_points.txt +3 -0
- node_mantis-0.1.0.dist-info/licenses/LICENSE.txt +18 -0
- node_mantis-0.1.0.dist-info/top_level.txt +1 -0
- nodemantis/__init__.py +116 -0
- nodemantis/__main__.py +4 -0
- nodemantis/_async.py +65 -0
- nodemantis/_constants.py +1 -0
- nodemantis/_framing.py +122 -0
- nodemantis/_host.py +152 -0
- nodemantis/_process.py +445 -0
- nodemantis/_protocol.py +126 -0
- nodemantis/_rpc.py +529 -0
- nodemantis/_runtime_bin/README.md +9 -0
- nodemantis/_runtime_bin/nodemantis-runtime.exe +0 -0
- nodemantis/_runtime_bin/runtime-manifest.json +8 -0
- nodemantis/browser.py +45 -0
- nodemantis/cli.py +236 -0
- nodemantis/config.py +116 -0
- nodemantis/errors.py +203 -0
- nodemantis/fixtures/smoke.html +22 -0
- nodemantis/managed_page.py +713 -0
- nodemantis/preflight.py +125 -0
- nodemantis/py.typed +1 -0
- nodemantis/runtime.py +74 -0
- nodemantis/runtime_broker.py +25 -0
- nodemantis/session.py +727 -0
- nodemantis/smoke.py +105 -0
- nodemantis/types.py +345 -0
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
"""Bounded asynchronous page capabilities for native raw-CDP sessions.
|
|
2
|
+
|
|
3
|
+
``ManagedPage`` deliberately is not a Playwright page. It exposes common
|
|
4
|
+
navigation and browser-state operations without selectors, page evaluation,
|
|
5
|
+
arbitrary CDP, or event registration. Mutating calls share the owning
|
|
6
|
+
session's serialized operation queue; event waits and their lifecycle handles
|
|
7
|
+
use the concurrent path so they can be armed before an agent action.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
import asyncio
|
|
14
|
+
from dataclasses import asdict, dataclass, is_dataclass
|
|
15
|
+
from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Sequence, Union
|
|
16
|
+
|
|
17
|
+
from .errors import NodeMantisError
|
|
18
|
+
from .types import BrowserGoResult, parse_go_result
|
|
19
|
+
|
|
20
|
+
ManagedCookieSameSite = Literal["Strict", "Lax", "None"]
|
|
21
|
+
ManagedDownloadState = Literal["in-progress", "completed", "cancelled", "failed"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ManagedViewport:
|
|
26
|
+
width: int
|
|
27
|
+
height: int
|
|
28
|
+
device_scale_factor: Optional[float] = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class ManagedHistoryResult:
|
|
33
|
+
navigated: bool
|
|
34
|
+
url: str
|
|
35
|
+
title: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class ManagedCookie:
|
|
40
|
+
name: str
|
|
41
|
+
value: str
|
|
42
|
+
domain: str
|
|
43
|
+
path: str
|
|
44
|
+
expires: float
|
|
45
|
+
http_only: bool
|
|
46
|
+
secure: bool
|
|
47
|
+
same_site: ManagedCookieSameSite
|
|
48
|
+
partition_key: Optional[str] = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class ManagedCookieInput:
|
|
53
|
+
name: str
|
|
54
|
+
value: str
|
|
55
|
+
url: Optional[str] = None
|
|
56
|
+
domain: Optional[str] = None
|
|
57
|
+
path: Optional[str] = None
|
|
58
|
+
expires: Optional[float] = None
|
|
59
|
+
http_only: Optional[bool] = None
|
|
60
|
+
secure: Optional[bool] = None
|
|
61
|
+
same_site: Optional[ManagedCookieSameSite] = None
|
|
62
|
+
partition_key: Optional[str] = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class ManagedStorageEntry:
|
|
68
|
+
name: str
|
|
69
|
+
value: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class ManagedOriginStorage:
|
|
74
|
+
origin: str
|
|
75
|
+
local_storage: tuple[ManagedStorageEntry, ...]
|
|
76
|
+
session_storage: tuple[ManagedStorageEntry, ...]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class ManagedStorageState:
|
|
81
|
+
cookies: tuple[ManagedCookie, ...]
|
|
82
|
+
origins: tuple[ManagedOriginStorage, ...]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class ManagedDownloadProgress:
|
|
87
|
+
state: ManagedDownloadState
|
|
88
|
+
received_bytes: float
|
|
89
|
+
total_bytes: Optional[float] = None
|
|
90
|
+
failure: Optional[str] = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
Request = Callable[[str, Optional[dict[str, Any]]], Awaitable[Any]]
|
|
94
|
+
AttachmentRequest = Callable[[str, Optional[dict[str, Any]]], Awaitable[Any]]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class ManagedPage:
|
|
98
|
+
"""Small, asynchronous page surface backed by native managed-page RPCs."""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
request: Request,
|
|
103
|
+
concurrent: Request,
|
|
104
|
+
request_attachment: AttachmentRequest,
|
|
105
|
+
) -> None:
|
|
106
|
+
self.__request = request
|
|
107
|
+
self.__concurrent = concurrent
|
|
108
|
+
self.__request_attachment = request_attachment
|
|
109
|
+
|
|
110
|
+
async def navigate(
|
|
111
|
+
self,
|
|
112
|
+
url: str,
|
|
113
|
+
*,
|
|
114
|
+
wait_until: Optional[str] = None,
|
|
115
|
+
timeout: Optional[float] = None,
|
|
116
|
+
) -> BrowserGoResult:
|
|
117
|
+
_non_empty_string(url, "url")
|
|
118
|
+
_navigation_timeout(timeout)
|
|
119
|
+
return parse_go_result(
|
|
120
|
+
await self.__request(
|
|
121
|
+
"managed/page/navigate",
|
|
122
|
+
_compact({"url": url, "waitUntil": wait_until, "timeout": timeout}),
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
async def back(
|
|
127
|
+
self,
|
|
128
|
+
*,
|
|
129
|
+
wait_until: Optional[str] = None,
|
|
130
|
+
timeout: Optional[float] = None,
|
|
131
|
+
) -> ManagedHistoryResult:
|
|
132
|
+
return await self._history("managed/page/back", wait_until, timeout)
|
|
133
|
+
|
|
134
|
+
async def forward(
|
|
135
|
+
self,
|
|
136
|
+
*,
|
|
137
|
+
wait_until: Optional[str] = None,
|
|
138
|
+
timeout: Optional[float] = None,
|
|
139
|
+
) -> ManagedHistoryResult:
|
|
140
|
+
return await self._history("managed/page/forward", wait_until, timeout)
|
|
141
|
+
|
|
142
|
+
async def reload(
|
|
143
|
+
self,
|
|
144
|
+
*,
|
|
145
|
+
wait_until: Optional[str] = None,
|
|
146
|
+
timeout: Optional[float] = None,
|
|
147
|
+
) -> BrowserGoResult:
|
|
148
|
+
_navigation_timeout(timeout)
|
|
149
|
+
return parse_go_result(
|
|
150
|
+
await self.__request(
|
|
151
|
+
"managed/page/reload",
|
|
152
|
+
_compact({"waitUntil": wait_until, "timeout": timeout}),
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
async def url(self) -> str:
|
|
157
|
+
value = await self.__request("managed/page/url", None)
|
|
158
|
+
if not isinstance(value, str):
|
|
159
|
+
raise _invalid_runtime_result("url")
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
async def title(self) -> str:
|
|
163
|
+
value = await self.__request("managed/page/title", None)
|
|
164
|
+
if not isinstance(value, str):
|
|
165
|
+
raise _invalid_runtime_result("title")
|
|
166
|
+
return value
|
|
167
|
+
|
|
168
|
+
async def screenshot(
|
|
169
|
+
self,
|
|
170
|
+
*,
|
|
171
|
+
type: Optional[str] = None, # noqa: A002 - mirrors the managed-page API
|
|
172
|
+
quality: Optional[int] = None,
|
|
173
|
+
full_page: Optional[bool] = None,
|
|
174
|
+
omit_background: Optional[bool] = None,
|
|
175
|
+
clip: Optional[Mapping[str, Any]] = None,
|
|
176
|
+
timeout: Optional[float] = None,
|
|
177
|
+
) -> bytes:
|
|
178
|
+
_validate_screenshot(
|
|
179
|
+
type, quality, full_page, omit_background, clip, timeout
|
|
180
|
+
)
|
|
181
|
+
frame = await self.__request_attachment(
|
|
182
|
+
"managed/page/screenshot",
|
|
183
|
+
_compact(
|
|
184
|
+
{
|
|
185
|
+
"type": type,
|
|
186
|
+
"quality": quality,
|
|
187
|
+
"fullPage": full_page,
|
|
188
|
+
"omitBackground": omit_background,
|
|
189
|
+
"clip": dict(clip) if clip is not None else None,
|
|
190
|
+
"timeout": timeout,
|
|
191
|
+
}
|
|
192
|
+
),
|
|
193
|
+
)
|
|
194
|
+
result = getattr(frame, "result", None)
|
|
195
|
+
attachment = getattr(frame, "attachment", None)
|
|
196
|
+
if not isinstance(result, dict) or result.get("kind") != "screenshot":
|
|
197
|
+
raise _invalid_runtime_result("screenshot")
|
|
198
|
+
if not isinstance(attachment, (bytes, bytearray, memoryview)):
|
|
199
|
+
raise _invalid_runtime_result("screenshot")
|
|
200
|
+
return bytes(attachment)
|
|
201
|
+
|
|
202
|
+
async def cookies(
|
|
203
|
+
self, urls: Optional[Union[str, Sequence[str]]] = None
|
|
204
|
+
) -> tuple[ManagedCookie, ...]:
|
|
205
|
+
normalized: Optional[list[str]]
|
|
206
|
+
if urls is None:
|
|
207
|
+
normalized = None
|
|
208
|
+
elif isinstance(urls, str):
|
|
209
|
+
normalized = [urls]
|
|
210
|
+
elif isinstance(urls, Sequence) and all(
|
|
211
|
+
isinstance(url, str) for url in urls
|
|
212
|
+
):
|
|
213
|
+
normalized = list(urls)
|
|
214
|
+
else:
|
|
215
|
+
raise TypeError("urls must be a string or a sequence of strings")
|
|
216
|
+
value = await self.__request(
|
|
217
|
+
"managed/page/cookies/get", _compact({"urls": normalized})
|
|
218
|
+
)
|
|
219
|
+
if not isinstance(value, list):
|
|
220
|
+
raise _invalid_runtime_result("cookies/get")
|
|
221
|
+
try:
|
|
222
|
+
return tuple(_parse_cookie(item) for item in value)
|
|
223
|
+
except (TypeError, ValueError) as error:
|
|
224
|
+
raise _invalid_runtime_result("cookies/get") from error
|
|
225
|
+
|
|
226
|
+
async def set_cookies(
|
|
227
|
+
self,
|
|
228
|
+
cookies: Sequence[Union[ManagedCookieInput, Mapping[str, Any]]],
|
|
229
|
+
) -> None:
|
|
230
|
+
if (
|
|
231
|
+
isinstance(cookies, (str, bytes))
|
|
232
|
+
or not isinstance(cookies, Sequence)
|
|
233
|
+
or not cookies
|
|
234
|
+
):
|
|
235
|
+
raise ValueError("cookies must contain at least one cookie")
|
|
236
|
+
normalized = [_cookie_input_wire(cookie) for cookie in cookies]
|
|
237
|
+
await self.__request("managed/page/cookies/set", {"cookies": normalized})
|
|
238
|
+
|
|
239
|
+
async def storage_state(self) -> ManagedStorageState:
|
|
240
|
+
value = await self.__request("managed/page/storage/get", None)
|
|
241
|
+
try:
|
|
242
|
+
return _parse_storage_state(value)
|
|
243
|
+
except (TypeError, ValueError) as error:
|
|
244
|
+
raise _invalid_runtime_result("storage/get") from error
|
|
245
|
+
|
|
246
|
+
async def restore_storage(
|
|
247
|
+
self, state: Union[ManagedStorageState, Mapping[str, Any]]
|
|
248
|
+
) -> None:
|
|
249
|
+
normalized = _storage_state_wire(state)
|
|
250
|
+
await self.__request("managed/page/storage/restore", {"state": normalized})
|
|
251
|
+
|
|
252
|
+
async def viewport(self) -> ManagedViewport:
|
|
253
|
+
value = await self.__request("managed/page/viewport/get", None)
|
|
254
|
+
try:
|
|
255
|
+
return _parse_viewport(value)
|
|
256
|
+
except (TypeError, ValueError) as error:
|
|
257
|
+
raise _invalid_runtime_result("viewport/get") from error
|
|
258
|
+
|
|
259
|
+
async def set_viewport(
|
|
260
|
+
self, viewport: Union[ManagedViewport, Mapping[str, Any]]
|
|
261
|
+
) -> None:
|
|
262
|
+
normalized = _viewport_wire(viewport)
|
|
263
|
+
await self.__request("managed/page/viewport/set", {"viewport": normalized})
|
|
264
|
+
|
|
265
|
+
async def wait_for_file_chooser(
|
|
266
|
+
self, *, timeout: Optional[float] = None
|
|
267
|
+
) -> "ManagedFileChooser":
|
|
268
|
+
_non_negative_number(timeout, "file chooser timeout")
|
|
269
|
+
value = await self.__concurrent(
|
|
270
|
+
"managed/page/file-chooser/wait", _compact({"timeout": timeout})
|
|
271
|
+
)
|
|
272
|
+
if (
|
|
273
|
+
not isinstance(value, dict)
|
|
274
|
+
or not isinstance(value.get("id"), str)
|
|
275
|
+
or not value["id"]
|
|
276
|
+
or not isinstance(value.get("multiple"), bool)
|
|
277
|
+
or not isinstance(value.get("accept"), list)
|
|
278
|
+
or not all(isinstance(item, str) for item in value["accept"])
|
|
279
|
+
):
|
|
280
|
+
raise _invalid_runtime_result("file-chooser/wait")
|
|
281
|
+
return ManagedFileChooser(
|
|
282
|
+
self.__concurrent,
|
|
283
|
+
value["id"],
|
|
284
|
+
value["multiple"],
|
|
285
|
+
tuple(value["accept"]),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
async def wait_for_download(
|
|
289
|
+
self, *, timeout: Optional[float] = None
|
|
290
|
+
) -> "ManagedDownload":
|
|
291
|
+
_non_negative_number(timeout, "download timeout")
|
|
292
|
+
value = await self.__concurrent(
|
|
293
|
+
"managed/page/download/wait", _compact({"timeout": timeout})
|
|
294
|
+
)
|
|
295
|
+
if (
|
|
296
|
+
not isinstance(value, dict)
|
|
297
|
+
or not isinstance(value.get("id"), str)
|
|
298
|
+
or not value["id"]
|
|
299
|
+
or not isinstance(value.get("url"), str)
|
|
300
|
+
or not isinstance(value.get("suggestedFilename"), str)
|
|
301
|
+
):
|
|
302
|
+
raise _invalid_runtime_result("download/wait")
|
|
303
|
+
return ManagedDownload(
|
|
304
|
+
self.__concurrent,
|
|
305
|
+
value["id"],
|
|
306
|
+
value["url"],
|
|
307
|
+
value["suggestedFilename"],
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
async def _history(
|
|
311
|
+
self, method: str, wait_until: Optional[str], timeout: Optional[float]
|
|
312
|
+
) -> ManagedHistoryResult:
|
|
313
|
+
_navigation_timeout(timeout)
|
|
314
|
+
value = await self.__request(
|
|
315
|
+
method, _compact({"waitUntil": wait_until, "timeout": timeout})
|
|
316
|
+
)
|
|
317
|
+
if (
|
|
318
|
+
not isinstance(value, dict)
|
|
319
|
+
or not isinstance(value.get("navigated"), bool)
|
|
320
|
+
or not isinstance(value.get("url"), str)
|
|
321
|
+
or not isinstance(value.get("title"), str)
|
|
322
|
+
):
|
|
323
|
+
raise _invalid_runtime_result(method.rsplit("/", 1)[-1])
|
|
324
|
+
return ManagedHistoryResult(value["navigated"], value["url"], value["title"])
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class ManagedFileChooser:
|
|
328
|
+
def __init__(
|
|
329
|
+
self,
|
|
330
|
+
concurrent: Request,
|
|
331
|
+
chooser_id: str,
|
|
332
|
+
multiple: bool,
|
|
333
|
+
accept: tuple[str, ...],
|
|
334
|
+
) -> None:
|
|
335
|
+
self.id = chooser_id
|
|
336
|
+
self.multiple = multiple
|
|
337
|
+
self.accept = accept
|
|
338
|
+
self.__concurrent = concurrent
|
|
339
|
+
self._handled = False
|
|
340
|
+
self._lock = asyncio.Lock()
|
|
341
|
+
|
|
342
|
+
async def set_files(self, paths: Union[str, Sequence[str]]) -> None:
|
|
343
|
+
normalized = [paths] if isinstance(paths, str) else list(paths)
|
|
344
|
+
if not normalized or any(
|
|
345
|
+
not isinstance(path, str) or not path for path in normalized
|
|
346
|
+
):
|
|
347
|
+
raise ValueError("paths must contain at least one non-empty file path")
|
|
348
|
+
async with self._lock:
|
|
349
|
+
self._assert_pending()
|
|
350
|
+
await self.__concurrent(
|
|
351
|
+
"managed/page/file-chooser/set-files",
|
|
352
|
+
{"chooserId": self.id, "paths": normalized},
|
|
353
|
+
)
|
|
354
|
+
self._handled = True
|
|
355
|
+
|
|
356
|
+
async def cancel(self) -> None:
|
|
357
|
+
async with self._lock:
|
|
358
|
+
self._assert_pending()
|
|
359
|
+
await self.__concurrent(
|
|
360
|
+
"managed/page/file-chooser/cancel", {"chooserId": self.id}
|
|
361
|
+
)
|
|
362
|
+
self._handled = True
|
|
363
|
+
|
|
364
|
+
def _assert_pending(self) -> None:
|
|
365
|
+
if self._handled:
|
|
366
|
+
raise NodeMantisError("Managed file chooser is already handled")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
class ManagedDownload:
|
|
370
|
+
def __init__(
|
|
371
|
+
self,
|
|
372
|
+
concurrent: Request,
|
|
373
|
+
download_id: str,
|
|
374
|
+
url: str,
|
|
375
|
+
suggested_filename: str,
|
|
376
|
+
) -> None:
|
|
377
|
+
self.id = download_id
|
|
378
|
+
self.url = url
|
|
379
|
+
self.suggested_filename = suggested_filename
|
|
380
|
+
self.__concurrent = concurrent
|
|
381
|
+
|
|
382
|
+
async def progress(self) -> ManagedDownloadProgress:
|
|
383
|
+
return await self._progress("managed/page/download/progress", {})
|
|
384
|
+
|
|
385
|
+
async def wait_for_completion(
|
|
386
|
+
self, *, timeout: Optional[float] = None
|
|
387
|
+
) -> ManagedDownloadProgress:
|
|
388
|
+
_non_negative_number(timeout, "download completion timeout")
|
|
389
|
+
return await self._progress(
|
|
390
|
+
"managed/page/download/wait-complete", _compact({"timeout": timeout})
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
async def save_as(self, path: str) -> None:
|
|
394
|
+
_non_empty_string(path, "path")
|
|
395
|
+
await self.__concurrent(
|
|
396
|
+
"managed/page/download/save", {"downloadId": self.id, "path": path}
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
async def cancel(self) -> None:
|
|
400
|
+
await self.__concurrent("managed/page/download/cancel", {"downloadId": self.id})
|
|
401
|
+
|
|
402
|
+
async def _progress(
|
|
403
|
+
self, method: str, params: dict[str, Any]
|
|
404
|
+
) -> ManagedDownloadProgress:
|
|
405
|
+
value = await self.__concurrent(method, {"downloadId": self.id, **params})
|
|
406
|
+
if not isinstance(value, dict):
|
|
407
|
+
raise _invalid_runtime_result(method)
|
|
408
|
+
state = value.get("state")
|
|
409
|
+
received = value.get("receivedBytes")
|
|
410
|
+
total = value.get("totalBytes")
|
|
411
|
+
failure = value.get("failure")
|
|
412
|
+
if (
|
|
413
|
+
state not in {"in-progress", "completed", "cancelled", "failed"}
|
|
414
|
+
or not _is_non_negative_number(received)
|
|
415
|
+
or (total is not None and not _is_non_negative_number(total))
|
|
416
|
+
or (failure is not None and not isinstance(failure, str))
|
|
417
|
+
):
|
|
418
|
+
raise _invalid_runtime_result(method)
|
|
419
|
+
return ManagedDownloadProgress(state, received, total, failure)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _compact(record: dict[str, Any]) -> dict[str, Any]:
|
|
423
|
+
return {key: value for key, value in record.items() if value is not None}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _invalid_runtime_result(operation: str) -> NodeMantisError:
|
|
427
|
+
return NodeMantisError(
|
|
428
|
+
f"Native runtime returned an invalid managed page result for {operation}"
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _non_empty_string(value: Any, field: str) -> None:
|
|
433
|
+
if not isinstance(value, str) or not value:
|
|
434
|
+
raise ValueError(f"{field} must not be empty")
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _is_number(value: Any) -> bool:
|
|
438
|
+
return (
|
|
439
|
+
isinstance(value, (int, float))
|
|
440
|
+
and not isinstance(value, bool)
|
|
441
|
+
and math.isfinite(value)
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _is_non_negative_number(value: Any) -> bool:
|
|
446
|
+
return _is_number(value) and value >= 0
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _non_negative_number(value: Any, field: str) -> None:
|
|
450
|
+
if value is not None and not _is_non_negative_number(value):
|
|
451
|
+
raise ValueError(f"{field} must be a non-negative finite number")
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _navigation_timeout(timeout: Any) -> None:
|
|
455
|
+
_non_negative_number(timeout, "navigation timeout")
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _validate_screenshot(
|
|
459
|
+
image_type: Optional[str],
|
|
460
|
+
quality: Optional[int],
|
|
461
|
+
full_page: Optional[bool],
|
|
462
|
+
omit_background: Optional[bool],
|
|
463
|
+
clip: Optional[Mapping[str, Any]],
|
|
464
|
+
timeout: Optional[float],
|
|
465
|
+
) -> None:
|
|
466
|
+
if image_type is not None and image_type not in {"png", "jpeg", "webp"}:
|
|
467
|
+
raise ValueError("screenshot type must be png, jpeg, or webp")
|
|
468
|
+
if quality is not None and (
|
|
469
|
+
not isinstance(quality, int)
|
|
470
|
+
or isinstance(quality, bool)
|
|
471
|
+
or quality < 0
|
|
472
|
+
or quality > 100
|
|
473
|
+
):
|
|
474
|
+
raise ValueError("screenshot quality must be an integer from 0 to 100")
|
|
475
|
+
if image_type == "png" and quality is not None:
|
|
476
|
+
raise ValueError("screenshot quality is unavailable for PNG images")
|
|
477
|
+
if full_page is not None and not isinstance(full_page, bool):
|
|
478
|
+
raise TypeError("screenshot full_page must be a boolean")
|
|
479
|
+
if omit_background is not None and not isinstance(omit_background, bool):
|
|
480
|
+
raise TypeError("screenshot omit_background must be a boolean")
|
|
481
|
+
if full_page is True and clip is not None:
|
|
482
|
+
raise ValueError("screenshot full_page and clip cannot be combined")
|
|
483
|
+
if clip is not None:
|
|
484
|
+
if not isinstance(clip, Mapping):
|
|
485
|
+
raise TypeError("screenshot clip must be a mapping")
|
|
486
|
+
values = [clip.get(field) for field in ("x", "y", "width", "height")]
|
|
487
|
+
if not all(_is_number(value) for value in values) or values[2] <= 0 or values[3] <= 0:
|
|
488
|
+
raise ValueError(
|
|
489
|
+
"screenshot clip must have finite coordinates and positive dimensions"
|
|
490
|
+
)
|
|
491
|
+
_non_negative_number(timeout, "screenshot timeout")
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _mapping(value: Any, name: str) -> dict[str, Any]:
|
|
495
|
+
if is_dataclass(value) and not isinstance(value, type):
|
|
496
|
+
return asdict(value)
|
|
497
|
+
if isinstance(value, Mapping):
|
|
498
|
+
return dict(value)
|
|
499
|
+
raise TypeError(f"{name} must be a mapping or managed-page dataclass")
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _rename(record: dict[str, Any], names: dict[str, str], where: str) -> dict[str, Any]:
|
|
503
|
+
wire: dict[str, Any] = {}
|
|
504
|
+
for key, value in record.items():
|
|
505
|
+
if value is None:
|
|
506
|
+
continue
|
|
507
|
+
wire_key = names.get(key)
|
|
508
|
+
if wire_key is None:
|
|
509
|
+
raise TypeError(f"Unknown field {key!r} for {where}")
|
|
510
|
+
if wire_key in wire:
|
|
511
|
+
raise TypeError(f"Duplicate field {wire_key!r} for {where}")
|
|
512
|
+
wire[wire_key] = value
|
|
513
|
+
return wire
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
_COOKIE_NAMES = {
|
|
517
|
+
"name": "name",
|
|
518
|
+
"value": "value",
|
|
519
|
+
"url": "url",
|
|
520
|
+
"domain": "domain",
|
|
521
|
+
"path": "path",
|
|
522
|
+
"expires": "expires",
|
|
523
|
+
"http_only": "httpOnly",
|
|
524
|
+
"httpOnly": "httpOnly",
|
|
525
|
+
"secure": "secure",
|
|
526
|
+
"same_site": "sameSite",
|
|
527
|
+
"sameSite": "sameSite",
|
|
528
|
+
"partition_key": "partitionKey",
|
|
529
|
+
"partitionKey": "partitionKey",
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _cookie_input_wire(value: Any) -> dict[str, Any]:
|
|
534
|
+
wire = _rename(_mapping(value, "cookie"), _COOKIE_NAMES, "cookie")
|
|
535
|
+
if not isinstance(wire.get("name"), str) or not wire["name"]:
|
|
536
|
+
raise ValueError("cookie name must not be empty")
|
|
537
|
+
if not isinstance(wire.get("value"), str):
|
|
538
|
+
raise TypeError("cookie value must be a string")
|
|
539
|
+
if "url" not in wire and "domain" not in wire:
|
|
540
|
+
raise ValueError("cookie must include url or domain")
|
|
541
|
+
for field in ("url", "domain", "path", "partitionKey"):
|
|
542
|
+
if field in wire and not isinstance(wire[field], str):
|
|
543
|
+
raise TypeError(f"cookie {field} must be a string")
|
|
544
|
+
for field in ("httpOnly", "secure"):
|
|
545
|
+
if field in wire and not isinstance(wire[field], bool):
|
|
546
|
+
raise TypeError(f"cookie {field} must be a boolean")
|
|
547
|
+
if "expires" in wire and not _is_number(wire["expires"]):
|
|
548
|
+
raise TypeError("cookie expires must be a finite number")
|
|
549
|
+
if "sameSite" in wire and wire["sameSite"] not in {"Strict", "Lax", "None"}:
|
|
550
|
+
raise ValueError("cookie same_site must be Strict, Lax, or None")
|
|
551
|
+
return wire
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _parse_cookie(value: Any) -> ManagedCookie:
|
|
556
|
+
if not isinstance(value, dict):
|
|
557
|
+
raise TypeError("cookie is not an object")
|
|
558
|
+
required_strings = ("name", "value", "domain", "path")
|
|
559
|
+
if any(not isinstance(value.get(field), str) for field in required_strings):
|
|
560
|
+
raise TypeError("cookie has invalid string fields")
|
|
561
|
+
if not _is_number(value.get("expires")):
|
|
562
|
+
raise TypeError("cookie expires is invalid")
|
|
563
|
+
if not isinstance(value.get("httpOnly"), bool) or not isinstance(value.get("secure"), bool):
|
|
564
|
+
raise TypeError("cookie flags are invalid")
|
|
565
|
+
if value.get("sameSite") not in {"Strict", "Lax", "None"}:
|
|
566
|
+
raise ValueError("cookie sameSite is invalid")
|
|
567
|
+
partition_key = value.get("partitionKey")
|
|
568
|
+
if partition_key is not None and not isinstance(partition_key, str):
|
|
569
|
+
raise TypeError("cookie partitionKey is invalid")
|
|
570
|
+
return ManagedCookie(
|
|
571
|
+
value["name"],
|
|
572
|
+
value["value"],
|
|
573
|
+
value["domain"],
|
|
574
|
+
value["path"],
|
|
575
|
+
value["expires"],
|
|
576
|
+
value["httpOnly"],
|
|
577
|
+
value["secure"],
|
|
578
|
+
value["sameSite"],
|
|
579
|
+
partition_key,
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _parse_storage_entries(value: Any) -> tuple[ManagedStorageEntry, ...]:
|
|
584
|
+
if not isinstance(value, list):
|
|
585
|
+
raise TypeError("storage entries are not a list")
|
|
586
|
+
entries = []
|
|
587
|
+
for item in value:
|
|
588
|
+
if (
|
|
589
|
+
not isinstance(item, dict)
|
|
590
|
+
or not isinstance(item.get("name"), str)
|
|
591
|
+
or not isinstance(item.get("value"), str)
|
|
592
|
+
):
|
|
593
|
+
raise TypeError("storage entry is invalid")
|
|
594
|
+
entries.append(ManagedStorageEntry(item["name"], item["value"]))
|
|
595
|
+
return tuple(entries)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _parse_storage_state(value: Any) -> ManagedStorageState:
|
|
599
|
+
if not isinstance(value, dict) or not isinstance(value.get("cookies"), list) or not isinstance(value.get("origins"), list):
|
|
600
|
+
raise TypeError("storage state is invalid")
|
|
601
|
+
cookies = tuple(_parse_cookie(cookie) for cookie in value["cookies"])
|
|
602
|
+
origins = []
|
|
603
|
+
for origin in value["origins"]:
|
|
604
|
+
if not isinstance(origin, dict) or not isinstance(origin.get("origin"), str):
|
|
605
|
+
raise TypeError("origin storage is invalid")
|
|
606
|
+
origins.append(
|
|
607
|
+
ManagedOriginStorage(
|
|
608
|
+
origin["origin"],
|
|
609
|
+
_parse_storage_entries(origin.get("localStorage")),
|
|
610
|
+
_parse_storage_entries(origin.get("sessionStorage")),
|
|
611
|
+
)
|
|
612
|
+
)
|
|
613
|
+
return ManagedStorageState(cookies, tuple(origins))
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _storage_entries_wire(entries: Any) -> list[dict[str, str]]:
|
|
617
|
+
if isinstance(entries, (str, bytes)) or not isinstance(entries, Sequence):
|
|
618
|
+
raise TypeError("storage entries must be a sequence")
|
|
619
|
+
wire = []
|
|
620
|
+
for entry in entries:
|
|
621
|
+
record = _mapping(entry, "storage entry")
|
|
622
|
+
if set(record) != {"name", "value"} or not all(
|
|
623
|
+
isinstance(record[field], str) for field in ("name", "value")
|
|
624
|
+
):
|
|
625
|
+
raise TypeError("storage entry must contain string name and value")
|
|
626
|
+
wire.append(record)
|
|
627
|
+
return wire
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _storage_state_wire(value: Any) -> dict[str, Any]:
|
|
631
|
+
record = _mapping(value, "storage state")
|
|
632
|
+
if set(record) != {"cookies", "origins"}:
|
|
633
|
+
raise TypeError("state must be a ManagedStorageState")
|
|
634
|
+
cookies = [_cookie_output_wire(cookie) for cookie in record["cookies"]]
|
|
635
|
+
origins = []
|
|
636
|
+
for origin in record["origins"]:
|
|
637
|
+
item = _mapping(origin, "origin storage")
|
|
638
|
+
normalized = _rename(
|
|
639
|
+
item,
|
|
640
|
+
{
|
|
641
|
+
"origin": "origin",
|
|
642
|
+
"local_storage": "localStorage",
|
|
643
|
+
"localStorage": "localStorage",
|
|
644
|
+
"session_storage": "sessionStorage",
|
|
645
|
+
"sessionStorage": "sessionStorage",
|
|
646
|
+
},
|
|
647
|
+
"origin storage",
|
|
648
|
+
)
|
|
649
|
+
if not isinstance(normalized.get("origin"), str):
|
|
650
|
+
raise TypeError("origin storage origin must be a string")
|
|
651
|
+
normalized["localStorage"] = _storage_entries_wire(normalized.get("localStorage"))
|
|
652
|
+
normalized["sessionStorage"] = _storage_entries_wire(normalized.get("sessionStorage"))
|
|
653
|
+
origins.append(normalized)
|
|
654
|
+
return {"cookies": cookies, "origins": origins}
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _cookie_output_wire(value: Any) -> dict[str, Any]:
|
|
658
|
+
record = _mapping(value, "cookie")
|
|
659
|
+
wire = _rename(_compact(record), _COOKIE_NAMES, "cookie")
|
|
660
|
+
parsed = _parse_cookie(wire)
|
|
661
|
+
return _compact(
|
|
662
|
+
{
|
|
663
|
+
"name": parsed.name,
|
|
664
|
+
"value": parsed.value,
|
|
665
|
+
"domain": parsed.domain,
|
|
666
|
+
"path": parsed.path,
|
|
667
|
+
"expires": parsed.expires,
|
|
668
|
+
"httpOnly": parsed.http_only,
|
|
669
|
+
"secure": parsed.secure,
|
|
670
|
+
"sameSite": parsed.same_site,
|
|
671
|
+
"partitionKey": parsed.partition_key,
|
|
672
|
+
}
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def _parse_viewport(value: Any) -> ManagedViewport:
|
|
677
|
+
if not isinstance(value, dict):
|
|
678
|
+
raise TypeError("viewport is not an object")
|
|
679
|
+
width = value.get("width")
|
|
680
|
+
height = value.get("height")
|
|
681
|
+
scale = value.get("deviceScaleFactor")
|
|
682
|
+
if (
|
|
683
|
+
not isinstance(width, int)
|
|
684
|
+
or isinstance(width, bool)
|
|
685
|
+
or width <= 0
|
|
686
|
+
or not isinstance(height, int)
|
|
687
|
+
or isinstance(height, bool)
|
|
688
|
+
or height <= 0
|
|
689
|
+
or (scale is not None and (not _is_number(scale) or scale <= 0))
|
|
690
|
+
):
|
|
691
|
+
raise ValueError("viewport dimensions must be positive integers")
|
|
692
|
+
return ManagedViewport(width, height, scale)
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _viewport_wire(value: Any) -> dict[str, Any]:
|
|
696
|
+
record = _rename(
|
|
697
|
+
_mapping(value, "viewport"),
|
|
698
|
+
{
|
|
699
|
+
"width": "width",
|
|
700
|
+
"height": "height",
|
|
701
|
+
"device_scale_factor": "deviceScaleFactor",
|
|
702
|
+
"deviceScaleFactor": "deviceScaleFactor",
|
|
703
|
+
},
|
|
704
|
+
"viewport",
|
|
705
|
+
)
|
|
706
|
+
parsed = _parse_viewport(record)
|
|
707
|
+
return _compact(
|
|
708
|
+
{
|
|
709
|
+
"width": parsed.width,
|
|
710
|
+
"height": parsed.height,
|
|
711
|
+
"deviceScaleFactor": parsed.device_scale_factor,
|
|
712
|
+
}
|
|
713
|
+
)
|