From f2dca6bfb30cba700e1b5a3db4e22c78ce2e47cd Mon Sep 17 00:00:00 2001 From: reformedot Date: Mon, 25 Aug 2025 09:47:59 +0100 Subject: [PATCH 1/5] feat: added browser-use custom CDP domain + option to define CDP version + updated specification --- cdp_use/cdp/__init__.py | 42 ++--- cdp_use/cdp/audits/types.py | 17 +- cdp_use/cdp/browseruse/__init__.py | 9 + cdp_use/cdp/browseruse/commands.py | 8 + cdp_use/cdp/browseruse/events.py | 33 ++++ cdp_use/cdp/browseruse/library.py | 19 ++ cdp_use/cdp/browseruse/registration.py | 51 ++++++ cdp_use/cdp/browseruse/types.py | 8 + cdp_use/cdp/css/commands.py | 14 +- cdp_use/cdp/css/library.py | 13 ++ cdp_use/cdp/css/types.py | 10 ++ cdp_use/cdp/dom/commands.py | 15 ++ cdp_use/cdp/dom/library.py | 21 ++- cdp_use/cdp/dom/types.py | 2 +- cdp_use/cdp/emulation/commands.py | 43 +++++ cdp_use/cdp/emulation/library.py | 40 +++++ cdp_use/cdp/emulation/types.py | 55 ++++++ cdp_use/cdp/library.py | 82 +++++---- cdp_use/cdp/media/events.py | 9 +- cdp_use/cdp/media/registration.py | 14 +- cdp_use/cdp/media/types.py | 13 +- cdp_use/cdp/network/commands.py | 7 + cdp_use/cdp/network/library.py | 14 ++ cdp_use/cdp/network/types.py | 11 +- cdp_use/cdp/overlay/library.py | 5 +- cdp_use/cdp/page/commands.py | 2 + cdp_use/cdp/page/events.py | 3 +- cdp_use/cdp/page/registration.py | 3 +- cdp_use/cdp/page/types.py | 2 +- cdp_use/cdp/preload/types.py | 4 +- cdp_use/cdp/registration_library.py | 50 +++--- cdp_use/cdp/registry.py | 7 +- cdp_use/cdp/target/commands.py | 11 ++ cdp_use/cdp/target/library.py | 14 ++ cdp_use/cdp/target/types.py | 2 + cdp_use/client.py | 215 +++++++++++++---------- cdp_use/custom_protocols/browseruse.json | 56 ++++++ cdp_use/generator/constants.py | 19 +- cdp_use/generator/generate.py | 23 ++- cdp_use/generator/registry_generator.py | 75 ++++---- uv.lock | 2 +- 41 files changed, 790 insertions(+), 253 deletions(-) create mode 100644 cdp_use/cdp/browseruse/__init__.py create mode 100644 cdp_use/cdp/browseruse/commands.py create mode 100644 cdp_use/cdp/browseruse/events.py create mode 100644 cdp_use/cdp/browseruse/library.py create mode 100644 cdp_use/cdp/browseruse/registration.py create mode 100644 cdp_use/cdp/browseruse/types.py create mode 100644 cdp_use/custom_protocols/browseruse.json diff --git a/cdp_use/cdp/__init__.py b/cdp_use/cdp/__init__.py index 7386383..ad4f07d 100644 --- a/cdp_use/cdp/__init__.py +++ b/cdp_use/cdp/__init__.py @@ -13,34 +13,41 @@ from . import accessibility from . import animation from . import audits -from . import extensions from . import autofill from . import backgroundservice +from . import bluetoothemulation from . import browser from . import css from . import cachestorage from . import cast from . import dom from . import domdebugger -from . import eventbreakpoints from . import domsnapshot from . import domstorage +from . import deviceaccess from . import deviceorientation from . import emulation +from . import eventbreakpoints +from . import extensions +from . import fedcm +from . import fetch +from . import filesystem from . import headlessexperimental from . import io -from . import filesystem from . import indexeddb from . import input from . import inspector from . import layertree from . import log +from . import media from . import memory from . import network from . import overlay +from . import pwa from . import page from . import performance from . import performancetimeline +from . import preload from . import security from . import serviceworker from . import storage @@ -48,15 +55,9 @@ from . import target from . import tethering from . import tracing -from . import fetch from . import webaudio from . import webauthn -from . import media -from . import deviceaccess -from . import preload -from . import fedcm -from . import pwa -from . import bluetoothemulation +from . import browseruse from .library import CDPLibrary from .registry import EventRegistry @@ -72,34 +73,41 @@ "accessibility", "animation", "audits", - "extensions", "autofill", "backgroundservice", + "bluetoothemulation", "browser", "css", "cachestorage", "cast", "dom", "domdebugger", - "eventbreakpoints", "domsnapshot", "domstorage", + "deviceaccess", "deviceorientation", "emulation", + "eventbreakpoints", + "extensions", + "fedcm", + "fetch", + "filesystem", "headlessexperimental", "io", - "filesystem", "indexeddb", "input", "inspector", "layertree", "log", + "media", "memory", "network", "overlay", + "pwa", "page", "performance", "performancetimeline", + "preload", "security", "serviceworker", "storage", @@ -107,15 +115,9 @@ "target", "tethering", "tracing", - "fetch", "webaudio", "webauthn", - "media", - "deviceaccess", - "preload", - "fedcm", - "pwa", - "bluetoothemulation", + "browseruse", "CDPLibrary", "EventRegistry", "CDPRegistrationLibrary", diff --git a/cdp_use/cdp/audits/types.py b/cdp_use/cdp/audits/types.py index a5f792d..2ff95e3 100644 --- a/cdp_use/cdp/audits/types.py +++ b/cdp_use/cdp/audits/types.py @@ -236,6 +236,10 @@ class CorsIssueDetails(TypedDict): +UnencodedDigestError = Literal["MalformedDictionary", "UnknownAlgorithm", "IncorrectDigestType", "IncorrectDigestLength"] + + + class AttributionReportingIssueDetails(TypedDict): """Details for issues around \"Attribution Reporting API\" usage. Explainer: https://github.com/WICG/attribution-reporting-api""" @@ -281,6 +285,12 @@ class SRIMessageSignatureIssueDetails(TypedDict): +class UnencodedDigestIssueDetails(TypedDict): + error: "UnencodedDigestError" + request: "AffectedRequest" + + + GenericIssueErrorType = Literal["FormLabelForNameError", "FormDuplicateIdForInputError", "FormInputWithNoLabelError", "FormAutocompleteAttributeEmptyError", "FormEmptyIdAndNameAttributesForInputError", "FormAriaLabelledByToNonExistingId", "FormInputAssignedAutocompleteValueToIdOrNameAttributeError", "FormLabelHasNeitherForNorNestedInput", "FormLabelForMatchesNonExistingIdError", "FormInputHasWrongButWellIntendedAutocompleteValueError", "ResponseWasBlockedByORB"] @@ -438,7 +448,7 @@ class PropertyRuleIssueDetails(TypedDict): -UserReidentificationIssueType = Literal["BlockedFrameNavigation", "BlockedSubresource"] +UserReidentificationIssueType = Literal["BlockedFrameNavigation", "BlockedSubresource", "NoisedCanvasReadback"] @@ -449,10 +459,12 @@ class UserReidentificationIssueDetails(TypedDict): type: "UserReidentificationIssueType" request: "NotRequired[AffectedRequest]" """Applies to BlockedFrameNavigation and BlockedSubresource issue types.""" + sourceCodeLocation: "NotRequired[SourceCodeLocation]" + """Applies to NoisedCanvasReadback issue type.""" -InspectorIssueCode = Literal["CookieIssue", "MixedContentIssue", "BlockedByResponseIssue", "HeavyAdIssue", "ContentSecurityPolicyIssue", "SharedArrayBufferIssue", "LowTextContrastIssue", "CorsIssue", "AttributionReportingIssue", "QuirksModeIssue", "PartitioningBlobURLIssue", "NavigatorUserAgentIssue", "GenericIssue", "DeprecationIssue", "ClientHintIssue", "FederatedAuthRequestIssue", "BounceTrackingIssue", "CookieDeprecationMetadataIssue", "StylesheetLoadingIssue", "FederatedAuthUserInfoRequestIssue", "PropertyRuleIssue", "SharedDictionaryIssue", "ElementAccessibilityIssue", "SRIMessageSignatureIssue", "UserReidentificationIssue"] +InspectorIssueCode = Literal["CookieIssue", "MixedContentIssue", "BlockedByResponseIssue", "HeavyAdIssue", "ContentSecurityPolicyIssue", "SharedArrayBufferIssue", "LowTextContrastIssue", "CorsIssue", "AttributionReportingIssue", "QuirksModeIssue", "PartitioningBlobURLIssue", "NavigatorUserAgentIssue", "GenericIssue", "DeprecationIssue", "ClientHintIssue", "FederatedAuthRequestIssue", "BounceTrackingIssue", "CookieDeprecationMetadataIssue", "StylesheetLoadingIssue", "FederatedAuthUserInfoRequestIssue", "PropertyRuleIssue", "SharedDictionaryIssue", "ElementAccessibilityIssue", "SRIMessageSignatureIssue", "UnencodedDigestIssue", "UserReidentificationIssue"] """A unique identifier for the type of issue. Each type may use one of the optional fields in InspectorIssueDetails to convey more specific information about the kind of issue.""" @@ -488,6 +500,7 @@ class InspectorIssueDetails(TypedDict, total=False): sharedDictionaryIssueDetails: "SharedDictionaryIssueDetails" elementAccessibilityIssueDetails: "ElementAccessibilityIssueDetails" sriMessageSignatureIssueDetails: "SRIMessageSignatureIssueDetails" + unencodedDigestIssueDetails: "UnencodedDigestIssueDetails" userReidentificationIssueDetails: "UserReidentificationIssueDetails" diff --git a/cdp_use/cdp/browseruse/__init__.py b/cdp_use/cdp/browseruse/__init__.py new file mode 100644 index 0000000..442b436 --- /dev/null +++ b/cdp_use/cdp/browseruse/__init__.py @@ -0,0 +1,9 @@ +# This file is auto-generated by the CDP protocol generator. +# Do not edit this file manually as your changes will be overwritten. +# Generated from Chrome DevTools Protocol specifications. + +"""CDP BrowserUse Domain""" + +from .types import * +from .commands import * +from .events import * diff --git a/cdp_use/cdp/browseruse/commands.py b/cdp_use/cdp/browseruse/commands.py new file mode 100644 index 0000000..858f792 --- /dev/null +++ b/cdp_use/cdp/browseruse/commands.py @@ -0,0 +1,8 @@ +# This file is auto-generated by the CDP protocol generator. +# Do not edit this file manually as your changes will be overwritten. +# Generated from Chrome DevTools Protocol specifications. + +"""CDP BrowserUse Domain Commands""" + + +# No commands defined for this domain \ No newline at end of file diff --git a/cdp_use/cdp/browseruse/events.py b/cdp_use/cdp/browseruse/events.py new file mode 100644 index 0000000..61001c0 --- /dev/null +++ b/cdp_use/cdp/browseruse/events.py @@ -0,0 +1,33 @@ +# This file is auto-generated by the CDP protocol generator. +# Do not edit this file manually as your changes will be overwritten. +# Generated from Chrome DevTools Protocol specifications. + +"""CDP BrowserUse Domain Events""" + +from typing_extensions import NotRequired, TypedDict + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..target.types import TargetID + +"""Captcha solving started.""" +class CaptchaSolverStartedEvent(TypedDict): + targetId: "TargetID" + vendor: "str" + url: "str" + startedAt: "int" + """Unix millis""" + eventTimeout: "NotRequired[float]" + + + +"""Captcha solving finished.""" +class CaptchaSolverFinishedEvent(TypedDict): + targetId: "TargetID" + vendor: "str" + url: "str" + durationMs: "int" + finishedAt: "int" + """Unix millis""" + eventTimeout: "NotRequired[float]" diff --git a/cdp_use/cdp/browseruse/library.py b/cdp_use/cdp/browseruse/library.py new file mode 100644 index 0000000..25baf7a --- /dev/null +++ b/cdp_use/cdp/browseruse/library.py @@ -0,0 +1,19 @@ +# This file is auto-generated by the CDP protocol generator. +# Do not edit this file manually as your changes will be overwritten. +# Generated from Chrome DevTools Protocol specifications. + +"""CDP BrowserUse Domain Library""" + + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ...client import CDPClient + +class BrowserUseClient: + """Client for BrowserUse domain commands.""" + + def __init__(self, client: 'CDPClient'): + self._client = client + + diff --git a/cdp_use/cdp/browseruse/registration.py b/cdp_use/cdp/browseruse/registration.py new file mode 100644 index 0000000..f06fc65 --- /dev/null +++ b/cdp_use/cdp/browseruse/registration.py @@ -0,0 +1,51 @@ +# This file is auto-generated by the CDP protocol generator. +# Do not edit this file manually as your changes will be overwritten. +# Generated from Chrome DevTools Protocol specifications. + +"""CDP BrowserUse Domain Event Registration""" + +from typing import Callable, Optional + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..registry import EventRegistry + from .events import CaptchaSolverFinishedEvent, CaptchaSolverStartedEvent + +class BrowserUseRegistration: + """Event registration interface for BrowserUse domain.""" + + def __init__(self, registry: 'EventRegistry'): + self._registry = registry + self._domain = "BrowserUse" + + def captchaSolverStarted( + self, + callback: Callable[['CaptchaSolverStartedEvent', Optional[str]], None], + ) -> None: + """ + Register a callback for captchaSolverStarted events. + + Captcha solving started. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("BrowserUse.captchaSolverStarted", callback) + + def captchaSolverFinished( + self, + callback: Callable[['CaptchaSolverFinishedEvent', Optional[str]], None], + ) -> None: + """ + Register a callback for captchaSolverFinished events. + + Captcha solving finished. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("BrowserUse.captchaSolverFinished", callback) + diff --git a/cdp_use/cdp/browseruse/types.py b/cdp_use/cdp/browseruse/types.py new file mode 100644 index 0000000..2b9cb24 --- /dev/null +++ b/cdp_use/cdp/browseruse/types.py @@ -0,0 +1,8 @@ +# This file is auto-generated by the CDP protocol generator. +# Do not edit this file manually as your changes will be overwritten. +# Generated from Chrome DevTools Protocol specifications. + +"""CDP BrowserUse Domain Types""" + + +# No types defined for this domain \ No newline at end of file diff --git a/cdp_use/cdp/css/commands.py b/cdp_use/cdp/css/commands.py index aa3e672..5e0f7cd 100644 --- a/cdp_use/cdp/css/commands.py +++ b/cdp_use/cdp/css/commands.py @@ -4,7 +4,7 @@ """CDP CSS Domain Commands""" -from typing import List +from typing import Any, Dict, List from typing_extensions import NotRequired, TypedDict from typing import TYPE_CHECKING @@ -29,6 +29,7 @@ from .types import CSSScope from .types import CSSStyle from .types import CSSSupports + from .types import ComputedStyleExtraFields from .types import InheritedAnimatedStyleEntry from .types import InheritedPseudoElementMatches from .types import InheritedStyleEntry @@ -134,13 +135,15 @@ class GetComputedStyleForNodeParameters(TypedDict): class GetComputedStyleForNodeReturns(TypedDict): computedStyle: "List[CSSComputedStyleProperty]" """Computed style for the specified DOM node.""" + extraFields: "ComputedStyleExtraFields" + """A list of non-standard \"extra fields\" which blink stores alongside each +computed style.""" class ResolveValuesParameters(TypedDict): values: "List[str]" - """Substitution functions (var()/env()/attr()) and cascade-dependent -keywords (revert/revert-layer) do not work.""" + """Cascade-dependent keywords (revert/revert-layer) do not work.""" nodeId: "NodeId" """Id of the node in whose context the expression is evaluated""" propertyName: "NotRequired[str]" @@ -231,6 +234,11 @@ class GetMatchedStylesForNodeReturns(TypedDict): +class GetEnvironmentVariablesReturns(TypedDict): + environmentVariables: "Dict[str, Any]" + + + class GetMediaQueriesReturns(TypedDict): medias: "List[CSSMedia]" diff --git a/cdp_use/cdp/css/library.py b/cdp_use/cdp/css/library.py index a0bf628..50b6387 100644 --- a/cdp_use/cdp/css/library.py +++ b/cdp_use/cdp/css/library.py @@ -24,6 +24,7 @@ from .commands import GetBackgroundColorsReturns from .commands import GetComputedStyleForNodeParameters from .commands import GetComputedStyleForNodeReturns + from .commands import GetEnvironmentVariablesReturns from .commands import GetInlineStylesForNodeParameters from .commands import GetInlineStylesForNodeReturns from .commands import GetLayersForNodeParameters @@ -252,6 +253,18 @@ async def getMatchedStylesForNode( session_id=session_id, )) + async def getEnvironmentVariables( + self, + params: None = None, + session_id: Optional[str] = None, + ) -> "GetEnvironmentVariablesReturns": + """Returns the values of the default UA-defined environment variables used in env()""" + return cast("GetEnvironmentVariablesReturns", await self._client.send_raw( + method="CSS.getEnvironmentVariables", + params=params, + session_id=session_id, + )) + async def getMediaQueries( self, params: None = None, diff --git a/cdp_use/cdp/css/types.py b/cdp_use/cdp/css/types.py index 8cfcd3b..17be237 100644 --- a/cdp_use/cdp/css/types.py +++ b/cdp_use/cdp/css/types.py @@ -263,6 +263,14 @@ class CSSComputedStyleProperty(TypedDict): +class ComputedStyleExtraFields(TypedDict): + isAppearanceBase: "bool" + """Returns whether or not this node is being rendered with base appearance, +which happens when it has its appearance property set to base/base-select +or it is in the subtree of an element being rendered with base appearance.""" + + + class CSSStyle(TypedDict): """CSS style representation.""" @@ -371,6 +379,8 @@ class CSSContainerQuery(TypedDict): """Optional logical axes queried for the container.""" queriesScrollState: "NotRequired[bool]" """true if the query contains scroll-state() queries.""" + queriesAnchored: "NotRequired[bool]" + """true if the query contains anchored() queries.""" diff --git a/cdp_use/cdp/dom/commands.py b/cdp_use/cdp/dom/commands.py index c74b55c..439d60e 100644 --- a/cdp_use/cdp/dom/commands.py +++ b/cdp_use/cdp/dom/commands.py @@ -561,6 +561,7 @@ class GetContainerForNodeParameters(TypedDict): physicalAxes: "NotRequired[PhysicalAxes]" logicalAxes: "NotRequired[LogicalAxes]" queriesScrollState: "NotRequired[bool]" + queriesAnchored: "NotRequired[bool]" class GetContainerForNodeReturns(TypedDict): @@ -593,3 +594,17 @@ class GetAnchorElementParameters(TypedDict): class GetAnchorElementReturns(TypedDict): nodeId: "NodeId" """The anchor element of the given anchor query.""" + + + +class ForceShowPopoverParameters(TypedDict): + nodeId: "NodeId" + """Id of the popover HTMLElement""" + enable: "bool" + """If true, opens the popover and keeps it open. If false, closes the +popover if it was previously force-opened.""" + + +class ForceShowPopoverReturns(TypedDict): + nodeIds: "List[NodeId]" + """List of popovers that were closed in order to respect popover stacking order.""" diff --git a/cdp_use/cdp/dom/library.py b/cdp_use/cdp/dom/library.py index 93b479f..d3027ef 100644 --- a/cdp_use/cdp/dom/library.py +++ b/cdp_use/cdp/dom/library.py @@ -19,6 +19,8 @@ from .commands import DiscardSearchResultsParameters from .commands import EnableParameters from .commands import FocusParameters + from .commands import ForceShowPopoverParameters + from .commands import ForceShowPopoverReturns from .commands import GetAnchorElementParameters from .commands import GetAnchorElementReturns from .commands import GetAttributesParameters @@ -707,9 +709,9 @@ async def getContainerForNode( ) -> "GetContainerForNodeReturns": """Returns the query container of the given node based on container query conditions: containerName, physical and logical axes, and whether it queries -scroll-state. If no axes are provided and queriesScrollState is false, the -style container is returned, which is the direct parent or the closest -element with a matching container-name.""" +scroll-state or anchored elements. If no axes are provided and +queriesScrollState is false, the style container is returned, which is the +direct parent or the closest element with a matching container-name.""" return cast("GetContainerForNodeReturns", await self._client.send_raw( method="DOM.getContainerForNode", params=params, @@ -742,4 +744,17 @@ async def getAnchorElement( session_id=session_id, )) + async def forceShowPopover( + self, + params: "ForceShowPopoverParameters", + session_id: Optional[str] = None, + ) -> "ForceShowPopoverReturns": + """When enabling, this API force-opens the popover identified by nodeId +and keeps it open until disabled.""" + return cast("ForceShowPopoverReturns", await self._client.send_raw( + method="DOM.forceShowPopover", + params=params, + session_id=session_id, + )) + diff --git a/cdp_use/cdp/dom/types.py b/cdp_use/cdp/dom/types.py index 7901d8a..89c6530 100644 --- a/cdp_use/cdp/dom/types.py +++ b/cdp_use/cdp/dom/types.py @@ -35,7 +35,7 @@ class BackendNode(TypedDict): -PseudoType = Literal["first-line", "first-letter", "checkmark", "before", "after", "picker-icon", "marker", "backdrop", "column", "selection", "search-text", "target-text", "spelling-error", "grammar-error", "highlight", "first-line-inherited", "scroll-marker", "scroll-marker-group", "scroll-button", "scrollbar", "scrollbar-thumb", "scrollbar-button", "scrollbar-track", "scrollbar-track-piece", "scrollbar-corner", "resizer", "input-list-button", "view-transition", "view-transition-group", "view-transition-image-pair", "view-transition-group-children", "view-transition-old", "view-transition-new", "placeholder", "file-selector-button", "details-content", "picker", "permission-icon"] +PseudoType = Literal["first-line", "first-letter", "checkmark", "before", "after", "picker-icon", "interest-hint", "marker", "backdrop", "column", "selection", "search-text", "target-text", "spelling-error", "grammar-error", "highlight", "first-line-inherited", "scroll-marker", "scroll-marker-group", "scroll-button", "scrollbar", "scrollbar-thumb", "scrollbar-button", "scrollbar-track", "scrollbar-track-piece", "scrollbar-corner", "resizer", "input-list-button", "view-transition", "view-transition-group", "view-transition-image-pair", "view-transition-group-children", "view-transition-old", "view-transition-new", "placeholder", "file-selector-button", "details-content", "picker", "permission-icon"] """Pseudo element type.""" diff --git a/cdp_use/cdp/emulation/commands.py b/cdp_use/cdp/emulation/commands.py index 9dcb38d..b4623d4 100644 --- a/cdp_use/cdp/emulation/commands.py +++ b/cdp_use/cdp/emulation/commands.py @@ -21,12 +21,15 @@ from .types import PressureSource from .types import PressureState from .types import SafeAreaInsets + from .types import ScreenId + from .types import ScreenInfo from .types import ScreenOrientation from .types import SensorMetadata from .types import SensorReading from .types import SensorType from .types import UserAgentMetadata from .types import VirtualTimePolicy + from .types import WorkAreaInsets class CanEmulateReturns(TypedDict): result: "bool" @@ -396,3 +399,43 @@ class SetSmallViewportHeightDifferenceOverrideParameters(TypedDict): of size 100lvh.""" + + + +class GetScreenInfosReturns(TypedDict): + screenInfos: "List[ScreenInfo]" + + + +class AddScreenParameters(TypedDict): + left: "int" + """Offset of the left edge of the screen in pixels.""" + top: "int" + """Offset of the top edge of the screen in pixels.""" + width: "int" + """The width of the screen in pixels.""" + height: "int" + """The height of the screen in pixels.""" + workAreaInsets: "NotRequired[WorkAreaInsets]" + """Specifies the screen's work area. Default is entire screen.""" + devicePixelRatio: "NotRequired[float]" + """Specifies the screen's device pixel ratio. Default is 1.""" + rotation: "NotRequired[int]" + """Specifies the screen's rotation angle. Available values are 0, 90, 180 and 270. Default is 0.""" + colorDepth: "NotRequired[int]" + """Specifies the screen's color depth in bits. Default is 24.""" + label: "NotRequired[str]" + """Specifies the descriptive label for the screen. Default is none.""" + isInternal: "NotRequired[bool]" + """Indicates whether the screen is internal to the device or external, attached to the device. Default is false.""" + + +class AddScreenReturns(TypedDict): + screenInfo: "ScreenInfo" + + + +class RemoveScreenParameters(TypedDict): + screenId: "ScreenId" + + diff --git a/cdp_use/cdp/emulation/library.py b/cdp_use/cdp/emulation/library.py index 0acc278..81f8ea0 100644 --- a/cdp_use/cdp/emulation/library.py +++ b/cdp_use/cdp/emulation/library.py @@ -10,9 +10,13 @@ if TYPE_CHECKING: from ...client import CDPClient + from .commands import AddScreenParameters + from .commands import AddScreenReturns from .commands import CanEmulateReturns from .commands import GetOverriddenSensorInformationParameters from .commands import GetOverriddenSensorInformationReturns + from .commands import GetScreenInfosReturns + from .commands import RemoveScreenParameters from .commands import SetAutoDarkModeOverrideParameters from .commands import SetAutomationOverrideParameters from .commands import SetCPUThrottlingRateParameters @@ -597,4 +601,40 @@ async def setSmallViewportHeightDifferenceOverride( session_id=session_id, )) + async def getScreenInfos( + self, + params: None = None, + session_id: Optional[str] = None, + ) -> "GetScreenInfosReturns": + """Returns device's screen configuration.""" + return cast("GetScreenInfosReturns", await self._client.send_raw( + method="Emulation.getScreenInfos", + params=params, + session_id=session_id, + )) + + async def addScreen( + self, + params: "AddScreenParameters", + session_id: Optional[str] = None, + ) -> "AddScreenReturns": + """Add a new screen to the device. Only supported in headless mode.""" + return cast("AddScreenReturns", await self._client.send_raw( + method="Emulation.addScreen", + params=params, + session_id=session_id, + )) + + async def removeScreen( + self, + params: "RemoveScreenParameters", + session_id: Optional[str] = None, + ) -> "Dict[str, Any]": + """Remove screen from the device. Only supported in headless mode.""" + return cast("Dict[str, Any]", await self._client.send_raw( + method="Emulation.removeScreen", + params=params, + session_id=session_id, + )) + diff --git a/cdp_use/cdp/emulation/types.py b/cdp_use/cdp/emulation/types.py index 2dc77a4..e07061e 100644 --- a/cdp_use/cdp/emulation/types.py +++ b/cdp_use/cdp/emulation/types.py @@ -154,5 +154,60 @@ class PressureMetadata(TypedDict, total=False): +class WorkAreaInsets(TypedDict, total=False): + top: "int" + """Work area top inset in pixels. Default is 0;""" + left: "int" + """Work area left inset in pixels. Default is 0;""" + bottom: "int" + """Work area bottom inset in pixels. Default is 0;""" + right: "int" + """Work area right inset in pixels. Default is 0;""" + + + +ScreenId = str + + + +class ScreenInfo(TypedDict): + """Screen information similar to the one returned by window.getScreenDetails() method, +see https://w3c.github.io/window-management/#screendetailed.""" + + left: "int" + """Offset of the left edge of the screen.""" + top: "int" + """Offset of the top edge of the screen.""" + width: "int" + """Width of the screen.""" + height: "int" + """Height of the screen.""" + availLeft: "int" + """Offset of the left edge of the available screen area.""" + availTop: "int" + """Offset of the top edge of the available screen area.""" + availWidth: "int" + """Width of the available screen area.""" + availHeight: "int" + """Height of the available screen area.""" + devicePixelRatio: "float" + """Specifies the screen's device pixel ratio.""" + orientation: "ScreenOrientation" + """Specifies the screen's orientation.""" + colorDepth: "int" + """Specifies the screen's color depth in bits.""" + isExtended: "bool" + """Indicates whether the device has multiple screens.""" + isInternal: "bool" + """Indicates whether the screen is internal to the device or external, attached to the device.""" + isPrimary: "bool" + """Indicates whether the screen is set as the the operating system primary screen.""" + label: "str" + """Specifies the descriptive label for the screen.""" + id: "ScreenId" + """Specifies the unique identifier of the screen.""" + + + DisabledImageType = Literal["avif", "webp"] """Enum of image types that can be disabled.""" diff --git a/cdp_use/cdp/library.py b/cdp_use/cdp/library.py index 6a0a57d..ed14529 100644 --- a/cdp_use/cdp/library.py +++ b/cdp_use/cdp/library.py @@ -51,10 +51,6 @@ def __init__(self, client: 'CDPClient'): from .audits.library import AuditsClient self.Audits = AuditsClient(client) - # Extensions domain - from .extensions.library import ExtensionsClient - self.Extensions = ExtensionsClient(client) - # Autofill domain from .autofill.library import AutofillClient self.Autofill = AutofillClient(client) @@ -63,6 +59,10 @@ def __init__(self, client: 'CDPClient'): from .backgroundservice.library import BackgroundServiceClient self.BackgroundService = BackgroundServiceClient(client) + # BluetoothEmulation domain + from .bluetoothemulation.library import BluetoothEmulationClient + self.BluetoothEmulation = BluetoothEmulationClient(client) + # Browser domain from .browser.library import BrowserClient self.Browser = BrowserClient(client) @@ -87,10 +87,6 @@ def __init__(self, client: 'CDPClient'): from .domdebugger.library import DOMDebuggerClient self.DOMDebugger = DOMDebuggerClient(client) - # EventBreakpoints domain - from .eventbreakpoints.library import EventBreakpointsClient - self.EventBreakpoints = EventBreakpointsClient(client) - # DOMSnapshot domain from .domsnapshot.library import DOMSnapshotClient self.DOMSnapshot = DOMSnapshotClient(client) @@ -99,6 +95,10 @@ def __init__(self, client: 'CDPClient'): from .domstorage.library import DOMStorageClient self.DOMStorage = DOMStorageClient(client) + # DeviceAccess domain + from .deviceaccess.library import DeviceAccessClient + self.DeviceAccess = DeviceAccessClient(client) + # DeviceOrientation domain from .deviceorientation.library import DeviceOrientationClient self.DeviceOrientation = DeviceOrientationClient(client) @@ -107,6 +107,26 @@ def __init__(self, client: 'CDPClient'): from .emulation.library import EmulationClient self.Emulation = EmulationClient(client) + # EventBreakpoints domain + from .eventbreakpoints.library import EventBreakpointsClient + self.EventBreakpoints = EventBreakpointsClient(client) + + # Extensions domain + from .extensions.library import ExtensionsClient + self.Extensions = ExtensionsClient(client) + + # FedCm domain + from .fedcm.library import FedCmClient + self.FedCm = FedCmClient(client) + + # Fetch domain + from .fetch.library import FetchClient + self.Fetch = FetchClient(client) + + # FileSystem domain + from .filesystem.library import FileSystemClient + self.FileSystem = FileSystemClient(client) + # HeadlessExperimental domain from .headlessexperimental.library import HeadlessExperimentalClient self.HeadlessExperimental = HeadlessExperimentalClient(client) @@ -115,10 +135,6 @@ def __init__(self, client: 'CDPClient'): from .io.library import IOClient self.IO = IOClient(client) - # FileSystem domain - from .filesystem.library import FileSystemClient - self.FileSystem = FileSystemClient(client) - # IndexedDB domain from .indexeddb.library import IndexedDBClient self.IndexedDB = IndexedDBClient(client) @@ -139,6 +155,10 @@ def __init__(self, client: 'CDPClient'): from .log.library import LogClient self.Log = LogClient(client) + # Media domain + from .media.library import MediaClient + self.Media = MediaClient(client) + # Memory domain from .memory.library import MemoryClient self.Memory = MemoryClient(client) @@ -151,6 +171,10 @@ def __init__(self, client: 'CDPClient'): from .overlay.library import OverlayClient self.Overlay = OverlayClient(client) + # PWA domain + from .pwa.library import PWAClient + self.PWA = PWAClient(client) + # Page domain from .page.library import PageClient self.Page = PageClient(client) @@ -163,6 +187,10 @@ def __init__(self, client: 'CDPClient'): from .performancetimeline.library import PerformanceTimelineClient self.PerformanceTimeline = PerformanceTimelineClient(client) + # Preload domain + from .preload.library import PreloadClient + self.Preload = PreloadClient(client) + # Security domain from .security.library import SecurityClient self.Security = SecurityClient(client) @@ -191,10 +219,6 @@ def __init__(self, client: 'CDPClient'): from .tracing.library import TracingClient self.Tracing = TracingClient(client) - # Fetch domain - from .fetch.library import FetchClient - self.Fetch = FetchClient(client) - # WebAudio domain from .webaudio.library import WebAudioClient self.WebAudio = WebAudioClient(client) @@ -203,27 +227,7 @@ def __init__(self, client: 'CDPClient'): from .webauthn.library import WebAuthnClient self.WebAuthn = WebAuthnClient(client) - # Media domain - from .media.library import MediaClient - self.Media = MediaClient(client) - - # DeviceAccess domain - from .deviceaccess.library import DeviceAccessClient - self.DeviceAccess = DeviceAccessClient(client) - - # Preload domain - from .preload.library import PreloadClient - self.Preload = PreloadClient(client) - - # FedCm domain - from .fedcm.library import FedCmClient - self.FedCm = FedCmClient(client) - - # PWA domain - from .pwa.library import PWAClient - self.PWA = PWAClient(client) - - # BluetoothEmulation domain - from .bluetoothemulation.library import BluetoothEmulationClient - self.BluetoothEmulation = BluetoothEmulationClient(client) + # BrowserUse domain + from .browseruse.library import BrowserUseClient + self.BrowserUse = BrowserUseClient(client) diff --git a/cdp_use/cdp/media/events.py b/cdp_use/cdp/media/events.py index bc2bc81..1c893cb 100644 --- a/cdp_use/cdp/media/events.py +++ b/cdp_use/cdp/media/events.py @@ -10,6 +10,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: + from .types import Player from .types import PlayerError from .types import PlayerEvent from .types import PlayerId @@ -47,7 +48,7 @@ class PlayerErrorsRaisedEvent(TypedDict): """Called whenever a player is created, or when a new agent joins and receives -a list of active players. If an agent is restored, it will receive the full -list of player ids and all events again.""" -class PlayersCreatedEvent(TypedDict): - players: "List[PlayerId]" +a list of active players. If an agent is restored, it will receive one +event for each active player.""" +class PlayerCreatedEvent(TypedDict): + player: "Player" diff --git a/cdp_use/cdp/media/registration.py b/cdp_use/cdp/media/registration.py index 28e0f75..93d94b9 100644 --- a/cdp_use/cdp/media/registration.py +++ b/cdp_use/cdp/media/registration.py @@ -10,7 +10,7 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import PlayerErrorsRaisedEvent, PlayerEventsAddedEvent, PlayerMessagesLoggedEvent, PlayerPropertiesChangedEvent, PlayersCreatedEvent + from .events import PlayerCreatedEvent, PlayerErrorsRaisedEvent, PlayerEventsAddedEvent, PlayerMessagesLoggedEvent, PlayerPropertiesChangedEvent class MediaRegistration: """Event registration interface for Media domain.""" @@ -81,20 +81,20 @@ def playerErrorsRaised( """ self._registry.register("Media.playerErrorsRaised", callback) - def playersCreated( + def playerCreated( self, - callback: Callable[['PlayersCreatedEvent', Optional[str]], None], + callback: Callable[['PlayerCreatedEvent', Optional[str]], None], ) -> None: """ - Register a callback for playersCreated events. + Register a callback for playerCreated events. Called whenever a player is created, or when a new agent joins and receives -a list of active players. If an agent is restored, it will receive the full -list of player ids and all events again. +a list of active players. If an agent is restored, it will receive one +event for each active player. Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ - self._registry.register("Media.playersCreated", callback) + self._registry.register("Media.playerCreated", callback) diff --git a/cdp_use/cdp/media/types.py b/cdp_use/cdp/media/types.py index 4209bbc..800468b 100644 --- a/cdp_use/cdp/media/types.py +++ b/cdp_use/cdp/media/types.py @@ -5,7 +5,12 @@ """CDP Media Domain Types""" from typing import Any, Dict, List -from typing_extensions import TypedDict +from typing_extensions import NotRequired, TypedDict + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..dom.types import BackendNodeId PlayerId = str """Players will get an ID that is unique within the agent context.""" @@ -73,3 +78,9 @@ class PlayerError(TypedDict): caused by an WindowsError""" data: "Dict[str, Any]" """Extra data attached to an error, such as an HRESULT, Video Codec, etc.""" + + + +class Player(TypedDict): + playerId: "PlayerId" + domNodeId: "NotRequired[BackendNodeId]" diff --git a/cdp_use/cdp/network/commands.py b/cdp_use/cdp/network/commands.py index ea76e70..81045ff 100644 --- a/cdp_use/cdp/network/commands.py +++ b/cdp_use/cdp/network/commands.py @@ -26,6 +26,7 @@ from .types import ErrorReason from .types import Headers from .types import InterceptionId + from .types import IpProxyStatus from .types import LoadNetworkResourceOptions from .types import LoadNetworkResourcePageResult from .types import RequestId @@ -33,6 +34,12 @@ from .types import SecurityIsolationStatus from .types import TimeSinceEpoch +class GetIPProtectionProxyStatusReturns(TypedDict): + status: "IpProxyStatus" + """Whether IP proxy is available""" + + + class SetAcceptedEncodingsParameters(TypedDict): encodings: "List[ContentEncoding]" """List of accepted content encodings.""" diff --git a/cdp_use/cdp/network/library.py b/cdp_use/cdp/network/library.py index dc61750..bb33a3a 100644 --- a/cdp_use/cdp/network/library.py +++ b/cdp_use/cdp/network/library.py @@ -23,6 +23,7 @@ from .commands import GetCertificateReturns from .commands import GetCookiesParameters from .commands import GetCookiesReturns + from .commands import GetIPProtectionProxyStatusReturns from .commands import GetRequestPostDataParameters from .commands import GetRequestPostDataReturns from .commands import GetResponseBodyForInterceptionParameters @@ -59,6 +60,19 @@ class NetworkClient: def __init__(self, client: 'CDPClient'): self._client = client + async def getIPProtectionProxyStatus( + self, + params: None = None, + session_id: Optional[str] = None, + ) -> "GetIPProtectionProxyStatusReturns": + """Returns enum representing if IP Proxy of requests is available +or reason it is not active.""" + return cast("GetIPProtectionProxyStatusReturns", await self._client.send_raw( + method="Network.getIPProtectionProxyStatus", + params=params, + session_id=session_id, + )) + async def setAcceptedEncodings( self, params: "SetAcceptedEncodingsParameters", diff --git a/cdp_use/cdp/network/types.py b/cdp_use/cdp/network/types.py index 62e06dd..eb9c87f 100644 --- a/cdp_use/cdp/network/types.py +++ b/cdp_use/cdp/network/types.py @@ -250,6 +250,12 @@ class SecurityDetails(TypedDict): +IpProxyStatus = Literal["Available", "FeatureNotEnabled", "MaskedDomainListNotEnabled", "MaskedDomainListNotPopulated", "AuthTokensUnavailable", "Unavailable", "BypassedByDevTools"] +"""Sets Controls for IP Proxy of requests. +Page reload is required before the new behavior will be observed.""" + + + CorsError = Literal["DisallowedByMode", "InvalidResponse", "WildcardOriginNotAllowed", "MissingAllowOriginHeader", "MultipleAllowOriginValues", "InvalidAllowOriginValue", "AllowOriginMismatch", "InvalidAllowCredentials", "CorsDisabledScheme", "PreflightInvalidStatus", "PreflightDisallowedRedirect", "PreflightWildcardOriginNotAllowed", "PreflightMissingAllowOriginHeader", "PreflightMultipleAllowOriginValues", "PreflightInvalidAllowOriginValue", "PreflightAllowOriginMismatch", "PreflightInvalidAllowCredentials", "PreflightMissingAllowExternal", "PreflightInvalidAllowExternal", "PreflightMissingAllowPrivateNetwork", "PreflightInvalidAllowPrivateNetwork", "InvalidAllowMethodsPreflightResponse", "InvalidAllowHeadersPreflightResponse", "MethodDisallowedByPreflightResponse", "HeaderDisallowedByPreflightResponse", "RedirectContainsCredentials", "InsecurePrivateNetwork", "InvalidPrivateNetworkAccess", "UnexpectedPrivateNetworkAccess", "NoCorsRedirectModeNotFollow", "PreflightMissingPrivateNetworkAccessId", "PreflightMissingPrivateNetworkAccessName", "PrivateNetworkAccessPermissionUnavailable", "PrivateNetworkAccessPermissionDenied", "LocalNetworkAccessPermissionDenied"] """The reason why request was blocked.""" @@ -367,6 +373,9 @@ class Response(TypedDict): """Security state of the request resource.""" securityDetails: "NotRequired[SecurityDetails]" """Security details for the request.""" + isIpProtectionUsed: "NotRequired[bool]" + """Indicates whether the request was sent through IP Protection proxies. If +set to true, the request used the IP Protection privacy feature.""" @@ -767,7 +776,7 @@ class DirectUDPMessage(TypedDict): -IPAddressSpace = Literal["Loopback", "Private", "Public", "Unknown"] +IPAddressSpace = Literal["Loopback", "Local", "Public", "Unknown"] diff --git a/cdp_use/cdp/overlay/library.py b/cdp_use/cdp/overlay/library.py index db8c7d1..b569f0e 100644 --- a/cdp_use/cdp/overlay/library.py +++ b/cdp_use/cdp/overlay/library.py @@ -163,7 +163,10 @@ async def highlightRect( params: "HighlightRectParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - """Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport.""" + """Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport. +Issue: the method does not handle device pixel ratio (DPR) correctly. +The coordinates currently have to be adjusted by the client +if DPR is not 1 (see crbug.com/437807128).""" return cast("Dict[str, Any]", await self._client.send_raw( method="Overlay.highlightRect", params=params, diff --git a/cdp_use/cdp/page/commands.py b/cdp_use/cdp/page/commands.py index 968dcc0..a42be01 100644 --- a/cdp_use/cdp/page/commands.py +++ b/cdp_use/cdp/page/commands.py @@ -266,6 +266,8 @@ class NavigateReturns(TypedDict): as the previously committed loaderId would not change.""" errorText: "str" """User friendly error message, present if and only if navigation has failed.""" + isDownload: "bool" + """Whether the navigation resulted in a download.""" diff --git a/cdp_use/cdp/page/events.py b/cdp_use/cdp/page/events.py index 2f3f4c8..305b03c 100644 --- a/cdp_use/cdp/page/events.py +++ b/cdp_use/cdp/page/events.py @@ -305,8 +305,7 @@ class WindowOpenEvent(TypedDict): -"""Issued for every compilation cache generated. Is only available -if Page.setGenerateCompilationCache is enabled.""" +"""Issued for every compilation cache generated.""" class CompilationCacheProducedEvent(TypedDict): url: "str" data: "str" diff --git a/cdp_use/cdp/page/registration.py b/cdp_use/cdp/page/registration.py index e32f3f8..e43569e 100644 --- a/cdp_use/cdp/page/registration.py +++ b/cdp_use/cdp/page/registration.py @@ -471,8 +471,7 @@ def compilationCacheProduced( """ Register a callback for compilationCacheProduced events. - Issued for every compilation cache generated. Is only available -if Page.setGenerateCompilationCache is enabled. + Issued for every compilation cache generated. Args: callback: Function to call when event occurs. diff --git a/cdp_use/cdp/page/types.py b/cdp_use/cdp/page/types.py index 1b33c97..0b7a0f7 100644 --- a/cdp_use/cdp/page/types.py +++ b/cdp_use/cdp/page/types.py @@ -82,7 +82,7 @@ class AdScriptAncestry(TypedDict): -PermissionsPolicyFeature = Literal["accelerometer", "all-screens-capture", "ambient-light-sensor", "aria-notify", "attribution-reporting", "autoplay", "bluetooth", "browsing-topics", "camera", "captured-surface-control", "ch-dpr", "ch-device-memory", "ch-downlink", "ch-ect", "ch-prefers-color-scheme", "ch-prefers-reduced-motion", "ch-prefers-reduced-transparency", "ch-rtt", "ch-save-data", "ch-ua", "ch-ua-arch", "ch-ua-bitness", "ch-ua-high-entropy-values", "ch-ua-platform", "ch-ua-model", "ch-ua-mobile", "ch-ua-form-factors", "ch-ua-full-version", "ch-ua-full-version-list", "ch-ua-platform-version", "ch-ua-wow64", "ch-viewport-height", "ch-viewport-width", "ch-width", "clipboard-read", "clipboard-write", "compute-pressure", "controlled-frame", "cross-origin-isolated", "deferred-fetch", "deferred-fetch-minimal", "device-attributes", "digital-credentials-get", "direct-sockets", "direct-sockets-private", "display-capture", "document-domain", "encrypted-media", "execution-while-out-of-viewport", "execution-while-not-rendered", "fenced-unpartitioned-storage-read", "focus-without-user-activation", "fullscreen", "frobulate", "gamepad", "geolocation", "gyroscope", "hid", "identity-credentials-get", "idle-detection", "interest-cohort", "join-ad-interest-group", "keyboard-map", "language-detector", "language-model", "local-fonts", "local-network-access", "magnetometer", "media-playback-while-not-visible", "microphone", "midi", "on-device-speech-recognition", "otp-credentials", "payment", "picture-in-picture", "popins", "private-aggregation", "private-state-token-issuance", "private-state-token-redemption", "publickey-credentials-create", "publickey-credentials-get", "record-ad-auction-events", "rewriter", "run-ad-auction", "screen-wake-lock", "serial", "shared-autofill", "shared-storage", "shared-storage-select-url", "smart-card", "speaker-selection", "storage-access", "sub-apps", "summarizer", "sync-xhr", "translator", "unload", "usb", "usb-unrestricted", "vertical-scroll", "web-app-installation", "web-printing", "web-share", "window-management", "writer", "xr-spatial-tracking"] +PermissionsPolicyFeature = Literal["accelerometer", "all-screens-capture", "ambient-light-sensor", "aria-notify", "attribution-reporting", "autoplay", "bluetooth", "browsing-topics", "camera", "captured-surface-control", "ch-dpr", "ch-device-memory", "ch-downlink", "ch-ect", "ch-prefers-color-scheme", "ch-prefers-reduced-motion", "ch-prefers-reduced-transparency", "ch-rtt", "ch-save-data", "ch-ua", "ch-ua-arch", "ch-ua-bitness", "ch-ua-high-entropy-values", "ch-ua-platform", "ch-ua-model", "ch-ua-mobile", "ch-ua-form-factors", "ch-ua-full-version", "ch-ua-full-version-list", "ch-ua-platform-version", "ch-ua-wow64", "ch-viewport-height", "ch-viewport-width", "ch-width", "clipboard-read", "clipboard-write", "compute-pressure", "controlled-frame", "cross-origin-isolated", "deferred-fetch", "deferred-fetch-minimal", "device-attributes", "digital-credentials-create", "digital-credentials-get", "direct-sockets", "direct-sockets-private", "display-capture", "document-domain", "encrypted-media", "execution-while-out-of-viewport", "execution-while-not-rendered", "fenced-unpartitioned-storage-read", "focus-without-user-activation", "fullscreen", "frobulate", "gamepad", "geolocation", "gyroscope", "hid", "identity-credentials-get", "idle-detection", "interest-cohort", "join-ad-interest-group", "keyboard-map", "language-detector", "language-model", "local-fonts", "local-network-access", "magnetometer", "media-playback-while-not-visible", "microphone", "midi", "on-device-speech-recognition", "otp-credentials", "payment", "picture-in-picture", "popins", "private-aggregation", "private-state-token-issuance", "private-state-token-redemption", "publickey-credentials-create", "publickey-credentials-get", "record-ad-auction-events", "rewriter", "run-ad-auction", "screen-wake-lock", "serial", "shared-autofill", "shared-storage", "shared-storage-select-url", "smart-card", "speaker-selection", "storage-access", "sub-apps", "summarizer", "sync-xhr", "translator", "unload", "usb", "usb-unrestricted", "vertical-scroll", "web-app-installation", "web-printing", "web-share", "window-management", "writer", "xr-spatial-tracking"] """All Permissions Policy features. This enum should match the one defined in services/network/public/cpp/permissions_policy/permissions_policy_features.json5. LINT.IfChange(PermissionsPolicyFeature)""" diff --git a/cdp_use/cdp/preload/types.py b/cdp_use/cdp/preload/types.py index db0f467..fb250ce 100644 --- a/cdp_use/cdp/preload/types.py +++ b/cdp_use/cdp/preload/types.py @@ -55,7 +55,7 @@ class RuleSet(TypedDict): -RuleSetErrorType = Literal["SourceIsNotJsonObject", "InvalidRulesSkipped"] +RuleSetErrorType = Literal["SourceIsNotJsonObject", "InvalidRulesSkipped", "InvalidRulesetLevelTag"] @@ -111,7 +111,7 @@ class PreloadingAttemptSource(TypedDict): -PrerenderFinalStatus = Literal["Activated", "Destroyed", "LowEndDevice", "InvalidSchemeRedirect", "InvalidSchemeNavigation", "NavigationRequestBlockedByCsp", "MojoBinderPolicy", "RendererProcessCrashed", "RendererProcessKilled", "Download", "TriggerDestroyed", "NavigationNotCommitted", "NavigationBadHttpStatus", "ClientCertRequested", "NavigationRequestNetworkError", "CancelAllHostsForTesting", "DidFailLoad", "Stop", "SslCertificateError", "LoginAuthRequested", "UaChangeRequiresReload", "BlockedByClient", "AudioOutputDeviceRequested", "MixedContent", "TriggerBackgrounded", "MemoryLimitExceeded", "DataSaverEnabled", "TriggerUrlHasEffectiveUrl", "ActivatedBeforeStarted", "InactivePageRestriction", "StartFailed", "TimeoutBackgrounded", "CrossSiteRedirectInInitialNavigation", "CrossSiteNavigationInInitialNavigation", "SameSiteCrossOriginRedirectNotOptInInInitialNavigation", "SameSiteCrossOriginNavigationNotOptInInInitialNavigation", "ActivationNavigationParameterMismatch", "ActivatedInBackground", "EmbedderHostDisallowed", "ActivationNavigationDestroyedBeforeSuccess", "TabClosedByUserGesture", "TabClosedWithoutUserGesture", "PrimaryMainFrameRendererProcessCrashed", "PrimaryMainFrameRendererProcessKilled", "ActivationFramePolicyNotCompatible", "PreloadingDisabled", "BatterySaverEnabled", "ActivatedDuringMainFrameNavigation", "PreloadingUnsupportedByWebContents", "CrossSiteRedirectInMainFrameNavigation", "CrossSiteNavigationInMainFrameNavigation", "SameSiteCrossOriginRedirectNotOptInInMainFrameNavigation", "SameSiteCrossOriginNavigationNotOptInInMainFrameNavigation", "MemoryPressureOnTrigger", "MemoryPressureAfterTriggered", "PrerenderingDisabledByDevTools", "SpeculationRuleRemoved", "ActivatedWithAuxiliaryBrowsingContexts", "MaxNumOfRunningEagerPrerendersExceeded", "MaxNumOfRunningNonEagerPrerendersExceeded", "MaxNumOfRunningEmbedderPrerendersExceeded", "PrerenderingUrlHasEffectiveUrl", "RedirectedPrerenderingUrlHasEffectiveUrl", "ActivationUrlHasEffectiveUrl", "JavaScriptInterfaceAdded", "JavaScriptInterfaceRemoved", "AllPrerenderingCanceled", "WindowClosed", "SlowNetwork", "OtherPrerenderedPageActivated", "V8OptimizerDisabled", "PrerenderFailedDuringPrefetch", "BrowsingDataRemoved"] +PrerenderFinalStatus = Literal["Activated", "Destroyed", "LowEndDevice", "InvalidSchemeRedirect", "InvalidSchemeNavigation", "NavigationRequestBlockedByCsp", "MojoBinderPolicy", "RendererProcessCrashed", "RendererProcessKilled", "Download", "TriggerDestroyed", "NavigationNotCommitted", "NavigationBadHttpStatus", "ClientCertRequested", "NavigationRequestNetworkError", "CancelAllHostsForTesting", "DidFailLoad", "Stop", "SslCertificateError", "LoginAuthRequested", "UaChangeRequiresReload", "BlockedByClient", "AudioOutputDeviceRequested", "MixedContent", "TriggerBackgrounded", "MemoryLimitExceeded", "DataSaverEnabled", "TriggerUrlHasEffectiveUrl", "ActivatedBeforeStarted", "InactivePageRestriction", "StartFailed", "TimeoutBackgrounded", "CrossSiteRedirectInInitialNavigation", "CrossSiteNavigationInInitialNavigation", "SameSiteCrossOriginRedirectNotOptInInInitialNavigation", "SameSiteCrossOriginNavigationNotOptInInInitialNavigation", "ActivationNavigationParameterMismatch", "ActivatedInBackground", "EmbedderHostDisallowed", "ActivationNavigationDestroyedBeforeSuccess", "TabClosedByUserGesture", "TabClosedWithoutUserGesture", "PrimaryMainFrameRendererProcessCrashed", "PrimaryMainFrameRendererProcessKilled", "ActivationFramePolicyNotCompatible", "PreloadingDisabled", "BatterySaverEnabled", "ActivatedDuringMainFrameNavigation", "PreloadingUnsupportedByWebContents", "CrossSiteRedirectInMainFrameNavigation", "CrossSiteNavigationInMainFrameNavigation", "SameSiteCrossOriginRedirectNotOptInInMainFrameNavigation", "SameSiteCrossOriginNavigationNotOptInInMainFrameNavigation", "MemoryPressureOnTrigger", "MemoryPressureAfterTriggered", "PrerenderingDisabledByDevTools", "SpeculationRuleRemoved", "ActivatedWithAuxiliaryBrowsingContexts", "MaxNumOfRunningEagerPrerendersExceeded", "MaxNumOfRunningNonEagerPrerendersExceeded", "MaxNumOfRunningEmbedderPrerendersExceeded", "PrerenderingUrlHasEffectiveUrl", "RedirectedPrerenderingUrlHasEffectiveUrl", "ActivationUrlHasEffectiveUrl", "JavaScriptInterfaceAdded", "JavaScriptInterfaceRemoved", "AllPrerenderingCanceled", "WindowClosed", "SlowNetwork", "OtherPrerenderedPageActivated", "V8OptimizerDisabled", "PrerenderFailedDuringPrefetch", "BrowsingDataRemoved", "PrerenderHostReused"] """List of FinalStatus reasons for Prerender2.""" diff --git a/cdp_use/cdp/registration_library.py b/cdp_use/cdp/registration_library.py index be8cde6..1cf62fb 100644 --- a/cdp_use/cdp/registration_library.py +++ b/cdp_use/cdp/registration_library.py @@ -55,6 +55,10 @@ def __init__(self, registry: 'EventRegistry'): from .backgroundservice.registration import BackgroundServiceRegistration self.BackgroundService = BackgroundServiceRegistration(registry) + # BluetoothEmulation domain registration + from .bluetoothemulation.registration import BluetoothEmulationRegistration + self.BluetoothEmulation = BluetoothEmulationRegistration(registry) + # Browser domain registration from .browser.registration import BrowserRegistration self.Browser = BrowserRegistration(registry) @@ -75,10 +79,22 @@ def __init__(self, registry: 'EventRegistry'): from .domstorage.registration import DOMStorageRegistration self.DOMStorage = DOMStorageRegistration(registry) + # DeviceAccess domain registration + from .deviceaccess.registration import DeviceAccessRegistration + self.DeviceAccess = DeviceAccessRegistration(registry) + # Emulation domain registration from .emulation.registration import EmulationRegistration self.Emulation = EmulationRegistration(registry) + # FedCm domain registration + from .fedcm.registration import FedCmRegistration + self.FedCm = FedCmRegistration(registry) + + # Fetch domain registration + from .fetch.registration import FetchRegistration + self.Fetch = FetchRegistration(registry) + # Input domain registration from .input.registration import InputRegistration self.Input = InputRegistration(registry) @@ -95,6 +111,10 @@ def __init__(self, registry: 'EventRegistry'): from .log.registration import LogRegistration self.Log = LogRegistration(registry) + # Media domain registration + from .media.registration import MediaRegistration + self.Media = MediaRegistration(registry) + # Network domain registration from .network.registration import NetworkRegistration self.Network = NetworkRegistration(registry) @@ -115,6 +135,10 @@ def __init__(self, registry: 'EventRegistry'): from .performancetimeline.registration import PerformanceTimelineRegistration self.PerformanceTimeline = PerformanceTimelineRegistration(registry) + # Preload domain registration + from .preload.registration import PreloadRegistration + self.Preload = PreloadRegistration(registry) + # Security domain registration from .security.registration import SecurityRegistration self.Security = SecurityRegistration(registry) @@ -139,10 +163,6 @@ def __init__(self, registry: 'EventRegistry'): from .tracing.registration import TracingRegistration self.Tracing = TracingRegistration(registry) - # Fetch domain registration - from .fetch.registration import FetchRegistration - self.Fetch = FetchRegistration(registry) - # WebAudio domain registration from .webaudio.registration import WebAudioRegistration self.WebAudio = WebAudioRegistration(registry) @@ -151,23 +171,7 @@ def __init__(self, registry: 'EventRegistry'): from .webauthn.registration import WebAuthnRegistration self.WebAuthn = WebAuthnRegistration(registry) - # Media domain registration - from .media.registration import MediaRegistration - self.Media = MediaRegistration(registry) - - # DeviceAccess domain registration - from .deviceaccess.registration import DeviceAccessRegistration - self.DeviceAccess = DeviceAccessRegistration(registry) - - # Preload domain registration - from .preload.registration import PreloadRegistration - self.Preload = PreloadRegistration(registry) - - # FedCm domain registration - from .fedcm.registration import FedCmRegistration - self.FedCm = FedCmRegistration(registry) - - # BluetoothEmulation domain registration - from .bluetoothemulation.registration import BluetoothEmulationRegistration - self.BluetoothEmulation = BluetoothEmulationRegistration(registry) + # BrowserUse domain registration + from .browseruse.registration import BrowserUseRegistration + self.BrowserUse = BrowserUseRegistration(registry) diff --git a/cdp_use/cdp/registry.py b/cdp_use/cdp/registry.py index d52a2f9..baa7348 100644 --- a/cdp_use/cdp/registry.py +++ b/cdp_use/cdp/registry.py @@ -5,6 +5,7 @@ """CDP Event Registry""" import logging +import inspect from typing import Any, Callable, Dict, Optional logger = logging.getLogger(__name__) @@ -60,16 +61,10 @@ async def handle_event( """ if method in self._handlers: try: - import asyncio - import inspect handler = self._handlers[method] - - # Check if handler is async if inspect.iscoroutinefunction(handler): - # Await async handlers await handler(params, session_id) else: - # Call sync handlers directly handler(params, session_id) return True except Exception as e: diff --git a/cdp_use/cdp/target/commands.py b/cdp_use/cdp/target/commands.py index bc5671c..4ab7437 100644 --- a/cdp_use/cdp/target/commands.py +++ b/cdp_use/cdp/target/commands.py @@ -223,3 +223,14 @@ class SetRemoteLocationsParameters(TypedDict): """List of remote locations.""" + + + +class OpenDevToolsParameters(TypedDict): + targetId: "TargetID" + """This can be the page or tab target ID.""" + + +class OpenDevToolsReturns(TypedDict): + targetId: "TargetID" + """The targetId of DevTools page target.""" diff --git a/cdp_use/cdp/target/library.py b/cdp_use/cdp/target/library.py index 5b43cce..32fbaf7 100644 --- a/cdp_use/cdp/target/library.py +++ b/cdp_use/cdp/target/library.py @@ -29,6 +29,8 @@ from .commands import GetTargetInfoReturns from .commands import GetTargetsParameters from .commands import GetTargetsReturns + from .commands import OpenDevToolsParameters + from .commands import OpenDevToolsReturns from .commands import SendMessageToTargetParameters from .commands import SetAutoAttachParameters from .commands import SetDiscoverTargetsParameters @@ -268,4 +270,16 @@ async def setRemoteLocations( session_id=session_id, )) + async def openDevTools( + self, + params: "OpenDevToolsParameters", + session_id: Optional[str] = None, + ) -> "OpenDevToolsReturns": + """Opens a DevTools window for the target.""" + return cast("OpenDevToolsReturns", await self._client.send_raw( + method="Target.openDevTools", + params=params, + session_id=session_id, + )) + diff --git a/cdp_use/cdp/target/types.py b/cdp_use/cdp/target/types.py index 206a4d1..54fb5dd 100644 --- a/cdp_use/cdp/target/types.py +++ b/cdp_use/cdp/target/types.py @@ -37,6 +37,8 @@ class TargetInfo(TypedDict): """Whether the target has access to the originating window.""" openerFrameId: "NotRequired[FrameId]" """Frame id of originating window (is only set if target has an opener).""" + parentFrameId: "NotRequired[FrameId]" + """Id of the parent frame, only present for the \"iframe\" targets.""" browserContextId: "NotRequired[BrowserContextID]" subtype: "NotRequired[str]" """Provides additional details for specific target types. For example, for diff --git a/cdp_use/client.py b/cdp_use/client.py index 044c818..26aa60f 100644 --- a/cdp_use/client.py +++ b/cdp_use/client.py @@ -15,202 +15,214 @@ # Set up logging logger = logging.getLogger(__name__) + # Custom formatter for websocket messages class WebSocketLogFilter(logging.Filter): def __init__(self): super().__init__() self.ping_times = {} # Track ping send times by ping data self.ping_timeout_tasks = {} # Track timeout tasks - + def filter(self, record): # Only process websocket client messages - if record.name != 'websockets.client': + if record.name != "websockets.client": return True - + # Change the logger name - record.name = 'cdp_use.client' - + record.name = "cdp_use.client" + # Process the message msg = record.getMessage() - + # === SPECIAL CASES (suppress or consolidate) === - + # Handle PING/PONG sequences - if '> PING' in msg: - match = re.search(r'> PING ([a-f0-9 ]+) \[binary', msg) + if "> PING" in msg: + match = re.search(r"> PING ([a-f0-9 ]+) \[binary", msg) if match: ping_data = match.group(1) self.ping_times[ping_data] = time.time() - + # Schedule timeout warning async def check_timeout(): await asyncio.sleep(3) if ping_data in self.ping_times: del self.ping_times[ping_data] - timeout_logger = logging.getLogger('cdp_use.client') - timeout_logger.warning('⚠️ PING not answered by browser... (>3s and no PONG received)') - + timeout_logger = logging.getLogger("cdp_use.client") + timeout_logger.warning( + "⚠️ PING not answered by browser... (>3s and no PONG received)" + ) + try: loop = asyncio.get_event_loop() - self.ping_timeout_tasks[ping_data] = loop.create_task(check_timeout()) + self.ping_timeout_tasks[ping_data] = loop.create_task( + check_timeout() + ) except RuntimeError: pass - + return False # Suppress the PING message - - elif '< PONG' in msg: - match = re.search(r'< PONG ([a-f0-9 ]+) \[binary', msg) + + elif "< PONG" in msg: + match = re.search(r"< PONG ([a-f0-9 ]+) \[binary", msg) if match: pong_data = match.group(1) if pong_data in self.ping_times: elapsed = (time.time() - self.ping_times[pong_data]) * 1000 del self.ping_times[pong_data] - + if pong_data in self.ping_timeout_tasks: self.ping_timeout_tasks[pong_data].cancel() del self.ping_timeout_tasks[pong_data] - - record.msg = f'✔ PING ({elapsed:.1f}ms)' + + record.msg = f"✔ PING ({elapsed:.1f}ms)" record.args = () return True return False - + # Suppress keepalive and EOF messages - elif ('% sent keepalive ping' in msg or '% received keepalive pong' in msg or - '> EOF' in msg or '< EOF' in msg): + elif ( + "% sent keepalive ping" in msg + or "% received keepalive pong" in msg + or "> EOF" in msg + or "< EOF" in msg + ): return False - + # Connection state messages - elif '= connection is' in msg: - if 'CONNECTING' in msg: - record.msg = '🔗 Connecting...' - elif 'OPEN' in msg: - record.msg = '✅ Connected' - elif 'CLOSING' in msg or 'CLOSED' in msg: - record.msg = '🔌 Disconnected' + elif "= connection is" in msg: + if "CONNECTING" in msg: + record.msg = "🔗 Connecting..." + elif "OPEN" in msg: + record.msg = "✅ Connected" + elif "CLOSING" in msg or "CLOSED" in msg: + record.msg = "🔌 Disconnected" else: - msg = msg.replace('= ', '') + msg = msg.replace("= ", "") record.msg = msg record.args = () return True - - elif 'x half-closing TCP connection' in msg: - record.msg = '👋 Closing our half of the TCP connection' + + elif "x half-closing TCP connection" in msg: + record.msg = "👋 Closing our half of the TCP connection" record.args = () return True - + # === GENERIC PROCESSING === - + # Parse CDP messages - be flexible with regex matching - if 'TEXT' in msg: + if "TEXT" in msg: # Determine direction - is_outgoing = '>' in msg[:10] # Check start of message for direction - + is_outgoing = ">" in msg[:10] # Check start of message for direction + # Extract and handle size - size_match = re.search(r'\[(\d+) bytes\]', msg) + size_match = re.search(r"\[(\d+) bytes\]", msg) if size_match: size_bytes = int(size_match.group(1)) # Only show size if > 5kb - size_str = f' [{size_bytes // 1024}kb]' if size_bytes > 5120 else '' + size_str = f" [{size_bytes // 1024}kb]" if size_bytes > 5120 else "" # Remove size from message for cleaner parsing - msg_clean = msg[:msg.rfind('[')].strip() if '[' in msg else msg + msg_clean = msg[: msg.rfind("[")].strip() if "[" in msg else msg else: - size_str = '' + size_str = "" msg_clean = msg - + # Extract id (flexible) id_match = re.search(r'(?:"id":|id:)\s*(\d+)', msg_clean) msg_id = id_match.group(1) if id_match else None - + # Extract method (flexible) - method_match = re.search(r'(?:"method":|method:)\s*"?([A-Za-z.]+)', msg_clean) + method_match = re.search( + r'(?:"method":|method:)\s*"?([A-Za-z.]+)', msg_clean + ) method = method_match.group(1) if method_match else None - + # Remove quotes from entire message for cleaner output - msg_clean = msg_clean.replace('"', '') - + msg_clean = msg_clean.replace('"', "") + # Build formatted message based on what we found if is_outgoing and msg_id and method: # Outgoing request - params_match = re.search(r'(?:params:)\s*({[^}]*})', msg_clean) - params_str = params_match.group(1) if params_match else '' - - if params_str == '{}' or not params_str: - record.msg = f'🌎 ← #{msg_id}: {method}(){size_str}' + params_match = re.search(r"(?:params:)\s*({[^}]*})", msg_clean) + params_str = params_match.group(1) if params_match else "" + + if params_str == "{}" or not params_str: + record.msg = f"🌎 ← #{msg_id}: {method}(){size_str}" else: - record.msg = f'🌎 ← #{msg_id}: {method}({params_str}){size_str}' + record.msg = f"🌎 ← #{msg_id}: {method}({params_str}){size_str}" record.args = () return True - + elif not is_outgoing and msg_id: # Incoming response - if 'result:' in msg_clean: + if "result:" in msg_clean: # Extract whatever comes after result: - result_match = re.search(r'result:\s*({.*})', msg_clean) + result_match = re.search(r"result:\s*({.*})", msg_clean) if result_match: result_str = result_match.group(1) - + # Clean up common artifacts - result_str = re.sub(r'},?sessionId:[^}]*}?$', '}', result_str) - + result_str = re.sub(r"},?sessionId:[^}]*}?$", "}", result_str) + # Suppress empty results - if result_str == '{}': + if result_str == "{}": return False - + # Truncate if too long if len(result_str) > 200: - result_str = result_str[:200] + '...' - - record.msg = f'🌎 → #{msg_id}: ↳ {result_str}{size_str}' + result_str = result_str[:200] + "..." + + record.msg = f"🌎 → #{msg_id}: ↳ {result_str}{size_str}" record.args = () return True - - elif 'error:' in msg_clean: - error_match = re.search(r'error:\s*({[^}]*})', msg_clean) - error_str = error_match.group(1) if error_match else 'error' - record.msg = f'🌎 → #{msg_id}: ❌ {error_str}{size_str}' + + elif "error:" in msg_clean: + error_match = re.search(r"error:\s*({[^}]*})", msg_clean) + error_str = error_match.group(1) if error_match else "error" + record.msg = f"🌎 → #{msg_id}: ❌ {error_str}{size_str}" record.args = () return True - + elif not is_outgoing and method: # Event - params_match = re.search(r'params:\s*({.*})', msg_clean) - params_str = params_match.group(1) if params_match else '' - + params_match = re.search(r"params:\s*({.*})", msg_clean) + params_str = params_match.group(1) if params_match else "" + # Clean up common artifacts - params_str = re.sub(r'},?sessionId:[^}]*}?$', '}', params_str) - + params_str = re.sub(r"},?sessionId:[^}]*}?$", "}", params_str) + # Truncate if too long if len(params_str) > 200: - params_str = params_str[:200] + '...' - - if params_str == '{}' or not params_str: - record.msg = f'🌎 → Event: {method}(){size_str}' + params_str = params_str[:200] + "..." + + if params_str == "{}" or not params_str: + record.msg = f"🌎 → Event: {method}(){size_str}" else: - record.msg = f'🌎 → Event: {method}({params_str}){size_str}' + record.msg = f"🌎 → Event: {method}({params_str}){size_str}" record.args = () return True - + # === GENERIC ARROW REPLACEMENT === # Replace all arrows: > becomes ←, < becomes → # Add emoji for TEXT messages - if ' TEXT ' in msg: - msg = re.sub(r'^>', '🌎 ←', msg) - msg = re.sub(r'^<', '🌎 →', msg) - msg = msg.replace(' TEXT ', ' ') + if " TEXT " in msg: + msg = re.sub(r"^>", "🌎 ←", msg) + msg = re.sub(r"^<", "🌎 →", msg) + msg = msg.replace(" TEXT ", " ") else: - msg = re.sub(r'^>', '←', msg) - msg = re.sub(r'^<', '→', msg) - + msg = re.sub(r"^>", "←", msg) + msg = re.sub(r"^<", "→", msg) + # Remove all quotes - msg = re.sub(r"['\"]", '', msg) - + msg = re.sub(r"['\"]", "", msg) + record.msg = msg record.args = () return True + # Configure websockets logger -ws_logger = logging.getLogger('websockets.client') +ws_logger = logging.getLogger("websockets.client") ws_logger.addFilter(WebSocketLogFilter()) @@ -373,3 +385,16 @@ async def send_raw( # Wait for the response return await future + + async def emit_event( + self, + method: str, + params: Optional[Any] = None, + session_id: Optional[str] = None, + ) -> bool: + """Emit a synthetic/custom event through the registry. + + Useful for custom domains (e.g., BrowserUse) where events are + produced by your application rather than the browser. + """ + return await self._event_registry.handle_event(method, params or {}, session_id) diff --git a/cdp_use/custom_protocols/browseruse.json b/cdp_use/custom_protocols/browseruse.json new file mode 100644 index 0000000..4c17209 --- /dev/null +++ b/cdp_use/custom_protocols/browseruse.json @@ -0,0 +1,56 @@ +{ + "domains": [ + { + "domain": "BrowserUse", + "description": "Custom domain for BrowserUse specific automation events.", + "types": [], + "commands": [], + "events": [ + { + "name": "captchaSolverStarted", + "description": "Captcha solving started.", + "parameters": [ + { "name": "targetId", "$ref": "Target.TargetID" }, + { + "name": "vendor", + "type": "string" + }, + { + "name": "url", + "type": "string" + }, + { + "name": "startedAt", + "type": "integer", + "description": "Unix millis" + }, + { "name": "eventTimeout", "type": "number", "optional": true } + ] + }, + { + "name": "captchaSolverFinished", + "description": "Captcha solving finished.", + "parameters": [ + { "name": "targetId", "$ref": "Target.TargetID" }, + { + "name": "vendor", + "type": "string" + }, + { + "name": "url", + "type": "string" + }, + { "name": "durationMs", "type": "integer" }, + { + "name": "finishedAt", + "type": "integer", + "description": "Unix millis" + }, + { "name": "eventTimeout", "type": "number", "optional": true } + ] + } + ] + } + ] +} + diff --git a/cdp_use/generator/constants.py b/cdp_use/generator/constants.py index 3b2a46b..bde64fa 100644 --- a/cdp_use/generator/constants.py +++ b/cdp_use/generator/constants.py @@ -1,3 +1,18 @@ -JS_PROTOCOL_FILE = "https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/refs/heads/master/json/js_protocol.json" +""" +CDP Protocol Version Configuration -BROWSER_PROTOCOL_FILE = "https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/refs/heads/master/json/browser_protocol.json" +Change CDP_VERSION to pin a specific version of the Chrome DevTools Protocol. + +Examples: + - Latest master: "refs/heads/master" + - Specific commit: "4b0c3f2e8c5d6a7b9e1f2a3c4d5e6f7a8b9c0d1e" + - Tagged version: "refs/tags/v1.3" (when available) + +To find commits: https://github.com/ChromeDevTools/devtools-protocol/commits/master +""" + +CDP_VERSION = "refs/heads/master" # Change this to pin a specific version + +JS_PROTOCOL_FILE = f"https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/{CDP_VERSION}/json/js_protocol.json" + +BROWSER_PROTOCOL_FILE = f"https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/{CDP_VERSION}/json/browser_protocol.json" diff --git a/cdp_use/generator/generate.py b/cdp_use/generator/generate.py index 02fb945..eaa9a14 100644 --- a/cdp_use/generator/generate.py +++ b/cdp_use/generator/generate.py @@ -10,15 +10,17 @@ from pathlib import Path from urllib.request import urlretrieve -from .constants import BROWSER_PROTOCOL_FILE, JS_PROTOCOL_FILE +from .constants import BROWSER_PROTOCOL_FILE, CDP_VERSION, JS_PROTOCOL_FILE from .generator import CDPGenerator def download_protocol_files() -> tuple[str, str]: - """Download the latest protocol files from the official repository.""" + """Download the protocol files from the official repository.""" temp_dir = Path(tempfile.mkdtemp()) - print("Downloading Chrome DevTools Protocol specifications...") + print( + f"Downloading Chrome DevTools Protocol specifications (version: {CDP_VERSION})..." + ) # Download JavaScript protocol js_protocol_path = temp_dir / "js_protocol.json" @@ -41,9 +43,20 @@ def main(): # Download protocol files js_file, browser_file = download_protocol_files() - # Create generator and run it + # Discover any custom protocol JSON files placed under cdp_use/custom_protocols/ + project_root = Path(__file__).resolve().parents[2] + custom_dir = project_root / "cdp_use" / "custom_protocols" + custom_protocol_files: list[str] = [] + if custom_dir.exists() and custom_dir.is_dir(): + for path in sorted(custom_dir.glob("*.json")): + print(f" Including custom protocol: {path}") + custom_protocol_files.append(str(path)) + + # Create generator and run it, appending any custom protocol files generator = CDPGenerator() - generator.generate_all(protocol_files=[js_file, browser_file]) + generator.generate_all( + protocol_files=[js_file, browser_file, *custom_protocol_files] + ) print("🎉 CDP type-safe client generation completed!") print("") diff --git a/cdp_use/generator/registry_generator.py b/cdp_use/generator/registry_generator.py index bec84e0..4cf980c 100644 --- a/cdp_use/generator/registry_generator.py +++ b/cdp_use/generator/registry_generator.py @@ -12,83 +12,94 @@ class RegistryGenerator: def generate_registry(self, domains: List[Dict[str, Any]]) -> str: """Generate the central registry.py file.""" - + content = """# This file is auto-generated by the CDP protocol generator. # Do not edit this file manually as your changes will be overwritten. # Generated from Chrome DevTools Protocol specifications. """ content += '"""CDP Event Registry"""\n\n' - + content += "import logging\n" + content += "import inspect\n" content += "from typing import Any, Callable, Dict, Optional\n\n" - + content += "logger = logging.getLogger(__name__)\n\n" - + content += "class EventRegistry:\n" content += ' """Central registry for managing CDP event callbacks."""\n\n' content += " def __init__(self):\n" content += " self._handlers: Dict[str, Callable[[Any, Optional[str]], None]] = {}\n\n" - + content += " def register(\n" content += " self,\n" content += " method: str,\n" content += " callback: Callable[[Any, Optional[str]], None],\n" content += " ) -> None:\n" content += ' """\n' - content += ' Register a callback for a specific CDP event method.\n' - content += ' \n' - content += ' Args:\n' - content += ' method: The CDP method name (e.g., "Page.frameAttached")\n' - content += ' callback: Function to call when event occurs.\n' - content += ' Receives (event_data, session_id) as parameters.\n' + content += " Register a callback for a specific CDP event method.\n" + content += " \n" + content += " Args:\n" + content += ( + ' method: The CDP method name (e.g., "Page.frameAttached")\n' + ) + content += " callback: Function to call when event occurs.\n" + content += ( + " Receives (event_data, session_id) as parameters.\n" + ) content += ' """\n' content += ' logger.debug(f"Registering handler for {method}")\n' content += " self._handlers[method] = callback\n\n" - + content += " def unregister(self, method: str) -> None:\n" content += ' """\n' - content += ' Unregister a callback for a specific CDP event method.\n' - content += ' \n' - content += ' Args:\n' - content += ' method: The CDP method name to unregister\n' + content += " Unregister a callback for a specific CDP event method.\n" + content += " \n" + content += " Args:\n" + content += " method: The CDP method name to unregister\n" content += ' """\n' content += ' logger.debug(f"Unregistering handler for {method}")\n' content += " self._handlers.pop(method, None)\n\n" - - content += " def handle_event(\n" + + content += " async def handle_event(\n" content += " self,\n" content += " method: str,\n" content += " params: Any,\n" content += " session_id: Optional[str] = None,\n" content += " ) -> bool:\n" content += ' """\n' - content += ' Handle an incoming CDP event.\n' - content += ' \n' - content += ' Args:\n' - content += ' method: The CDP method name\n' - content += ' params: The event parameters\n' - content += ' session_id: Optional session ID\n' - content += ' \n' - content += ' Returns:\n' - content += ' True if a handler was found and called, False otherwise\n' + content += " Handle an incoming CDP event.\n" + content += " \n" + content += " Args:\n" + content += " method: The CDP method name\n" + content += " params: The event parameters\n" + content += " session_id: Optional session ID\n" + content += " \n" + content += " Returns:\n" + content += ( + " True if a handler was found and called, False otherwise\n" + ) content += ' """\n' content += " if method in self._handlers:\n" content += " try:\n" - content += " self._handlers[method](params, session_id)\n" + content += " handler = self._handlers[method]\n" + content += " if inspect.iscoroutinefunction(handler):\n" + content += " await handler(params, session_id)\n" + content += " else:\n" + content += " handler(params, session_id)\n" content += " return True\n" content += " except Exception as e:\n" content += ' logger.error(f"Error in event handler for {method}: {e}")\n' content += " return False\n" content += " return False\n\n" - + content += " def clear(self) -> None:\n" content += ' """Clear all registered handlers."""\n' content += ' logger.debug("Clearing all event handlers")\n' content += " self._handlers.clear()\n\n" - + content += " def get_registered_methods(self) -> list[str]:\n" content += ' """Get a list of all registered method names."""\n' content += " return list(self._handlers.keys())\n" - - return content \ No newline at end of file + + return content diff --git a/uv.lock b/uv.lock index 6d24399..6bd00c9 100644 --- a/uv.lock +++ b/uv.lock @@ -32,7 +32,7 @@ wheels = [ [[package]] name = "cdp-use" -version = "1.3.1" +version = "1.4.0" source = { editable = "." } dependencies = [ { name = "httpx" }, From 89d5732d35a221879028b4ec5a40ed29171711f7 Mon Sep 17 00:00:00 2001 From: reformedot Date: Wed, 26 Nov 2025 11:23:48 -0800 Subject: [PATCH 2/5] feat: update CDP specifications and add Taskfile for cache management --- README.md | 18 + Taskfile.yml | 38 + cdp_use/cdp/accessibility/commands.py | 6 +- cdp_use/cdp/accessibility/events.py | 5 +- cdp_use/cdp/accessibility/library.py | 125 +-- cdp_use/cdp/accessibility/registration.py | 28 +- cdp_use/cdp/accessibility/types.py | 110 ++- cdp_use/cdp/animation/commands.py | 18 +- cdp_use/cdp/animation/events.py | 11 +- cdp_use/cdp/animation/library.py | 135 +-- cdp_use/cdp/animation/registration.py | 35 +- cdp_use/cdp/animation/types.py | 9 +- cdp_use/cdp/audits/commands.py | 5 +- cdp_use/cdp/audits/events.py | 1 + cdp_use/cdp/audits/library.py | 78 +- cdp_use/cdp/audits/registration.py | 8 +- cdp_use/cdp/audits/types.py | 423 ++++++--- cdp_use/cdp/autofill/commands.py | 12 +- cdp_use/cdp/autofill/events.py | 2 + cdp_use/cdp/autofill/library.py | 59 +- cdp_use/cdp/autofill/registration.py | 10 +- cdp_use/cdp/autofill/types.py | 23 +- cdp_use/cdp/backgroundservice/commands.py | 12 +- cdp_use/cdp/backgroundservice/events.py | 5 +- cdp_use/cdp/backgroundservice/library.py | 57 +- cdp_use/cdp/backgroundservice/registration.py | 34 +- cdp_use/cdp/backgroundservice/types.py | 11 +- cdp_use/cdp/bluetoothemulation/commands.py | 36 +- cdp_use/cdp/bluetoothemulation/events.py | 8 +- cdp_use/cdp/bluetoothemulation/library.py | 230 +++-- .../cdp/bluetoothemulation/registration.py | 78 +- cdp_use/cdp/bluetoothemulation/types.py | 18 +- cdp_use/cdp/browser/commands.py | 45 +- cdp_use/cdp/browser/events.py | 5 +- cdp_use/cdp/browser/library.py | 280 +++--- cdp_use/cdp/browser/registration.py | 16 +- cdp_use/cdp/browser/types.py | 52 +- cdp_use/cdp/browseruse/commands.py | 2 +- cdp_use/cdp/browseruse/events.py | 13 +- cdp_use/cdp/browseruse/library.py | 6 +- cdp_use/cdp/browseruse/registration.py | 35 +- cdp_use/cdp/browseruse/types.py | 2 +- cdp_use/cdp/cachestorage/commands.py | 9 +- cdp_use/cdp/cachestorage/events.py | 2 +- cdp_use/cdp/cachestorage/library.py | 70 +- cdp_use/cdp/cachestorage/registration.py | 2 +- cdp_use/cdp/cachestorage/types.py | 9 +- cdp_use/cdp/cast/commands.py | 15 +- cdp_use/cdp/cast/events.py | 5 +- cdp_use/cdp/cast/library.py | 93 +- cdp_use/cdp/cast/registration.py | 40 +- cdp_use/cdp/cast/types.py | 1 + cdp_use/cdp/console/commands.py | 2 +- cdp_use/cdp/console/events.py | 2 + cdp_use/cdp/console/library.py | 46 +- cdp_use/cdp/console/registration.py | 10 +- cdp_use/cdp/console/types.py | 1 + cdp_use/cdp/css/commands.py | 52 +- cdp_use/cdp/css/events.py | 15 +- cdp_use/cdp/css/library.py | 548 ++++++----- cdp_use/cdp/css/registration.py | 76 +- cdp_use/cdp/css/types.py | 73 +- cdp_use/cdp/debugger/commands.py | 60 +- cdp_use/cdp/debugger/events.py | 14 +- cdp_use/cdp/debugger/library.py | 506 ++++++----- cdp_use/cdp/debugger/registration.py | 66 +- cdp_use/cdp/debugger/types.py | 12 - cdp_use/cdp/deviceaccess/commands.py | 6 +- cdp_use/cdp/deviceaccess/events.py | 2 + cdp_use/cdp/deviceaccess/library.py | 57 +- cdp_use/cdp/deviceaccess/registration.py | 22 +- cdp_use/cdp/deviceaccess/types.py | 2 - cdp_use/cdp/deviceorientation/commands.py | 3 +- cdp_use/cdp/deviceorientation/events.py | 2 +- cdp_use/cdp/deviceorientation/library.py | 31 +- cdp_use/cdp/deviceorientation/registration.py | 2 +- cdp_use/cdp/deviceorientation/types.py | 2 +- cdp_use/cdp/dom/commands.py | 74 +- cdp_use/cdp/dom/events.py | 55 +- cdp_use/cdp/dom/library.py | 750 +++++++++------ cdp_use/cdp/dom/registration.py | 164 ++-- cdp_use/cdp/dom/types.py | 63 +- cdp_use/cdp/domdebugger/commands.py | 28 +- cdp_use/cdp/domdebugger/events.py | 2 +- cdp_use/cdp/domdebugger/library.py | 135 +-- cdp_use/cdp/domdebugger/registration.py | 2 +- cdp_use/cdp/domdebugger/types.py | 2 - cdp_use/cdp/domsnapshot/commands.py | 2 +- cdp_use/cdp/domsnapshot/events.py | 2 +- cdp_use/cdp/domsnapshot/library.py | 69 +- cdp_use/cdp/domsnapshot/registration.py | 2 +- cdp_use/cdp/domsnapshot/types.py | 19 +- cdp_use/cdp/domstorage/commands.py | 10 +- cdp_use/cdp/domstorage/events.py | 4 +- cdp_use/cdp/domstorage/library.py | 83 +- cdp_use/cdp/domstorage/registration.py | 27 +- cdp_use/cdp/domstorage/types.py | 2 - cdp_use/cdp/emulation/commands.py | 110 +-- cdp_use/cdp/emulation/events.py | 2 + cdp_use/cdp/emulation/library.py | 665 ++++++++------ cdp_use/cdp/emulation/registration.py | 10 +- cdp_use/cdp/emulation/types.py | 36 +- cdp_use/cdp/eventbreakpoints/commands.py | 6 +- cdp_use/cdp/eventbreakpoints/events.py | 2 +- cdp_use/cdp/eventbreakpoints/library.py | 44 +- cdp_use/cdp/eventbreakpoints/registration.py | 2 +- cdp_use/cdp/eventbreakpoints/types.py | 2 +- cdp_use/cdp/extensions/commands.py | 14 +- cdp_use/cdp/extensions/events.py | 2 +- cdp_use/cdp/extensions/library.py | 99 +- cdp_use/cdp/extensions/registration.py | 2 +- cdp_use/cdp/fedcm/commands.py | 15 +- cdp_use/cdp/fedcm/events.py | 4 +- cdp_use/cdp/fedcm/library.py | 98 +- cdp_use/cdp/fedcm/registration.py | 26 +- cdp_use/cdp/fedcm/types.py | 4 - cdp_use/cdp/fetch/commands.py | 20 +- cdp_use/cdp/fetch/events.py | 5 +- cdp_use/cdp/fetch/library.py | 164 ++-- cdp_use/cdp/fetch/registration.py | 58 +- cdp_use/cdp/fetch/types.py | 5 - cdp_use/cdp/filesystem/commands.py | 1 + cdp_use/cdp/filesystem/events.py | 2 +- cdp_use/cdp/filesystem/library.py | 18 +- cdp_use/cdp/filesystem/registration.py | 2 +- cdp_use/cdp/filesystem/types.py | 3 +- cdp_use/cdp/headlessexperimental/commands.py | 1 + cdp_use/cdp/headlessexperimental/events.py | 2 +- cdp_use/cdp/headlessexperimental/library.py | 50 +- .../cdp/headlessexperimental/registration.py | 2 +- cdp_use/cdp/headlessexperimental/types.py | 1 + cdp_use/cdp/heapprofiler/commands.py | 21 +- cdp_use/cdp/heapprofiler/events.py | 9 +- cdp_use/cdp/heapprofiler/library.py | 163 ++-- cdp_use/cdp/heapprofiler/registration.py | 50 +- cdp_use/cdp/heapprofiler/types.py | 3 - cdp_use/cdp/indexeddb/commands.py | 17 +- cdp_use/cdp/indexeddb/events.py | 2 +- cdp_use/cdp/indexeddb/library.py | 122 ++- cdp_use/cdp/indexeddb/registration.py | 2 +- cdp_use/cdp/indexeddb/types.py | 7 +- cdp_use/cdp/input/commands.py | 36 +- cdp_use/cdp/input/events.py | 2 + cdp_use/cdp/input/library.py | 182 ++-- cdp_use/cdp/input/registration.py | 22 +- cdp_use/cdp/input/types.py | 6 +- cdp_use/cdp/inspector/commands.py | 2 +- cdp_use/cdp/inspector/events.py | 15 +- cdp_use/cdp/inspector/library.py | 31 +- cdp_use/cdp/inspector/registration.py | 42 +- cdp_use/cdp/inspector/types.py | 2 +- cdp_use/cdp/io/commands.py | 5 +- cdp_use/cdp/io/events.py | 2 +- cdp_use/cdp/io/library.py | 44 +- cdp_use/cdp/io/registration.py | 2 +- cdp_use/cdp/io/types.py | 1 - cdp_use/cdp/layertree/commands.py | 9 +- cdp_use/cdp/layertree/events.py | 2 +- cdp_use/cdp/layertree/library.py | 122 ++- cdp_use/cdp/layertree/registration.py | 12 +- cdp_use/cdp/layertree/types.py | 6 - cdp_use/cdp/library.py | 58 +- cdp_use/cdp/log/commands.py | 3 +- cdp_use/cdp/log/events.py | 2 + cdp_use/cdp/log/library.py | 72 +- cdp_use/cdp/log/registration.py | 10 +- cdp_use/cdp/log/types.py | 2 +- cdp_use/cdp/media/commands.py | 2 +- cdp_use/cdp/media/events.py | 14 +- cdp_use/cdp/media/library.py | 31 +- cdp_use/cdp/media/registration.py | 80 +- cdp_use/cdp/media/types.py | 11 +- cdp_use/cdp/memory/commands.py | 14 +- cdp_use/cdp/memory/events.py | 2 +- cdp_use/cdp/memory/library.py | 156 ++-- cdp_use/cdp/memory/registration.py | 2 +- cdp_use/cdp/memory/types.py | 4 - cdp_use/cdp/network/commands.py | 101 +-- cdp_use/cdp/network/events.py | 174 ++-- cdp_use/cdp/network/library.py | 546 ++++++----- cdp_use/cdp/network/registration.py | 516 +++++------ cdp_use/cdp/network/types.py | 356 +++++--- cdp_use/cdp/overlay/commands.py | 72 +- cdp_use/cdp/overlay/events.py | 11 +- cdp_use/cdp/overlay/library.py | 400 ++++---- cdp_use/cdp/overlay/registration.py | 47 +- cdp_use/cdp/overlay/types.py | 24 +- cdp_use/cdp/page/commands.py | 112 +-- cdp_use/cdp/page/events.py | 82 +- cdp_use/cdp/page/library.py | 855 +++++++++++------- cdp_use/cdp/page/registration.py | 360 ++++---- cdp_use/cdp/page/types.py | 410 +++++++-- cdp_use/cdp/performance/commands.py | 7 +- cdp_use/cdp/performance/events.py | 2 + cdp_use/cdp/performance/library.py | 61 +- cdp_use/cdp/performance/registration.py | 10 +- cdp_use/cdp/performance/types.py | 1 + cdp_use/cdp/performancetimeline/commands.py | 3 +- cdp_use/cdp/performancetimeline/events.py | 2 + cdp_use/cdp/performancetimeline/library.py | 20 +- .../cdp/performancetimeline/registration.py | 10 +- cdp_use/cdp/performancetimeline/types.py | 4 +- cdp_use/cdp/preload/commands.py | 2 +- cdp_use/cdp/preload/events.py | 15 +- cdp_use/cdp/preload/library.py | 31 +- cdp_use/cdp/preload/registration.py | 54 +- cdp_use/cdp/preload/types.py | 154 +++- cdp_use/cdp/profiler/commands.py | 7 +- cdp_use/cdp/profiler/events.py | 7 +- cdp_use/cdp/profiler/library.py | 132 +-- cdp_use/cdp/profiler/registration.py | 42 +- cdp_use/cdp/profiler/types.py | 6 +- cdp_use/cdp/pwa/commands.py | 15 +- cdp_use/cdp/pwa/events.py | 2 +- cdp_use/cdp/pwa/library.py | 191 ++-- cdp_use/cdp/pwa/registration.py | 2 +- cdp_use/cdp/pwa/types.py | 5 +- cdp_use/cdp/registration_library.py | 44 +- cdp_use/cdp/registry.py | 9 +- cdp_use/cdp/runtime/commands.py | 32 +- cdp_use/cdp/runtime/events.py | 23 +- cdp_use/cdp/runtime/library.py | 336 ++++--- cdp_use/cdp/runtime/registration.py | 82 +- cdp_use/cdp/runtime/types.py | 28 +- cdp_use/cdp/schema/commands.py | 1 + cdp_use/cdp/schema/events.py | 2 +- cdp_use/cdp/schema/library.py | 18 +- cdp_use/cdp/schema/registration.py | 2 +- cdp_use/cdp/schema/types.py | 1 + cdp_use/cdp/security/commands.py | 9 +- cdp_use/cdp/security/events.py | 8 +- cdp_use/cdp/security/library.py | 72 +- cdp_use/cdp/security/registration.py | 44 +- cdp_use/cdp/security/types.py | 13 +- cdp_use/cdp/serviceworker/commands.py | 27 +- cdp_use/cdp/serviceworker/events.py | 3 +- cdp_use/cdp/serviceworker/library.py | 161 ++-- cdp_use/cdp/serviceworker/registration.py | 22 +- cdp_use/cdp/serviceworker/types.py | 13 +- cdp_use/cdp/storage/commands.py | 93 +- cdp_use/cdp/storage/events.py | 32 +- cdp_use/cdp/storage/library.py | 521 +++++++---- cdp_use/cdp/storage/registration.py | 212 +++-- cdp_use/cdp/storage/types.py | 187 ++-- cdp_use/cdp/systeminfo/commands.py | 3 +- cdp_use/cdp/systeminfo/events.py | 2 +- cdp_use/cdp/systeminfo/library.py | 44 +- cdp_use/cdp/systeminfo/registration.py | 2 +- cdp_use/cdp/systeminfo/types.py | 29 +- cdp_use/cdp/target/commands.py | 40 +- cdp_use/cdp/target/events.py | 20 +- cdp_use/cdp/target/library.py | 283 +++--- cdp_use/cdp/target/registration.py | 98 +- cdp_use/cdp/target/types.py | 6 - cdp_use/cdp/tethering/commands.py | 6 +- cdp_use/cdp/tethering/events.py | 2 + cdp_use/cdp/tethering/library.py | 31 +- cdp_use/cdp/tethering/registration.py | 10 +- cdp_use/cdp/tethering/types.py | 2 +- cdp_use/cdp/tracing/commands.py | 8 +- cdp_use/cdp/tracing/events.py | 7 +- cdp_use/cdp/tracing/library.py | 70 +- cdp_use/cdp/tracing/registration.py | 44 +- cdp_use/cdp/tracing/types.py | 6 +- cdp_use/cdp/webaudio/commands.py | 1 + cdp_use/cdp/webaudio/events.py | 38 +- cdp_use/cdp/webaudio/library.py | 44 +- cdp_use/cdp/webaudio/registration.py | 110 +-- cdp_use/cdp/webaudio/types.py | 12 - cdp_use/cdp/webauthn/commands.py | 30 +- cdp_use/cdp/webauthn/events.py | 11 +- cdp_use/cdp/webauthn/library.py | 184 ++-- cdp_use/cdp/webauthn/registration.py | 59 +- cdp_use/cdp/webauthn/types.py | 5 - cdp_use/custom_protocols/browseruse.json | 9 +- cdp_use/generator/generator.py | 6 +- cdp_use/generator/registration_generator.py | 27 +- .../registration_library_generator.py | 8 +- pyproject.toml | 29 +- 279 files changed, 9291 insertions(+), 7179 deletions(-) create mode 100644 Taskfile.yml diff --git a/README.md b/README.md index 3e6dd64..8e202d3 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,13 @@ class CDPRegistrationLibrary: ### Regenerating Types ```bash +# Using task (recommended) +task generate + +# Or directly with uv +uv run python -m cdp_use.generator + +# Or with python python -m cdp_use.generator ``` @@ -215,6 +222,17 @@ This will: 3. Create domain-specific client classes 4. Format the code +### Available Tasks + +```bash +task generate # Regenerate CDP types from protocol definitions +task build # Build the distribution package +task lint # Run ruff linter +task format # Format code with ruff +task example # Run the simple example +task clean # Clean generated files and build artifacts +``` + ### Project Structure ``` diff --git a/Taskfile.yml b/Taskfile.yml new file mode 100644 index 0000000..2697557 --- /dev/null +++ b/Taskfile.yml @@ -0,0 +1,38 @@ +version: "3" + +tasks: + generate: + desc: "Regenerate CDP types from protocol definitions" + cmds: + - uv run python -m cdp_use.generator + + build: + desc: "Build the distribution package" + cmds: + - uv build + + install: + desc: "Install package in development mode" + cmds: + - uv pip install -e . + + lint: + desc: "Run ruff linter" + cmds: + - uv run ruff check cdp_use/ --statistics + + format: + desc: "Format code with ruff" + cmds: + - uv run ruff format cdp_use/ + + example: + desc: "Run the simple example" + cmds: + - uv run python simple.py + + clean: + desc: "Clean generated files and build artifacts" + cmds: + - rm -rf dist/ build/ *.egg-info + - find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true diff --git a/cdp_use/cdp/accessibility/commands.py b/cdp_use/cdp/accessibility/commands.py index 7566128..f5979af 100644 --- a/cdp_use/cdp/accessibility/commands.py +++ b/cdp_use/cdp/accessibility/commands.py @@ -17,6 +17,7 @@ from .types import AXNode from .types import AXNodeId + class GetPartialAXTreeParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node to get the partial accessibility tree for.""" @@ -34,7 +35,6 @@ class GetPartialAXTreeReturns(TypedDict): children, if requested.""" - class GetFullAXTreeParameters(TypedDict, total=False): depth: "int" """The maximum depth at which descendants of the root node should be retrieved. @@ -48,7 +48,6 @@ class GetFullAXTreeReturns(TypedDict): nodes: "List[AXNode]" - class GetRootAXNodeParameters(TypedDict, total=False): frameId: "FrameId" """The frame in whose document the node resides. @@ -59,7 +58,6 @@ class GetRootAXNodeReturns(TypedDict): node: "AXNode" - class GetAXNodeAndAncestorsParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node to get.""" @@ -73,7 +71,6 @@ class GetAXNodeAndAncestorsReturns(TypedDict): nodes: "List[AXNode]" - class GetChildAXNodesParameters(TypedDict): id: "AXNodeId" frameId: "NotRequired[FrameId]" @@ -85,7 +82,6 @@ class GetChildAXNodesReturns(TypedDict): nodes: "List[AXNode]" - class QueryAXTreeParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node for the root to query.""" diff --git a/cdp_use/cdp/accessibility/events.py b/cdp_use/cdp/accessibility/events.py index e27e603..1174d50 100644 --- a/cdp_use/cdp/accessibility/events.py +++ b/cdp_use/cdp/accessibility/events.py @@ -14,13 +14,16 @@ """The loadComplete event mirrors the load complete event sent by the browser to assistive technology when the web page has finished loading.""" + + class LoadCompleteEvent(TypedDict): root: "AXNode" """New document root node.""" - """The nodesUpdated event is sent every time a previously requested node has changed the in tree.""" + + class NodesUpdatedEvent(TypedDict): nodes: "List[AXNode]" """Updated node data.""" diff --git a/cdp_use/cdp/accessibility/library.py b/cdp_use/cdp/accessibility/library.py index 0d7ee1f..11cf929 100644 --- a/cdp_use/cdp/accessibility/library.py +++ b/cdp_use/cdp/accessibility/library.py @@ -23,10 +23,11 @@ from .commands import QueryAXTreeParameters from .commands import QueryAXTreeReturns + class AccessibilityClient: """Client for Accessibility domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -35,11 +36,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables the accessibility domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Accessibility.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Accessibility.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -47,12 +51,15 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls. -This turns on accessibility for the page, which can impact performance until accessibility is disabled.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Accessibility.enable", - params=params, - session_id=session_id, - )) + This turns on accessibility for the page, which can impact performance until accessibility is disabled.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Accessibility.enable", + params=params, + session_id=session_id, + ), + ) async def getPartialAXTree( self, @@ -60,11 +67,14 @@ async def getPartialAXTree( session_id: Optional[str] = None, ) -> "GetPartialAXTreeReturns": """Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists.""" - return cast("GetPartialAXTreeReturns", await self._client.send_raw( - method="Accessibility.getPartialAXTree", - params=params, - session_id=session_id, - )) + return cast( + "GetPartialAXTreeReturns", + await self._client.send_raw( + method="Accessibility.getPartialAXTree", + params=params, + session_id=session_id, + ), + ) async def getFullAXTree( self, @@ -72,11 +82,14 @@ async def getFullAXTree( session_id: Optional[str] = None, ) -> "GetFullAXTreeReturns": """Fetches the entire accessibility tree for the root Document""" - return cast("GetFullAXTreeReturns", await self._client.send_raw( - method="Accessibility.getFullAXTree", - params=params, - session_id=session_id, - )) + return cast( + "GetFullAXTreeReturns", + await self._client.send_raw( + method="Accessibility.getFullAXTree", + params=params, + session_id=session_id, + ), + ) async def getRootAXNode( self, @@ -84,12 +97,15 @@ async def getRootAXNode( session_id: Optional[str] = None, ) -> "GetRootAXNodeReturns": """Fetches the root node. -Requires `enable()` to have been called previously.""" - return cast("GetRootAXNodeReturns", await self._client.send_raw( - method="Accessibility.getRootAXNode", - params=params, - session_id=session_id, - )) + Requires `enable()` to have been called previously.""" + return cast( + "GetRootAXNodeReturns", + await self._client.send_raw( + method="Accessibility.getRootAXNode", + params=params, + session_id=session_id, + ), + ) async def getAXNodeAndAncestors( self, @@ -97,12 +113,15 @@ async def getAXNodeAndAncestors( session_id: Optional[str] = None, ) -> "GetAXNodeAndAncestorsReturns": """Fetches a node and all ancestors up to and including the root. -Requires `enable()` to have been called previously.""" - return cast("GetAXNodeAndAncestorsReturns", await self._client.send_raw( - method="Accessibility.getAXNodeAndAncestors", - params=params, - session_id=session_id, - )) + Requires `enable()` to have been called previously.""" + return cast( + "GetAXNodeAndAncestorsReturns", + await self._client.send_raw( + method="Accessibility.getAXNodeAndAncestors", + params=params, + session_id=session_id, + ), + ) async def getChildAXNodes( self, @@ -110,12 +129,15 @@ async def getChildAXNodes( session_id: Optional[str] = None, ) -> "GetChildAXNodesReturns": """Fetches a particular accessibility node by AXNodeId. -Requires `enable()` to have been called previously.""" - return cast("GetChildAXNodesReturns", await self._client.send_raw( - method="Accessibility.getChildAXNodes", - params=params, - session_id=session_id, - )) + Requires `enable()` to have been called previously.""" + return cast( + "GetChildAXNodesReturns", + await self._client.send_raw( + method="Accessibility.getChildAXNodes", + params=params, + session_id=session_id, + ), + ) async def queryAXTree( self, @@ -123,14 +145,15 @@ async def queryAXTree( session_id: Optional[str] = None, ) -> "QueryAXTreeReturns": """Query a DOM node's accessibility subtree for accessible name and role. -This command computes the name and role for all nodes in the subtree, including those that are -ignored for accessibility, and returns those that match the specified name and role. If no DOM -node is specified, or the DOM node does not exist, the command returns an error. If neither -`accessibleName` or `role` is specified, it returns all the accessibility nodes in the subtree.""" - return cast("QueryAXTreeReturns", await self._client.send_raw( - method="Accessibility.queryAXTree", - params=params, - session_id=session_id, - )) - - + This command computes the name and role for all nodes in the subtree, including those that are + ignored for accessibility, and returns those that match the specified name and role. If no DOM + node is specified, or the DOM node does not exist, the command returns an error. If neither + `accessibleName` or `role` is specified, it returns all the accessibility nodes in the subtree.""" + return cast( + "QueryAXTreeReturns", + await self._client.send_raw( + method="Accessibility.queryAXTree", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/accessibility/registration.py b/cdp_use/cdp/accessibility/registration.py index 6524531..7b29c32 100644 --- a/cdp_use/cdp/accessibility/registration.py +++ b/cdp_use/cdp/accessibility/registration.py @@ -12,41 +12,41 @@ from ..registry import EventRegistry from .events import LoadCompleteEvent, NodesUpdatedEvent + class AccessibilityRegistration: """Event registration interface for Accessibility domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Accessibility" def loadComplete( self, - callback: Callable[['LoadCompleteEvent', Optional[str]], None], + callback: Callable[["LoadCompleteEvent", Optional[str]], None], ) -> None: """ - Register a callback for loadComplete events. - - The loadComplete event mirrors the load complete event sent by the browser to assistive -technology when the web page has finished loading. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for loadComplete events. + + The loadComplete event mirrors the load complete event sent by the browser to assistive + technology when the web page has finished loading. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Accessibility.loadComplete", callback) def nodesUpdated( self, - callback: Callable[['NodesUpdatedEvent', Optional[str]], None], + callback: Callable[["NodesUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for nodesUpdated events. - + The nodesUpdated event is sent every time a previously requested node has changed the in tree. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Accessibility.nodesUpdated", callback) - diff --git a/cdp_use/cdp/accessibility/types.py b/cdp_use/cdp/accessibility/types.py index eac8b69..70117b9 100644 --- a/cdp_use/cdp/accessibility/types.py +++ b/cdp_use/cdp/accessibility/types.py @@ -18,22 +18,49 @@ """Unique accessibility node identifier.""" - -AXValueType = Literal["boolean", "tristate", "booleanOrUndefined", "idref", "idrefList", "integer", "node", "nodeList", "number", "string", "computedString", "token", "tokenList", "domRelation", "role", "internalRole", "valueUndefined"] +AXValueType = Literal[ + "boolean", + "tristate", + "booleanOrUndefined", + "idref", + "idrefList", + "integer", + "node", + "nodeList", + "number", + "string", + "computedString", + "token", + "tokenList", + "domRelation", + "role", + "internalRole", + "valueUndefined", +] """Enum of possible property types.""" - -AXValueSourceType = Literal["attribute", "implicit", "style", "contents", "placeholder", "relatedElement"] +AXValueSourceType = Literal[ + "attribute", "implicit", "style", "contents", "placeholder", "relatedElement" +] """Enum of possible property sources.""" - -AXValueNativeSourceType = Literal["description", "figcaption", "label", "labelfor", "labelwrapped", "legend", "rubyannotation", "tablecaption", "title", "other"] +AXValueNativeSourceType = Literal[ + "description", + "figcaption", + "label", + "labelfor", + "labelwrapped", + "legend", + "rubyannotation", + "tablecaption", + "title", + "other", +] """Enum of possible native property sources (as a subtype of a particular AXValueSourceType).""" - class AXValueSource(TypedDict): """A single source for a computed AX property.""" @@ -57,7 +84,6 @@ class AXValueSource(TypedDict): """Reason for the value being invalid, if it is.""" - class AXRelatedNode(TypedDict): backendDOMNodeId: "BackendNodeId" """The BackendNodeId of the related DOM node.""" @@ -67,7 +93,6 @@ class AXRelatedNode(TypedDict): """The text alternative of this node in the current context.""" - class AXProperty(TypedDict): name: "AXPropertyName" """The name of this property.""" @@ -75,7 +100,6 @@ class AXProperty(TypedDict): """The value of this property.""" - class AXValue(TypedDict): """A single computed AX property.""" @@ -89,15 +113,73 @@ class AXValue(TypedDict): """The sources which contributed to the computation of this property.""" - -AXPropertyName = Literal["actions", "busy", "disabled", "editable", "focusable", "focused", "hidden", "hiddenRoot", "invalid", "keyshortcuts", "settable", "roledescription", "live", "atomic", "relevant", "root", "autocomplete", "hasPopup", "level", "multiselectable", "orientation", "multiline", "readonly", "required", "valuemin", "valuemax", "valuetext", "checked", "expanded", "modal", "pressed", "selected", "activedescendant", "controls", "describedby", "details", "errormessage", "flowto", "labelledby", "owns", "url"] +AXPropertyName = Literal[ + "actions", + "busy", + "disabled", + "editable", + "focusable", + "focused", + "hidden", + "hiddenRoot", + "invalid", + "keyshortcuts", + "settable", + "roledescription", + "live", + "atomic", + "relevant", + "root", + "autocomplete", + "hasPopup", + "level", + "multiselectable", + "orientation", + "multiline", + "readonly", + "required", + "valuemin", + "valuemax", + "valuetext", + "checked", + "expanded", + "modal", + "pressed", + "selected", + "activedescendant", + "controls", + "describedby", + "details", + "errormessage", + "flowto", + "labelledby", + "owns", + "url", + "activeFullscreenElement", + "activeModalDialog", + "activeAriaModalDialog", + "ariaHiddenElement", + "ariaHiddenSubtree", + "emptyAlt", + "emptyText", + "inertElement", + "inertSubtree", + "labelContainer", + "labelFor", + "notRendered", + "notVisible", + "presentationalRole", + "probablyPresentational", + "inactiveCarouselTabContent", + "uninteresting", +] """Values of AXProperty name: - from 'busy' to 'roledescription': states which apply to every AX node - from 'live' to 'root': attributes which apply to nodes in live regions - from 'autocomplete' to 'valuetext': attributes which apply to widgets - from 'checked' to 'selected': states which apply to widgets -- from 'activedescendant' to 'owns' - relationships between elements other than parent/child/sibling.""" - +- from 'activedescendant' to 'owns': relationships between elements other than parent/child/sibling +- from 'activeFullscreenElement' to 'uninteresting': reasons why this noode is hidden""" class AXNode(TypedDict): diff --git a/cdp_use/cdp/animation/commands.py b/cdp_use/cdp/animation/commands.py index 79afb62..2c16e24 100644 --- a/cdp_use/cdp/animation/commands.py +++ b/cdp_use/cdp/animation/commands.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: from ..runtime.types import RemoteObject + class GetCurrentTimeParameters(TypedDict): id: "str" """Id of animation.""" @@ -22,21 +23,16 @@ class GetCurrentTimeReturns(TypedDict): """Current time of the page.""" - class GetPlaybackRateReturns(TypedDict): playbackRate: "float" """Playback rate for animations on page.""" - class ReleaseAnimationsParameters(TypedDict): animations: "List[str]" """List of animation ids to seek.""" - - - class ResolveAnimationParameters(TypedDict): animationId: "str" """Animation id.""" @@ -47,7 +43,6 @@ class ResolveAnimationReturns(TypedDict): """Corresponding remote object.""" - class SeekAnimationsParameters(TypedDict): animations: "List[str]" """List of animation ids to seek.""" @@ -55,9 +50,6 @@ class SeekAnimationsParameters(TypedDict): """Set the current time of each animation.""" - - - class SetPausedParameters(TypedDict): animations: "List[str]" """Animations to set the pause state of.""" @@ -65,17 +57,11 @@ class SetPausedParameters(TypedDict): """Paused state to set to.""" - - - class SetPlaybackRateParameters(TypedDict): playbackRate: "float" """Playback rate for animations on page""" - - - class SetTimingParameters(TypedDict): animationId: "str" """Animation id.""" @@ -83,5 +69,3 @@ class SetTimingParameters(TypedDict): """Duration of the animation.""" delay: "float" """Delay of the animation.""" - - diff --git a/cdp_use/cdp/animation/events.py b/cdp_use/cdp/animation/events.py index e2bd3ac..f018183 100644 --- a/cdp_use/cdp/animation/events.py +++ b/cdp_use/cdp/animation/events.py @@ -12,27 +12,32 @@ from .types import Animation """Event for when an animation has been cancelled.""" + + class AnimationCanceledEvent(TypedDict): id: "str" """Id of the animation that was cancelled.""" - """Event for each animation that has been created.""" + + class AnimationCreatedEvent(TypedDict): id: "str" """Id of the animation that was created.""" - """Event for animation that has been started.""" + + class AnimationStartedEvent(TypedDict): animation: "Animation" """Animation that was started.""" - """Event for animation that has been updated.""" + + class AnimationUpdatedEvent(TypedDict): animation: "Animation" """Animation that was updated.""" diff --git a/cdp_use/cdp/animation/library.py b/cdp_use/cdp/animation/library.py index 53aac6e..13bd075 100644 --- a/cdp_use/cdp/animation/library.py +++ b/cdp_use/cdp/animation/library.py @@ -21,10 +21,11 @@ from .commands import SetPlaybackRateParameters from .commands import SetTimingParameters + class AnimationClient: """Client for Animation domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -33,11 +34,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables animation domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -45,11 +49,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables animation domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.enable", + params=params, + session_id=session_id, + ), + ) async def getCurrentTime( self, @@ -57,11 +64,14 @@ async def getCurrentTime( session_id: Optional[str] = None, ) -> "GetCurrentTimeReturns": """Returns the current time of the an animation.""" - return cast("GetCurrentTimeReturns", await self._client.send_raw( - method="Animation.getCurrentTime", - params=params, - session_id=session_id, - )) + return cast( + "GetCurrentTimeReturns", + await self._client.send_raw( + method="Animation.getCurrentTime", + params=params, + session_id=session_id, + ), + ) async def getPlaybackRate( self, @@ -69,11 +79,14 @@ async def getPlaybackRate( session_id: Optional[str] = None, ) -> "GetPlaybackRateReturns": """Gets the playback rate of the document timeline.""" - return cast("GetPlaybackRateReturns", await self._client.send_raw( - method="Animation.getPlaybackRate", - params=params, - session_id=session_id, - )) + return cast( + "GetPlaybackRateReturns", + await self._client.send_raw( + method="Animation.getPlaybackRate", + params=params, + session_id=session_id, + ), + ) async def releaseAnimations( self, @@ -81,11 +94,14 @@ async def releaseAnimations( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Releases a set of animations to no longer be manipulated.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.releaseAnimations", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.releaseAnimations", + params=params, + session_id=session_id, + ), + ) async def resolveAnimation( self, @@ -93,11 +109,14 @@ async def resolveAnimation( session_id: Optional[str] = None, ) -> "ResolveAnimationReturns": """Gets the remote object of the Animation.""" - return cast("ResolveAnimationReturns", await self._client.send_raw( - method="Animation.resolveAnimation", - params=params, - session_id=session_id, - )) + return cast( + "ResolveAnimationReturns", + await self._client.send_raw( + method="Animation.resolveAnimation", + params=params, + session_id=session_id, + ), + ) async def seekAnimations( self, @@ -105,11 +124,14 @@ async def seekAnimations( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Seek a set of animations to a particular time within each animation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.seekAnimations", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.seekAnimations", + params=params, + session_id=session_id, + ), + ) async def setPaused( self, @@ -117,11 +139,14 @@ async def setPaused( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets the paused state of a set of animations.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.setPaused", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.setPaused", + params=params, + session_id=session_id, + ), + ) async def setPlaybackRate( self, @@ -129,11 +154,14 @@ async def setPlaybackRate( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets the playback rate of the document timeline.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.setPlaybackRate", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.setPlaybackRate", + params=params, + session_id=session_id, + ), + ) async def setTiming( self, @@ -141,10 +169,11 @@ async def setTiming( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets the timing of an animation node.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Animation.setTiming", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Animation.setTiming", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/animation/registration.py b/cdp_use/cdp/animation/registration.py index 580a86f..7bcb66c 100644 --- a/cdp_use/cdp/animation/registration.py +++ b/cdp_use/cdp/animation/registration.py @@ -10,24 +10,30 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import AnimationCanceledEvent, AnimationCreatedEvent, AnimationStartedEvent, AnimationUpdatedEvent + from .events import ( + AnimationCanceledEvent, + AnimationCreatedEvent, + AnimationStartedEvent, + AnimationUpdatedEvent, + ) + class AnimationRegistration: """Event registration interface for Animation domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Animation" def animationCanceled( self, - callback: Callable[['AnimationCanceledEvent', Optional[str]], None], + callback: Callable[["AnimationCanceledEvent", Optional[str]], None], ) -> None: """ Register a callback for animationCanceled events. - + Event for when an animation has been cancelled. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -36,13 +42,13 @@ def animationCanceled( def animationCreated( self, - callback: Callable[['AnimationCreatedEvent', Optional[str]], None], + callback: Callable[["AnimationCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for animationCreated events. - + Event for each animation that has been created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -51,13 +57,13 @@ def animationCreated( def animationStarted( self, - callback: Callable[['AnimationStartedEvent', Optional[str]], None], + callback: Callable[["AnimationStartedEvent", Optional[str]], None], ) -> None: """ Register a callback for animationStarted events. - + Event for animation that has been started. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -66,16 +72,15 @@ def animationStarted( def animationUpdated( self, - callback: Callable[['AnimationUpdatedEvent', Optional[str]], None], + callback: Callable[["AnimationUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for animationUpdated events. - + Event for animation that has been updated. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Animation.animationUpdated", callback) - diff --git a/cdp_use/cdp/animation/types.py b/cdp_use/cdp/animation/types.py index 03a48a0..0c291d8 100644 --- a/cdp_use/cdp/animation/types.py +++ b/cdp_use/cdp/animation/types.py @@ -13,6 +13,7 @@ from ..dom.types import BackendNodeId from ..dom.types import ScrollOrientation + class Animation(TypedDict): """Animation instance.""" @@ -44,7 +45,6 @@ class Animation(TypedDict): """View or scroll timeline""" - class ViewOrScrollTimeline(TypedDict): """Timeline instance""" @@ -64,7 +64,6 @@ class ViewOrScrollTimeline(TypedDict): """Orientation of the scroll""" - class AnimationEffect(TypedDict): """AnimationEffect instance""" @@ -74,8 +73,8 @@ class AnimationEffect(TypedDict): """`AnimationEffect`'s end delay.""" iterationStart: "float" """`AnimationEffect`'s iteration start.""" - iterations: "float" - """`AnimationEffect`'s iterations.""" + iterations: "NotRequired[float]" + """`AnimationEffect`'s iterations. Omitted if the value is infinite.""" duration: "float" """`AnimationEffect`'s iteration duration. Milliseconds for time based animations and @@ -93,7 +92,6 @@ class AnimationEffect(TypedDict): """`AnimationEffect`'s timing function.""" - class KeyframesRule(TypedDict): """Keyframes Rule""" @@ -103,7 +101,6 @@ class KeyframesRule(TypedDict): """List of animation keyframes.""" - class KeyframeStyle(TypedDict): """Keyframe Style""" diff --git a/cdp_use/cdp/audits/commands.py b/cdp_use/cdp/audits/commands.py index 4355511..34776c8 100644 --- a/cdp_use/cdp/audits/commands.py +++ b/cdp_use/cdp/audits/commands.py @@ -13,6 +13,7 @@ from ..network.types import RequestId from .types import GenericIssueDetails + class GetEncodedResponseParameters(TypedDict): requestId: "RequestId" """Identifier of the network request to get content for.""" @@ -33,14 +34,10 @@ class GetEncodedResponseReturns(TypedDict): """Size after re-encoding.""" - class CheckContrastParameters(TypedDict, total=False): reportAAA: "bool" """Whether to report WCAG AAA level issues. Default is false.""" - - - class CheckFormsIssuesReturns(TypedDict): formIssues: "List[GenericIssueDetails]" diff --git a/cdp_use/cdp/audits/events.py b/cdp_use/cdp/audits/events.py index 7d65536..7ae372d 100644 --- a/cdp_use/cdp/audits/events.py +++ b/cdp_use/cdp/audits/events.py @@ -11,5 +11,6 @@ if TYPE_CHECKING: from .types import InspectorIssue + class IssueAddedEvent(TypedDict): issue: "InspectorIssue" diff --git a/cdp_use/cdp/audits/library.py b/cdp_use/cdp/audits/library.py index 6f7724e..940835c 100644 --- a/cdp_use/cdp/audits/library.py +++ b/cdp_use/cdp/audits/library.py @@ -15,10 +15,11 @@ from .commands import GetEncodedResponseParameters from .commands import GetEncodedResponseReturns + class AuditsClient: """Client for Audits domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getEncodedResponse( @@ -27,12 +28,15 @@ async def getEncodedResponse( session_id: Optional[str] = None, ) -> "GetEncodedResponseReturns": """Returns the response body and size if it were re-encoded with the specified settings. Only -applies to images.""" - return cast("GetEncodedResponseReturns", await self._client.send_raw( - method="Audits.getEncodedResponse", - params=params, - session_id=session_id, - )) + applies to images.""" + return cast( + "GetEncodedResponseReturns", + await self._client.send_raw( + method="Audits.getEncodedResponse", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -40,11 +44,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables issues domain, prevents further issues from being reported to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Audits.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Audits.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -52,12 +59,15 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables issues domain, sends the issues collected so far to the client by means of the -`issueAdded` event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Audits.enable", - params=params, - session_id=session_id, - )) + `issueAdded` event.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Audits.enable", + params=params, + session_id=session_id, + ), + ) async def checkContrast( self, @@ -65,12 +75,15 @@ async def checkContrast( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Runs the contrast check for the target page. Found issues are reported -using Audits.issueAdded event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Audits.checkContrast", - params=params, - session_id=session_id, - )) + using Audits.issueAdded event.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Audits.checkContrast", + params=params, + session_id=session_id, + ), + ) async def checkFormsIssues( self, @@ -78,11 +91,12 @@ async def checkFormsIssues( session_id: Optional[str] = None, ) -> "CheckFormsIssuesReturns": """Runs the form issues check for the target page. Found issues are reported -using Audits.issueAdded event.""" - return cast("CheckFormsIssuesReturns", await self._client.send_raw( - method="Audits.checkFormsIssues", - params=params, - session_id=session_id, - )) - - + using Audits.issueAdded event.""" + return cast( + "CheckFormsIssuesReturns", + await self._client.send_raw( + method="Audits.checkFormsIssues", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/audits/registration.py b/cdp_use/cdp/audits/registration.py index d5d8745..92a4247 100644 --- a/cdp_use/cdp/audits/registration.py +++ b/cdp_use/cdp/audits/registration.py @@ -12,23 +12,23 @@ from ..registry import EventRegistry from .events import IssueAddedEvent + class AuditsRegistration: """Event registration interface for Audits domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Audits" def issueAdded( self, - callback: Callable[['IssueAddedEvent', Optional[str]], None], + callback: Callable[["IssueAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for issueAdded events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Audits.issueAdded", callback) - diff --git a/cdp_use/cdp/audits/types.py b/cdp_use/cdp/audits/types.py index 2ff95e3..1ee14f8 100644 --- a/cdp_use/cdp/audits/types.py +++ b/cdp_use/cdp/audits/types.py @@ -20,6 +20,7 @@ from ..page.types import FrameId from ..runtime.types import ScriptId + class AffectedCookie(TypedDict): """Information about a cookie that is affected by an inspector issue.""" @@ -29,7 +30,6 @@ class AffectedCookie(TypedDict): domain: "str" - class AffectedRequest(TypedDict): """Information about a request that is affected by an inspector issue.""" @@ -38,31 +38,52 @@ class AffectedRequest(TypedDict): url: "str" - class AffectedFrame(TypedDict): """Information about the frame affected by an inspector issue.""" frameId: "FrameId" - -CookieExclusionReason = Literal["ExcludeSameSiteUnspecifiedTreatedAsLax", "ExcludeSameSiteNoneInsecure", "ExcludeSameSiteLax", "ExcludeSameSiteStrict", "ExcludeInvalidSameParty", "ExcludeSamePartyCrossPartyContext", "ExcludeDomainNonASCII", "ExcludeThirdPartyCookieBlockedInFirstPartySet", "ExcludeThirdPartyPhaseout", "ExcludePortMismatch", "ExcludeSchemeMismatch"] - - - -CookieWarningReason = Literal["WarnSameSiteUnspecifiedCrossSiteContext", "WarnSameSiteNoneInsecure", "WarnSameSiteUnspecifiedLaxAllowUnsafe", "WarnSameSiteStrictLaxDowngradeStrict", "WarnSameSiteStrictCrossDowngradeStrict", "WarnSameSiteStrictCrossDowngradeLax", "WarnSameSiteLaxCrossDowngradeStrict", "WarnSameSiteLaxCrossDowngradeLax", "WarnAttributeValueExceedsMaxSize", "WarnDomainNonASCII", "WarnThirdPartyPhaseout", "WarnCrossSiteRedirectDowngradeChangesInclusion", "WarnDeprecationTrialMetadata", "WarnThirdPartyCookieHeuristic"] - +CookieExclusionReason = Literal[ + "ExcludeSameSiteUnspecifiedTreatedAsLax", + "ExcludeSameSiteNoneInsecure", + "ExcludeSameSiteLax", + "ExcludeSameSiteStrict", + "ExcludeInvalidSameParty", + "ExcludeSamePartyCrossPartyContext", + "ExcludeDomainNonASCII", + "ExcludeThirdPartyCookieBlockedInFirstPartySet", + "ExcludeThirdPartyPhaseout", + "ExcludePortMismatch", + "ExcludeSchemeMismatch", +] + + +CookieWarningReason = Literal[ + "WarnSameSiteUnspecifiedCrossSiteContext", + "WarnSameSiteNoneInsecure", + "WarnSameSiteUnspecifiedLaxAllowUnsafe", + "WarnSameSiteStrictLaxDowngradeStrict", + "WarnSameSiteStrictCrossDowngradeStrict", + "WarnSameSiteStrictCrossDowngradeLax", + "WarnSameSiteLaxCrossDowngradeStrict", + "WarnSameSiteLaxCrossDowngradeLax", + "WarnAttributeValueExceedsMaxSize", + "WarnDomainNonASCII", + "WarnThirdPartyPhaseout", + "WarnCrossSiteRedirectDowngradeChangesInclusion", + "WarnDeprecationTrialMetadata", + "WarnThirdPartyCookieHeuristic", +] CookieOperation = Literal["SetCookie", "ReadCookie"] - InsightType = Literal["GitHubResource", "GracePeriod", "Heuristics"] """Represents the category of insight that a cookie issue falls under.""" - class CookieIssueInsight(TypedDict): """Information about the suggested solution to a cookie issue.""" @@ -71,11 +92,10 @@ class CookieIssueInsight(TypedDict): """Link to table entry in third-party cookie migration readiness list.""" - class CookieIssueDetails(TypedDict): """This information is currently necessary, as the front-end has a difficult -time finding a specific cookie. With this, we can convey specific error -information without the cookie.""" + time finding a specific cookie. With this, we can convey specific error + information without the cookie.""" cookie: "NotRequired[AffectedCookie]" """If AffectedCookie is not set then rawCookieLine contains the raw @@ -95,13 +115,42 @@ class CookieIssueDetails(TypedDict): """The recommended solution to the issue.""" - -MixedContentResolutionStatus = Literal["MixedContentBlocked", "MixedContentAutomaticallyUpgraded", "MixedContentWarning"] - - - -MixedContentResourceType = Literal["AttributionSrc", "Audio", "Beacon", "CSPReport", "Download", "EventSource", "Favicon", "Font", "Form", "Frame", "Image", "Import", "JSON", "Manifest", "Ping", "PluginData", "PluginResource", "Prefetch", "Resource", "Script", "ServiceWorker", "SharedWorker", "SpeculationRules", "Stylesheet", "Track", "Video", "Worker", "XMLHttpRequest", "XSLT"] - +MixedContentResolutionStatus = Literal[ + "MixedContentBlocked", "MixedContentAutomaticallyUpgraded", "MixedContentWarning" +] + + +MixedContentResourceType = Literal[ + "AttributionSrc", + "Audio", + "Beacon", + "CSPReport", + "Download", + "EventSource", + "Favicon", + "Font", + "Form", + "Frame", + "Image", + "Import", + "JSON", + "Manifest", + "Ping", + "PluginData", + "PluginResource", + "Prefetch", + "Resource", + "Script", + "ServiceWorker", + "SharedWorker", + "SpeculationRules", + "Stylesheet", + "Track", + "Video", + "Worker", + "XMLHttpRequest", + "XSLT", +] class MixedContentIssueDetails(TypedDict): @@ -123,17 +172,24 @@ class MixedContentIssueDetails(TypedDict): """Optional because not every mixed content issue is necessarily linked to a frame.""" - -BlockedByResponseReason = Literal["CoepFrameResourceNeedsCoepHeader", "CoopSandboxedIFrameCannotNavigateToCoopPage", "CorpNotSameOrigin", "CorpNotSameOriginAfterDefaultedToSameOriginByCoep", "CorpNotSameOriginAfterDefaultedToSameOriginByDip", "CorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip", "CorpNotSameSite", "SRIMessageSignatureMismatch"] +BlockedByResponseReason = Literal[ + "CoepFrameResourceNeedsCoepHeader", + "CoopSandboxedIFrameCannotNavigateToCoopPage", + "CorpNotSameOrigin", + "CorpNotSameOriginAfterDefaultedToSameOriginByCoep", + "CorpNotSameOriginAfterDefaultedToSameOriginByDip", + "CorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip", + "CorpNotSameSite", + "SRIMessageSignatureMismatch", +] """Enum indicating the reason a response has been blocked. These reasons are refinements of the net error BLOCKED_BY_RESPONSE.""" - class BlockedByResponseIssueDetails(TypedDict): """Details for a request that has been blocked with the BLOCKED_BY_RESPONSE -code. Currently only used for COEP/COOP, but may be extended to include -some CSP errors in the future.""" + code. Currently only used for COEP/COOP, but may be extended to include + some CSP errors in the future.""" request: "AffectedRequest" parentFrame: "NotRequired[AffectedFrame]" @@ -141,15 +197,12 @@ class BlockedByResponseIssueDetails(TypedDict): reason: "BlockedByResponseReason" - HeavyAdResolutionStatus = Literal["HeavyAdBlocked", "HeavyAdWarning"] - HeavyAdReason = Literal["NetworkTotalLimit", "CpuTotalLimit", "CpuPeakLimit"] - class HeavyAdIssueDetails(TypedDict): resolution: "HeavyAdResolutionStatus" """The resolution status, either blocking the content or warning.""" @@ -159,9 +212,15 @@ class HeavyAdIssueDetails(TypedDict): """The frame that was blocked.""" - -ContentSecurityPolicyViolationType = Literal["kInlineViolation", "kEvalViolation", "kURLViolation", "kSRIViolation", "kTrustedTypesSinkViolation", "kTrustedTypesPolicyViolation", "kWasmEvalViolation"] - +ContentSecurityPolicyViolationType = Literal[ + "kInlineViolation", + "kEvalViolation", + "kURLViolation", + "kSRIViolation", + "kTrustedTypesSinkViolation", + "kTrustedTypesPolicyViolation", + "kWasmEvalViolation", +] class SourceCodeLocation(TypedDict): @@ -171,7 +230,6 @@ class SourceCodeLocation(TypedDict): columnNumber: "int" - class ContentSecurityPolicyIssueDetails(TypedDict): blockedURL: "NotRequired[str]" """The url not included in allowed sources.""" @@ -184,21 +242,18 @@ class ContentSecurityPolicyIssueDetails(TypedDict): violatingNodeId: "NotRequired[BackendNodeId]" - SharedArrayBufferIssueType = Literal["TransferIssue", "CreationIssue"] - class SharedArrayBufferIssueDetails(TypedDict): """Details for a issue arising from an SAB being instantiated in, or -transferred to a context that is not cross-origin isolated.""" + transferred to a context that is not cross-origin isolated.""" sourceCodeLocation: "SourceCodeLocation" isWarning: "bool" type: "SharedArrayBufferIssueType" - class LowTextContrastIssueDetails(TypedDict): violatingNodeId: "BackendNodeId" violatingNodeSelector: "str" @@ -209,10 +264,9 @@ class LowTextContrastIssueDetails(TypedDict): fontWeight: "str" - class CorsIssueDetails(TypedDict): """Details for a CORS related issue, e.g. a warning or error related to -CORS RFC1918 enforcement.""" + CORS RFC1918 enforcement.""" corsErrorStatus: "CorsErrorStatus" isWarning: "bool" @@ -223,26 +277,96 @@ class CorsIssueDetails(TypedDict): clientSecurityState: "NotRequired[ClientSecurityState]" - -AttributionReportingIssueType = Literal["PermissionPolicyDisabled", "UntrustworthyReportingOrigin", "InsecureContext", "InvalidHeader", "InvalidRegisterTriggerHeader", "SourceAndTriggerHeaders", "SourceIgnored", "TriggerIgnored", "OsSourceIgnored", "OsTriggerIgnored", "InvalidRegisterOsSourceHeader", "InvalidRegisterOsTriggerHeader", "WebAndOsHeaders", "NoWebOrOsSupport", "NavigationRegistrationWithoutTransientUserActivation", "InvalidInfoHeader", "NoRegisterSourceHeader", "NoRegisterTriggerHeader", "NoRegisterOsSourceHeader", "NoRegisterOsTriggerHeader", "NavigationRegistrationUniqueScopeAlreadySet"] - - - -SharedDictionaryError = Literal["UseErrorCrossOriginNoCorsRequest", "UseErrorDictionaryLoadFailure", "UseErrorMatchingDictionaryNotUsed", "UseErrorUnexpectedContentDictionaryHeader", "WriteErrorCossOriginNoCorsRequest", "WriteErrorDisallowedBySettings", "WriteErrorExpiredResponse", "WriteErrorFeatureDisabled", "WriteErrorInsufficientResources", "WriteErrorInvalidMatchField", "WriteErrorInvalidStructuredHeader", "WriteErrorNavigationRequest", "WriteErrorNoMatchField", "WriteErrorNonListMatchDestField", "WriteErrorNonSecureContext", "WriteErrorNonStringIdField", "WriteErrorNonStringInMatchDestList", "WriteErrorNonStringMatchField", "WriteErrorNonTokenTypeField", "WriteErrorRequestAborted", "WriteErrorShuttingDown", "WriteErrorTooLongIdField", "WriteErrorUnsupportedType"] - - - -SRIMessageSignatureError = Literal["MissingSignatureHeader", "MissingSignatureInputHeader", "InvalidSignatureHeader", "InvalidSignatureInputHeader", "SignatureHeaderValueIsNotByteSequence", "SignatureHeaderValueIsParameterized", "SignatureHeaderValueIsIncorrectLength", "SignatureInputHeaderMissingLabel", "SignatureInputHeaderValueNotInnerList", "SignatureInputHeaderValueMissingComponents", "SignatureInputHeaderInvalidComponentType", "SignatureInputHeaderInvalidComponentName", "SignatureInputHeaderInvalidHeaderComponentParameter", "SignatureInputHeaderInvalidDerivedComponentParameter", "SignatureInputHeaderKeyIdLength", "SignatureInputHeaderInvalidParameter", "SignatureInputHeaderMissingRequiredParameters", "ValidationFailedSignatureExpired", "ValidationFailedInvalidLength", "ValidationFailedSignatureMismatch", "ValidationFailedIntegrityMismatch"] - - - -UnencodedDigestError = Literal["MalformedDictionary", "UnknownAlgorithm", "IncorrectDigestType", "IncorrectDigestLength"] - +AttributionReportingIssueType = Literal[ + "PermissionPolicyDisabled", + "UntrustworthyReportingOrigin", + "InsecureContext", + "InvalidHeader", + "InvalidRegisterTriggerHeader", + "SourceAndTriggerHeaders", + "SourceIgnored", + "TriggerIgnored", + "OsSourceIgnored", + "OsTriggerIgnored", + "InvalidRegisterOsSourceHeader", + "InvalidRegisterOsTriggerHeader", + "WebAndOsHeaders", + "NoWebOrOsSupport", + "NavigationRegistrationWithoutTransientUserActivation", + "InvalidInfoHeader", + "NoRegisterSourceHeader", + "NoRegisterTriggerHeader", + "NoRegisterOsSourceHeader", + "NoRegisterOsTriggerHeader", + "NavigationRegistrationUniqueScopeAlreadySet", +] + + +SharedDictionaryError = Literal[ + "UseErrorCrossOriginNoCorsRequest", + "UseErrorDictionaryLoadFailure", + "UseErrorMatchingDictionaryNotUsed", + "UseErrorUnexpectedContentDictionaryHeader", + "WriteErrorCossOriginNoCorsRequest", + "WriteErrorDisallowedBySettings", + "WriteErrorExpiredResponse", + "WriteErrorFeatureDisabled", + "WriteErrorInsufficientResources", + "WriteErrorInvalidMatchField", + "WriteErrorInvalidStructuredHeader", + "WriteErrorInvalidTTLField", + "WriteErrorNavigationRequest", + "WriteErrorNoMatchField", + "WriteErrorNonIntegerTTLField", + "WriteErrorNonListMatchDestField", + "WriteErrorNonSecureContext", + "WriteErrorNonStringIdField", + "WriteErrorNonStringInMatchDestList", + "WriteErrorNonStringMatchField", + "WriteErrorNonTokenTypeField", + "WriteErrorRequestAborted", + "WriteErrorShuttingDown", + "WriteErrorTooLongIdField", + "WriteErrorUnsupportedType", +] + + +SRIMessageSignatureError = Literal[ + "MissingSignatureHeader", + "MissingSignatureInputHeader", + "InvalidSignatureHeader", + "InvalidSignatureInputHeader", + "SignatureHeaderValueIsNotByteSequence", + "SignatureHeaderValueIsParameterized", + "SignatureHeaderValueIsIncorrectLength", + "SignatureInputHeaderMissingLabel", + "SignatureInputHeaderValueNotInnerList", + "SignatureInputHeaderValueMissingComponents", + "SignatureInputHeaderInvalidComponentType", + "SignatureInputHeaderInvalidComponentName", + "SignatureInputHeaderInvalidHeaderComponentParameter", + "SignatureInputHeaderInvalidDerivedComponentParameter", + "SignatureInputHeaderKeyIdLength", + "SignatureInputHeaderInvalidParameter", + "SignatureInputHeaderMissingRequiredParameters", + "ValidationFailedSignatureExpired", + "ValidationFailedInvalidLength", + "ValidationFailedSignatureMismatch", + "ValidationFailedIntegrityMismatch", +] + + +UnencodedDigestError = Literal[ + "MalformedDictionary", + "UnknownAlgorithm", + "IncorrectDigestType", + "IncorrectDigestLength", +] class AttributionReportingIssueDetails(TypedDict): """Details for issues around \"Attribution Reporting API\" usage. -Explainer: https://github.com/WICG/attribution-reporting-api""" + Explainer: https://github.com/WICG/attribution-reporting-api""" violationType: "AttributionReportingIssueType" request: "NotRequired[AffectedRequest]" @@ -250,10 +374,9 @@ class AttributionReportingIssueDetails(TypedDict): invalidParameter: "NotRequired[str]" - class QuirksModeIssueDetails(TypedDict): """Details for issues about documents in Quirks Mode -or Limited Quirks Mode that affects page layouting.""" + or Limited Quirks Mode that affects page layouting.""" isLimitedQuirksMode: "bool" """If false, it means the document's mode is \"quirks\" @@ -264,19 +387,16 @@ class QuirksModeIssueDetails(TypedDict): loaderId: "LoaderId" - class NavigatorUserAgentIssueDetails(TypedDict): url: "str" location: "NotRequired[SourceCodeLocation]" - class SharedDictionaryIssueDetails(TypedDict): sharedDictionaryError: "SharedDictionaryError" request: "AffectedRequest" - class SRIMessageSignatureIssueDetails(TypedDict): error: "SRIMessageSignatureError" signatureBase: "str" @@ -284,15 +404,25 @@ class SRIMessageSignatureIssueDetails(TypedDict): request: "AffectedRequest" - class UnencodedDigestIssueDetails(TypedDict): error: "UnencodedDigestError" request: "AffectedRequest" - -GenericIssueErrorType = Literal["FormLabelForNameError", "FormDuplicateIdForInputError", "FormInputWithNoLabelError", "FormAutocompleteAttributeEmptyError", "FormEmptyIdAndNameAttributesForInputError", "FormAriaLabelledByToNonExistingId", "FormInputAssignedAutocompleteValueToIdOrNameAttributeError", "FormLabelHasNeitherForNorNestedInput", "FormLabelForMatchesNonExistingIdError", "FormInputHasWrongButWellIntendedAutocompleteValueError", "ResponseWasBlockedByORB"] - +GenericIssueErrorType = Literal[ + "FormLabelForNameError", + "FormDuplicateIdForInputError", + "FormInputWithNoLabelError", + "FormAutocompleteAttributeEmptyError", + "FormEmptyIdAndNameAttributesForInputError", + "FormAriaLabelledByToNonExistingIdError", + "FormInputAssignedAutocompleteValueToIdOrNameAttributeError", + "FormLabelHasNeitherForNorNestedInputError", + "FormLabelForMatchesNonExistingIdError", + "FormInputHasWrongButWellIntendedAutocompleteValueError", + "ResponseWasBlockedByORB", + "NavigationEntryMarkedSkippable", +] class GenericIssueDetails(TypedDict): @@ -306,10 +436,9 @@ class GenericIssueDetails(TypedDict): request: "NotRequired[AffectedRequest]" - class DeprecationIssueDetails(TypedDict): """This issue tracks information needed to print a deprecation message. -https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/frame/third_party/blink/renderer/core/frame/deprecation/README.md""" + https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/frame/third_party/blink/renderer/core/frame/deprecation/README.md""" affectedFrame: "NotRequired[AffectedFrame]" sourceCodeLocation: "SourceCodeLocation" @@ -317,24 +446,22 @@ class DeprecationIssueDetails(TypedDict): """One of the deprecation names from third_party/blink/renderer/core/frame/deprecation/deprecation.json5""" - class BounceTrackingIssueDetails(TypedDict): """This issue warns about sites in the redirect chain of a finished navigation -that may be flagged as trackers and have their state cleared if they don't -receive a user interaction. Note that in this context 'site' means eTLD+1. -For example, if the URL `https://example.test:80/bounce` was in the -redirect chain, the site reported would be `example.test`.""" + that may be flagged as trackers and have their state cleared if they don't + receive a user interaction. Note that in this context 'site' means eTLD+1. + For example, if the URL `https://example.test:80/bounce` was in the + redirect chain, the site reported would be `example.test`.""" trackingSites: "List[str]" - class CookieDeprecationMetadataIssueDetails(TypedDict): """This issue warns about third-party sites that are accessing cookies on the -current page, and have been permitted due to having a global metadata grant. -Note that in this context 'site' means eTLD+1. For example, if the URL -`https://example.test:80/web_page` was accessing cookies, the site reported -would be `example.test`.""" + current page, and have been permitted due to having a global metadata grant. + Note that in this context 'site' means eTLD+1. For example, if the URL + `https://example.test:80/web_page` was accessing cookies, the site reported + would be `example.test`.""" allowedSites: "List[str]" optOutPercentage: "float" @@ -342,45 +469,97 @@ class CookieDeprecationMetadataIssueDetails(TypedDict): operation: "CookieOperation" - ClientHintIssueReason = Literal["MetaTagAllowListInvalidOrigin", "MetaTagModifiedHTML"] - class FederatedAuthRequestIssueDetails(TypedDict): federatedAuthRequestIssueReason: "FederatedAuthRequestIssueReason" - -FederatedAuthRequestIssueReason = Literal["ShouldEmbargo", "TooManyRequests", "WellKnownHttpNotFound", "WellKnownNoResponse", "WellKnownInvalidResponse", "WellKnownListEmpty", "WellKnownInvalidContentType", "ConfigNotInWellKnown", "WellKnownTooBig", "ConfigHttpNotFound", "ConfigNoResponse", "ConfigInvalidResponse", "ConfigInvalidContentType", "ClientMetadataHttpNotFound", "ClientMetadataNoResponse", "ClientMetadataInvalidResponse", "ClientMetadataInvalidContentType", "IdpNotPotentiallyTrustworthy", "DisabledInSettings", "DisabledInFlags", "ErrorFetchingSignin", "InvalidSigninResponse", "AccountsHttpNotFound", "AccountsNoResponse", "AccountsInvalidResponse", "AccountsListEmpty", "AccountsInvalidContentType", "IdTokenHttpNotFound", "IdTokenNoResponse", "IdTokenInvalidResponse", "IdTokenIdpErrorResponse", "IdTokenCrossSiteIdpErrorResponse", "IdTokenInvalidRequest", "IdTokenInvalidContentType", "ErrorIdToken", "Canceled", "RpPageNotVisible", "SilentMediationFailure", "ThirdPartyCookiesBlocked", "NotSignedInWithIdp", "MissingTransientUserActivation", "ReplacedByActiveMode", "InvalidFieldsSpecified", "RelyingPartyOriginIsOpaque", "TypeNotMatching", "UiDismissedNoEmbargo", "CorsError", "SuppressedBySegmentationPlatform"] +FederatedAuthRequestIssueReason = Literal[ + "ShouldEmbargo", + "TooManyRequests", + "WellKnownHttpNotFound", + "WellKnownNoResponse", + "WellKnownInvalidResponse", + "WellKnownListEmpty", + "WellKnownInvalidContentType", + "ConfigNotInWellKnown", + "WellKnownTooBig", + "ConfigHttpNotFound", + "ConfigNoResponse", + "ConfigInvalidResponse", + "ConfigInvalidContentType", + "ClientMetadataHttpNotFound", + "ClientMetadataNoResponse", + "ClientMetadataInvalidResponse", + "ClientMetadataInvalidContentType", + "IdpNotPotentiallyTrustworthy", + "DisabledInSettings", + "DisabledInFlags", + "ErrorFetchingSignin", + "InvalidSigninResponse", + "AccountsHttpNotFound", + "AccountsNoResponse", + "AccountsInvalidResponse", + "AccountsListEmpty", + "AccountsInvalidContentType", + "IdTokenHttpNotFound", + "IdTokenNoResponse", + "IdTokenInvalidResponse", + "IdTokenIdpErrorResponse", + "IdTokenCrossSiteIdpErrorResponse", + "IdTokenInvalidRequest", + "IdTokenInvalidContentType", + "ErrorIdToken", + "Canceled", + "RpPageNotVisible", + "SilentMediationFailure", + "ThirdPartyCookiesBlocked", + "NotSignedInWithIdp", + "MissingTransientUserActivation", + "ReplacedByActiveMode", + "InvalidFieldsSpecified", + "RelyingPartyOriginIsOpaque", + "TypeNotMatching", + "UiDismissedNoEmbargo", + "CorsError", + "SuppressedBySegmentationPlatform", +] """Represents the failure reason when a federated authentication reason fails. Should be updated alongside RequestIdTokenStatus in third_party/blink/public/mojom/devtools/inspector_issue.mojom to include all cases except for success.""" - class FederatedAuthUserInfoRequestIssueDetails(TypedDict): federatedAuthUserInfoRequestIssueReason: "FederatedAuthUserInfoRequestIssueReason" - -FederatedAuthUserInfoRequestIssueReason = Literal["NotSameOrigin", "NotIframe", "NotPotentiallyTrustworthy", "NoApiPermission", "NotSignedInWithIdp", "NoAccountSharingPermission", "InvalidConfigOrWellKnown", "InvalidAccountsResponse", "NoReturningUserFromFetchedAccounts"] +FederatedAuthUserInfoRequestIssueReason = Literal[ + "NotSameOrigin", + "NotIframe", + "NotPotentiallyTrustworthy", + "NoApiPermission", + "NotSignedInWithIdp", + "NoAccountSharingPermission", + "InvalidConfigOrWellKnown", + "InvalidAccountsResponse", + "NoReturningUserFromFetchedAccounts", +] """Represents the failure reason when a getUserInfo() call fails. Should be updated alongside FederatedAuthUserInfoRequestResult in third_party/blink/public/mojom/devtools/inspector_issue.mojom.""" - class ClientHintIssueDetails(TypedDict): """This issue tracks client hints related issues. It's used to deprecate old -features, encourage the use of new ones, and provide general guidance.""" + features, encourage the use of new ones, and provide general guidance.""" sourceCodeLocation: "SourceCodeLocation" clientHintIssueReason: "ClientHintIssueReason" - class FailedRequestInfo(TypedDict): url: "str" """The URL that failed to load.""" @@ -389,9 +568,9 @@ class FailedRequestInfo(TypedDict): requestId: "NotRequired[RequestId]" - -PartitioningBlobURLInfo = Literal["BlockedCrossPartitionFetching", "EnforceNoopenerForNavigation"] - +PartitioningBlobURLInfo = Literal[ + "BlockedCrossPartitionFetching", "EnforceNoopenerForNavigation" +] class PartitioningBlobURLIssueDetails(TypedDict): @@ -401,9 +580,14 @@ class PartitioningBlobURLIssueDetails(TypedDict): """Additional information about the Partitioning Blob URL issue.""" - -ElementAccessibilityIssueReason = Literal["DisallowedSelectChild", "DisallowedOptGroupChild", "NonPhrasingContentOptionChild", "InteractiveContentOptionChild", "InteractiveContentLegendChild", "InteractiveContentSummaryDescendant"] - +ElementAccessibilityIssueReason = Literal[ + "DisallowedSelectChild", + "DisallowedOptGroupChild", + "NonPhrasingContentOptionChild", + "InteractiveContentOptionChild", + "InteractiveContentLegendChild", + "InteractiveContentSummaryDescendant", +] class ElementAccessibilityIssueDetails(TypedDict): @@ -414,11 +598,9 @@ class ElementAccessibilityIssueDetails(TypedDict): hasDisallowedAttributes: "bool" - StyleSheetLoadingIssueReason = Literal["LateImportRule", "RequestFailed"] - class StylesheetLoadingIssueDetails(TypedDict): """This issue warns when a referenced stylesheet couldn't be loaded.""" @@ -430,14 +612,14 @@ class StylesheetLoadingIssueDetails(TypedDict): """Contains additional info when the failure was due to a request.""" - -PropertyRuleIssueReason = Literal["InvalidSyntax", "InvalidInitialValue", "InvalidInherits", "InvalidName"] - +PropertyRuleIssueReason = Literal[ + "InvalidSyntax", "InvalidInitialValue", "InvalidInherits", "InvalidName" +] class PropertyRuleIssueDetails(TypedDict): """This issue warns about errors in property rules that lead to property -registrations being ignored.""" + registrations being ignored.""" sourceCodeLocation: "SourceCodeLocation" """Source code position of the property rule.""" @@ -447,14 +629,14 @@ class PropertyRuleIssueDetails(TypedDict): """The value of the property rule property that failed to parse""" - -UserReidentificationIssueType = Literal["BlockedFrameNavigation", "BlockedSubresource", "NoisedCanvasReadback"] - +UserReidentificationIssueType = Literal[ + "BlockedFrameNavigation", "BlockedSubresource", "NoisedCanvasReadback" +] class UserReidentificationIssueDetails(TypedDict): """This issue warns about uses of APIs that may be considered misuse to -re-identify users.""" + re-identify users.""" type: "UserReidentificationIssueType" request: "NotRequired[AffectedRequest]" @@ -463,18 +645,43 @@ class UserReidentificationIssueDetails(TypedDict): """Applies to NoisedCanvasReadback issue type.""" - -InspectorIssueCode = Literal["CookieIssue", "MixedContentIssue", "BlockedByResponseIssue", "HeavyAdIssue", "ContentSecurityPolicyIssue", "SharedArrayBufferIssue", "LowTextContrastIssue", "CorsIssue", "AttributionReportingIssue", "QuirksModeIssue", "PartitioningBlobURLIssue", "NavigatorUserAgentIssue", "GenericIssue", "DeprecationIssue", "ClientHintIssue", "FederatedAuthRequestIssue", "BounceTrackingIssue", "CookieDeprecationMetadataIssue", "StylesheetLoadingIssue", "FederatedAuthUserInfoRequestIssue", "PropertyRuleIssue", "SharedDictionaryIssue", "ElementAccessibilityIssue", "SRIMessageSignatureIssue", "UnencodedDigestIssue", "UserReidentificationIssue"] +InspectorIssueCode = Literal[ + "CookieIssue", + "MixedContentIssue", + "BlockedByResponseIssue", + "HeavyAdIssue", + "ContentSecurityPolicyIssue", + "SharedArrayBufferIssue", + "LowTextContrastIssue", + "CorsIssue", + "AttributionReportingIssue", + "QuirksModeIssue", + "PartitioningBlobURLIssue", + "NavigatorUserAgentIssue", + "GenericIssue", + "DeprecationIssue", + "ClientHintIssue", + "FederatedAuthRequestIssue", + "BounceTrackingIssue", + "CookieDeprecationMetadataIssue", + "StylesheetLoadingIssue", + "FederatedAuthUserInfoRequestIssue", + "PropertyRuleIssue", + "SharedDictionaryIssue", + "ElementAccessibilityIssue", + "SRIMessageSignatureIssue", + "UnencodedDigestIssue", + "UserReidentificationIssue", +] """A unique identifier for the type of issue. Each type may use one of the optional fields in InspectorIssueDetails to convey more specific information about the kind of issue.""" - class InspectorIssueDetails(TypedDict, total=False): """This struct holds a list of optional fields with additional information -specific to the kind of issue. When adding a new issue code, please also -add a new optional field to this type.""" + specific to the kind of issue. When adding a new issue code, please also + add a new optional field to this type.""" cookieIssueDetails: "CookieIssueDetails" mixedContentIssueDetails: "MixedContentIssueDetails" @@ -504,13 +711,11 @@ class InspectorIssueDetails(TypedDict, total=False): userReidentificationIssueDetails: "UserReidentificationIssueDetails" - IssueId = str """A unique id for a DevTools inspector issue. Allows other entities (e.g. exceptions, CDP message, console messages, etc.) to reference an issue.""" - class InspectorIssue(TypedDict): """An inspector issue reported from the back-end.""" diff --git a/cdp_use/cdp/autofill/commands.py b/cdp_use/cdp/autofill/commands.py index 9155e78..61703ad 100644 --- a/cdp_use/cdp/autofill/commands.py +++ b/cdp_use/cdp/autofill/commands.py @@ -15,19 +15,17 @@ from .types import Address from .types import CreditCard + class TriggerParameters(TypedDict): fieldId: "BackendNodeId" """Identifies a field that serves as an anchor for autofill.""" frameId: "NotRequired[FrameId]" """Identifies the frame that field belongs to.""" - card: "CreditCard" - """Credit card information to fill out the form. Credit card data is not saved.""" - - - + card: "NotRequired[CreditCard]" + """Credit card information to fill out the form. Credit card data is not saved. Mutually exclusive with `address`.""" + address: "NotRequired[Address]" + """Address to fill out the form. Address data is not saved. Mutually exclusive with `card`.""" class SetAddressesParameters(TypedDict): addresses: "List[Address]" - - diff --git a/cdp_use/cdp/autofill/events.py b/cdp_use/cdp/autofill/events.py index 4d5f38c..e503e80 100644 --- a/cdp_use/cdp/autofill/events.py +++ b/cdp_use/cdp/autofill/events.py @@ -14,6 +14,8 @@ from .types import FilledField """Emitted when an address form is filled.""" + + class AddressFormFilledEvent(TypedDict): filledFields: "List[FilledField]" """Information about the fields that were filled""" diff --git a/cdp_use/cdp/autofill/library.py b/cdp_use/cdp/autofill/library.py index 58463ec..7977e73 100644 --- a/cdp_use/cdp/autofill/library.py +++ b/cdp_use/cdp/autofill/library.py @@ -13,10 +13,11 @@ from .commands import SetAddressesParameters from .commands import TriggerParameters + class AutofillClient: """Client for Autofill domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def trigger( @@ -25,12 +26,15 @@ async def trigger( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Trigger autofill on a form identified by the fieldId. -If the field and related form cannot be autofilled, returns an error.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Autofill.trigger", - params=params, - session_id=session_id, - )) + If the field and related form cannot be autofilled, returns an error.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Autofill.trigger", + params=params, + session_id=session_id, + ), + ) async def setAddresses( self, @@ -38,11 +42,14 @@ async def setAddresses( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set addresses so that developers can verify their forms implementation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Autofill.setAddresses", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Autofill.setAddresses", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -50,11 +57,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables autofill domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Autofill.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Autofill.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -62,10 +72,11 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables autofill domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Autofill.enable", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Autofill.enable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/autofill/registration.py b/cdp_use/cdp/autofill/registration.py index fc8a1c9..5b04cf0 100644 --- a/cdp_use/cdp/autofill/registration.py +++ b/cdp_use/cdp/autofill/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import AddressFormFilledEvent + class AutofillRegistration: """Event registration interface for Autofill domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Autofill" def addressFormFilled( self, - callback: Callable[['AddressFormFilledEvent', Optional[str]], None], + callback: Callable[["AddressFormFilledEvent", Optional[str]], None], ) -> None: """ Register a callback for addressFormFilled events. - + Emitted when an address form is filled. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Autofill.addressFormFilled", callback) - diff --git a/cdp_use/cdp/autofill/types.py b/cdp_use/cdp/autofill/types.py index b17f6bf..bae4a85 100644 --- a/cdp_use/cdp/autofill/types.py +++ b/cdp_use/cdp/autofill/types.py @@ -14,6 +14,7 @@ from ..dom.types import BackendNodeId from ..page.types import FrameId + class CreditCard(TypedDict): number: "str" """16-digit credit card number.""" @@ -27,47 +28,43 @@ class CreditCard(TypedDict): """3-digit card verification code.""" - class AddressField(TypedDict): name: "str" - """address field name, for example GIVEN_NAME.""" + """address field name, for example GIVEN_NAME. +The full list of supported field names: +https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/field_types.cc;l=38""" value: "str" """address field value, for example Jon Doe.""" - class AddressFields(TypedDict): """A list of address fields.""" fields: "List[AddressField]" - class Address(TypedDict): fields: "List[AddressField]" """fields and values defining an address.""" - class AddressUI(TypedDict): """Defines how an address can be displayed like in chrome://settings/addresses. -Address UI is a two dimensional array, each inner array is an \"address information line\", and when rendered in a UI surface should be displayed as such. -The following address UI for instance: -[[{name: \"GIVE_NAME\", value: \"Jon\"}, {name: \"FAMILY_NAME\", value: \"Doe\"}], [{name: \"CITY\", value: \"Munich\"}, {name: \"ZIP\", value: \"81456\"}]] -should allow the receiver to render: -Jon Doe -Munich 81456""" + Address UI is a two dimensional array, each inner array is an \"address information line\", and when rendered in a UI surface should be displayed as such. + The following address UI for instance: + [[{name: \"GIVE_NAME\", value: \"Jon\"}, {name: \"FAMILY_NAME\", value: \"Doe\"}], [{name: \"CITY\", value: \"Munich\"}, {name: \"ZIP\", value: \"81456\"}]] + should allow the receiver to render: + Jon Doe + Munich 81456""" addressFields: "List[AddressFields]" """A two dimension array containing the representation of values from an address profile.""" - FillingStrategy = Literal["autocompleteAttribute", "autofillInferred"] """Specified whether a filled field was done so by using the html autocomplete attribute or autofill heuristics.""" - class FilledField(TypedDict): htmlType: "str" """The type of the field, e.g text, password etc.""" diff --git a/cdp_use/cdp/backgroundservice/commands.py b/cdp_use/cdp/backgroundservice/commands.py index 9eec56d..1bae035 100644 --- a/cdp_use/cdp/backgroundservice/commands.py +++ b/cdp_use/cdp/backgroundservice/commands.py @@ -11,29 +11,19 @@ if TYPE_CHECKING: from .types import ServiceName + class StartObservingParameters(TypedDict): service: "ServiceName" - - - class StopObservingParameters(TypedDict): service: "ServiceName" - - - class SetRecordingParameters(TypedDict): shouldRecord: "bool" service: "ServiceName" - - - class ClearEventsParameters(TypedDict): service: "ServiceName" - - diff --git a/cdp_use/cdp/backgroundservice/events.py b/cdp_use/cdp/backgroundservice/events.py index bc8d80e..c9ca967 100644 --- a/cdp_use/cdp/backgroundservice/events.py +++ b/cdp_use/cdp/backgroundservice/events.py @@ -13,13 +13,16 @@ from .types import ServiceName """Called when the recording state for the service has been updated.""" + + class RecordingStateChangedEvent(TypedDict): isRecording: "bool" service: "ServiceName" - """Called with all existing backgroundServiceEvents when enabled, and all new events afterwards if enabled and recording.""" + + class BackgroundServiceEventReceivedEvent(TypedDict): backgroundServiceEvent: "BackgroundServiceEvent" diff --git a/cdp_use/cdp/backgroundservice/library.py b/cdp_use/cdp/backgroundservice/library.py index fc632a2..21b3015 100644 --- a/cdp_use/cdp/backgroundservice/library.py +++ b/cdp_use/cdp/backgroundservice/library.py @@ -15,10 +15,11 @@ from .commands import StartObservingParameters from .commands import StopObservingParameters + class BackgroundServiceClient: """Client for BackgroundService domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def startObserving( @@ -27,11 +28,14 @@ async def startObserving( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables event updates for the service.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BackgroundService.startObserving", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BackgroundService.startObserving", + params=params, + session_id=session_id, + ), + ) async def stopObserving( self, @@ -39,11 +43,14 @@ async def stopObserving( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables event updates for the service.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BackgroundService.stopObserving", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BackgroundService.stopObserving", + params=params, + session_id=session_id, + ), + ) async def setRecording( self, @@ -51,11 +58,14 @@ async def setRecording( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set the recording state for the service.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BackgroundService.setRecording", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BackgroundService.setRecording", + params=params, + session_id=session_id, + ), + ) async def clearEvents( self, @@ -63,10 +73,11 @@ async def clearEvents( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears all stored data for the service.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BackgroundService.clearEvents", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BackgroundService.clearEvents", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/backgroundservice/registration.py b/cdp_use/cdp/backgroundservice/registration.py index 967a3d3..0d88fe1 100644 --- a/cdp_use/cdp/backgroundservice/registration.py +++ b/cdp_use/cdp/backgroundservice/registration.py @@ -12,22 +12,23 @@ from ..registry import EventRegistry from .events import BackgroundServiceEventReceivedEvent, RecordingStateChangedEvent + class BackgroundServiceRegistration: """Event registration interface for BackgroundService domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "BackgroundService" def recordingStateChanged( self, - callback: Callable[['RecordingStateChangedEvent', Optional[str]], None], + callback: Callable[["RecordingStateChangedEvent", Optional[str]], None], ) -> None: """ Register a callback for recordingStateChanged events. - + Called when the recording state for the service has been updated. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -36,17 +37,20 @@ def recordingStateChanged( def backgroundServiceEventReceived( self, - callback: Callable[['BackgroundServiceEventReceivedEvent', Optional[str]], None], + callback: Callable[ + ["BackgroundServiceEventReceivedEvent", Optional[str]], None + ], ) -> None: """ - Register a callback for backgroundServiceEventReceived events. - - Called with all existing backgroundServiceEvents when enabled, and all new -events afterwards if enabled and recording. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. - """ - self._registry.register("BackgroundService.backgroundServiceEventReceived", callback) + Register a callback for backgroundServiceEventReceived events. + Called with all existing backgroundServiceEvents when enabled, and all new + events afterwards if enabled and recording. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register( + "BackgroundService.backgroundServiceEventReceived", callback + ) diff --git a/cdp_use/cdp/backgroundservice/types.py b/cdp_use/cdp/backgroundservice/types.py index 5c4d82b..9a4655e 100644 --- a/cdp_use/cdp/backgroundservice/types.py +++ b/cdp_use/cdp/backgroundservice/types.py @@ -14,13 +14,19 @@ from ..network.types import TimeSinceEpoch from ..serviceworker.types import RegistrationID -ServiceName = Literal["backgroundFetch", "backgroundSync", "pushMessaging", "notifications", "paymentHandler", "periodicBackgroundSync"] +ServiceName = Literal[ + "backgroundFetch", + "backgroundSync", + "pushMessaging", + "notifications", + "paymentHandler", + "periodicBackgroundSync", +] """The Background Service that will be associated with the commands/events. Every Background Service operates independently, but they share the same API.""" - class EventMetadata(TypedDict): """A key-value pair for additional event information to pass along.""" @@ -28,7 +34,6 @@ class EventMetadata(TypedDict): value: "str" - class BackgroundServiceEvent(TypedDict): timestamp: "TimeSinceEpoch" """Timestamp of the event (in seconds).""" diff --git a/cdp_use/cdp/bluetoothemulation/commands.py b/cdp_use/cdp/bluetoothemulation/commands.py index b004846..779cd4d 100644 --- a/cdp_use/cdp/bluetoothemulation/commands.py +++ b/cdp_use/cdp/bluetoothemulation/commands.py @@ -18,6 +18,7 @@ from .types import ManufacturerData from .types import ScanEntry + class EnableParameters(TypedDict): state: "CentralState" """State of the simulated central.""" @@ -25,17 +26,11 @@ class EnableParameters(TypedDict): """If the simulated central supports low-energy.""" - - - class SetSimulatedCentralStateParameters(TypedDict): state: "CentralState" """State of the simulated central.""" - - - class SimulatePreconnectedPeripheralParameters(TypedDict): address: "str" name: "str" @@ -43,25 +38,16 @@ class SimulatePreconnectedPeripheralParameters(TypedDict): knownServiceUuids: "List[str]" - - - class SimulateAdvertisementParameters(TypedDict): entry: "ScanEntry" - - - class SimulateGATTOperationResponseParameters(TypedDict): address: "str" type: "GATTOperationType" code: "int" - - - class SimulateCharacteristicOperationResponseParameters(TypedDict): characteristicId: "str" type: "CharacteristicOperationType" @@ -69,9 +55,6 @@ class SimulateCharacteristicOperationResponseParameters(TypedDict): data: "NotRequired[str]" - - - class SimulateDescriptorOperationResponseParameters(TypedDict): descriptorId: "str" type: "DescriptorOperationType" @@ -79,9 +62,6 @@ class SimulateDescriptorOperationResponseParameters(TypedDict): data: "NotRequired[str]" - - - class AddServiceParameters(TypedDict): address: "str" serviceUuid: "str" @@ -92,14 +72,10 @@ class AddServiceReturns(TypedDict): """An identifier that uniquely represents this service.""" - class RemoveServiceParameters(TypedDict): serviceId: "str" - - - class AddCharacteristicParameters(TypedDict): serviceId: "str" characteristicUuid: "str" @@ -111,14 +87,10 @@ class AddCharacteristicReturns(TypedDict): """An identifier that uniquely represents this characteristic.""" - class RemoveCharacteristicParameters(TypedDict): characteristicId: "str" - - - class AddDescriptorParameters(TypedDict): characteristicId: "str" descriptorUuid: "str" @@ -129,15 +101,9 @@ class AddDescriptorReturns(TypedDict): """An identifier that uniquely represents this descriptor.""" - class RemoveDescriptorParameters(TypedDict): descriptorId: "str" - - - class SimulateGATTDisconnectionParameters(TypedDict): address: "str" - - diff --git a/cdp_use/cdp/bluetoothemulation/events.py b/cdp_use/cdp/bluetoothemulation/events.py index 3e31001..e44a490 100644 --- a/cdp_use/cdp/bluetoothemulation/events.py +++ b/cdp_use/cdp/bluetoothemulation/events.py @@ -16,15 +16,18 @@ """Event for when a GATT operation of |type| to the peripheral with |address| happened.""" + + class GattOperationReceivedEvent(TypedDict): address: "str" type: "GATTOperationType" - """Event for when a characteristic operation of |type| to the characteristic respresented by |characteristicId| happened. |data| and |writeType| is expected to exist when |type| is write.""" + + class CharacteristicOperationReceivedEvent(TypedDict): characteristicId: "str" type: "CharacteristicOperationType" @@ -32,10 +35,11 @@ class CharacteristicOperationReceivedEvent(TypedDict): writeType: "NotRequired[CharacteristicWriteType]" - """Event for when a descriptor operation of |type| to the descriptor respresented by |descriptorId| happened. |data| is expected to exist when |type| is write.""" + + class DescriptorOperationReceivedEvent(TypedDict): descriptorId: "str" type: "DescriptorOperationType" diff --git a/cdp_use/cdp/bluetoothemulation/library.py b/cdp_use/cdp/bluetoothemulation/library.py index 7cbea6b..2f138b0 100644 --- a/cdp_use/cdp/bluetoothemulation/library.py +++ b/cdp_use/cdp/bluetoothemulation/library.py @@ -28,10 +28,11 @@ from .commands import SimulateGATTOperationResponseParameters from .commands import SimulatePreconnectedPeripheralParameters + class BluetoothEmulationClient: """Client for BluetoothEmulation domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -40,11 +41,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable the BluetoothEmulation domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.enable", + params=params, + session_id=session_id, + ), + ) async def setSimulatedCentralState( self, @@ -52,11 +56,14 @@ async def setSimulatedCentralState( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set the state of the simulated central.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.setSimulatedCentralState", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.setSimulatedCentralState", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -64,11 +71,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disable the BluetoothEmulation domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.disable", + params=params, + session_id=session_id, + ), + ) async def simulatePreconnectedPeripheral( self, @@ -76,12 +86,15 @@ async def simulatePreconnectedPeripheral( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulates a peripheral with |address|, |name| and |knownServiceUuids| -that has already been connected to the system.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.simulatePreconnectedPeripheral", - params=params, - session_id=session_id, - )) + that has already been connected to the system.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.simulatePreconnectedPeripheral", + params=params, + session_id=session_id, + ), + ) async def simulateAdvertisement( self, @@ -89,12 +102,15 @@ async def simulateAdvertisement( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulates an advertisement packet described in |entry| being received by -the central.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.simulateAdvertisement", - params=params, - session_id=session_id, - )) + the central.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.simulateAdvertisement", + params=params, + session_id=session_id, + ), + ) async def simulateGATTOperationResponse( self, @@ -102,13 +118,16 @@ async def simulateGATTOperationResponse( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulates the response code from the peripheral with |address| for a -GATT operation of |type|. The |code| value follows the HCI Error Codes from -Bluetooth Core Specification Vol 2 Part D 1.3 List Of Error Codes.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.simulateGATTOperationResponse", - params=params, - session_id=session_id, - )) + GATT operation of |type|. The |code| value follows the HCI Error Codes from + Bluetooth Core Specification Vol 2 Part D 1.3 List Of Error Codes.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.simulateGATTOperationResponse", + params=params, + session_id=session_id, + ), + ) async def simulateCharacteristicOperationResponse( self, @@ -116,15 +135,18 @@ async def simulateCharacteristicOperationResponse( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulates the response from the characteristic with |characteristicId| for a -characteristic operation of |type|. The |code| value follows the Error -Codes from Bluetooth Core Specification Vol 3 Part F 3.4.1.1 Error Response. -The |data| is expected to exist when simulating a successful read operation -response.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.simulateCharacteristicOperationResponse", - params=params, - session_id=session_id, - )) + characteristic operation of |type|. The |code| value follows the Error + Codes from Bluetooth Core Specification Vol 3 Part F 3.4.1.1 Error Response. + The |data| is expected to exist when simulating a successful read operation + response.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.simulateCharacteristicOperationResponse", + params=params, + session_id=session_id, + ), + ) async def simulateDescriptorOperationResponse( self, @@ -132,15 +154,18 @@ async def simulateDescriptorOperationResponse( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulates the response from the descriptor with |descriptorId| for a -descriptor operation of |type|. The |code| value follows the Error -Codes from Bluetooth Core Specification Vol 3 Part F 3.4.1.1 Error Response. -The |data| is expected to exist when simulating a successful read operation -response.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.simulateDescriptorOperationResponse", - params=params, - session_id=session_id, - )) + descriptor operation of |type|. The |code| value follows the Error + Codes from Bluetooth Core Specification Vol 3 Part F 3.4.1.1 Error Response. + The |data| is expected to exist when simulating a successful read operation + response.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.simulateDescriptorOperationResponse", + params=params, + session_id=session_id, + ), + ) async def addService( self, @@ -148,11 +173,14 @@ async def addService( session_id: Optional[str] = None, ) -> "AddServiceReturns": """Adds a service with |serviceUuid| to the peripheral with |address|.""" - return cast("AddServiceReturns", await self._client.send_raw( - method="BluetoothEmulation.addService", - params=params, - session_id=session_id, - )) + return cast( + "AddServiceReturns", + await self._client.send_raw( + method="BluetoothEmulation.addService", + params=params, + session_id=session_id, + ), + ) async def removeService( self, @@ -160,11 +188,14 @@ async def removeService( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes the service respresented by |serviceId| from the simulated central.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.removeService", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.removeService", + params=params, + session_id=session_id, + ), + ) async def addCharacteristic( self, @@ -172,12 +203,15 @@ async def addCharacteristic( session_id: Optional[str] = None, ) -> "AddCharacteristicReturns": """Adds a characteristic with |characteristicUuid| and |properties| to the -service represented by |serviceId|.""" - return cast("AddCharacteristicReturns", await self._client.send_raw( - method="BluetoothEmulation.addCharacteristic", - params=params, - session_id=session_id, - )) + service represented by |serviceId|.""" + return cast( + "AddCharacteristicReturns", + await self._client.send_raw( + method="BluetoothEmulation.addCharacteristic", + params=params, + session_id=session_id, + ), + ) async def removeCharacteristic( self, @@ -185,12 +219,15 @@ async def removeCharacteristic( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes the characteristic respresented by |characteristicId| from the -simulated central.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.removeCharacteristic", - params=params, - session_id=session_id, - )) + simulated central.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.removeCharacteristic", + params=params, + session_id=session_id, + ), + ) async def addDescriptor( self, @@ -198,12 +235,15 @@ async def addDescriptor( session_id: Optional[str] = None, ) -> "AddDescriptorReturns": """Adds a descriptor with |descriptorUuid| to the characteristic respresented -by |characteristicId|.""" - return cast("AddDescriptorReturns", await self._client.send_raw( - method="BluetoothEmulation.addDescriptor", - params=params, - session_id=session_id, - )) + by |characteristicId|.""" + return cast( + "AddDescriptorReturns", + await self._client.send_raw( + method="BluetoothEmulation.addDescriptor", + params=params, + session_id=session_id, + ), + ) async def removeDescriptor( self, @@ -211,11 +251,14 @@ async def removeDescriptor( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes the descriptor with |descriptorId| from the simulated central.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.removeDescriptor", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.removeDescriptor", + params=params, + session_id=session_id, + ), + ) async def simulateGATTDisconnection( self, @@ -223,10 +266,11 @@ async def simulateGATTDisconnection( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulates a GATT disconnection from the peripheral with |address|.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="BluetoothEmulation.simulateGATTDisconnection", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="BluetoothEmulation.simulateGATTDisconnection", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/bluetoothemulation/registration.py b/cdp_use/cdp/bluetoothemulation/registration.py index 154821c..1a813f7 100644 --- a/cdp_use/cdp/bluetoothemulation/registration.py +++ b/cdp_use/cdp/bluetoothemulation/registration.py @@ -10,62 +10,72 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import CharacteristicOperationReceivedEvent, DescriptorOperationReceivedEvent, GattOperationReceivedEvent + from .events import ( + CharacteristicOperationReceivedEvent, + DescriptorOperationReceivedEvent, + GattOperationReceivedEvent, + ) + class BluetoothEmulationRegistration: """Event registration interface for BluetoothEmulation domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "BluetoothEmulation" def gattOperationReceived( self, - callback: Callable[['GattOperationReceivedEvent', Optional[str]], None], + callback: Callable[["GattOperationReceivedEvent", Optional[str]], None], ) -> None: """ - Register a callback for gattOperationReceived events. - - Event for when a GATT operation of |type| to the peripheral with |address| -happened. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for gattOperationReceived events. + + Event for when a GATT operation of |type| to the peripheral with |address| + happened. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("BluetoothEmulation.gattOperationReceived", callback) def characteristicOperationReceived( self, - callback: Callable[['CharacteristicOperationReceivedEvent', Optional[str]], None], + callback: Callable[ + ["CharacteristicOperationReceivedEvent", Optional[str]], None + ], ) -> None: """ - Register a callback for characteristicOperationReceived events. - - Event for when a characteristic operation of |type| to the characteristic -respresented by |characteristicId| happened. |data| and |writeType| is -expected to exist when |type| is write. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for characteristicOperationReceived events. + + Event for when a characteristic operation of |type| to the characteristic + respresented by |characteristicId| happened. |data| and |writeType| is + expected to exist when |type| is write. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ - self._registry.register("BluetoothEmulation.characteristicOperationReceived", callback) + self._registry.register( + "BluetoothEmulation.characteristicOperationReceived", callback + ) def descriptorOperationReceived( self, - callback: Callable[['DescriptorOperationReceivedEvent', Optional[str]], None], + callback: Callable[["DescriptorOperationReceivedEvent", Optional[str]], None], ) -> None: """ - Register a callback for descriptorOperationReceived events. - - Event for when a descriptor operation of |type| to the descriptor -respresented by |descriptorId| happened. |data| is expected to exist when -|type| is write. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. - """ - self._registry.register("BluetoothEmulation.descriptorOperationReceived", callback) + Register a callback for descriptorOperationReceived events. + Event for when a descriptor operation of |type| to the descriptor + respresented by |descriptorId| happened. |data| is expected to exist when + |type| is write. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register( + "BluetoothEmulation.descriptorOperationReceived", callback + ) diff --git a/cdp_use/cdp/bluetoothemulation/types.py b/cdp_use/cdp/bluetoothemulation/types.py index d290226..da09a04 100644 --- a/cdp_use/cdp/bluetoothemulation/types.py +++ b/cdp_use/cdp/bluetoothemulation/types.py @@ -12,27 +12,26 @@ """Indicates the various states of Central.""" - GATTOperationType = Literal["connection", "discovery"] """Indicates the various types of GATT event.""" - -CharacteristicWriteType = Literal["write-default-deprecated", "write-with-response", "write-without-response"] +CharacteristicWriteType = Literal[ + "write-default-deprecated", "write-with-response", "write-without-response" +] """Indicates the various types of characteristic write.""" - -CharacteristicOperationType = Literal["read", "write", "subscribe-to-notifications", "unsubscribe-from-notifications"] +CharacteristicOperationType = Literal[ + "read", "write", "subscribe-to-notifications", "unsubscribe-from-notifications" +] """Indicates the various types of characteristic operation.""" - DescriptorOperationType = Literal["read", "write"] """Indicates the various types of descriptor operation.""" - class ManufacturerData(TypedDict): """Stores the manufacturer data""" @@ -44,7 +43,6 @@ class ManufacturerData(TypedDict): """Manufacturer-specific data (Encoded as a base64 string when passed over JSON)""" - class ScanRecord(TypedDict, total=False): """Stores the byte data of the advertisement packet sent by a Bluetooth device.""" @@ -59,7 +57,6 @@ class ScanRecord(TypedDict, total=False): manufacturer specific data.""" - class ScanEntry(TypedDict): """Stores the advertisement packet information that is sent by a Bluetooth device.""" @@ -68,10 +65,9 @@ class ScanEntry(TypedDict): scanRecord: "ScanRecord" - class CharacteristicProperties(TypedDict, total=False): """Describes the properties of a characteristic. This follows Bluetooth Core -Specification BT 4.2 Vol 3 Part G 3.3.1. Characteristic Properties.""" + Specification BT 4.2 Vol 3 Part G 3.3.1. Characteristic Properties.""" broadcast: "bool" read: "bool" diff --git a/cdp_use/cdp/browser/commands.py b/cdp_use/cdp/browser/commands.py index 6e1bc0d..bcf3ec0 100644 --- a/cdp_use/cdp/browser/commands.py +++ b/cdp_use/cdp/browser/commands.py @@ -21,20 +21,22 @@ from .types import PrivacySandboxAPI from .types import WindowID + class SetPermissionParameters(TypedDict): permission: "PermissionDescriptor" """Descriptor of permission to override.""" setting: "PermissionSetting" """Setting of the permission.""" origin: "NotRequired[str]" - """Origin the permission applies to, all origins if not specified.""" + """Embedding origin the permission applies to, all origins if not specified.""" + embeddedOrigin: "NotRequired[str]" + """Embedded origin the permission applies to. It is ignored unless the embedding origin is +present and valid. If the embedding origin is provided but the embedded origin isn't, the +embedding origin is used as the embedded origin.""" browserContextId: "NotRequired[BrowserContextID]" """Context to override. When omitted, default browser context is used.""" - - - class GrantPermissionsParameters(TypedDict): permissions: "List[PermissionType]" origin: "NotRequired[str]" @@ -43,17 +45,11 @@ class GrantPermissionsParameters(TypedDict): """BrowserContext to override permissions. When omitted, default browser context is used.""" - - - class ResetPermissionsParameters(TypedDict, total=False): browserContextId: "BrowserContextID" """BrowserContext to reset permissions. When omitted, default browser context is used.""" - - - class SetDownloadBehaviorParameters(TypedDict): behavior: "str" """Whether to allow all or deny all download requests, or use default Chrome behavior if @@ -68,9 +64,6 @@ class SetDownloadBehaviorParameters(TypedDict): """Whether to emit download events (defaults to false).""" - - - class CancelDownloadParameters(TypedDict): guid: "str" """Global unique identifier of the download.""" @@ -78,9 +71,6 @@ class CancelDownloadParameters(TypedDict): """BrowserContext to perform the action in. When omitted, default browser context is used.""" - - - class GetVersionReturns(TypedDict): protocolVersion: "str" """Protocol version.""" @@ -94,13 +84,11 @@ class GetVersionReturns(TypedDict): """V8 version.""" - class GetBrowserCommandLineReturns(TypedDict): arguments: "List[str]" """Commandline parameters""" - class GetHistogramsParameters(TypedDict, total=False): query: "str" """Requested substring in name. Only histograms which have query as a @@ -115,7 +103,6 @@ class GetHistogramsReturns(TypedDict): """Histograms.""" - class GetHistogramParameters(TypedDict): name: "str" """Requested histogram name.""" @@ -128,7 +115,6 @@ class GetHistogramReturns(TypedDict): """Histogram.""" - class GetWindowBoundsParameters(TypedDict): windowId: "WindowID" """Browser window id.""" @@ -140,7 +126,6 @@ class GetWindowBoundsReturns(TypedDict): position and size are returned.""" - class GetWindowForTargetParameters(TypedDict, total=False): targetId: "TargetID" """Devtools agent host id. If called as a part of the session, associated targetId is used.""" @@ -154,7 +139,6 @@ class GetWindowForTargetReturns(TypedDict): position and size are returned.""" - class SetWindowBoundsParameters(TypedDict): windowId: "WindowID" """Browser window id.""" @@ -163,9 +147,6 @@ class SetWindowBoundsParameters(TypedDict): with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged.""" - - - class SetContentsSizeParameters(TypedDict): windowId: "WindowID" """Browser window id.""" @@ -177,32 +158,20 @@ class SetContentsSizeParameters(TypedDict): Must be specified if 'width' is omitted.""" - - - class SetDockTileParameters(TypedDict, total=False): badgeLabel: "str" image: "str" """Png encoded image. (Encoded as a base64 string when passed over JSON)""" - - - class ExecuteBrowserCommandParameters(TypedDict): commandId: "BrowserCommandId" - - - class AddPrivacySandboxEnrollmentOverrideParameters(TypedDict): url: "str" - - - class AddPrivacySandboxCoordinatorKeyConfigParameters(TypedDict): api: "PrivacySandboxAPI" coordinatorOrigin: "str" @@ -210,5 +179,3 @@ class AddPrivacySandboxCoordinatorKeyConfigParameters(TypedDict): browserContextId: "NotRequired[BrowserContextID]" """BrowserContext to perform the action in. When omitted, default browser context is used.""" - - diff --git a/cdp_use/cdp/browser/events.py b/cdp_use/cdp/browser/events.py index 96dcbce..975b57c 100644 --- a/cdp_use/cdp/browser/events.py +++ b/cdp_use/cdp/browser/events.py @@ -12,6 +12,8 @@ from ..page.types import FrameId """Fired when page is about to start a download.""" + + class DownloadWillBeginEvent(TypedDict): frameId: "FrameId" """Id of the frame that caused the download to begin.""" @@ -23,8 +25,9 @@ class DownloadWillBeginEvent(TypedDict): """Suggested file name of the resource (the actual name of the file saved on disk may differ).""" - """Fired when download makes progress. Last call has |done| == true.""" + + class DownloadProgressEvent(TypedDict): guid: "str" """Global unique identifier of the download.""" diff --git a/cdp_use/cdp/browser/library.py b/cdp_use/cdp/browser/library.py index 4134dbc..37fae6d 100644 --- a/cdp_use/cdp/browser/library.py +++ b/cdp_use/cdp/browser/library.py @@ -32,10 +32,11 @@ from .commands import SetPermissionParameters from .commands import SetWindowBoundsParameters + class BrowserClient: """Client for Browser domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def setPermission( @@ -43,24 +44,31 @@ async def setPermission( params: "SetPermissionParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - """Set permission settings for given origin.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.setPermission", - params=params, - session_id=session_id, - )) + """Set permission settings for given embedding and embedded origins.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.setPermission", + params=params, + session_id=session_id, + ), + ) async def grantPermissions( self, params: "GrantPermissionsParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - """Grant specific permissions to the given origin and reject all others.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.grantPermissions", - params=params, - session_id=session_id, - )) + """Grant specific permissions to the given origin and reject all others. Deprecated. Use + setPermission instead.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.grantPermissions", + params=params, + session_id=session_id, + ), + ) async def resetPermissions( self, @@ -68,11 +76,14 @@ async def resetPermissions( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Reset all permission management for all origins.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.resetPermissions", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.resetPermissions", + params=params, + session_id=session_id, + ), + ) async def setDownloadBehavior( self, @@ -80,11 +91,14 @@ async def setDownloadBehavior( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set the behavior when downloading a file.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.setDownloadBehavior", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.setDownloadBehavior", + params=params, + session_id=session_id, + ), + ) async def cancelDownload( self, @@ -92,11 +106,14 @@ async def cancelDownload( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Cancel a download if in progress""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.cancelDownload", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.cancelDownload", + params=params, + session_id=session_id, + ), + ) async def close( self, @@ -104,11 +121,14 @@ async def close( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Close browser gracefully.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.close", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.close", + params=params, + session_id=session_id, + ), + ) async def crash( self, @@ -116,11 +136,14 @@ async def crash( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Crashes browser on the main thread.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.crash", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.crash", + params=params, + session_id=session_id, + ), + ) async def crashGpuProcess( self, @@ -128,11 +151,14 @@ async def crashGpuProcess( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Crashes GPU process.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.crashGpuProcess", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.crashGpuProcess", + params=params, + session_id=session_id, + ), + ) async def getVersion( self, @@ -140,11 +166,14 @@ async def getVersion( session_id: Optional[str] = None, ) -> "GetVersionReturns": """Returns version information.""" - return cast("GetVersionReturns", await self._client.send_raw( - method="Browser.getVersion", - params=params, - session_id=session_id, - )) + return cast( + "GetVersionReturns", + await self._client.send_raw( + method="Browser.getVersion", + params=params, + session_id=session_id, + ), + ) async def getBrowserCommandLine( self, @@ -152,12 +181,15 @@ async def getBrowserCommandLine( session_id: Optional[str] = None, ) -> "GetBrowserCommandLineReturns": """Returns the command line switches for the browser process if, and only if ---enable-automation is on the commandline.""" - return cast("GetBrowserCommandLineReturns", await self._client.send_raw( - method="Browser.getBrowserCommandLine", - params=params, - session_id=session_id, - )) + --enable-automation is on the commandline.""" + return cast( + "GetBrowserCommandLineReturns", + await self._client.send_raw( + method="Browser.getBrowserCommandLine", + params=params, + session_id=session_id, + ), + ) async def getHistograms( self, @@ -165,11 +197,14 @@ async def getHistograms( session_id: Optional[str] = None, ) -> "GetHistogramsReturns": """Get Chrome histograms.""" - return cast("GetHistogramsReturns", await self._client.send_raw( - method="Browser.getHistograms", - params=params, - session_id=session_id, - )) + return cast( + "GetHistogramsReturns", + await self._client.send_raw( + method="Browser.getHistograms", + params=params, + session_id=session_id, + ), + ) async def getHistogram( self, @@ -177,11 +212,14 @@ async def getHistogram( session_id: Optional[str] = None, ) -> "GetHistogramReturns": """Get a Chrome histogram by name.""" - return cast("GetHistogramReturns", await self._client.send_raw( - method="Browser.getHistogram", - params=params, - session_id=session_id, - )) + return cast( + "GetHistogramReturns", + await self._client.send_raw( + method="Browser.getHistogram", + params=params, + session_id=session_id, + ), + ) async def getWindowBounds( self, @@ -189,11 +227,14 @@ async def getWindowBounds( session_id: Optional[str] = None, ) -> "GetWindowBoundsReturns": """Get position and size of the browser window.""" - return cast("GetWindowBoundsReturns", await self._client.send_raw( - method="Browser.getWindowBounds", - params=params, - session_id=session_id, - )) + return cast( + "GetWindowBoundsReturns", + await self._client.send_raw( + method="Browser.getWindowBounds", + params=params, + session_id=session_id, + ), + ) async def getWindowForTarget( self, @@ -201,11 +242,14 @@ async def getWindowForTarget( session_id: Optional[str] = None, ) -> "GetWindowForTargetReturns": """Get the browser window that contains the devtools target.""" - return cast("GetWindowForTargetReturns", await self._client.send_raw( - method="Browser.getWindowForTarget", - params=params, - session_id=session_id, - )) + return cast( + "GetWindowForTargetReturns", + await self._client.send_raw( + method="Browser.getWindowForTarget", + params=params, + session_id=session_id, + ), + ) async def setWindowBounds( self, @@ -213,11 +257,14 @@ async def setWindowBounds( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set position and/or size of the browser window.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.setWindowBounds", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.setWindowBounds", + params=params, + session_id=session_id, + ), + ) async def setContentsSize( self, @@ -225,11 +272,14 @@ async def setContentsSize( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set size of the browser contents resizing browser window as necessary.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.setContentsSize", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.setContentsSize", + params=params, + session_id=session_id, + ), + ) async def setDockTile( self, @@ -237,11 +287,14 @@ async def setDockTile( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set dock tile details, platform-specific.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.setDockTile", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.setDockTile", + params=params, + session_id=session_id, + ), + ) async def executeBrowserCommand( self, @@ -249,11 +302,14 @@ async def executeBrowserCommand( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Invoke custom browser commands used by telemetry.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.executeBrowserCommand", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.executeBrowserCommand", + params=params, + session_id=session_id, + ), + ) async def addPrivacySandboxEnrollmentOverride( self, @@ -261,12 +317,15 @@ async def addPrivacySandboxEnrollmentOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Allows a site to use privacy sandbox features that require enrollment -without the site actually being enrolled. Only supported on page targets.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.addPrivacySandboxEnrollmentOverride", - params=params, - session_id=session_id, - )) + without the site actually being enrolled. Only supported on page targets.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.addPrivacySandboxEnrollmentOverride", + params=params, + session_id=session_id, + ), + ) async def addPrivacySandboxCoordinatorKeyConfig( self, @@ -274,13 +333,14 @@ async def addPrivacySandboxCoordinatorKeyConfig( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Configures encryption keys used with a given privacy sandbox API to talk -to a trusted coordinator. Since this is intended for test automation only, -coordinatorOrigin must be a .test domain. No existing coordinator -configuration for the origin may exist.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Browser.addPrivacySandboxCoordinatorKeyConfig", - params=params, - session_id=session_id, - )) - - + to a trusted coordinator. Since this is intended for test automation only, + coordinatorOrigin must be a .test domain. No existing coordinator + configuration for the origin may exist.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Browser.addPrivacySandboxCoordinatorKeyConfig", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/browser/registration.py b/cdp_use/cdp/browser/registration.py index 2c4beb3..f5fb2bc 100644 --- a/cdp_use/cdp/browser/registration.py +++ b/cdp_use/cdp/browser/registration.py @@ -12,22 +12,23 @@ from ..registry import EventRegistry from .events import DownloadProgressEvent, DownloadWillBeginEvent + class BrowserRegistration: """Event registration interface for Browser domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Browser" def downloadWillBegin( self, - callback: Callable[['DownloadWillBeginEvent', Optional[str]], None], + callback: Callable[["DownloadWillBeginEvent", Optional[str]], None], ) -> None: """ Register a callback for downloadWillBegin events. - + Fired when page is about to start a download. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -36,16 +37,15 @@ def downloadWillBegin( def downloadProgress( self, - callback: Callable[['DownloadProgressEvent', Optional[str]], None], + callback: Callable[["DownloadProgressEvent", Optional[str]], None], ) -> None: """ Register a callback for downloadProgress events. - + Fired when download makes progress. Last call has |done| == true. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Browser.downloadProgress", callback) - diff --git a/cdp_use/cdp/browser/types.py b/cdp_use/cdp/browser/types.py index aa22b0c..f7121fa 100644 --- a/cdp_use/cdp/browser/types.py +++ b/cdp_use/cdp/browser/types.py @@ -11,16 +11,13 @@ BrowserContextID = str - WindowID = int - WindowState = Literal["normal", "minimized", "maximized", "fullscreen"] """The state of the browser window.""" - class Bounds(TypedDict, total=False): """Browser window bounds information""" @@ -36,18 +33,53 @@ class Bounds(TypedDict, total=False): """The window state. Default to normal.""" - -PermissionType = Literal["ar", "audioCapture", "automaticFullscreen", "backgroundFetch", "backgroundSync", "cameraPanTiltZoom", "capturedSurfaceControl", "clipboardReadWrite", "clipboardSanitizedWrite", "displayCapture", "durableStorage", "geolocation", "handTracking", "idleDetection", "keyboardLock", "localFonts", "localNetworkAccess", "midi", "midiSysex", "nfc", "notifications", "paymentHandler", "periodicBackgroundSync", "pointerLock", "protectedMediaIdentifier", "sensors", "smartCard", "speakerSelection", "storageAccess", "topLevelStorageAccess", "videoCapture", "vr", "wakeLockScreen", "wakeLockSystem", "webAppInstallation", "webPrinting", "windowManagement"] - +PermissionType = Literal[ + "ar", + "audioCapture", + "automaticFullscreen", + "backgroundFetch", + "backgroundSync", + "cameraPanTiltZoom", + "capturedSurfaceControl", + "clipboardReadWrite", + "clipboardSanitizedWrite", + "displayCapture", + "durableStorage", + "geolocation", + "handTracking", + "idleDetection", + "keyboardLock", + "localFonts", + "localNetworkAccess", + "midi", + "midiSysex", + "nfc", + "notifications", + "paymentHandler", + "periodicBackgroundSync", + "pointerLock", + "protectedMediaIdentifier", + "sensors", + "smartCard", + "speakerSelection", + "storageAccess", + "topLevelStorageAccess", + "videoCapture", + "vr", + "wakeLockScreen", + "wakeLockSystem", + "webAppInstallation", + "webPrinting", + "windowManagement", +] PermissionSetting = Literal["granted", "denied", "prompt"] - class PermissionDescriptor(TypedDict): """Definition of PermissionDescriptor defined in the Permissions API: -https://w3c.github.io/permissions/#dom-permissiondescriptor.""" + https://w3c.github.io/permissions/#dom-permissiondescriptor.""" name: "str" """Name of permission. @@ -65,12 +97,10 @@ class PermissionDescriptor(TypedDict): """For \"camera\" permission, may specify panTiltZoom.""" - BrowserCommandId = Literal["openTabSearch", "closeTabSearch", "openGlic"] """Browser command ids used by executeBrowserCommand.""" - class Bucket(TypedDict): """Chrome histogram bucket.""" @@ -82,7 +112,6 @@ class Bucket(TypedDict): """Number of samples.""" - class Histogram(TypedDict): """Chrome histogram.""" @@ -96,5 +125,4 @@ class Histogram(TypedDict): """Buckets.""" - PrivacySandboxAPI = Literal["BiddingAndAuctionServices", "TrustedKeyValue"] diff --git a/cdp_use/cdp/browseruse/commands.py b/cdp_use/cdp/browseruse/commands.py index 858f792..57c19aa 100644 --- a/cdp_use/cdp/browseruse/commands.py +++ b/cdp_use/cdp/browseruse/commands.py @@ -5,4 +5,4 @@ """CDP BrowserUse Domain Commands""" -# No commands defined for this domain \ No newline at end of file +# No commands defined for this domain diff --git a/cdp_use/cdp/browseruse/events.py b/cdp_use/cdp/browseruse/events.py index 61001c0..958ef0a 100644 --- a/cdp_use/cdp/browseruse/events.py +++ b/cdp_use/cdp/browseruse/events.py @@ -12,6 +12,8 @@ from ..target.types import TargetID """Captcha solving started.""" + + class CaptchaSolverStartedEvent(TypedDict): targetId: "TargetID" vendor: "str" @@ -21,8 +23,9 @@ class CaptchaSolverStartedEvent(TypedDict): eventTimeout: "NotRequired[float]" - """Captcha solving finished.""" + + class CaptchaSolverFinishedEvent(TypedDict): targetId: "TargetID" vendor: "str" @@ -31,3 +34,11 @@ class CaptchaSolverFinishedEvent(TypedDict): finishedAt: "int" """Unix millis""" eventTimeout: "NotRequired[float]" + + +"""Fired when a target is activated via Target.activateTarget.""" + + +class ActiveTargetChangedEvent(TypedDict): + targetId: "TargetID" + eventTimeout: "NotRequired[float]" diff --git a/cdp_use/cdp/browseruse/library.py b/cdp_use/cdp/browseruse/library.py index 25baf7a..1c334e0 100644 --- a/cdp_use/cdp/browseruse/library.py +++ b/cdp_use/cdp/browseruse/library.py @@ -4,16 +4,14 @@ """CDP BrowserUse Domain Library""" - from typing import TYPE_CHECKING if TYPE_CHECKING: from ...client import CDPClient + class BrowserUseClient: """Client for BrowserUse domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client - - diff --git a/cdp_use/cdp/browseruse/registration.py b/cdp_use/cdp/browseruse/registration.py index f06fc65..fccac4c 100644 --- a/cdp_use/cdp/browseruse/registration.py +++ b/cdp_use/cdp/browseruse/registration.py @@ -10,24 +10,29 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import CaptchaSolverFinishedEvent, CaptchaSolverStartedEvent + from .events import ( + ActiveTargetChangedEvent, + CaptchaSolverFinishedEvent, + CaptchaSolverStartedEvent, + ) + class BrowserUseRegistration: """Event registration interface for BrowserUse domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "BrowserUse" def captchaSolverStarted( self, - callback: Callable[['CaptchaSolverStartedEvent', Optional[str]], None], + callback: Callable[["CaptchaSolverStartedEvent", Optional[str]], None], ) -> None: """ Register a callback for captchaSolverStarted events. - + Captcha solving started. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -36,16 +41,30 @@ def captchaSolverStarted( def captchaSolverFinished( self, - callback: Callable[['CaptchaSolverFinishedEvent', Optional[str]], None], + callback: Callable[["CaptchaSolverFinishedEvent", Optional[str]], None], ) -> None: """ Register a callback for captchaSolverFinished events. - + Captcha solving finished. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("BrowserUse.captchaSolverFinished", callback) + def activeTargetChanged( + self, + callback: Callable[["ActiveTargetChangedEvent", Optional[str]], None], + ) -> None: + """ + Register a callback for activeTargetChanged events. + + Fired when a target is activated via Target.activateTarget. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("BrowserUse.activeTargetChanged", callback) diff --git a/cdp_use/cdp/browseruse/types.py b/cdp_use/cdp/browseruse/types.py index 2b9cb24..c92a3d2 100644 --- a/cdp_use/cdp/browseruse/types.py +++ b/cdp_use/cdp/browseruse/types.py @@ -5,4 +5,4 @@ """CDP BrowserUse Domain Types""" -# No types defined for this domain \ No newline at end of file +# No types defined for this domain diff --git a/cdp_use/cdp/cachestorage/commands.py b/cdp_use/cdp/cachestorage/commands.py index a1c9de4..53834b5 100644 --- a/cdp_use/cdp/cachestorage/commands.py +++ b/cdp_use/cdp/cachestorage/commands.py @@ -17,14 +17,12 @@ from .types import DataEntry from .types import Header + class DeleteCacheParameters(TypedDict): cacheId: "CacheId" """Id of cache for deletion.""" - - - class DeleteEntryParameters(TypedDict): cacheId: "CacheId" """Id of cache where the entry will be deleted.""" @@ -32,9 +30,6 @@ class DeleteEntryParameters(TypedDict): """URL spec of the request.""" - - - class RequestCacheNamesParameters(TypedDict, total=False): securityOrigin: "str" """At least and at most one of securityOrigin, storageKey, storageBucket must be specified. @@ -50,7 +45,6 @@ class RequestCacheNamesReturns(TypedDict): """Caches for the security origin.""" - class RequestCachedResponseParameters(TypedDict): cacheId: "CacheId" """Id of cache that contains the entry.""" @@ -65,7 +59,6 @@ class RequestCachedResponseReturns(TypedDict): """Response read from the cache.""" - class RequestEntriesParameters(TypedDict): cacheId: "CacheId" """ID of cache to get entries from.""" diff --git a/cdp_use/cdp/cachestorage/events.py b/cdp_use/cdp/cachestorage/events.py index 5bdfada..efd8af7 100644 --- a/cdp_use/cdp/cachestorage/events.py +++ b/cdp_use/cdp/cachestorage/events.py @@ -5,4 +5,4 @@ """CDP CacheStorage Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/cachestorage/library.py b/cdp_use/cdp/cachestorage/library.py index 0d43f43..0bfafd1 100644 --- a/cdp_use/cdp/cachestorage/library.py +++ b/cdp_use/cdp/cachestorage/library.py @@ -19,10 +19,11 @@ from .commands import RequestEntriesParameters from .commands import RequestEntriesReturns + class CacheStorageClient: """Client for CacheStorage domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def deleteCache( @@ -31,11 +32,14 @@ async def deleteCache( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes a cache.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CacheStorage.deleteCache", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CacheStorage.deleteCache", + params=params, + session_id=session_id, + ), + ) async def deleteEntry( self, @@ -43,11 +47,14 @@ async def deleteEntry( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes a cache entry.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CacheStorage.deleteEntry", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CacheStorage.deleteEntry", + params=params, + session_id=session_id, + ), + ) async def requestCacheNames( self, @@ -55,11 +62,14 @@ async def requestCacheNames( session_id: Optional[str] = None, ) -> "RequestCacheNamesReturns": """Requests cache names.""" - return cast("RequestCacheNamesReturns", await self._client.send_raw( - method="CacheStorage.requestCacheNames", - params=params, - session_id=session_id, - )) + return cast( + "RequestCacheNamesReturns", + await self._client.send_raw( + method="CacheStorage.requestCacheNames", + params=params, + session_id=session_id, + ), + ) async def requestCachedResponse( self, @@ -67,11 +77,14 @@ async def requestCachedResponse( session_id: Optional[str] = None, ) -> "RequestCachedResponseReturns": """Fetches cache entry.""" - return cast("RequestCachedResponseReturns", await self._client.send_raw( - method="CacheStorage.requestCachedResponse", - params=params, - session_id=session_id, - )) + return cast( + "RequestCachedResponseReturns", + await self._client.send_raw( + method="CacheStorage.requestCachedResponse", + params=params, + session_id=session_id, + ), + ) async def requestEntries( self, @@ -79,10 +92,11 @@ async def requestEntries( session_id: Optional[str] = None, ) -> "RequestEntriesReturns": """Requests data from cache.""" - return cast("RequestEntriesReturns", await self._client.send_raw( - method="CacheStorage.requestEntries", - params=params, - session_id=session_id, - )) - - + return cast( + "RequestEntriesReturns", + await self._client.send_raw( + method="CacheStorage.requestEntries", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/cachestorage/registration.py b/cdp_use/cdp/cachestorage/registration.py index 90c8307..e501b21 100644 --- a/cdp_use/cdp/cachestorage/registration.py +++ b/cdp_use/cdp/cachestorage/registration.py @@ -5,4 +5,4 @@ """CDP CacheStorage Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/cachestorage/types.py b/cdp_use/cdp/cachestorage/types.py index 702dbf0..e498afa 100644 --- a/cdp_use/cdp/cachestorage/types.py +++ b/cdp_use/cdp/cachestorage/types.py @@ -17,12 +17,12 @@ """Unique identifier of the Cache object.""" - -CachedResponseType = Literal["basic", "cors", "default", "error", "opaqueResponse", "opaqueRedirect"] +CachedResponseType = Literal[ + "basic", "cors", "default", "error", "opaqueResponse", "opaqueRedirect" +] """type of HTTP response cached""" - class DataEntry(TypedDict): """Data entry.""" @@ -44,7 +44,6 @@ class DataEntry(TypedDict): """Response headers""" - class Cache(TypedDict): """Cache identifier.""" @@ -60,13 +59,11 @@ class Cache(TypedDict): """The name of the cache.""" - class Header(TypedDict): name: "str" value: "str" - class CachedResponse(TypedDict): """Cached response""" diff --git a/cdp_use/cdp/cast/commands.py b/cdp_use/cdp/cast/commands.py index aeabbe9..1303036 100644 --- a/cdp_use/cdp/cast/commands.py +++ b/cdp_use/cdp/cast/commands.py @@ -6,35 +6,22 @@ from typing_extensions import TypedDict + class EnableParameters(TypedDict, total=False): presentationUrl: "str" - - - class SetSinkToUseParameters(TypedDict): sinkName: "str" - - - class StartDesktopMirroringParameters(TypedDict): sinkName: "str" - - - class StartTabMirroringParameters(TypedDict): sinkName: "str" - - - class StopCastingParameters(TypedDict): sinkName: "str" - - diff --git a/cdp_use/cdp/cast/events.py b/cdp_use/cdp/cast/events.py index 26f6846..1f2e036 100644 --- a/cdp_use/cdp/cast/events.py +++ b/cdp_use/cdp/cast/events.py @@ -14,12 +14,15 @@ """This is fired whenever the list of available sinks changes. A sink is a device or a software surface that you can cast to.""" + + class SinksUpdatedEvent(TypedDict): sinks: "List[Sink]" - """This is fired whenever the outstanding issue/error message changes. |issueMessage| is empty if there is no issue.""" + + class IssueUpdatedEvent(TypedDict): issueMessage: "str" diff --git a/cdp_use/cdp/cast/library.py b/cdp_use/cdp/cast/library.py index 69de83b..f5a7133 100644 --- a/cdp_use/cdp/cast/library.py +++ b/cdp_use/cdp/cast/library.py @@ -16,10 +16,11 @@ from .commands import StartTabMirroringParameters from .commands import StopCastingParameters + class CastClient: """Client for Cast domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -28,15 +29,18 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Starts observing for sinks that can be used for tab mirroring, and if set, -sinks compatible with |presentationUrl| as well. When sinks are found, a -|sinksUpdated| event is fired. -Also starts observing for issue messages. When an issue is added or removed, -an |issueUpdated| event is fired.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Cast.enable", - params=params, - session_id=session_id, - )) + sinks compatible with |presentationUrl| as well. When sinks are found, a + |sinksUpdated| event is fired. + Also starts observing for issue messages. When an issue is added or removed, + an |issueUpdated| event is fired.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Cast.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -44,11 +48,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stops observing for sinks and issues.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Cast.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Cast.disable", + params=params, + session_id=session_id, + ), + ) async def setSinkToUse( self, @@ -56,12 +63,15 @@ async def setSinkToUse( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets a sink to be used when the web page requests the browser to choose a -sink via Presentation API, Remote Playback API, or Cast SDK.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Cast.setSinkToUse", - params=params, - session_id=session_id, - )) + sink via Presentation API, Remote Playback API, or Cast SDK.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Cast.setSinkToUse", + params=params, + session_id=session_id, + ), + ) async def startDesktopMirroring( self, @@ -69,11 +79,14 @@ async def startDesktopMirroring( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Starts mirroring the desktop to the sink.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Cast.startDesktopMirroring", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Cast.startDesktopMirroring", + params=params, + session_id=session_id, + ), + ) async def startTabMirroring( self, @@ -81,11 +94,14 @@ async def startTabMirroring( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Starts mirroring the tab to the sink.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Cast.startTabMirroring", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Cast.startTabMirroring", + params=params, + session_id=session_id, + ), + ) async def stopCasting( self, @@ -93,10 +109,11 @@ async def stopCasting( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stops the active Cast session on the sink.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Cast.stopCasting", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Cast.stopCasting", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/cast/registration.py b/cdp_use/cdp/cast/registration.py index 6b539c4..ca074d7 100644 --- a/cdp_use/cdp/cast/registration.py +++ b/cdp_use/cdp/cast/registration.py @@ -12,42 +12,42 @@ from ..registry import EventRegistry from .events import IssueUpdatedEvent, SinksUpdatedEvent + class CastRegistration: """Event registration interface for Cast domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Cast" def sinksUpdated( self, - callback: Callable[['SinksUpdatedEvent', Optional[str]], None], + callback: Callable[["SinksUpdatedEvent", Optional[str]], None], ) -> None: """ - Register a callback for sinksUpdated events. - - This is fired whenever the list of available sinks changes. A sink is a -device or a software surface that you can cast to. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for sinksUpdated events. + + This is fired whenever the list of available sinks changes. A sink is a + device or a software surface that you can cast to. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Cast.sinksUpdated", callback) def issueUpdated( self, - callback: Callable[['IssueUpdatedEvent', Optional[str]], None], + callback: Callable[["IssueUpdatedEvent", Optional[str]], None], ) -> None: """ - Register a callback for issueUpdated events. - - This is fired whenever the outstanding issue/error message changes. -|issueMessage| is empty if there is no issue. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for issueUpdated events. + + This is fired whenever the outstanding issue/error message changes. + |issueMessage| is empty if there is no issue. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Cast.issueUpdated", callback) - diff --git a/cdp_use/cdp/cast/types.py b/cdp_use/cdp/cast/types.py index b25751a..80b2ff8 100644 --- a/cdp_use/cdp/cast/types.py +++ b/cdp_use/cdp/cast/types.py @@ -6,6 +6,7 @@ from typing_extensions import NotRequired, TypedDict + class Sink(TypedDict): name: "str" id: "str" diff --git a/cdp_use/cdp/console/commands.py b/cdp_use/cdp/console/commands.py index f1a45e3..2c083d3 100644 --- a/cdp_use/cdp/console/commands.py +++ b/cdp_use/cdp/console/commands.py @@ -5,4 +5,4 @@ """CDP Console Domain Commands""" -# No commands defined for this domain \ No newline at end of file +# No commands defined for this domain diff --git a/cdp_use/cdp/console/events.py b/cdp_use/cdp/console/events.py index b16b86a..5de0026 100644 --- a/cdp_use/cdp/console/events.py +++ b/cdp_use/cdp/console/events.py @@ -12,6 +12,8 @@ from .types import ConsoleMessage """Issued when new console message is added.""" + + class MessageAddedEvent(TypedDict): message: "ConsoleMessage" """Console message that has been added.""" diff --git a/cdp_use/cdp/console/library.py b/cdp_use/cdp/console/library.py index baa6e63..cddf77c 100644 --- a/cdp_use/cdp/console/library.py +++ b/cdp_use/cdp/console/library.py @@ -11,10 +11,11 @@ if TYPE_CHECKING: from ...client import CDPClient + class ConsoleClient: """Client for Console domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def clearMessages( @@ -23,11 +24,14 @@ async def clearMessages( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Does nothing.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Console.clearMessages", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Console.clearMessages", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -35,11 +39,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables console domain, prevents further console messages from being reported to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Console.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Console.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -47,11 +54,12 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables console domain, sends the messages collected so far to the client by means of the -`messageAdded` notification.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Console.enable", - params=params, - session_id=session_id, - )) - - + `messageAdded` notification.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Console.enable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/console/registration.py b/cdp_use/cdp/console/registration.py index ca1ad0a..9843cb3 100644 --- a/cdp_use/cdp/console/registration.py +++ b/cdp_use/cdp/console/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import MessageAddedEvent + class ConsoleRegistration: """Event registration interface for Console domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Console" def messageAdded( self, - callback: Callable[['MessageAddedEvent', Optional[str]], None], + callback: Callable[["MessageAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for messageAdded events. - + Issued when new console message is added. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Console.messageAdded", callback) - diff --git a/cdp_use/cdp/console/types.py b/cdp_use/cdp/console/types.py index f01c833..f62e479 100644 --- a/cdp_use/cdp/console/types.py +++ b/cdp_use/cdp/console/types.py @@ -6,6 +6,7 @@ from typing_extensions import NotRequired, TypedDict + class ConsoleMessage(TypedDict): """Console message.""" diff --git a/cdp_use/cdp/css/commands.py b/cdp_use/cdp/css/commands.py index 5e0f7cd..8302a76 100644 --- a/cdp_use/cdp/css/commands.py +++ b/cdp_use/cdp/css/commands.py @@ -14,9 +14,9 @@ from ..dom.types import PseudoType from ..page.types import FrameId from .types import CSSAnimationStyle + from .types import CSSAtRule from .types import CSSComputedStyleProperty from .types import CSSContainerQuery - from .types import CSSFontPaletteValuesRule from .types import CSSFunctionRule from .types import CSSKeyframesRule from .types import CSSLayerData @@ -43,6 +43,7 @@ from .types import StyleSheetId from .types import Value + class AddRuleParameters(TypedDict): styleSheetId: "StyleSheetId" """The css style sheet identifier where a new rule should be inserted.""" @@ -61,7 +62,6 @@ class AddRuleReturns(TypedDict): """The newly created rule.""" - class CollectClassNamesParameters(TypedDict): styleSheetId: "StyleSheetId" @@ -71,7 +71,6 @@ class CollectClassNamesReturns(TypedDict): """Class name list.""" - class CreateStyleSheetParameters(TypedDict): frameId: "FrameId" """Identifier of the frame where \"via-inspector\" stylesheet should be created.""" @@ -87,7 +86,6 @@ class CreateStyleSheetReturns(TypedDict): """Identifier of the created \"via-inspector\" stylesheet.""" - class ForcePseudoStateParameters(TypedDict): nodeId: "NodeId" """The element id for which to force the pseudo state.""" @@ -95,9 +93,6 @@ class ForcePseudoStateParameters(TypedDict): """Element pseudo classes to force when computing the element's style.""" - - - class ForceStartingStyleParameters(TypedDict): nodeId: "NodeId" """The element id for which to force the starting-style state.""" @@ -105,9 +100,6 @@ class ForceStartingStyleParameters(TypedDict): """Boolean indicating if this is on or off.""" - - - class GetBackgroundColorsParameters(TypedDict): nodeId: "NodeId" """Id of the node to get background colors for.""" @@ -127,7 +119,6 @@ class GetBackgroundColorsReturns(TypedDict): '100').""" - class GetComputedStyleForNodeParameters(TypedDict): nodeId: "NodeId" @@ -140,7 +131,6 @@ class GetComputedStyleForNodeReturns(TypedDict): computed style.""" - class ResolveValuesParameters(TypedDict): values: "List[str]" """Cascade-dependent keywords (revert/revert-layer) do not work.""" @@ -159,7 +149,6 @@ class ResolveValuesReturns(TypedDict): results: "List[str]" - class GetLonghandPropertiesParameters(TypedDict): shorthandName: "str" value: "str" @@ -169,7 +158,6 @@ class GetLonghandPropertiesReturns(TypedDict): longhandProperties: "List[CSSProperty]" - class GetInlineStylesForNodeParameters(TypedDict): nodeId: "NodeId" @@ -181,7 +169,6 @@ class GetInlineStylesForNodeReturns(TypedDict): """Attribute-defined element style (e.g. resulting from \"width=20 height=100%\").""" - class GetAnimatedStylesForNodeParameters(TypedDict): nodeId: "NodeId" @@ -196,7 +183,6 @@ class GetAnimatedStylesForNodeReturns(TypedDict): the inheritance chain of the element.""" - class GetMatchedStylesForNodeParameters(TypedDict): nodeId: "NodeId" @@ -225,25 +211,22 @@ class GetMatchedStylesForNodeReturns(TypedDict): """A list of CSS at-property rules matching this node.""" cssPropertyRegistrations: "List[CSSPropertyRegistration]" """A list of CSS property registrations matching this node.""" - cssFontPaletteValuesRule: "CSSFontPaletteValuesRule" - """A font-palette-values rule matching this node.""" + cssAtRules: "List[CSSAtRule]" + """A list of simple @rules matching this node or its pseudo-elements.""" parentLayoutNodeId: "NodeId" """Id of the first parent element that does not have display: contents.""" cssFunctionRules: "List[CSSFunctionRule]" """A list of CSS at-function rules referenced by styles of this node.""" - class GetEnvironmentVariablesReturns(TypedDict): environmentVariables: "Dict[str, Any]" - class GetMediaQueriesReturns(TypedDict): medias: "List[CSSMedia]" - class GetPlatformFontsForNodeParameters(TypedDict): nodeId: "NodeId" @@ -253,7 +236,6 @@ class GetPlatformFontsForNodeReturns(TypedDict): """Usage statistics for every employed platform font.""" - class GetStyleSheetTextParameters(TypedDict): styleSheetId: "StyleSheetId" @@ -263,7 +245,6 @@ class GetStyleSheetTextReturns(TypedDict): """The stylesheet text.""" - class GetLayersForNodeParameters(TypedDict): nodeId: "NodeId" @@ -272,7 +253,6 @@ class GetLayersForNodeReturns(TypedDict): rootLayer: "CSSLayerData" - class GetLocationForSelectorParameters(TypedDict): styleSheetId: "StyleSheetId" selectorText: "str" @@ -282,27 +262,19 @@ class GetLocationForSelectorReturns(TypedDict): ranges: "List[SourceRange]" - class TrackComputedStyleUpdatesForNodeParameters(TypedDict, total=False): nodeId: "NodeId" - - - class TrackComputedStyleUpdatesParameters(TypedDict): propertiesToTrack: "List[CSSComputedStyleProperty]" - - - class TakeComputedStyleUpdatesReturns(TypedDict): nodeIds: "List[NodeId]" """The list of node Ids that have their tracked computed styles updated.""" - class SetEffectivePropertyValueForNodeParameters(TypedDict): nodeId: "NodeId" """The element id for which to set property.""" @@ -310,9 +282,6 @@ class SetEffectivePropertyValueForNodeParameters(TypedDict): value: "str" - - - class SetPropertyRulePropertyNameParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -324,7 +293,6 @@ class SetPropertyRulePropertyNameReturns(TypedDict): """The resulting key text after modification.""" - class SetKeyframeKeyParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -336,7 +304,6 @@ class SetKeyframeKeyReturns(TypedDict): """The resulting key text after modification.""" - class SetMediaTextParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -348,7 +315,6 @@ class SetMediaTextReturns(TypedDict): """The resulting CSS media rule after modification.""" - class SetContainerQueryTextParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -360,7 +326,6 @@ class SetContainerQueryTextReturns(TypedDict): """The resulting CSS container query rule after modification.""" - class SetSupportsTextParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -372,7 +337,6 @@ class SetSupportsTextReturns(TypedDict): """The resulting CSS Supports rule after modification.""" - class SetScopeTextParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -384,7 +348,6 @@ class SetScopeTextReturns(TypedDict): """The resulting CSS Scope rule after modification.""" - class SetRuleSelectorParameters(TypedDict): styleSheetId: "StyleSheetId" range: "SourceRange" @@ -396,7 +359,6 @@ class SetRuleSelectorReturns(TypedDict): """The resulting selector list after modification.""" - class SetStyleSheetTextParameters(TypedDict): styleSheetId: "StyleSheetId" text: "str" @@ -407,7 +369,6 @@ class SetStyleSheetTextReturns(TypedDict): """URL of source map associated with script (if any).""" - class SetStyleTextsParameters(TypedDict): edits: "List[StyleDeclarationEdit]" nodeForPropertySyntaxValidation: "NotRequired[NodeId]" @@ -421,21 +382,16 @@ class SetStyleTextsReturns(TypedDict): """The resulting styles after modification.""" - class StopRuleUsageTrackingReturns(TypedDict): ruleUsage: "List[RuleUsage]" - class TakeCoverageDeltaReturns(TypedDict): coverage: "List[RuleUsage]" timestamp: "float" """Monotonically increasing time, in seconds.""" - class SetLocalFontsEnabledParameters(TypedDict): enabled: "bool" """Whether rendering of local fonts is enabled.""" - - diff --git a/cdp_use/cdp/css/events.py b/cdp_use/cdp/css/events.py index f34ddf8..1716044 100644 --- a/cdp_use/cdp/css/events.py +++ b/cdp_use/cdp/css/events.py @@ -16,39 +16,44 @@ """Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded web font.""" + + class FontsUpdatedEvent(TypedDict, total=False): font: "FontFace" """The web font that has loaded.""" - """Fires whenever a MediaQuery result changes (for example, after a browser window has been resized.) The current implementation considers only viewport-dependent media features.""" + + class MediaQueryResultChangedEvent(TypedDict): pass - """Fired whenever an active document stylesheet is added.""" + + class StyleSheetAddedEvent(TypedDict): header: "CSSStyleSheetHeader" """Added stylesheet metainfo.""" - """Fired whenever a stylesheet is changed as a result of the client operation.""" + + class StyleSheetChangedEvent(TypedDict): styleSheetId: "StyleSheetId" - """Fired whenever an active document stylesheet is removed.""" + + class StyleSheetRemovedEvent(TypedDict): styleSheetId: "StyleSheetId" """Identifier of the removed stylesheet.""" - class ComputedStyleUpdatedEvent(TypedDict): nodeId: "NodeId" """The node id that has updated computed styles.""" diff --git a/cdp_use/cdp/css/library.py b/cdp_use/cdp/css/library.py index 50b6387..6ec0b6e 100644 --- a/cdp_use/cdp/css/library.py +++ b/cdp_use/cdp/css/library.py @@ -68,10 +68,11 @@ from .commands import TrackComputedStyleUpdatesForNodeParameters from .commands import TrackComputedStyleUpdatesParameters + class CSSClient: """Client for CSS domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def addRule( @@ -80,12 +81,15 @@ async def addRule( session_id: Optional[str] = None, ) -> "AddRuleReturns": """Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the -position specified by `location`.""" - return cast("AddRuleReturns", await self._client.send_raw( - method="CSS.addRule", - params=params, - session_id=session_id, - )) + position specified by `location`.""" + return cast( + "AddRuleReturns", + await self._client.send_raw( + method="CSS.addRule", + params=params, + session_id=session_id, + ), + ) async def collectClassNames( self, @@ -93,11 +97,14 @@ async def collectClassNames( session_id: Optional[str] = None, ) -> "CollectClassNamesReturns": """Returns all class names from specified stylesheet.""" - return cast("CollectClassNamesReturns", await self._client.send_raw( - method="CSS.collectClassNames", - params=params, - session_id=session_id, - )) + return cast( + "CollectClassNamesReturns", + await self._client.send_raw( + method="CSS.collectClassNames", + params=params, + session_id=session_id, + ), + ) async def createStyleSheet( self, @@ -105,11 +112,14 @@ async def createStyleSheet( session_id: Optional[str] = None, ) -> "CreateStyleSheetReturns": """Creates a new special \"via-inspector\" stylesheet in the frame with given `frameId`.""" - return cast("CreateStyleSheetReturns", await self._client.send_raw( - method="CSS.createStyleSheet", - params=params, - session_id=session_id, - )) + return cast( + "CreateStyleSheetReturns", + await self._client.send_raw( + method="CSS.createStyleSheet", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -117,11 +127,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables the CSS agent for the given page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -129,12 +142,15 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been -enabled until the result of this command is received.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.enable", - params=params, - session_id=session_id, - )) + enabled until the result of this command is received.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.enable", + params=params, + session_id=session_id, + ), + ) async def forcePseudoState( self, @@ -142,12 +158,15 @@ async def forcePseudoState( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Ensures that the given node will have specified pseudo-classes whenever its style is computed by -the browser.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.forcePseudoState", - params=params, - session_id=session_id, - )) + the browser.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.forcePseudoState", + params=params, + session_id=session_id, + ), + ) async def forceStartingStyle( self, @@ -155,22 +174,28 @@ async def forceStartingStyle( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Ensures that the given node is in its starting-style state.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.forceStartingStyle", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.forceStartingStyle", + params=params, + session_id=session_id, + ), + ) async def getBackgroundColors( self, params: "GetBackgroundColorsParameters", session_id: Optional[str] = None, ) -> "GetBackgroundColorsReturns": - return cast("GetBackgroundColorsReturns", await self._client.send_raw( - method="CSS.getBackgroundColors", - params=params, - session_id=session_id, - )) + return cast( + "GetBackgroundColorsReturns", + await self._client.send_raw( + method="CSS.getBackgroundColors", + params=params, + session_id=session_id, + ), + ) async def getComputedStyleForNode( self, @@ -178,11 +203,14 @@ async def getComputedStyleForNode( session_id: Optional[str] = None, ) -> "GetComputedStyleForNodeReturns": """Returns the computed style for a DOM node identified by `nodeId`.""" - return cast("GetComputedStyleForNodeReturns", await self._client.send_raw( - method="CSS.getComputedStyleForNode", - params=params, - session_id=session_id, - )) + return cast( + "GetComputedStyleForNodeReturns", + await self._client.send_raw( + method="CSS.getComputedStyleForNode", + params=params, + session_id=session_id, + ), + ) async def resolveValues( self, @@ -190,30 +218,36 @@ async def resolveValues( session_id: Optional[str] = None, ) -> "ResolveValuesReturns": """Resolve the specified values in the context of the provided element. -For example, a value of '1em' is evaluated according to the computed -'font-size' of the element and a value 'calc(1px + 2px)' will be -resolved to '3px'. -If the `propertyName` was specified the `values` are resolved as if -they were property's declaration. If a value cannot be parsed according -to the provided property syntax, the value is parsed using combined -syntax as if null `propertyName` was provided. If the value cannot be -resolved even then, return the provided value without any changes.""" - return cast("ResolveValuesReturns", await self._client.send_raw( - method="CSS.resolveValues", - params=params, - session_id=session_id, - )) + For example, a value of '1em' is evaluated according to the computed + 'font-size' of the element and a value 'calc(1px + 2px)' will be + resolved to '3px'. + If the `propertyName` was specified the `values` are resolved as if + they were property's declaration. If a value cannot be parsed according + to the provided property syntax, the value is parsed using combined + syntax as if null `propertyName` was provided. If the value cannot be + resolved even then, return the provided value without any changes.""" + return cast( + "ResolveValuesReturns", + await self._client.send_raw( + method="CSS.resolveValues", + params=params, + session_id=session_id, + ), + ) async def getLonghandProperties( self, params: "GetLonghandPropertiesParameters", session_id: Optional[str] = None, ) -> "GetLonghandPropertiesReturns": - return cast("GetLonghandPropertiesReturns", await self._client.send_raw( - method="CSS.getLonghandProperties", - params=params, - session_id=session_id, - )) + return cast( + "GetLonghandPropertiesReturns", + await self._client.send_raw( + method="CSS.getLonghandProperties", + params=params, + session_id=session_id, + ), + ) async def getInlineStylesForNode( self, @@ -221,12 +255,15 @@ async def getInlineStylesForNode( session_id: Optional[str] = None, ) -> "GetInlineStylesForNodeReturns": """Returns the styles defined inline (explicitly in the \"style\" attribute and implicitly, using DOM -attributes) for a DOM node identified by `nodeId`.""" - return cast("GetInlineStylesForNodeReturns", await self._client.send_raw( - method="CSS.getInlineStylesForNode", - params=params, - session_id=session_id, - )) + attributes) for a DOM node identified by `nodeId`.""" + return cast( + "GetInlineStylesForNodeReturns", + await self._client.send_raw( + method="CSS.getInlineStylesForNode", + params=params, + session_id=session_id, + ), + ) async def getAnimatedStylesForNode( self, @@ -234,12 +271,15 @@ async def getAnimatedStylesForNode( session_id: Optional[str] = None, ) -> "GetAnimatedStylesForNodeReturns": """Returns the styles coming from animations & transitions -including the animation & transition styles coming from inheritance chain.""" - return cast("GetAnimatedStylesForNodeReturns", await self._client.send_raw( - method="CSS.getAnimatedStylesForNode", - params=params, - session_id=session_id, - )) + including the animation & transition styles coming from inheritance chain.""" + return cast( + "GetAnimatedStylesForNodeReturns", + await self._client.send_raw( + method="CSS.getAnimatedStylesForNode", + params=params, + session_id=session_id, + ), + ) async def getMatchedStylesForNode( self, @@ -247,11 +287,14 @@ async def getMatchedStylesForNode( session_id: Optional[str] = None, ) -> "GetMatchedStylesForNodeReturns": """Returns requested styles for a DOM node identified by `nodeId`.""" - return cast("GetMatchedStylesForNodeReturns", await self._client.send_raw( - method="CSS.getMatchedStylesForNode", - params=params, - session_id=session_id, - )) + return cast( + "GetMatchedStylesForNodeReturns", + await self._client.send_raw( + method="CSS.getMatchedStylesForNode", + params=params, + session_id=session_id, + ), + ) async def getEnvironmentVariables( self, @@ -259,11 +302,14 @@ async def getEnvironmentVariables( session_id: Optional[str] = None, ) -> "GetEnvironmentVariablesReturns": """Returns the values of the default UA-defined environment variables used in env()""" - return cast("GetEnvironmentVariablesReturns", await self._client.send_raw( - method="CSS.getEnvironmentVariables", - params=params, - session_id=session_id, - )) + return cast( + "GetEnvironmentVariablesReturns", + await self._client.send_raw( + method="CSS.getEnvironmentVariables", + params=params, + session_id=session_id, + ), + ) async def getMediaQueries( self, @@ -271,11 +317,14 @@ async def getMediaQueries( session_id: Optional[str] = None, ) -> "GetMediaQueriesReturns": """Returns all media queries parsed by the rendering engine.""" - return cast("GetMediaQueriesReturns", await self._client.send_raw( - method="CSS.getMediaQueries", - params=params, - session_id=session_id, - )) + return cast( + "GetMediaQueriesReturns", + await self._client.send_raw( + method="CSS.getMediaQueries", + params=params, + session_id=session_id, + ), + ) async def getPlatformFontsForNode( self, @@ -283,12 +332,15 @@ async def getPlatformFontsForNode( session_id: Optional[str] = None, ) -> "GetPlatformFontsForNodeReturns": """Requests information about platform fonts which we used to render child TextNodes in the given -node.""" - return cast("GetPlatformFontsForNodeReturns", await self._client.send_raw( - method="CSS.getPlatformFontsForNode", - params=params, - session_id=session_id, - )) + node.""" + return cast( + "GetPlatformFontsForNodeReturns", + await self._client.send_raw( + method="CSS.getPlatformFontsForNode", + params=params, + session_id=session_id, + ), + ) async def getStyleSheetText( self, @@ -296,11 +348,14 @@ async def getStyleSheetText( session_id: Optional[str] = None, ) -> "GetStyleSheetTextReturns": """Returns the current textual content for a stylesheet.""" - return cast("GetStyleSheetTextReturns", await self._client.send_raw( - method="CSS.getStyleSheetText", - params=params, - session_id=session_id, - )) + return cast( + "GetStyleSheetTextReturns", + await self._client.send_raw( + method="CSS.getStyleSheetText", + params=params, + session_id=session_id, + ), + ) async def getLayersForNode( self, @@ -308,14 +363,17 @@ async def getLayersForNode( session_id: Optional[str] = None, ) -> "GetLayersForNodeReturns": """Returns all layers parsed by the rendering engine for the tree scope of a node. -Given a DOM element identified by nodeId, getLayersForNode returns the root -layer for the nearest ancestor document or shadow root. The layer root contains -the full layer tree for the tree scope and their ordering.""" - return cast("GetLayersForNodeReturns", await self._client.send_raw( - method="CSS.getLayersForNode", - params=params, - session_id=session_id, - )) + Given a DOM element identified by nodeId, getLayersForNode returns the root + layer for the nearest ancestor document or shadow root. The layer root contains + the full layer tree for the tree scope and their ordering.""" + return cast( + "GetLayersForNodeReturns", + await self._client.send_raw( + method="CSS.getLayersForNode", + params=params, + session_id=session_id, + ), + ) async def getLocationForSelector( self, @@ -323,12 +381,15 @@ async def getLocationForSelector( session_id: Optional[str] = None, ) -> "GetLocationForSelectorReturns": """Given a CSS selector text and a style sheet ID, getLocationForSelector -returns an array of locations of the CSS selector in the style sheet.""" - return cast("GetLocationForSelectorReturns", await self._client.send_raw( - method="CSS.getLocationForSelector", - params=params, - session_id=session_id, - )) + returns an array of locations of the CSS selector in the style sheet.""" + return cast( + "GetLocationForSelectorReturns", + await self._client.send_raw( + method="CSS.getLocationForSelector", + params=params, + session_id=session_id, + ), + ) async def trackComputedStyleUpdatesForNode( self, @@ -336,16 +397,19 @@ async def trackComputedStyleUpdatesForNode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Starts tracking the given node for the computed style updates -and whenever the computed style is updated for node, it queues -a `computedStyleUpdated` event with throttling. -There can only be 1 node tracked for computed style updates -so passing a new node id removes tracking from the previous node. -Pass `undefined` to disable tracking.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.trackComputedStyleUpdatesForNode", - params=params, - session_id=session_id, - )) + and whenever the computed style is updated for node, it queues + a `computedStyleUpdated` event with throttling. + There can only be 1 node tracked for computed style updates + so passing a new node id removes tracking from the previous node. + Pass `undefined` to disable tracking.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.trackComputedStyleUpdatesForNode", + params=params, + session_id=session_id, + ), + ) async def trackComputedStyleUpdates( self, @@ -353,16 +417,19 @@ async def trackComputedStyleUpdates( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Starts tracking the given computed styles for updates. The specified array of properties -replaces the one previously specified. Pass empty array to disable tracking. -Use takeComputedStyleUpdates to retrieve the list of nodes that had properties modified. -The changes to computed style properties are only tracked for nodes pushed to the front-end -by the DOM agent. If no changes to the tracked properties occur after the node has been pushed -to the front-end, no updates will be issued for the node.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.trackComputedStyleUpdates", - params=params, - session_id=session_id, - )) + replaces the one previously specified. Pass empty array to disable tracking. + Use takeComputedStyleUpdates to retrieve the list of nodes that had properties modified. + The changes to computed style properties are only tracked for nodes pushed to the front-end + by the DOM agent. If no changes to the tracked properties occur after the node has been pushed + to the front-end, no updates will be issued for the node.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.trackComputedStyleUpdates", + params=params, + session_id=session_id, + ), + ) async def takeComputedStyleUpdates( self, @@ -370,11 +437,14 @@ async def takeComputedStyleUpdates( session_id: Optional[str] = None, ) -> "TakeComputedStyleUpdatesReturns": """Polls the next batch of computed style updates.""" - return cast("TakeComputedStyleUpdatesReturns", await self._client.send_raw( - method="CSS.takeComputedStyleUpdates", - params=params, - session_id=session_id, - )) + return cast( + "TakeComputedStyleUpdatesReturns", + await self._client.send_raw( + method="CSS.takeComputedStyleUpdates", + params=params, + session_id=session_id, + ), + ) async def setEffectivePropertyValueForNode( self, @@ -382,12 +452,15 @@ async def setEffectivePropertyValueForNode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Find a rule with the given active property for the given node and set the new value for this -property""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.setEffectivePropertyValueForNode", - params=params, - session_id=session_id, - )) + property""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.setEffectivePropertyValueForNode", + params=params, + session_id=session_id, + ), + ) async def setPropertyRulePropertyName( self, @@ -395,11 +468,14 @@ async def setPropertyRulePropertyName( session_id: Optional[str] = None, ) -> "SetPropertyRulePropertyNameReturns": """Modifies the property rule property name.""" - return cast("SetPropertyRulePropertyNameReturns", await self._client.send_raw( - method="CSS.setPropertyRulePropertyName", - params=params, - session_id=session_id, - )) + return cast( + "SetPropertyRulePropertyNameReturns", + await self._client.send_raw( + method="CSS.setPropertyRulePropertyName", + params=params, + session_id=session_id, + ), + ) async def setKeyframeKey( self, @@ -407,11 +483,14 @@ async def setKeyframeKey( session_id: Optional[str] = None, ) -> "SetKeyframeKeyReturns": """Modifies the keyframe rule key text.""" - return cast("SetKeyframeKeyReturns", await self._client.send_raw( - method="CSS.setKeyframeKey", - params=params, - session_id=session_id, - )) + return cast( + "SetKeyframeKeyReturns", + await self._client.send_raw( + method="CSS.setKeyframeKey", + params=params, + session_id=session_id, + ), + ) async def setMediaText( self, @@ -419,11 +498,14 @@ async def setMediaText( session_id: Optional[str] = None, ) -> "SetMediaTextReturns": """Modifies the rule selector.""" - return cast("SetMediaTextReturns", await self._client.send_raw( - method="CSS.setMediaText", - params=params, - session_id=session_id, - )) + return cast( + "SetMediaTextReturns", + await self._client.send_raw( + method="CSS.setMediaText", + params=params, + session_id=session_id, + ), + ) async def setContainerQueryText( self, @@ -431,11 +513,14 @@ async def setContainerQueryText( session_id: Optional[str] = None, ) -> "SetContainerQueryTextReturns": """Modifies the expression of a container query.""" - return cast("SetContainerQueryTextReturns", await self._client.send_raw( - method="CSS.setContainerQueryText", - params=params, - session_id=session_id, - )) + return cast( + "SetContainerQueryTextReturns", + await self._client.send_raw( + method="CSS.setContainerQueryText", + params=params, + session_id=session_id, + ), + ) async def setSupportsText( self, @@ -443,11 +528,14 @@ async def setSupportsText( session_id: Optional[str] = None, ) -> "SetSupportsTextReturns": """Modifies the expression of a supports at-rule.""" - return cast("SetSupportsTextReturns", await self._client.send_raw( - method="CSS.setSupportsText", - params=params, - session_id=session_id, - )) + return cast( + "SetSupportsTextReturns", + await self._client.send_raw( + method="CSS.setSupportsText", + params=params, + session_id=session_id, + ), + ) async def setScopeText( self, @@ -455,11 +543,14 @@ async def setScopeText( session_id: Optional[str] = None, ) -> "SetScopeTextReturns": """Modifies the expression of a scope at-rule.""" - return cast("SetScopeTextReturns", await self._client.send_raw( - method="CSS.setScopeText", - params=params, - session_id=session_id, - )) + return cast( + "SetScopeTextReturns", + await self._client.send_raw( + method="CSS.setScopeText", + params=params, + session_id=session_id, + ), + ) async def setRuleSelector( self, @@ -467,11 +558,14 @@ async def setRuleSelector( session_id: Optional[str] = None, ) -> "SetRuleSelectorReturns": """Modifies the rule selector.""" - return cast("SetRuleSelectorReturns", await self._client.send_raw( - method="CSS.setRuleSelector", - params=params, - session_id=session_id, - )) + return cast( + "SetRuleSelectorReturns", + await self._client.send_raw( + method="CSS.setRuleSelector", + params=params, + session_id=session_id, + ), + ) async def setStyleSheetText( self, @@ -479,11 +573,14 @@ async def setStyleSheetText( session_id: Optional[str] = None, ) -> "SetStyleSheetTextReturns": """Sets the new stylesheet text.""" - return cast("SetStyleSheetTextReturns", await self._client.send_raw( - method="CSS.setStyleSheetText", - params=params, - session_id=session_id, - )) + return cast( + "SetStyleSheetTextReturns", + await self._client.send_raw( + method="CSS.setStyleSheetText", + params=params, + session_id=session_id, + ), + ) async def setStyleTexts( self, @@ -491,11 +588,14 @@ async def setStyleTexts( session_id: Optional[str] = None, ) -> "SetStyleTextsReturns": """Applies specified style edits one after another in the given order.""" - return cast("SetStyleTextsReturns", await self._client.send_raw( - method="CSS.setStyleTexts", - params=params, - session_id=session_id, - )) + return cast( + "SetStyleTextsReturns", + await self._client.send_raw( + method="CSS.setStyleTexts", + params=params, + session_id=session_id, + ), + ) async def startRuleUsageTracking( self, @@ -503,11 +603,14 @@ async def startRuleUsageTracking( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables the selector recording.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.startRuleUsageTracking", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.startRuleUsageTracking", + params=params, + session_id=session_id, + ), + ) async def stopRuleUsageTracking( self, @@ -515,12 +618,15 @@ async def stopRuleUsageTracking( session_id: Optional[str] = None, ) -> "StopRuleUsageTrackingReturns": """Stop tracking rule usage and return the list of rules that were used since last call to -`takeCoverageDelta` (or since start of coverage instrumentation).""" - return cast("StopRuleUsageTrackingReturns", await self._client.send_raw( - method="CSS.stopRuleUsageTracking", - params=params, - session_id=session_id, - )) + `takeCoverageDelta` (or since start of coverage instrumentation).""" + return cast( + "StopRuleUsageTrackingReturns", + await self._client.send_raw( + method="CSS.stopRuleUsageTracking", + params=params, + session_id=session_id, + ), + ) async def takeCoverageDelta( self, @@ -528,12 +634,15 @@ async def takeCoverageDelta( session_id: Optional[str] = None, ) -> "TakeCoverageDeltaReturns": """Obtain list of rules that became used since last call to this method (or since start of coverage -instrumentation).""" - return cast("TakeCoverageDeltaReturns", await self._client.send_raw( - method="CSS.takeCoverageDelta", - params=params, - session_id=session_id, - )) + instrumentation).""" + return cast( + "TakeCoverageDeltaReturns", + await self._client.send_raw( + method="CSS.takeCoverageDelta", + params=params, + session_id=session_id, + ), + ) async def setLocalFontsEnabled( self, @@ -541,10 +650,11 @@ async def setLocalFontsEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables/disables rendering of local CSS fonts (enabled by default).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="CSS.setLocalFontsEnabled", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="CSS.setLocalFontsEnabled", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/css/registration.py b/cdp_use/cdp/css/registration.py index f7d1356..203a95b 100644 --- a/cdp_use/cdp/css/registration.py +++ b/cdp_use/cdp/css/registration.py @@ -11,62 +11,63 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - ComputedStyleUpdatedEvent, - FontsUpdatedEvent, - MediaQueryResultChangedEvent, - StyleSheetAddedEvent, - StyleSheetChangedEvent, - StyleSheetRemovedEvent -) + ComputedStyleUpdatedEvent, + FontsUpdatedEvent, + MediaQueryResultChangedEvent, + StyleSheetAddedEvent, + StyleSheetChangedEvent, + StyleSheetRemovedEvent, + ) + class CSSRegistration: """Event registration interface for CSS domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "CSS" def fontsUpdated( self, - callback: Callable[['FontsUpdatedEvent', Optional[str]], None], + callback: Callable[["FontsUpdatedEvent", Optional[str]], None], ) -> None: """ - Register a callback for fontsUpdated events. - - Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded -web font. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for fontsUpdated events. + + Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded + web font. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("CSS.fontsUpdated", callback) def mediaQueryResultChanged( self, - callback: Callable[['MediaQueryResultChangedEvent', Optional[str]], None], + callback: Callable[["MediaQueryResultChangedEvent", Optional[str]], None], ) -> None: """ - Register a callback for mediaQueryResultChanged events. - - Fires whenever a MediaQuery result changes (for example, after a browser window has been -resized.) The current implementation considers only viewport-dependent media features. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for mediaQueryResultChanged events. + + Fires whenever a MediaQuery result changes (for example, after a browser window has been + resized.) The current implementation considers only viewport-dependent media features. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("CSS.mediaQueryResultChanged", callback) def styleSheetAdded( self, - callback: Callable[['StyleSheetAddedEvent', Optional[str]], None], + callback: Callable[["StyleSheetAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for styleSheetAdded events. - + Fired whenever an active document stylesheet is added. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -75,13 +76,13 @@ def styleSheetAdded( def styleSheetChanged( self, - callback: Callable[['StyleSheetChangedEvent', Optional[str]], None], + callback: Callable[["StyleSheetChangedEvent", Optional[str]], None], ) -> None: """ Register a callback for styleSheetChanged events. - + Fired whenever a stylesheet is changed as a result of the client operation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -90,13 +91,13 @@ def styleSheetChanged( def styleSheetRemoved( self, - callback: Callable[['StyleSheetRemovedEvent', Optional[str]], None], + callback: Callable[["StyleSheetRemovedEvent", Optional[str]], None], ) -> None: """ Register a callback for styleSheetRemoved events. - + Fired whenever an active document stylesheet is removed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -105,14 +106,13 @@ def styleSheetRemoved( def computedStyleUpdated( self, - callback: Callable[['ComputedStyleUpdatedEvent', Optional[str]], None], + callback: Callable[["ComputedStyleUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for computedStyleUpdated events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("CSS.computedStyleUpdated", callback) - diff --git a/cdp_use/cdp/css/types.py b/cdp_use/cdp/css/types.py index 17be237..e743b14 100644 --- a/cdp_use/cdp/css/types.py +++ b/cdp_use/cdp/css/types.py @@ -20,14 +20,12 @@ StyleSheetId = str - StyleSheetOrigin = Literal["injected", "user-agent", "inspector", "regular"] """Stylesheet type: "injected" for stylesheets injected via extension, "user-agent" for user-agent stylesheets, "inspector" for stylesheets created by the inspector (i.e. those holding the "via inspector" rules), "regular" for regular stylesheets.""" - class PseudoElementMatches(TypedDict): """CSS rule collection for a single pseudo style.""" @@ -39,7 +37,6 @@ class PseudoElementMatches(TypedDict): """Matches of CSS rules applicable to the pseudo style.""" - class CSSAnimationStyle(TypedDict): """CSS style coming from animations with the name of the animation.""" @@ -49,7 +46,6 @@ class CSSAnimationStyle(TypedDict): """The style coming from the animation.""" - class InheritedStyleEntry(TypedDict): """Inherited CSS rule collection from ancestor node.""" @@ -59,7 +55,6 @@ class InheritedStyleEntry(TypedDict): """Matches of CSS rules matching the ancestor node in the style inheritance chain.""" - class InheritedAnimatedStyleEntry(TypedDict, total=False): """Inherited CSS style collection for animated styles from ancestor node.""" @@ -69,7 +64,6 @@ class InheritedAnimatedStyleEntry(TypedDict, total=False): """The style coming from the transitions of the ancestor, if any, in the style inheritance chain.""" - class InheritedPseudoElementMatches(TypedDict): """Inherited pseudo element matches from pseudos of an ancestor node.""" @@ -77,7 +71,6 @@ class InheritedPseudoElementMatches(TypedDict): """Matches of pseudo styles from the pseudos of an ancestor node.""" - class RuleMatch(TypedDict): """Match data for a CSS rule.""" @@ -87,7 +80,6 @@ class RuleMatch(TypedDict): """Matching selector indices in the rule's selectorList selectors (0-based).""" - class Value(TypedDict): """Data for a simple selector (these are delimited by commas in a selector list).""" @@ -99,10 +91,9 @@ class Value(TypedDict): """Specificity of the selector.""" - class Specificity(TypedDict): """Specificity: -https://drafts.csswg.org/selectors/#specificity-rules""" + https://drafts.csswg.org/selectors/#specificity-rules""" a: "int" """The a component, which represents the number of ID selectors.""" @@ -113,7 +104,6 @@ class Specificity(TypedDict): """The c component, which represents the number of type selectors and pseudo-elements.""" - class SelectorList(TypedDict): """Selector list data.""" @@ -123,7 +113,6 @@ class SelectorList(TypedDict): """Rule selector text.""" - class CSSStyleSheetHeader(TypedDict): """CSS stylesheet metainformation.""" @@ -172,7 +161,6 @@ class CSSStyleSheetHeader(TypedDict): """If the style sheet was loaded from a network resource, this indicates when the resource failed to load""" - class CSSRule(TypedDict): """CSS rule representation.""" @@ -187,6 +175,8 @@ class CSSRule(TypedDict): """Parent stylesheet's origin.""" style: "CSSStyle" """Associated style declaration.""" + originTreeScopeNodeId: "NotRequired[BackendNodeId]" + """The BackendNodeId of the DOM node that constitutes the origin tree scope of this rule.""" media: "NotRequired[List[CSSMedia]]" """Media list array (for rules involving media queries). The array enumerates media queries starting with the innermost one, going outwards.""" @@ -209,13 +199,19 @@ class CSSRule(TypedDict): The array enumerates @starting-style at-rules starting with the innermost one, going outwards.""" - -CSSRuleType = Literal["MediaRule", "SupportsRule", "ContainerRule", "LayerRule", "ScopeRule", "StyleRule", "StartingStyleRule"] +CSSRuleType = Literal[ + "MediaRule", + "SupportsRule", + "ContainerRule", + "LayerRule", + "ScopeRule", + "StyleRule", + "StartingStyleRule", +] """Enum indicating the type of a CSS rule, used to represent the order of a style rule's ancestors. This list only contains rule types that are collected during the ancestor rule collection.""" - class RuleUsage(TypedDict): """CSS coverage information.""" @@ -230,7 +226,6 @@ class RuleUsage(TypedDict): """Indicates whether the rule was actually used by some element in the page.""" - class SourceRange(TypedDict): """Text range within a resource. All numbers are zero-based.""" @@ -244,7 +239,6 @@ class SourceRange(TypedDict): """End column of range (exclusive).""" - class ShorthandEntry(TypedDict): name: "str" """Shorthand name.""" @@ -254,7 +248,6 @@ class ShorthandEntry(TypedDict): """Whether the property has \"!important\" annotation (implies `false` if absent).""" - class CSSComputedStyleProperty(TypedDict): name: "str" """Computed style property name.""" @@ -262,7 +255,6 @@ class CSSComputedStyleProperty(TypedDict): """Computed style property value.""" - class ComputedStyleExtraFields(TypedDict): isAppearanceBase: "bool" """Returns whether or not this node is being rendered with base appearance, @@ -270,7 +262,6 @@ class ComputedStyleExtraFields(TypedDict): or it is in the subtree of an element being rendered with base appearance.""" - class CSSStyle(TypedDict): """CSS style representation.""" @@ -287,7 +278,6 @@ class CSSStyle(TypedDict): """Style declaration range in the enclosing stylesheet (if available).""" - class CSSProperty(TypedDict): """CSS property declaration data.""" @@ -312,7 +302,6 @@ class CSSProperty(TypedDict): This field will be empty if the given property is not a shorthand.""" - class CSSMedia(TypedDict): """CSS media rule descriptor.""" @@ -334,7 +323,6 @@ class CSSMedia(TypedDict): """Array of media queries.""" - class MediaQuery(TypedDict): """Media query descriptor.""" @@ -344,7 +332,6 @@ class MediaQuery(TypedDict): """Whether the media query condition is satisfied.""" - class MediaQueryExpression(TypedDict): """Media query expression descriptor.""" @@ -360,7 +347,6 @@ class MediaQueryExpression(TypedDict): """Computed length of media query expression (if applicable).""" - class CSSContainerQuery(TypedDict): """CSS container query rule descriptor.""" @@ -383,7 +369,6 @@ class CSSContainerQuery(TypedDict): """true if the query contains anchored() queries.""" - class CSSSupports(TypedDict): """CSS Supports at-rule descriptor.""" @@ -398,7 +383,6 @@ class CSSSupports(TypedDict): """Identifier of the stylesheet containing this object (if exists).""" - class CSSScope(TypedDict): """CSS Scope at-rule descriptor.""" @@ -411,7 +395,6 @@ class CSSScope(TypedDict): """Identifier of the stylesheet containing this object (if exists).""" - class CSSLayer(TypedDict): """CSS Layer at-rule descriptor.""" @@ -424,7 +407,6 @@ class CSSLayer(TypedDict): """Identifier of the stylesheet containing this object (if exists).""" - class CSSStartingStyle(TypedDict, total=False): """CSS Starting Style at-rule descriptor.""" @@ -435,7 +417,6 @@ class CSSStartingStyle(TypedDict, total=False): """Identifier of the stylesheet containing this object (if exists).""" - class CSSLayerData(TypedDict): """CSS Layer data.""" @@ -448,7 +429,6 @@ class CSSLayerData(TypedDict): A higher number has higher priority in the cascade order.""" - class PlatformFontUsage(TypedDict): """Information about amount of glyphs that were rendered with given font.""" @@ -462,7 +442,6 @@ class PlatformFontUsage(TypedDict): """Amount of glyphs that were rendered with this font.""" - class FontVariationAxis(TypedDict): """Information about font variation axes for variable fonts""" @@ -478,10 +457,9 @@ class FontVariationAxis(TypedDict): """The default value.""" - class FontFace(TypedDict): """Properties of a web font: https://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#font-descriptions -and additional information such as platformFontFamily and fontVariationAxes.""" + and additional information such as platformFontFamily and fontVariationAxes.""" fontFamily: "str" """The font-family.""" @@ -505,7 +483,6 @@ class FontFace(TypedDict): """Available variation settings (a.k.a. \"axes\").""" - class CSSTryRule(TypedDict): """CSS try rule representation.""" @@ -518,7 +495,6 @@ class CSSTryRule(TypedDict): """Associated style declaration.""" - class CSSPositionTryRule(TypedDict): """CSS @position-try rule representation.""" @@ -534,7 +510,6 @@ class CSSPositionTryRule(TypedDict): active: "bool" - class CSSKeyframesRule(TypedDict): """CSS keyframes rule representation.""" @@ -544,7 +519,6 @@ class CSSKeyframesRule(TypedDict): """List of keyframes.""" - class CSSPropertyRegistration(TypedDict): """Representation of a custom property registration through CSS.registerProperty""" @@ -554,22 +528,25 @@ class CSSPropertyRegistration(TypedDict): syntax: "str" +class CSSAtRule(TypedDict): + """CSS generic @rule representation.""" -class CSSFontPaletteValuesRule(TypedDict): - """CSS font-palette-values rule representation.""" - + type: "str" + """Type of at-rule.""" + subsection: "NotRequired[str]" + """Subsection of font-feature-values, if this is a subsection.""" + name: "NotRequired[Value]" + """LINT.ThenChange(//third_party/blink/renderer/core/inspector/inspector_style_sheet.cc:FontVariantAlternatesFeatureType,//third_party/blink/renderer/core/inspector/inspector_css_agent.cc:FontVariantAlternatesFeatureType) +Associated name, if applicable.""" styleSheetId: "NotRequired[StyleSheetId]" """The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.""" origin: "StyleSheetOrigin" """Parent stylesheet's origin.""" - fontPaletteName: "Value" - """Associated font palette name.""" style: "CSSStyle" """Associated style declaration.""" - class CSSPropertyRule(TypedDict): """CSS property at-rule representation.""" @@ -584,7 +561,6 @@ class CSSPropertyRule(TypedDict): """Associated style declaration.""" - class CSSFunctionParameter(TypedDict): """CSS function argument representation.""" @@ -594,7 +570,6 @@ class CSSFunctionParameter(TypedDict): """The parameter type.""" - class CSSFunctionConditionNode(TypedDict): """CSS function conditional block representation.""" @@ -610,7 +585,6 @@ class CSSFunctionConditionNode(TypedDict): """The condition text.""" - class CSSFunctionNode(TypedDict, total=False): """Section of the body of a CSS function rule.""" @@ -620,7 +594,6 @@ class CSSFunctionNode(TypedDict, total=False): """Values set by this node. If set, condition should not be set.""" - class CSSFunctionRule(TypedDict): """CSS function at-rule representation.""" @@ -637,7 +610,6 @@ class CSSFunctionRule(TypedDict): """Function body.""" - class CSSKeyframeRule(TypedDict): """CSS keyframe rule representation.""" @@ -652,7 +624,6 @@ class CSSKeyframeRule(TypedDict): """Associated style declaration.""" - class StyleDeclarationEdit(TypedDict): """A descriptor of operation to mutate style declaration text.""" diff --git a/cdp_use/cdp/debugger/commands.py b/cdp_use/cdp/debugger/commands.py index 62a473e..680ea77 100644 --- a/cdp_use/cdp/debugger/commands.py +++ b/cdp_use/cdp/debugger/commands.py @@ -29,15 +29,13 @@ from .types import SearchMatch from .types import WasmDisassemblyChunk + class ContinueToLocationParameters(TypedDict): location: "Location" """Location to continue to.""" targetCallFrames: "NotRequired[str]" - - - class EnableParameters(TypedDict, total=False): maxScriptsCacheSize: "float" """The maximum size in bytes of collected scripts (not referenced by other heap objects) @@ -49,7 +47,6 @@ class EnableReturns(TypedDict): """Unique identifier of the debugger.""" - class EvaluateOnCallFrameParameters(TypedDict): callFrameId: "CallFrameId" """Call frame identifier to evaluate on.""" @@ -81,7 +78,6 @@ class EvaluateOnCallFrameReturns(TypedDict): """Exception details.""" - class GetPossibleBreakpointsParameters(TypedDict): start: "Location" """Start of range to search possible breakpoint locations in.""" @@ -97,7 +93,6 @@ class GetPossibleBreakpointsReturns(TypedDict): """List of the possible breakpoint locations.""" - class GetScriptSourceParameters(TypedDict): scriptId: "ScriptId" """Id of the script to get source for.""" @@ -110,7 +105,6 @@ class GetScriptSourceReturns(TypedDict): """Wasm bytecode. (Encoded as a base64 string when passed over JSON)""" - class DisassembleWasmModuleParameters(TypedDict): scriptId: "ScriptId" """Id of the script to disassemble""" @@ -129,7 +123,6 @@ class DisassembleWasmModuleReturns(TypedDict): """The first chunk of disassembly.""" - class NextWasmDisassemblyChunkParameters(TypedDict): streamId: "str" @@ -139,7 +132,6 @@ class NextWasmDisassemblyChunkReturns(TypedDict): """The next chunk of disassembly.""" - class GetWasmBytecodeParameters(TypedDict): scriptId: "ScriptId" """Id of the Wasm script to get source for.""" @@ -150,7 +142,6 @@ class GetWasmBytecodeReturns(TypedDict): """Script source. (Encoded as a base64 string when passed over JSON)""" - class GetStackTraceParameters(TypedDict): stackTraceId: "StackTraceId" @@ -159,22 +150,15 @@ class GetStackTraceReturns(TypedDict): stackTrace: "StackTrace" - class PauseOnAsyncCallParameters(TypedDict): parentStackTraceId: "StackTraceId" """Debugger will pause when async call with given stack trace is started.""" - - - class RemoveBreakpointParameters(TypedDict): breakpointId: "BreakpointId" - - - class RestartFrameParameters(TypedDict): callFrameId: "CallFrameId" """Call frame identifier to evaluate on.""" @@ -192,7 +176,6 @@ class RestartFrameReturns(TypedDict): """Async stack trace, if any.""" - class ResumeParameters(TypedDict, total=False): terminateOnResume: "bool" """Set to true to terminate execution upon resuming execution. In contrast @@ -202,9 +185,6 @@ class ResumeParameters(TypedDict, total=False): If execution is currently not paused, this parameter has no effect.""" - - - class SearchInContentParameters(TypedDict): scriptId: "ScriptId" """Id of the script to search in.""" @@ -221,24 +201,17 @@ class SearchInContentReturns(TypedDict): """List of search matches.""" - class SetAsyncCallStackDepthParameters(TypedDict): maxDepth: "int" """Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async call stacks (default).""" - - - class SetBlackboxExecutionContextsParameters(TypedDict): uniqueIds: "List[str]" """Array of execution context unique ids for the debugger to ignore.""" - - - class SetBlackboxPatternsParameters(TypedDict): patterns: "List[str]" """Array of regexps that will be used to check script url for blackbox state.""" @@ -246,18 +219,12 @@ class SetBlackboxPatternsParameters(TypedDict): """If true, also ignore scripts with no source url.""" - - - class SetBlackboxedRangesParameters(TypedDict): scriptId: "ScriptId" """Id of the script.""" positions: "List[ScriptPosition]" - - - class SetBreakpointParameters(TypedDict): location: "Location" """Location to set breakpoint in.""" @@ -273,7 +240,6 @@ class SetBreakpointReturns(TypedDict): """Location this breakpoint resolved into.""" - class SetInstrumentationBreakpointParameters(TypedDict): instrumentation: "str" """Instrumentation name.""" @@ -284,7 +250,6 @@ class SetInstrumentationBreakpointReturns(TypedDict): """Id of the created breakpoint for further reference.""" - class SetBreakpointByUrlParameters(TypedDict): lineNumber: "int" """Line number to set breakpoint at.""" @@ -309,7 +274,6 @@ class SetBreakpointByUrlReturns(TypedDict): """List of the locations this breakpoint resolved into upon addition.""" - class SetBreakpointOnFunctionCallParameters(TypedDict): objectId: "RemoteObjectId" """Function object id.""" @@ -323,31 +287,21 @@ class SetBreakpointOnFunctionCallReturns(TypedDict): """Id of the created breakpoint for further reference.""" - class SetBreakpointsActiveParameters(TypedDict): active: "bool" """New value for breakpoints active state.""" - - - class SetPauseOnExceptionsParameters(TypedDict): state: "str" """Pause on exceptions mode.""" - - - class SetReturnValueParameters(TypedDict): newValue: "CallArgument" """New return value.""" - - - class SetScriptSourceParameters(TypedDict): scriptId: "ScriptId" """Id of the script to edit.""" @@ -378,15 +332,11 @@ class SetScriptSourceReturns(TypedDict): """Exception details if any. Only present when `status` is `CompileError`.""" - class SetSkipAllPausesParameters(TypedDict): skip: "bool" """New value for skip pauses state.""" - - - class SetVariableValueParameters(TypedDict): scopeNumber: "int" """0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' @@ -399,9 +349,6 @@ class SetVariableValueParameters(TypedDict): """Id of callframe that holds variable.""" - - - class StepIntoParameters(TypedDict, total=False): breakOnAsyncCall: "bool" """Debugger will pause on the execution of the first async task which was scheduled @@ -410,11 +357,6 @@ class StepIntoParameters(TypedDict, total=False): """The skipList specifies location ranges that should be skipped on step into.""" - - - class StepOverParameters(TypedDict, total=False): skipList: "List[LocationRange]" """The skipList specifies location ranges that should be skipped on step over.""" - - diff --git a/cdp_use/cdp/debugger/events.py b/cdp_use/cdp/debugger/events.py index 4a0b9b5..6b89d12 100644 --- a/cdp_use/cdp/debugger/events.py +++ b/cdp_use/cdp/debugger/events.py @@ -23,6 +23,8 @@ """Fired when breakpoint is resolved to an actual script and location. Deprecated in favor of `resolvedBreakpoints` in the `scriptParsed` event.""" + + class BreakpointResolvedEvent(TypedDict): breakpointId: "BreakpointId" """Breakpoint unique identifier.""" @@ -30,8 +32,9 @@ class BreakpointResolvedEvent(TypedDict): """Actual breakpoint location.""" - """Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria.""" + + class PausedEvent(TypedDict): callFrames: "List[CallFrame]" """Call stack the virtual machine stopped on.""" @@ -49,14 +52,16 @@ class PausedEvent(TypedDict): """Never present, will be removed.""" - """Fired when the virtual machine resumed execution.""" + + class ResumedEvent(TypedDict): pass - """Fired when virtual machine fails to parse the script.""" + + class ScriptFailedToParseEvent(TypedDict): scriptId: "ScriptId" """Identifier of the script parsed.""" @@ -96,9 +101,10 @@ class ScriptFailedToParseEvent(TypedDict): """The name the embedder supplied for this script.""" - """Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger.""" + + class ScriptParsedEvent(TypedDict): scriptId: "ScriptId" """Identifier of the script parsed.""" diff --git a/cdp_use/cdp/debugger/library.py b/cdp_use/cdp/debugger/library.py index b8a1771..9f495b4 100644 --- a/cdp_use/cdp/debugger/library.py +++ b/cdp_use/cdp/debugger/library.py @@ -56,10 +56,11 @@ from .commands import StepIntoParameters from .commands import StepOverParameters + class DebuggerClient: """Client for Debugger domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def continueToLocation( @@ -68,11 +69,14 @@ async def continueToLocation( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Continues execution until specific location is reached.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.continueToLocation", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.continueToLocation", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -80,11 +84,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables debugger for given page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -92,12 +99,15 @@ async def enable( session_id: Optional[str] = None, ) -> "EnableReturns": """Enables debugger for the given page. Clients should not assume that the debugging has been -enabled until the result for this command is received.""" - return cast("EnableReturns", await self._client.send_raw( - method="Debugger.enable", - params=params, - session_id=session_id, - )) + enabled until the result for this command is received.""" + return cast( + "EnableReturns", + await self._client.send_raw( + method="Debugger.enable", + params=params, + session_id=session_id, + ), + ) async def evaluateOnCallFrame( self, @@ -105,11 +115,14 @@ async def evaluateOnCallFrame( session_id: Optional[str] = None, ) -> "EvaluateOnCallFrameReturns": """Evaluates expression on a given call frame.""" - return cast("EvaluateOnCallFrameReturns", await self._client.send_raw( - method="Debugger.evaluateOnCallFrame", - params=params, - session_id=session_id, - )) + return cast( + "EvaluateOnCallFrameReturns", + await self._client.send_raw( + method="Debugger.evaluateOnCallFrame", + params=params, + session_id=session_id, + ), + ) async def getPossibleBreakpoints( self, @@ -117,12 +130,15 @@ async def getPossibleBreakpoints( session_id: Optional[str] = None, ) -> "GetPossibleBreakpointsReturns": """Returns possible locations for breakpoint. scriptId in start and end range locations should be -the same.""" - return cast("GetPossibleBreakpointsReturns", await self._client.send_raw( - method="Debugger.getPossibleBreakpoints", - params=params, - session_id=session_id, - )) + the same.""" + return cast( + "GetPossibleBreakpointsReturns", + await self._client.send_raw( + method="Debugger.getPossibleBreakpoints", + params=params, + session_id=session_id, + ), + ) async def getScriptSource( self, @@ -130,22 +146,28 @@ async def getScriptSource( session_id: Optional[str] = None, ) -> "GetScriptSourceReturns": """Returns source for the script with given id.""" - return cast("GetScriptSourceReturns", await self._client.send_raw( - method="Debugger.getScriptSource", - params=params, - session_id=session_id, - )) + return cast( + "GetScriptSourceReturns", + await self._client.send_raw( + method="Debugger.getScriptSource", + params=params, + session_id=session_id, + ), + ) async def disassembleWasmModule( self, params: "DisassembleWasmModuleParameters", session_id: Optional[str] = None, ) -> "DisassembleWasmModuleReturns": - return cast("DisassembleWasmModuleReturns", await self._client.send_raw( - method="Debugger.disassembleWasmModule", - params=params, - session_id=session_id, - )) + return cast( + "DisassembleWasmModuleReturns", + await self._client.send_raw( + method="Debugger.disassembleWasmModule", + params=params, + session_id=session_id, + ), + ) async def nextWasmDisassemblyChunk( self, @@ -153,14 +175,17 @@ async def nextWasmDisassemblyChunk( session_id: Optional[str] = None, ) -> "NextWasmDisassemblyChunkReturns": """Disassemble the next chunk of lines for the module corresponding to the -stream. If disassembly is complete, this API will invalidate the streamId -and return an empty chunk. Any subsequent calls for the now invalid stream -will return errors.""" - return cast("NextWasmDisassemblyChunkReturns", await self._client.send_raw( - method="Debugger.nextWasmDisassemblyChunk", - params=params, - session_id=session_id, - )) + stream. If disassembly is complete, this API will invalidate the streamId + and return an empty chunk. Any subsequent calls for the now invalid stream + will return errors.""" + return cast( + "NextWasmDisassemblyChunkReturns", + await self._client.send_raw( + method="Debugger.nextWasmDisassemblyChunk", + params=params, + session_id=session_id, + ), + ) async def getWasmBytecode( self, @@ -168,11 +193,14 @@ async def getWasmBytecode( session_id: Optional[str] = None, ) -> "GetWasmBytecodeReturns": """This command is deprecated. Use getScriptSource instead.""" - return cast("GetWasmBytecodeReturns", await self._client.send_raw( - method="Debugger.getWasmBytecode", - params=params, - session_id=session_id, - )) + return cast( + "GetWasmBytecodeReturns", + await self._client.send_raw( + method="Debugger.getWasmBytecode", + params=params, + session_id=session_id, + ), + ) async def getStackTrace( self, @@ -180,11 +208,14 @@ async def getStackTrace( session_id: Optional[str] = None, ) -> "GetStackTraceReturns": """Returns stack trace with given `stackTraceId`.""" - return cast("GetStackTraceReturns", await self._client.send_raw( - method="Debugger.getStackTrace", - params=params, - session_id=session_id, - )) + return cast( + "GetStackTraceReturns", + await self._client.send_raw( + method="Debugger.getStackTrace", + params=params, + session_id=session_id, + ), + ) async def pause( self, @@ -192,22 +223,28 @@ async def pause( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stops on the next JavaScript statement.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.pause", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.pause", + params=params, + session_id=session_id, + ), + ) async def pauseOnAsyncCall( self, params: "PauseOnAsyncCallParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.pauseOnAsyncCall", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.pauseOnAsyncCall", + params=params, + session_id=session_id, + ), + ) async def removeBreakpoint( self, @@ -215,11 +252,14 @@ async def removeBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes JavaScript breakpoint.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.removeBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.removeBreakpoint", + params=params, + session_id=session_id, + ), + ) async def restartFrame( self, @@ -227,23 +267,26 @@ async def restartFrame( session_id: Optional[str] = None, ) -> "RestartFrameReturns": """Restarts particular call frame from the beginning. The old, deprecated -behavior of `restartFrame` is to stay paused and allow further CDP commands -after a restart was scheduled. This can cause problems with restarting, so -we now continue execution immediatly after it has been scheduled until we -reach the beginning of the restarted frame. - -To stay back-wards compatible, `restartFrame` now expects a `mode` -parameter to be present. If the `mode` parameter is missing, `restartFrame` -errors out. - -The various return values are deprecated and `callFrames` is always empty. -Use the call frames from the `Debugger#paused` events instead, that fires -once V8 pauses at the beginning of the restarted function.""" - return cast("RestartFrameReturns", await self._client.send_raw( - method="Debugger.restartFrame", - params=params, - session_id=session_id, - )) + behavior of `restartFrame` is to stay paused and allow further CDP commands + after a restart was scheduled. This can cause problems with restarting, so + we now continue execution immediatly after it has been scheduled until we + reach the beginning of the restarted frame. + + To stay back-wards compatible, `restartFrame` now expects a `mode` + parameter to be present. If the `mode` parameter is missing, `restartFrame` + errors out. + + The various return values are deprecated and `callFrames` is always empty. + Use the call frames from the `Debugger#paused` events instead, that fires + once V8 pauses at the beginning of the restarted function.""" + return cast( + "RestartFrameReturns", + await self._client.send_raw( + method="Debugger.restartFrame", + params=params, + session_id=session_id, + ), + ) async def resume( self, @@ -251,11 +294,14 @@ async def resume( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Resumes JavaScript execution.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.resume", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.resume", + params=params, + session_id=session_id, + ), + ) async def searchInContent( self, @@ -263,11 +309,14 @@ async def searchInContent( session_id: Optional[str] = None, ) -> "SearchInContentReturns": """Searches for given string in script content.""" - return cast("SearchInContentReturns", await self._client.send_raw( - method="Debugger.searchInContent", - params=params, - session_id=session_id, - )) + return cast( + "SearchInContentReturns", + await self._client.send_raw( + method="Debugger.searchInContent", + params=params, + session_id=session_id, + ), + ) async def setAsyncCallStackDepth( self, @@ -275,11 +324,14 @@ async def setAsyncCallStackDepth( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables or disables async call stacks tracking.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setAsyncCallStackDepth", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setAsyncCallStackDepth", + params=params, + session_id=session_id, + ), + ) async def setBlackboxExecutionContexts( self, @@ -287,13 +339,16 @@ async def setBlackboxExecutionContexts( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Replace previous blackbox execution contexts with passed ones. Forces backend to skip -stepping/pausing in scripts in these execution contexts. VM will try to leave blackboxed script by -performing 'step in' several times, finally resorting to 'step out' if unsuccessful.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setBlackboxExecutionContexts", - params=params, - session_id=session_id, - )) + stepping/pausing in scripts in these execution contexts. VM will try to leave blackboxed script by + performing 'step in' several times, finally resorting to 'step out' if unsuccessful.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setBlackboxExecutionContexts", + params=params, + session_id=session_id, + ), + ) async def setBlackboxPatterns( self, @@ -301,13 +356,16 @@ async def setBlackboxPatterns( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in -scripts with url matching one of the patterns. VM will try to leave blackboxed script by -performing 'step in' several times, finally resorting to 'step out' if unsuccessful.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setBlackboxPatterns", - params=params, - session_id=session_id, - )) + scripts with url matching one of the patterns. VM will try to leave blackboxed script by + performing 'step in' several times, finally resorting to 'step out' if unsuccessful.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setBlackboxPatterns", + params=params, + session_id=session_id, + ), + ) async def setBlackboxedRanges( self, @@ -315,14 +373,17 @@ async def setBlackboxedRanges( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted -scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. -Positions array contains positions where blackbox state is changed. First interval isn't -blackboxed. Array should be sorted.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setBlackboxedRanges", - params=params, - session_id=session_id, - )) + scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + Positions array contains positions where blackbox state is changed. First interval isn't + blackboxed. Array should be sorted.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setBlackboxedRanges", + params=params, + session_id=session_id, + ), + ) async def setBreakpoint( self, @@ -330,11 +391,14 @@ async def setBreakpoint( session_id: Optional[str] = None, ) -> "SetBreakpointReturns": """Sets JavaScript breakpoint at a given location.""" - return cast("SetBreakpointReturns", await self._client.send_raw( - method="Debugger.setBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "SetBreakpointReturns", + await self._client.send_raw( + method="Debugger.setBreakpoint", + params=params, + session_id=session_id, + ), + ) async def setInstrumentationBreakpoint( self, @@ -342,11 +406,14 @@ async def setInstrumentationBreakpoint( session_id: Optional[str] = None, ) -> "SetInstrumentationBreakpointReturns": """Sets instrumentation breakpoint.""" - return cast("SetInstrumentationBreakpointReturns", await self._client.send_raw( - method="Debugger.setInstrumentationBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "SetInstrumentationBreakpointReturns", + await self._client.send_raw( + method="Debugger.setInstrumentationBreakpoint", + params=params, + session_id=session_id, + ), + ) async def setBreakpointByUrl( self, @@ -354,14 +421,17 @@ async def setBreakpointByUrl( session_id: Optional[str] = None, ) -> "SetBreakpointByUrlReturns": """Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this -command is issued, all existing parsed scripts will have breakpoints resolved and returned in -`locations` property. Further matching script parsing will result in subsequent -`breakpointResolved` events issued. This logical breakpoint will survive page reloads.""" - return cast("SetBreakpointByUrlReturns", await self._client.send_raw( - method="Debugger.setBreakpointByUrl", - params=params, - session_id=session_id, - )) + command is issued, all existing parsed scripts will have breakpoints resolved and returned in + `locations` property. Further matching script parsing will result in subsequent + `breakpointResolved` events issued. This logical breakpoint will survive page reloads.""" + return cast( + "SetBreakpointByUrlReturns", + await self._client.send_raw( + method="Debugger.setBreakpointByUrl", + params=params, + session_id=session_id, + ), + ) async def setBreakpointOnFunctionCall( self, @@ -369,13 +439,16 @@ async def setBreakpointOnFunctionCall( session_id: Optional[str] = None, ) -> "SetBreakpointOnFunctionCallReturns": """Sets JavaScript breakpoint before each call to the given function. -If another function was created from the same source as a given one, -calling it will also trigger the breakpoint.""" - return cast("SetBreakpointOnFunctionCallReturns", await self._client.send_raw( - method="Debugger.setBreakpointOnFunctionCall", - params=params, - session_id=session_id, - )) + If another function was created from the same source as a given one, + calling it will also trigger the breakpoint.""" + return cast( + "SetBreakpointOnFunctionCallReturns", + await self._client.send_raw( + method="Debugger.setBreakpointOnFunctionCall", + params=params, + session_id=session_id, + ), + ) async def setBreakpointsActive( self, @@ -383,11 +456,14 @@ async def setBreakpointsActive( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Activates / deactivates all breakpoints on the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setBreakpointsActive", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setBreakpointsActive", + params=params, + session_id=session_id, + ), + ) async def setPauseOnExceptions( self, @@ -395,12 +471,15 @@ async def setPauseOnExceptions( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions, -or caught exceptions, no exceptions. Initial pause on exceptions state is `none`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setPauseOnExceptions", - params=params, - session_id=session_id, - )) + or caught exceptions, no exceptions. Initial pause on exceptions state is `none`.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setPauseOnExceptions", + params=params, + session_id=session_id, + ), + ) async def setReturnValue( self, @@ -408,11 +487,14 @@ async def setReturnValue( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Changes return value in top frame. Available only at return break position.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setReturnValue", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setReturnValue", + params=params, + session_id=session_id, + ), + ) async def setScriptSource( self, @@ -421,16 +503,19 @@ async def setScriptSource( ) -> "SetScriptSourceReturns": """Edits JavaScript source live. -In general, functions that are currently on the stack can not be edited with -a single exception: If the edited function is the top-most stack frame and -that is the only activation of that function on the stack. In this case -the live edit will be successful and a `Debugger.restartFrame` for the -top-most function is automatically triggered.""" - return cast("SetScriptSourceReturns", await self._client.send_raw( - method="Debugger.setScriptSource", - params=params, - session_id=session_id, - )) + In general, functions that are currently on the stack can not be edited with + a single exception: If the edited function is the top-most stack frame and + that is the only activation of that function on the stack. In this case + the live edit will be successful and a `Debugger.restartFrame` for the + top-most function is automatically triggered.""" + return cast( + "SetScriptSourceReturns", + await self._client.send_raw( + method="Debugger.setScriptSource", + params=params, + session_id=session_id, + ), + ) async def setSkipAllPauses( self, @@ -438,11 +523,14 @@ async def setSkipAllPauses( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setSkipAllPauses", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setSkipAllPauses", + params=params, + session_id=session_id, + ), + ) async def setVariableValue( self, @@ -450,12 +538,15 @@ async def setVariableValue( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Changes value of variable in a callframe. Object-based scopes are not supported and must be -mutated manually.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.setVariableValue", - params=params, - session_id=session_id, - )) + mutated manually.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.setVariableValue", + params=params, + session_id=session_id, + ), + ) async def stepInto( self, @@ -463,11 +554,14 @@ async def stepInto( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Steps into the function call.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.stepInto", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.stepInto", + params=params, + session_id=session_id, + ), + ) async def stepOut( self, @@ -475,11 +569,14 @@ async def stepOut( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Steps out of the function call.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.stepOut", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.stepOut", + params=params, + session_id=session_id, + ), + ) async def stepOver( self, @@ -487,10 +584,11 @@ async def stepOver( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Steps over the statement.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Debugger.stepOver", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Debugger.stepOver", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/debugger/registration.py b/cdp_use/cdp/debugger/registration.py index 7bcfd60..5e31b6e 100644 --- a/cdp_use/cdp/debugger/registration.py +++ b/cdp_use/cdp/debugger/registration.py @@ -10,40 +10,47 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import BreakpointResolvedEvent, PausedEvent, ResumedEvent, ScriptFailedToParseEvent, ScriptParsedEvent + from .events import ( + BreakpointResolvedEvent, + PausedEvent, + ResumedEvent, + ScriptFailedToParseEvent, + ScriptParsedEvent, + ) + class DebuggerRegistration: """Event registration interface for Debugger domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Debugger" def breakpointResolved( self, - callback: Callable[['BreakpointResolvedEvent', Optional[str]], None], + callback: Callable[["BreakpointResolvedEvent", Optional[str]], None], ) -> None: """ - Register a callback for breakpointResolved events. - - Fired when breakpoint is resolved to an actual script and location. -Deprecated in favor of `resolvedBreakpoints` in the `scriptParsed` event. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for breakpointResolved events. + + Fired when breakpoint is resolved to an actual script and location. + Deprecated in favor of `resolvedBreakpoints` in the `scriptParsed` event. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Debugger.breakpointResolved", callback) def paused( self, - callback: Callable[['PausedEvent', Optional[str]], None], + callback: Callable[["PausedEvent", Optional[str]], None], ) -> None: """ Register a callback for paused events. - + Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -52,13 +59,13 @@ def paused( def resumed( self, - callback: Callable[['ResumedEvent', Optional[str]], None], + callback: Callable[["ResumedEvent", Optional[str]], None], ) -> None: """ Register a callback for resumed events. - + Fired when the virtual machine resumed execution. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -67,13 +74,13 @@ def resumed( def scriptFailedToParse( self, - callback: Callable[['ScriptFailedToParseEvent', Optional[str]], None], + callback: Callable[["ScriptFailedToParseEvent", Optional[str]], None], ) -> None: """ Register a callback for scriptFailedToParse events. - + Fired when virtual machine fails to parse the script. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -82,17 +89,16 @@ def scriptFailedToParse( def scriptParsed( self, - callback: Callable[['ScriptParsedEvent', Optional[str]], None], + callback: Callable[["ScriptParsedEvent", Optional[str]], None], ) -> None: """ - Register a callback for scriptParsed events. - - Fired when virtual machine parses script. This event is also fired for all known and uncollected -scripts upon enabling debugger. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for scriptParsed events. + + Fired when virtual machine parses script. This event is also fired for all known and uncollected + scripts upon enabling debugger. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Debugger.scriptParsed", callback) - diff --git a/cdp_use/cdp/debugger/types.py b/cdp_use/cdp/debugger/types.py index 557ad53..1953890 100644 --- a/cdp_use/cdp/debugger/types.py +++ b/cdp_use/cdp/debugger/types.py @@ -18,12 +18,10 @@ """Breakpoint identifier.""" - CallFrameId = str """Call frame identifier.""" - class Location(TypedDict): """Location in the source code.""" @@ -35,7 +33,6 @@ class Location(TypedDict): """Column number in the script (0-based).""" - class ScriptPosition(TypedDict): """Location in the source code.""" @@ -43,7 +40,6 @@ class ScriptPosition(TypedDict): columnNumber: "int" - class LocationRange(TypedDict): """Location range within one script.""" @@ -52,7 +48,6 @@ class LocationRange(TypedDict): end: "ScriptPosition" - class CallFrame(TypedDict): """JavaScript call frame. Array of call frames form the call stack.""" @@ -81,7 +76,6 @@ class CallFrame(TypedDict): successful, but it is very likely.""" - class Scope(TypedDict): """Scope description.""" @@ -98,7 +92,6 @@ class Scope(TypedDict): """Location in the source code where scope ends""" - class SearchMatch(TypedDict): """Search match for resource.""" @@ -108,7 +101,6 @@ class SearchMatch(TypedDict): """Line with match content.""" - class BreakLocation(TypedDict): scriptId: "ScriptId" """Script identifier as reported in the `Debugger.scriptParsed`.""" @@ -119,7 +111,6 @@ class BreakLocation(TypedDict): type: "NotRequired[str]" - class WasmDisassemblyChunk(TypedDict): lines: "List[str]" """The next chunk of disassembled lines.""" @@ -127,12 +118,10 @@ class WasmDisassemblyChunk(TypedDict): """The bytecode offsets describing the start of each line.""" - ScriptLanguage = Literal["JavaScript", "WebAssembly"] """Enum of possible script languages.""" - class DebugSymbols(TypedDict): """Debug symbols available for a wasm script.""" @@ -142,7 +131,6 @@ class DebugSymbols(TypedDict): """URL of the external symbol source.""" - class ResolvedBreakpoint(TypedDict): breakpointId: "BreakpointId" """Breakpoint unique identifier.""" diff --git a/cdp_use/cdp/deviceaccess/commands.py b/cdp_use/cdp/deviceaccess/commands.py index 922a841..6cfdb76 100644 --- a/cdp_use/cdp/deviceaccess/commands.py +++ b/cdp_use/cdp/deviceaccess/commands.py @@ -12,15 +12,11 @@ from .types import DeviceId from .types import RequestId + class SelectPromptParameters(TypedDict): id: "RequestId" deviceId: "DeviceId" - - - class CancelPromptParameters(TypedDict): id: "RequestId" - - diff --git a/cdp_use/cdp/deviceaccess/events.py b/cdp_use/cdp/deviceaccess/events.py index f7d85f5..5a79522 100644 --- a/cdp_use/cdp/deviceaccess/events.py +++ b/cdp_use/cdp/deviceaccess/events.py @@ -15,6 +15,8 @@ """A device request opened a user prompt to select a device. Respond with the selectPrompt or cancelPrompt command.""" + + class DeviceRequestPromptedEvent(TypedDict): id: "RequestId" devices: "List[PromptDevice]" diff --git a/cdp_use/cdp/deviceaccess/library.py b/cdp_use/cdp/deviceaccess/library.py index b2fae8c..bc16523 100644 --- a/cdp_use/cdp/deviceaccess/library.py +++ b/cdp_use/cdp/deviceaccess/library.py @@ -13,10 +13,11 @@ from .commands import CancelPromptParameters from .commands import SelectPromptParameters + class DeviceAccessClient: """Client for DeviceAccess domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -25,11 +26,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable events in this domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DeviceAccess.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DeviceAccess.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -37,11 +41,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disable events in this domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DeviceAccess.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DeviceAccess.disable", + params=params, + session_id=session_id, + ), + ) async def selectPrompt( self, @@ -49,11 +56,14 @@ async def selectPrompt( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Select a device in response to a DeviceAccess.deviceRequestPrompted event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DeviceAccess.selectPrompt", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DeviceAccess.selectPrompt", + params=params, + session_id=session_id, + ), + ) async def cancelPrompt( self, @@ -61,10 +71,11 @@ async def cancelPrompt( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Cancel a prompt in response to a DeviceAccess.deviceRequestPrompted event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DeviceAccess.cancelPrompt", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DeviceAccess.cancelPrompt", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/deviceaccess/registration.py b/cdp_use/cdp/deviceaccess/registration.py index e8154b9..f4a014b 100644 --- a/cdp_use/cdp/deviceaccess/registration.py +++ b/cdp_use/cdp/deviceaccess/registration.py @@ -12,26 +12,26 @@ from ..registry import EventRegistry from .events import DeviceRequestPromptedEvent + class DeviceAccessRegistration: """Event registration interface for DeviceAccess domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "DeviceAccess" def deviceRequestPrompted( self, - callback: Callable[['DeviceRequestPromptedEvent', Optional[str]], None], + callback: Callable[["DeviceRequestPromptedEvent", Optional[str]], None], ) -> None: """ - Register a callback for deviceRequestPrompted events. - - A device request opened a user prompt to select a device. Respond with the -selectPrompt or cancelPrompt command. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for deviceRequestPrompted events. + + A device request opened a user prompt to select a device. Respond with the + selectPrompt or cancelPrompt command. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("DeviceAccess.deviceRequestPrompted", callback) - diff --git a/cdp_use/cdp/deviceaccess/types.py b/cdp_use/cdp/deviceaccess/types.py index df90e65..53a573e 100644 --- a/cdp_use/cdp/deviceaccess/types.py +++ b/cdp_use/cdp/deviceaccess/types.py @@ -10,12 +10,10 @@ """Device request id.""" - DeviceId = str """A device id.""" - class PromptDevice(TypedDict): """Device information displayed in a user prompt to select a device.""" diff --git a/cdp_use/cdp/deviceorientation/commands.py b/cdp_use/cdp/deviceorientation/commands.py index 84f26e1..c39afb5 100644 --- a/cdp_use/cdp/deviceorientation/commands.py +++ b/cdp_use/cdp/deviceorientation/commands.py @@ -6,6 +6,7 @@ from typing_extensions import TypedDict + class SetDeviceOrientationOverrideParameters(TypedDict): alpha: "float" """Mock alpha""" @@ -13,5 +14,3 @@ class SetDeviceOrientationOverrideParameters(TypedDict): """Mock beta""" gamma: "float" """Mock gamma""" - - diff --git a/cdp_use/cdp/deviceorientation/events.py b/cdp_use/cdp/deviceorientation/events.py index a139c74..e17743e 100644 --- a/cdp_use/cdp/deviceorientation/events.py +++ b/cdp_use/cdp/deviceorientation/events.py @@ -5,4 +5,4 @@ """CDP DeviceOrientation Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/deviceorientation/library.py b/cdp_use/cdp/deviceorientation/library.py index 817fbd2..e9c4978 100644 --- a/cdp_use/cdp/deviceorientation/library.py +++ b/cdp_use/cdp/deviceorientation/library.py @@ -12,10 +12,11 @@ from ...client import CDPClient from .commands import SetDeviceOrientationOverrideParameters + class DeviceOrientationClient: """Client for DeviceOrientation domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def clearDeviceOrientationOverride( @@ -24,11 +25,14 @@ async def clearDeviceOrientationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the overridden Device Orientation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DeviceOrientation.clearDeviceOrientationOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DeviceOrientation.clearDeviceOrientationOverride", + params=params, + session_id=session_id, + ), + ) async def setDeviceOrientationOverride( self, @@ -36,10 +40,11 @@ async def setDeviceOrientationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the Device Orientation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DeviceOrientation.setDeviceOrientationOverride", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DeviceOrientation.setDeviceOrientationOverride", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/deviceorientation/registration.py b/cdp_use/cdp/deviceorientation/registration.py index 034120c..22a5617 100644 --- a/cdp_use/cdp/deviceorientation/registration.py +++ b/cdp_use/cdp/deviceorientation/registration.py @@ -5,4 +5,4 @@ """CDP DeviceOrientation Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/deviceorientation/types.py b/cdp_use/cdp/deviceorientation/types.py index 46de0c5..585c26e 100644 --- a/cdp_use/cdp/deviceorientation/types.py +++ b/cdp_use/cdp/deviceorientation/types.py @@ -5,4 +5,4 @@ """CDP DeviceOrientation Domain Types""" -# No types defined for this domain \ No newline at end of file +# No types defined for this domain diff --git a/cdp_use/cdp/dom/commands.py b/cdp_use/cdp/dom/commands.py index 439d60e..ad85de9 100644 --- a/cdp_use/cdp/dom/commands.py +++ b/cdp_use/cdp/dom/commands.py @@ -27,6 +27,7 @@ from .types import Quad from .types import Rect + class CollectClassNamesFromSubtreeParameters(TypedDict): nodeId: "NodeId" """Id of the node to collect class names.""" @@ -37,7 +38,6 @@ class CollectClassNamesFromSubtreeReturns(TypedDict): """Class name list.""" - class CopyToParameters(TypedDict): nodeId: "NodeId" """Id of the node to copy.""" @@ -53,7 +53,6 @@ class CopyToReturns(TypedDict): """Id of the node clone.""" - class DescribeNodeParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node.""" @@ -74,7 +73,6 @@ class DescribeNodeReturns(TypedDict): """Node description.""" - class ScrollIntoViewIfNeededParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node.""" @@ -87,25 +85,16 @@ class ScrollIntoViewIfNeededParameters(TypedDict, total=False): When omitted, center of the node will be used, similar to Element.scrollIntoView.""" - - - class DiscardSearchResultsParameters(TypedDict): searchId: "str" """Unique search session identifier.""" - - - class EnableParameters(TypedDict, total=False): includeWhitespace: "str" """Whether to include whitespaces in the children array of returned Nodes.""" - - - class FocusParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node.""" @@ -115,9 +104,6 @@ class FocusParameters(TypedDict, total=False): """JavaScript object id of the node wrapper.""" - - - class GetAttributesParameters(TypedDict): nodeId: "NodeId" """Id of the node to retrieve attributes for.""" @@ -128,7 +114,6 @@ class GetAttributesReturns(TypedDict): """An interleaved array of node attribute names and values.""" - class GetBoxModelParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node.""" @@ -143,7 +128,6 @@ class GetBoxModelReturns(TypedDict): """Box model for the node.""" - class GetContentQuadsParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node.""" @@ -158,7 +142,6 @@ class GetContentQuadsReturns(TypedDict): """Quads that describe node layout relative to viewport.""" - class GetDocumentParameters(TypedDict, total=False): depth: "int" """The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the @@ -173,7 +156,6 @@ class GetDocumentReturns(TypedDict): """Resulting node.""" - class GetFlattenedDocumentParameters(TypedDict, total=False): depth: "int" """The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the @@ -188,7 +170,6 @@ class GetFlattenedDocumentReturns(TypedDict): """Resulting node.""" - class GetNodesForSubtreeByStyleParameters(TypedDict): nodeId: "NodeId" """Node ID pointing to the root of a subtree.""" @@ -204,7 +185,6 @@ class GetNodesForSubtreeByStyleReturns(TypedDict): """Resulting nodes.""" - class GetNodeForLocationParameters(TypedDict): x: "int" """X coordinate.""" @@ -225,7 +205,6 @@ class GetNodeForLocationReturns(TypedDict): """Id of the node at given coordinates, only when enabled and requested document.""" - class GetOuterHTMLParameters(TypedDict, total=False): nodeId: "NodeId" """Identifier of the node.""" @@ -242,7 +221,6 @@ class GetOuterHTMLReturns(TypedDict): """Outer HTML markup.""" - class GetRelayoutBoundaryParameters(TypedDict): nodeId: "NodeId" """Id of the node.""" @@ -253,7 +231,6 @@ class GetRelayoutBoundaryReturns(TypedDict): """Relayout boundary node id for the given node.""" - class GetSearchResultsParameters(TypedDict): searchId: "str" """Unique search session identifier.""" @@ -268,7 +245,6 @@ class GetSearchResultsReturns(TypedDict): """Ids of the search result nodes.""" - class MoveToParameters(TypedDict): nodeId: "NodeId" """Id of the node to move.""" @@ -284,7 +260,6 @@ class MoveToReturns(TypedDict): """New id of the moved node.""" - class PerformSearchParameters(TypedDict): query: "str" """Plain text or query selector or XPath search query.""" @@ -299,7 +274,6 @@ class PerformSearchReturns(TypedDict): """Number of search results.""" - class PushNodeByPathToFrontendParameters(TypedDict): path: "str" """Path to node in the proprietary format.""" @@ -310,7 +284,6 @@ class PushNodeByPathToFrontendReturns(TypedDict): """Id of the node for given path.""" - class PushNodesByBackendIdsToFrontendParameters(TypedDict): backendNodeIds: "List[BackendNodeId]" """The array of backend node ids.""" @@ -322,7 +295,6 @@ class PushNodesByBackendIdsToFrontendReturns(TypedDict): backendNodeIds.""" - class QuerySelectorParameters(TypedDict): nodeId: "NodeId" """Id of the node to query upon.""" @@ -335,7 +307,6 @@ class QuerySelectorReturns(TypedDict): """Query selector result.""" - class QuerySelectorAllParameters(TypedDict): nodeId: "NodeId" """Id of the node to query upon.""" @@ -348,13 +319,11 @@ class QuerySelectorAllReturns(TypedDict): """Query selector result.""" - class GetTopLayerElementsReturns(TypedDict): nodeIds: "List[NodeId]" """NodeIds of top layer elements""" - class GetElementByRelationParameters(TypedDict): nodeId: "NodeId" """Id of the node from which to query the relation.""" @@ -367,7 +336,6 @@ class GetElementByRelationReturns(TypedDict): """NodeId of the element matching the queried relation.""" - class RemoveAttributeParameters(TypedDict): nodeId: "NodeId" """Id of the element to remove attribute from.""" @@ -375,17 +343,11 @@ class RemoveAttributeParameters(TypedDict): """Name of the attribute to remove.""" - - - class RemoveNodeParameters(TypedDict): nodeId: "NodeId" """Id of the node to remove.""" - - - class RequestChildNodesParameters(TypedDict): nodeId: "NodeId" """Id of the node to get children for.""" @@ -397,9 +359,6 @@ class RequestChildNodesParameters(TypedDict): (default is false).""" - - - class RequestNodeParameters(TypedDict): objectId: "RemoteObjectId" """JavaScript object id to convert into node.""" @@ -410,7 +369,6 @@ class RequestNodeReturns(TypedDict): """Node id for given object.""" - class ResolveNodeParameters(TypedDict, total=False): nodeId: "NodeId" """Id of the node to resolve.""" @@ -427,7 +385,6 @@ class ResolveNodeReturns(TypedDict): """JavaScript object wrapper for given node.""" - class SetAttributeValueParameters(TypedDict): nodeId: "NodeId" """Id of the element to set attribute for.""" @@ -437,9 +394,6 @@ class SetAttributeValueParameters(TypedDict): """Attribute value.""" - - - class SetAttributesAsTextParameters(TypedDict): nodeId: "NodeId" """Id of the element to set attributes for.""" @@ -450,9 +404,6 @@ class SetAttributesAsTextParameters(TypedDict): successfully.""" - - - class SetFileInputFilesParameters(TypedDict): files: "List[str]" """Array of file paths to set.""" @@ -464,17 +415,11 @@ class SetFileInputFilesParameters(TypedDict): """JavaScript object id of the node wrapper.""" - - - class SetNodeStackTracesEnabledParameters(TypedDict): enable: "bool" """Enable or disable.""" - - - class GetNodeStackTracesParameters(TypedDict): nodeId: "NodeId" """Id of the node to get stack traces for.""" @@ -485,7 +430,6 @@ class GetNodeStackTracesReturns(TypedDict): """Creation stack trace, if available.""" - class GetFileInfoParameters(TypedDict): objectId: "RemoteObjectId" """JavaScript object id of the node wrapper.""" @@ -495,21 +439,16 @@ class GetFileInfoReturns(TypedDict): path: "str" - class GetDetachedDomNodesReturns(TypedDict): detachedNodes: "List[DetachedElementInfo]" """The list of detached nodes""" - class SetInspectedNodeParameters(TypedDict): nodeId: "NodeId" """DOM node id to be accessible by means of $x command line API.""" - - - class SetNodeNameParameters(TypedDict): nodeId: "NodeId" """Id of the node to set name for.""" @@ -522,7 +461,6 @@ class SetNodeNameReturns(TypedDict): """New node's id.""" - class SetNodeValueParameters(TypedDict): nodeId: "NodeId" """Id of the node to set value for.""" @@ -530,9 +468,6 @@ class SetNodeValueParameters(TypedDict): """New node's value.""" - - - class SetOuterHTMLParameters(TypedDict): nodeId: "NodeId" """Id of the node to set markup for.""" @@ -540,9 +475,6 @@ class SetOuterHTMLParameters(TypedDict): """Outer HTML markup to set.""" - - - class GetFrameOwnerParameters(TypedDict): frameId: "FrameId" @@ -554,7 +486,6 @@ class GetFrameOwnerReturns(TypedDict): """Id of the node at given coordinates, only when enabled and requested document.""" - class GetContainerForNodeParameters(TypedDict): nodeId: "NodeId" containerName: "NotRequired[str]" @@ -569,7 +500,6 @@ class GetContainerForNodeReturns(TypedDict): """The container node for the given node, or null if not found.""" - class GetQueryingDescendantsForContainerParameters(TypedDict): nodeId: "NodeId" """Id of the container node to find querying descendants from.""" @@ -580,7 +510,6 @@ class GetQueryingDescendantsForContainerReturns(TypedDict): """Descendant nodes with container queries against the given container.""" - class GetAnchorElementParameters(TypedDict): nodeId: "NodeId" """Id of the positioned element from which to find the anchor.""" @@ -596,7 +525,6 @@ class GetAnchorElementReturns(TypedDict): """The anchor element of the given anchor query.""" - class ForceShowPopoverParameters(TypedDict): nodeId: "NodeId" """Id of the popover HTMLElement""" diff --git a/cdp_use/cdp/dom/events.py b/cdp_use/cdp/dom/events.py index 1af4b5d..cb16108 100644 --- a/cdp_use/cdp/dom/events.py +++ b/cdp_use/cdp/dom/events.py @@ -16,6 +16,8 @@ from .types import NodeId """Fired when `Element`'s attribute is modified.""" + + class AttributeModifiedEvent(TypedDict): nodeId: "NodeId" """Id of the node that has changed.""" @@ -25,8 +27,9 @@ class AttributeModifiedEvent(TypedDict): """Attribute value.""" - """Fired when `Element`'s attribute is removed.""" + + class AttributeRemovedEvent(TypedDict): nodeId: "NodeId" """Id of the node that has changed.""" @@ -34,8 +37,9 @@ class AttributeRemovedEvent(TypedDict): """A ttribute name.""" - """Mirrors `DOMCharacterDataModified` event.""" + + class CharacterDataModifiedEvent(TypedDict): nodeId: "NodeId" """Id of the node that has changed.""" @@ -43,8 +47,9 @@ class CharacterDataModifiedEvent(TypedDict): """New text value.""" - """Fired when `Container`'s child node count has changed.""" + + class ChildNodeCountUpdatedEvent(TypedDict): nodeId: "NodeId" """Id of the node that has changed.""" @@ -52,8 +57,9 @@ class ChildNodeCountUpdatedEvent(TypedDict): """New node count.""" - """Mirrors `DOMNodeInserted` event.""" + + class ChildNodeInsertedEvent(TypedDict): parentNodeId: "NodeId" """Id of the node that has changed.""" @@ -63,8 +69,9 @@ class ChildNodeInsertedEvent(TypedDict): """Inserted node data.""" - """Mirrors `DOMNodeRemoved` event.""" + + class ChildNodeRemovedEvent(TypedDict): parentNodeId: "NodeId" """Parent id.""" @@ -72,8 +79,9 @@ class ChildNodeRemovedEvent(TypedDict): """Id of the node that has been removed.""" - """Called when distribution is changed.""" + + class DistributedNodesUpdatedEvent(TypedDict): insertionPointId: "NodeId" """Insertion point where distributed nodes were updated.""" @@ -81,21 +89,24 @@ class DistributedNodesUpdatedEvent(TypedDict): """Distributed nodes for given insertion point.""" - """Fired when `Document` has been totally updated. Node ids are no longer valid.""" + + class DocumentUpdatedEvent(TypedDict): pass - """Fired when `Element`'s inline style is modified via a CSS property modification.""" + + class InlineStyleInvalidatedEvent(TypedDict): nodeIds: "List[NodeId]" """Ids of the nodes for which the inline styles have been invalidated.""" - """Called when a pseudo element is added to an element.""" + + class PseudoElementAddedEvent(TypedDict): parentId: "NodeId" """Pseudo element's parent element id.""" @@ -103,14 +114,16 @@ class PseudoElementAddedEvent(TypedDict): """The added pseudo element.""" - """Called when top layer elements are changed.""" + + class TopLayerElementsUpdatedEvent(TypedDict): pass - """Fired when a node's scrollability state changes.""" + + class ScrollableFlagUpdatedEvent(TypedDict): nodeId: "NodeId" """The id of the node.""" @@ -118,8 +131,19 @@ class ScrollableFlagUpdatedEvent(TypedDict): """If the node is scrollable.""" +"""Fired when a node's starting styles changes.""" + + +class AffectedByStartingStylesFlagUpdatedEvent(TypedDict): + nodeId: "NodeId" + """The id of the node.""" + affectedByStartingStyles: "bool" + """If the node has starting styles.""" + """Called when a pseudo element is removed from an element.""" + + class PseudoElementRemovedEvent(TypedDict): parentId: "NodeId" """Pseudo element's parent element id.""" @@ -127,9 +151,10 @@ class PseudoElementRemovedEvent(TypedDict): """The removed pseudo element id.""" - """Fired when backend wants to provide client with the missing DOM structure. This happens upon most of the calls requesting node ids.""" + + class SetChildNodesEvent(TypedDict): parentId: "NodeId" """Parent node id to populate with children.""" @@ -137,8 +162,9 @@ class SetChildNodesEvent(TypedDict): """Child nodes array.""" - """Called when shadow root is popped from the element.""" + + class ShadowRootPoppedEvent(TypedDict): hostId: "NodeId" """Host element id.""" @@ -146,8 +172,9 @@ class ShadowRootPoppedEvent(TypedDict): """Shadow root id.""" - """Called when shadow root is pushed into the element.""" + + class ShadowRootPushedEvent(TypedDict): hostId: "NodeId" """Host element id.""" diff --git a/cdp_use/cdp/dom/library.py b/cdp_use/cdp/dom/library.py index d3027ef..1dbddff 100644 --- a/cdp_use/cdp/dom/library.py +++ b/cdp_use/cdp/dom/library.py @@ -87,10 +87,11 @@ from .commands import SetNodeValueParameters from .commands import SetOuterHTMLParameters + class DOMClient: """Client for DOM domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def collectClassNamesFromSubtree( @@ -99,11 +100,14 @@ async def collectClassNamesFromSubtree( session_id: Optional[str] = None, ) -> "CollectClassNamesFromSubtreeReturns": """Collects class names for the node with given id and all of it's child nodes.""" - return cast("CollectClassNamesFromSubtreeReturns", await self._client.send_raw( - method="DOM.collectClassNamesFromSubtree", - params=params, - session_id=session_id, - )) + return cast( + "CollectClassNamesFromSubtreeReturns", + await self._client.send_raw( + method="DOM.collectClassNamesFromSubtree", + params=params, + session_id=session_id, + ), + ) async def copyTo( self, @@ -111,12 +115,15 @@ async def copyTo( session_id: Optional[str] = None, ) -> "CopyToReturns": """Creates a deep copy of the specified node and places it into the target container before the -given anchor.""" - return cast("CopyToReturns", await self._client.send_raw( - method="DOM.copyTo", - params=params, - session_id=session_id, - )) + given anchor.""" + return cast( + "CopyToReturns", + await self._client.send_raw( + method="DOM.copyTo", + params=params, + session_id=session_id, + ), + ) async def describeNode( self, @@ -124,12 +131,15 @@ async def describeNode( session_id: Optional[str] = None, ) -> "DescribeNodeReturns": """Describes node given its id, does not require domain to be enabled. Does not start tracking any -objects, can be used for automation.""" - return cast("DescribeNodeReturns", await self._client.send_raw( - method="DOM.describeNode", - params=params, - session_id=session_id, - )) + objects, can be used for automation.""" + return cast( + "DescribeNodeReturns", + await self._client.send_raw( + method="DOM.describeNode", + params=params, + session_id=session_id, + ), + ) async def scrollIntoViewIfNeeded( self, @@ -137,13 +147,16 @@ async def scrollIntoViewIfNeeded( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Scrolls the specified rect of the given node into view if not already visible. -Note: exactly one between nodeId, backendNodeId and objectId should be passed -to identify the node.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.scrollIntoViewIfNeeded", - params=params, - session_id=session_id, - )) + Note: exactly one between nodeId, backendNodeId and objectId should be passed + to identify the node.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.scrollIntoViewIfNeeded", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -151,11 +164,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables DOM agent for the given page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.disable", + params=params, + session_id=session_id, + ), + ) async def discardSearchResults( self, @@ -163,12 +179,15 @@ async def discardSearchResults( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Discards search results from the session with the given id. `getSearchResults` should no longer -be called for that search.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.discardSearchResults", - params=params, - session_id=session_id, - )) + be called for that search.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.discardSearchResults", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -176,11 +195,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables DOM agent for the given page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.enable", + params=params, + session_id=session_id, + ), + ) async def focus( self, @@ -188,11 +210,14 @@ async def focus( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Focuses the given element.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.focus", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.focus", + params=params, + session_id=session_id, + ), + ) async def getAttributes( self, @@ -200,11 +225,14 @@ async def getAttributes( session_id: Optional[str] = None, ) -> "GetAttributesReturns": """Returns attributes for the specified node.""" - return cast("GetAttributesReturns", await self._client.send_raw( - method="DOM.getAttributes", - params=params, - session_id=session_id, - )) + return cast( + "GetAttributesReturns", + await self._client.send_raw( + method="DOM.getAttributes", + params=params, + session_id=session_id, + ), + ) async def getBoxModel( self, @@ -212,11 +240,14 @@ async def getBoxModel( session_id: Optional[str] = None, ) -> "GetBoxModelReturns": """Returns boxes for the given node.""" - return cast("GetBoxModelReturns", await self._client.send_raw( - method="DOM.getBoxModel", - params=params, - session_id=session_id, - )) + return cast( + "GetBoxModelReturns", + await self._client.send_raw( + method="DOM.getBoxModel", + params=params, + session_id=session_id, + ), + ) async def getContentQuads( self, @@ -224,12 +255,15 @@ async def getContentQuads( session_id: Optional[str] = None, ) -> "GetContentQuadsReturns": """Returns quads that describe node position on the page. This method -might return multiple quads for inline nodes.""" - return cast("GetContentQuadsReturns", await self._client.send_raw( - method="DOM.getContentQuads", - params=params, - session_id=session_id, - )) + might return multiple quads for inline nodes.""" + return cast( + "GetContentQuadsReturns", + await self._client.send_raw( + method="DOM.getContentQuads", + params=params, + session_id=session_id, + ), + ) async def getDocument( self, @@ -237,12 +271,15 @@ async def getDocument( session_id: Optional[str] = None, ) -> "GetDocumentReturns": """Returns the root DOM node (and optionally the subtree) to the caller. -Implicitly enables the DOM domain events for the current target.""" - return cast("GetDocumentReturns", await self._client.send_raw( - method="DOM.getDocument", - params=params, - session_id=session_id, - )) + Implicitly enables the DOM domain events for the current target.""" + return cast( + "GetDocumentReturns", + await self._client.send_raw( + method="DOM.getDocument", + params=params, + session_id=session_id, + ), + ) async def getFlattenedDocument( self, @@ -250,13 +287,16 @@ async def getFlattenedDocument( session_id: Optional[str] = None, ) -> "GetFlattenedDocumentReturns": """Returns the root DOM node (and optionally the subtree) to the caller. -Deprecated, as it is not designed to work well with the rest of the DOM agent. -Use DOMSnapshot.captureSnapshot instead.""" - return cast("GetFlattenedDocumentReturns", await self._client.send_raw( - method="DOM.getFlattenedDocument", - params=params, - session_id=session_id, - )) + Deprecated, as it is not designed to work well with the rest of the DOM agent. + Use DOMSnapshot.captureSnapshot instead.""" + return cast( + "GetFlattenedDocumentReturns", + await self._client.send_raw( + method="DOM.getFlattenedDocument", + params=params, + session_id=session_id, + ), + ) async def getNodesForSubtreeByStyle( self, @@ -264,11 +304,14 @@ async def getNodesForSubtreeByStyle( session_id: Optional[str] = None, ) -> "GetNodesForSubtreeByStyleReturns": """Finds nodes with a given computed style in a subtree.""" - return cast("GetNodesForSubtreeByStyleReturns", await self._client.send_raw( - method="DOM.getNodesForSubtreeByStyle", - params=params, - session_id=session_id, - )) + return cast( + "GetNodesForSubtreeByStyleReturns", + await self._client.send_raw( + method="DOM.getNodesForSubtreeByStyle", + params=params, + session_id=session_id, + ), + ) async def getNodeForLocation( self, @@ -276,12 +319,15 @@ async def getNodeForLocation( session_id: Optional[str] = None, ) -> "GetNodeForLocationReturns": """Returns node id at given location. Depending on whether DOM domain is enabled, nodeId is -either returned or not.""" - return cast("GetNodeForLocationReturns", await self._client.send_raw( - method="DOM.getNodeForLocation", - params=params, - session_id=session_id, - )) + either returned or not.""" + return cast( + "GetNodeForLocationReturns", + await self._client.send_raw( + method="DOM.getNodeForLocation", + params=params, + session_id=session_id, + ), + ) async def getOuterHTML( self, @@ -289,11 +335,14 @@ async def getOuterHTML( session_id: Optional[str] = None, ) -> "GetOuterHTMLReturns": """Returns node's HTML markup.""" - return cast("GetOuterHTMLReturns", await self._client.send_raw( - method="DOM.getOuterHTML", - params=params, - session_id=session_id, - )) + return cast( + "GetOuterHTMLReturns", + await self._client.send_raw( + method="DOM.getOuterHTML", + params=params, + session_id=session_id, + ), + ) async def getRelayoutBoundary( self, @@ -301,11 +350,14 @@ async def getRelayoutBoundary( session_id: Optional[str] = None, ) -> "GetRelayoutBoundaryReturns": """Returns the id of the nearest ancestor that is a relayout boundary.""" - return cast("GetRelayoutBoundaryReturns", await self._client.send_raw( - method="DOM.getRelayoutBoundary", - params=params, - session_id=session_id, - )) + return cast( + "GetRelayoutBoundaryReturns", + await self._client.send_raw( + method="DOM.getRelayoutBoundary", + params=params, + session_id=session_id, + ), + ) async def getSearchResults( self, @@ -313,12 +365,15 @@ async def getSearchResults( session_id: Optional[str] = None, ) -> "GetSearchResultsReturns": """Returns search results from given `fromIndex` to given `toIndex` from the search with the given -identifier.""" - return cast("GetSearchResultsReturns", await self._client.send_raw( - method="DOM.getSearchResults", - params=params, - session_id=session_id, - )) + identifier.""" + return cast( + "GetSearchResultsReturns", + await self._client.send_raw( + method="DOM.getSearchResults", + params=params, + session_id=session_id, + ), + ) async def hideHighlight( self, @@ -326,11 +381,14 @@ async def hideHighlight( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Hides any highlight.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.hideHighlight", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.hideHighlight", + params=params, + session_id=session_id, + ), + ) async def highlightNode( self, @@ -338,11 +396,14 @@ async def highlightNode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights DOM node.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.highlightNode", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.highlightNode", + params=params, + session_id=session_id, + ), + ) async def highlightRect( self, @@ -350,11 +411,14 @@ async def highlightRect( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights given rectangle.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.highlightRect", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.highlightRect", + params=params, + session_id=session_id, + ), + ) async def markUndoableState( self, @@ -362,11 +426,14 @@ async def markUndoableState( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Marks last undoable state.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.markUndoableState", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.markUndoableState", + params=params, + session_id=session_id, + ), + ) async def moveTo( self, @@ -374,11 +441,14 @@ async def moveTo( session_id: Optional[str] = None, ) -> "MoveToReturns": """Moves node into the new container, places it before the given anchor.""" - return cast("MoveToReturns", await self._client.send_raw( - method="DOM.moveTo", - params=params, - session_id=session_id, - )) + return cast( + "MoveToReturns", + await self._client.send_raw( + method="DOM.moveTo", + params=params, + session_id=session_id, + ), + ) async def performSearch( self, @@ -386,12 +456,15 @@ async def performSearch( session_id: Optional[str] = None, ) -> "PerformSearchReturns": """Searches for a given string in the DOM tree. Use `getSearchResults` to access search results or -`cancelSearch` to end this search session.""" - return cast("PerformSearchReturns", await self._client.send_raw( - method="DOM.performSearch", - params=params, - session_id=session_id, - )) + `cancelSearch` to end this search session.""" + return cast( + "PerformSearchReturns", + await self._client.send_raw( + method="DOM.performSearch", + params=params, + session_id=session_id, + ), + ) async def pushNodeByPathToFrontend( self, @@ -399,11 +472,14 @@ async def pushNodeByPathToFrontend( session_id: Optional[str] = None, ) -> "PushNodeByPathToFrontendReturns": """Requests that the node is sent to the caller given its path. // FIXME, use XPath""" - return cast("PushNodeByPathToFrontendReturns", await self._client.send_raw( - method="DOM.pushNodeByPathToFrontend", - params=params, - session_id=session_id, - )) + return cast( + "PushNodeByPathToFrontendReturns", + await self._client.send_raw( + method="DOM.pushNodeByPathToFrontend", + params=params, + session_id=session_id, + ), + ) async def pushNodesByBackendIdsToFrontend( self, @@ -411,11 +487,14 @@ async def pushNodesByBackendIdsToFrontend( session_id: Optional[str] = None, ) -> "PushNodesByBackendIdsToFrontendReturns": """Requests that a batch of nodes is sent to the caller given their backend node ids.""" - return cast("PushNodesByBackendIdsToFrontendReturns", await self._client.send_raw( - method="DOM.pushNodesByBackendIdsToFrontend", - params=params, - session_id=session_id, - )) + return cast( + "PushNodesByBackendIdsToFrontendReturns", + await self._client.send_raw( + method="DOM.pushNodesByBackendIdsToFrontend", + params=params, + session_id=session_id, + ), + ) async def querySelector( self, @@ -423,11 +502,14 @@ async def querySelector( session_id: Optional[str] = None, ) -> "QuerySelectorReturns": """Executes `querySelector` on a given node.""" - return cast("QuerySelectorReturns", await self._client.send_raw( - method="DOM.querySelector", - params=params, - session_id=session_id, - )) + return cast( + "QuerySelectorReturns", + await self._client.send_raw( + method="DOM.querySelector", + params=params, + session_id=session_id, + ), + ) async def querySelectorAll( self, @@ -435,11 +517,14 @@ async def querySelectorAll( session_id: Optional[str] = None, ) -> "QuerySelectorAllReturns": """Executes `querySelectorAll` on a given node.""" - return cast("QuerySelectorAllReturns", await self._client.send_raw( - method="DOM.querySelectorAll", - params=params, - session_id=session_id, - )) + return cast( + "QuerySelectorAllReturns", + await self._client.send_raw( + method="DOM.querySelectorAll", + params=params, + session_id=session_id, + ), + ) async def getTopLayerElements( self, @@ -447,13 +532,16 @@ async def getTopLayerElements( session_id: Optional[str] = None, ) -> "GetTopLayerElementsReturns": """Returns NodeIds of current top layer elements. -Top layer is rendered closest to the user within a viewport, therefore its elements always -appear on top of all other content.""" - return cast("GetTopLayerElementsReturns", await self._client.send_raw( - method="DOM.getTopLayerElements", - params=params, - session_id=session_id, - )) + Top layer is rendered closest to the user within a viewport, therefore its elements always + appear on top of all other content.""" + return cast( + "GetTopLayerElementsReturns", + await self._client.send_raw( + method="DOM.getTopLayerElements", + params=params, + session_id=session_id, + ), + ) async def getElementByRelation( self, @@ -461,11 +549,14 @@ async def getElementByRelation( session_id: Optional[str] = None, ) -> "GetElementByRelationReturns": """Returns the NodeId of the matched element according to certain relations.""" - return cast("GetElementByRelationReturns", await self._client.send_raw( - method="DOM.getElementByRelation", - params=params, - session_id=session_id, - )) + return cast( + "GetElementByRelationReturns", + await self._client.send_raw( + method="DOM.getElementByRelation", + params=params, + session_id=session_id, + ), + ) async def redo( self, @@ -473,11 +564,14 @@ async def redo( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Re-does the last undone action.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.redo", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.redo", + params=params, + session_id=session_id, + ), + ) async def removeAttribute( self, @@ -485,11 +579,14 @@ async def removeAttribute( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes attribute with given name from an element with given id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.removeAttribute", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.removeAttribute", + params=params, + session_id=session_id, + ), + ) async def removeNode( self, @@ -497,11 +594,14 @@ async def removeNode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes node with given id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.removeNode", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.removeNode", + params=params, + session_id=session_id, + ), + ) async def requestChildNodes( self, @@ -509,13 +609,16 @@ async def requestChildNodes( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that children of the node with given id are returned to the caller in form of -`setChildNodes` events where not only immediate children are retrieved, but all children down to -the specified depth.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.requestChildNodes", - params=params, - session_id=session_id, - )) + `setChildNodes` events where not only immediate children are retrieved, but all children down to + the specified depth.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.requestChildNodes", + params=params, + session_id=session_id, + ), + ) async def requestNode( self, @@ -523,13 +626,16 @@ async def requestNode( session_id: Optional[str] = None, ) -> "RequestNodeReturns": """Requests that the node is sent to the caller given the JavaScript node object reference. All -nodes that form the path from the node to the root are also sent to the client as a series of -`setChildNodes` notifications.""" - return cast("RequestNodeReturns", await self._client.send_raw( - method="DOM.requestNode", - params=params, - session_id=session_id, - )) + nodes that form the path from the node to the root are also sent to the client as a series of + `setChildNodes` notifications.""" + return cast( + "RequestNodeReturns", + await self._client.send_raw( + method="DOM.requestNode", + params=params, + session_id=session_id, + ), + ) async def resolveNode( self, @@ -537,11 +643,14 @@ async def resolveNode( session_id: Optional[str] = None, ) -> "ResolveNodeReturns": """Resolves the JavaScript node object for a given NodeId or BackendNodeId.""" - return cast("ResolveNodeReturns", await self._client.send_raw( - method="DOM.resolveNode", - params=params, - session_id=session_id, - )) + return cast( + "ResolveNodeReturns", + await self._client.send_raw( + method="DOM.resolveNode", + params=params, + session_id=session_id, + ), + ) async def setAttributeValue( self, @@ -549,11 +658,14 @@ async def setAttributeValue( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets attribute for an element with given id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setAttributeValue", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setAttributeValue", + params=params, + session_id=session_id, + ), + ) async def setAttributesAsText( self, @@ -561,12 +673,15 @@ async def setAttributesAsText( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets attributes on element with given id. This method is useful when user edits some existing -attribute value and types in several attribute name/value pairs.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setAttributesAsText", - params=params, - session_id=session_id, - )) + attribute value and types in several attribute name/value pairs.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setAttributesAsText", + params=params, + session_id=session_id, + ), + ) async def setFileInputFiles( self, @@ -574,11 +689,14 @@ async def setFileInputFiles( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets files for the given file input element.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setFileInputFiles", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setFileInputFiles", + params=params, + session_id=session_id, + ), + ) async def setNodeStackTracesEnabled( self, @@ -586,11 +704,14 @@ async def setNodeStackTracesEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets if stack traces should be captured for Nodes. See `Node.getNodeStackTraces`. Default is disabled.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setNodeStackTracesEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setNodeStackTracesEnabled", + params=params, + session_id=session_id, + ), + ) async def getNodeStackTraces( self, @@ -598,11 +719,14 @@ async def getNodeStackTraces( session_id: Optional[str] = None, ) -> "GetNodeStackTracesReturns": """Gets stack traces associated with a Node. As of now, only provides stack trace for Node creation.""" - return cast("GetNodeStackTracesReturns", await self._client.send_raw( - method="DOM.getNodeStackTraces", - params=params, - session_id=session_id, - )) + return cast( + "GetNodeStackTracesReturns", + await self._client.send_raw( + method="DOM.getNodeStackTraces", + params=params, + session_id=session_id, + ), + ) async def getFileInfo( self, @@ -610,12 +734,15 @@ async def getFileInfo( session_id: Optional[str] = None, ) -> "GetFileInfoReturns": """Returns file information for the given -File wrapper.""" - return cast("GetFileInfoReturns", await self._client.send_raw( - method="DOM.getFileInfo", - params=params, - session_id=session_id, - )) + File wrapper.""" + return cast( + "GetFileInfoReturns", + await self._client.send_raw( + method="DOM.getFileInfo", + params=params, + session_id=session_id, + ), + ) async def getDetachedDomNodes( self, @@ -623,11 +750,14 @@ async def getDetachedDomNodes( session_id: Optional[str] = None, ) -> "GetDetachedDomNodesReturns": """Returns list of detached nodes""" - return cast("GetDetachedDomNodesReturns", await self._client.send_raw( - method="DOM.getDetachedDomNodes", - params=params, - session_id=session_id, - )) + return cast( + "GetDetachedDomNodesReturns", + await self._client.send_raw( + method="DOM.getDetachedDomNodes", + params=params, + session_id=session_id, + ), + ) async def setInspectedNode( self, @@ -635,12 +765,15 @@ async def setInspectedNode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables console to refer to the node with given id via $x (see Command Line API for more details -$x functions).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setInspectedNode", - params=params, - session_id=session_id, - )) + $x functions).""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setInspectedNode", + params=params, + session_id=session_id, + ), + ) async def setNodeName( self, @@ -648,11 +781,14 @@ async def setNodeName( session_id: Optional[str] = None, ) -> "SetNodeNameReturns": """Sets node name for a node with given id.""" - return cast("SetNodeNameReturns", await self._client.send_raw( - method="DOM.setNodeName", - params=params, - session_id=session_id, - )) + return cast( + "SetNodeNameReturns", + await self._client.send_raw( + method="DOM.setNodeName", + params=params, + session_id=session_id, + ), + ) async def setNodeValue( self, @@ -660,11 +796,14 @@ async def setNodeValue( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets node value for a node with given id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setNodeValue", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setNodeValue", + params=params, + session_id=session_id, + ), + ) async def setOuterHTML( self, @@ -672,11 +811,14 @@ async def setOuterHTML( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets node HTML markup, returns new node id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.setOuterHTML", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.setOuterHTML", + params=params, + session_id=session_id, + ), + ) async def undo( self, @@ -684,11 +826,14 @@ async def undo( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Undoes the last performed action.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOM.undo", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOM.undo", + params=params, + session_id=session_id, + ), + ) async def getFrameOwner( self, @@ -696,11 +841,14 @@ async def getFrameOwner( session_id: Optional[str] = None, ) -> "GetFrameOwnerReturns": """Returns iframe node that owns iframe with the given domain.""" - return cast("GetFrameOwnerReturns", await self._client.send_raw( - method="DOM.getFrameOwner", - params=params, - session_id=session_id, - )) + return cast( + "GetFrameOwnerReturns", + await self._client.send_raw( + method="DOM.getFrameOwner", + params=params, + session_id=session_id, + ), + ) async def getContainerForNode( self, @@ -708,15 +856,18 @@ async def getContainerForNode( session_id: Optional[str] = None, ) -> "GetContainerForNodeReturns": """Returns the query container of the given node based on container query -conditions: containerName, physical and logical axes, and whether it queries -scroll-state or anchored elements. If no axes are provided and -queriesScrollState is false, the style container is returned, which is the -direct parent or the closest element with a matching container-name.""" - return cast("GetContainerForNodeReturns", await self._client.send_raw( - method="DOM.getContainerForNode", - params=params, - session_id=session_id, - )) + conditions: containerName, physical and logical axes, and whether it queries + scroll-state or anchored elements. If no axes are provided and + queriesScrollState is false, the style container is returned, which is the + direct parent or the closest element with a matching container-name.""" + return cast( + "GetContainerForNodeReturns", + await self._client.send_raw( + method="DOM.getContainerForNode", + params=params, + session_id=session_id, + ), + ) async def getQueryingDescendantsForContainer( self, @@ -724,12 +875,15 @@ async def getQueryingDescendantsForContainer( session_id: Optional[str] = None, ) -> "GetQueryingDescendantsForContainerReturns": """Returns the descendants of a container query container that have -container queries against this container.""" - return cast("GetQueryingDescendantsForContainerReturns", await self._client.send_raw( - method="DOM.getQueryingDescendantsForContainer", - params=params, - session_id=session_id, - )) + container queries against this container.""" + return cast( + "GetQueryingDescendantsForContainerReturns", + await self._client.send_raw( + method="DOM.getQueryingDescendantsForContainer", + params=params, + session_id=session_id, + ), + ) async def getAnchorElement( self, @@ -737,12 +891,15 @@ async def getAnchorElement( session_id: Optional[str] = None, ) -> "GetAnchorElementReturns": """Returns the target anchor element of the given anchor query according to -https://www.w3.org/TR/css-anchor-position-1/#target.""" - return cast("GetAnchorElementReturns", await self._client.send_raw( - method="DOM.getAnchorElement", - params=params, - session_id=session_id, - )) + https://www.w3.org/TR/css-anchor-position-1/#target.""" + return cast( + "GetAnchorElementReturns", + await self._client.send_raw( + method="DOM.getAnchorElement", + params=params, + session_id=session_id, + ), + ) async def forceShowPopover( self, @@ -750,11 +907,12 @@ async def forceShowPopover( session_id: Optional[str] = None, ) -> "ForceShowPopoverReturns": """When enabling, this API force-opens the popover identified by nodeId -and keeps it open until disabled.""" - return cast("ForceShowPopoverReturns", await self._client.send_raw( - method="DOM.forceShowPopover", - params=params, - session_id=session_id, - )) - - + and keeps it open until disabled.""" + return cast( + "ForceShowPopoverReturns", + await self._client.send_raw( + method="DOM.forceShowPopover", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/dom/registration.py b/cdp_use/cdp/dom/registration.py index d91ce2c..434f1c4 100644 --- a/cdp_use/cdp/dom/registration.py +++ b/cdp_use/cdp/dom/registration.py @@ -11,40 +11,42 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - AttributeModifiedEvent, - AttributeRemovedEvent, - CharacterDataModifiedEvent, - ChildNodeCountUpdatedEvent, - ChildNodeInsertedEvent, - ChildNodeRemovedEvent, - DistributedNodesUpdatedEvent, - DocumentUpdatedEvent, - InlineStyleInvalidatedEvent, - PseudoElementAddedEvent, - PseudoElementRemovedEvent, - ScrollableFlagUpdatedEvent, - SetChildNodesEvent, - ShadowRootPoppedEvent, - ShadowRootPushedEvent, - TopLayerElementsUpdatedEvent -) + AffectedByStartingStylesFlagUpdatedEvent, + AttributeModifiedEvent, + AttributeRemovedEvent, + CharacterDataModifiedEvent, + ChildNodeCountUpdatedEvent, + ChildNodeInsertedEvent, + ChildNodeRemovedEvent, + DistributedNodesUpdatedEvent, + DocumentUpdatedEvent, + InlineStyleInvalidatedEvent, + PseudoElementAddedEvent, + PseudoElementRemovedEvent, + ScrollableFlagUpdatedEvent, + SetChildNodesEvent, + ShadowRootPoppedEvent, + ShadowRootPushedEvent, + TopLayerElementsUpdatedEvent, + ) + class DOMRegistration: """Event registration interface for DOM domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "DOM" def attributeModified( self, - callback: Callable[['AttributeModifiedEvent', Optional[str]], None], + callback: Callable[["AttributeModifiedEvent", Optional[str]], None], ) -> None: """ Register a callback for attributeModified events. - + Fired when `Element`'s attribute is modified. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -53,13 +55,13 @@ def attributeModified( def attributeRemoved( self, - callback: Callable[['AttributeRemovedEvent', Optional[str]], None], + callback: Callable[["AttributeRemovedEvent", Optional[str]], None], ) -> None: """ Register a callback for attributeRemoved events. - + Fired when `Element`'s attribute is removed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -68,13 +70,13 @@ def attributeRemoved( def characterDataModified( self, - callback: Callable[['CharacterDataModifiedEvent', Optional[str]], None], + callback: Callable[["CharacterDataModifiedEvent", Optional[str]], None], ) -> None: """ Register a callback for characterDataModified events. - + Mirrors `DOMCharacterDataModified` event. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -83,13 +85,13 @@ def characterDataModified( def childNodeCountUpdated( self, - callback: Callable[['ChildNodeCountUpdatedEvent', Optional[str]], None], + callback: Callable[["ChildNodeCountUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for childNodeCountUpdated events. - + Fired when `Container`'s child node count has changed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -98,13 +100,13 @@ def childNodeCountUpdated( def childNodeInserted( self, - callback: Callable[['ChildNodeInsertedEvent', Optional[str]], None], + callback: Callable[["ChildNodeInsertedEvent", Optional[str]], None], ) -> None: """ Register a callback for childNodeInserted events. - + Mirrors `DOMNodeInserted` event. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -113,13 +115,13 @@ def childNodeInserted( def childNodeRemoved( self, - callback: Callable[['ChildNodeRemovedEvent', Optional[str]], None], + callback: Callable[["ChildNodeRemovedEvent", Optional[str]], None], ) -> None: """ Register a callback for childNodeRemoved events. - + Mirrors `DOMNodeRemoved` event. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -128,13 +130,13 @@ def childNodeRemoved( def distributedNodesUpdated( self, - callback: Callable[['DistributedNodesUpdatedEvent', Optional[str]], None], + callback: Callable[["DistributedNodesUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for distributedNodesUpdated events. - + Called when distribution is changed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -143,13 +145,13 @@ def distributedNodesUpdated( def documentUpdated( self, - callback: Callable[['DocumentUpdatedEvent', Optional[str]], None], + callback: Callable[["DocumentUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for documentUpdated events. - + Fired when `Document` has been totally updated. Node ids are no longer valid. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -158,13 +160,13 @@ def documentUpdated( def inlineStyleInvalidated( self, - callback: Callable[['InlineStyleInvalidatedEvent', Optional[str]], None], + callback: Callable[["InlineStyleInvalidatedEvent", Optional[str]], None], ) -> None: """ Register a callback for inlineStyleInvalidated events. - + Fired when `Element`'s inline style is modified via a CSS property modification. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -173,13 +175,13 @@ def inlineStyleInvalidated( def pseudoElementAdded( self, - callback: Callable[['PseudoElementAddedEvent', Optional[str]], None], + callback: Callable[["PseudoElementAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for pseudoElementAdded events. - + Called when a pseudo element is added to an element. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -188,13 +190,13 @@ def pseudoElementAdded( def topLayerElementsUpdated( self, - callback: Callable[['TopLayerElementsUpdatedEvent', Optional[str]], None], + callback: Callable[["TopLayerElementsUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for topLayerElementsUpdated events. - + Called when top layer elements are changed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -203,28 +205,45 @@ def topLayerElementsUpdated( def scrollableFlagUpdated( self, - callback: Callable[['ScrollableFlagUpdatedEvent', Optional[str]], None], + callback: Callable[["ScrollableFlagUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for scrollableFlagUpdated events. - + Fired when a node's scrollability state changes. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("DOM.scrollableFlagUpdated", callback) + def affectedByStartingStylesFlagUpdated( + self, + callback: Callable[ + ["AffectedByStartingStylesFlagUpdatedEvent", Optional[str]], None + ], + ) -> None: + """ + Register a callback for affectedByStartingStylesFlagUpdated events. + + Fired when a node's starting styles changes. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("DOM.affectedByStartingStylesFlagUpdated", callback) + def pseudoElementRemoved( self, - callback: Callable[['PseudoElementRemovedEvent', Optional[str]], None], + callback: Callable[["PseudoElementRemovedEvent", Optional[str]], None], ) -> None: """ Register a callback for pseudoElementRemoved events. - + Called when a pseudo element is removed from an element. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -233,29 +252,29 @@ def pseudoElementRemoved( def setChildNodes( self, - callback: Callable[['SetChildNodesEvent', Optional[str]], None], + callback: Callable[["SetChildNodesEvent", Optional[str]], None], ) -> None: """ - Register a callback for setChildNodes events. - - Fired when backend wants to provide client with the missing DOM structure. This happens upon -most of the calls requesting node ids. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for setChildNodes events. + + Fired when backend wants to provide client with the missing DOM structure. This happens upon + most of the calls requesting node ids. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("DOM.setChildNodes", callback) def shadowRootPopped( self, - callback: Callable[['ShadowRootPoppedEvent', Optional[str]], None], + callback: Callable[["ShadowRootPoppedEvent", Optional[str]], None], ) -> None: """ Register a callback for shadowRootPopped events. - + Called when shadow root is popped from the element. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -264,16 +283,15 @@ def shadowRootPopped( def shadowRootPushed( self, - callback: Callable[['ShadowRootPushedEvent', Optional[str]], None], + callback: Callable[["ShadowRootPushedEvent", Optional[str]], None], ) -> None: """ Register a callback for shadowRootPushed events. - + Called when shadow root is pushed into the element. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("DOM.shadowRootPushed", callback) - diff --git a/cdp_use/cdp/dom/types.py b/cdp_use/cdp/dom/types.py index 89c6530..2bfb8b9 100644 --- a/cdp_use/cdp/dom/types.py +++ b/cdp_use/cdp/dom/types.py @@ -17,13 +17,11 @@ """Unique DOM node identifier.""" - BackendNodeId = int """Unique DOM node identifier used to reference a node that may not have been pushed to the front-end.""" - class BackendNode(TypedDict): """Backend node with a friendly name.""" @@ -34,40 +32,75 @@ class BackendNode(TypedDict): backendNodeId: "BackendNodeId" - -PseudoType = Literal["first-line", "first-letter", "checkmark", "before", "after", "picker-icon", "interest-hint", "marker", "backdrop", "column", "selection", "search-text", "target-text", "spelling-error", "grammar-error", "highlight", "first-line-inherited", "scroll-marker", "scroll-marker-group", "scroll-button", "scrollbar", "scrollbar-thumb", "scrollbar-button", "scrollbar-track", "scrollbar-track-piece", "scrollbar-corner", "resizer", "input-list-button", "view-transition", "view-transition-group", "view-transition-image-pair", "view-transition-group-children", "view-transition-old", "view-transition-new", "placeholder", "file-selector-button", "details-content", "picker", "permission-icon"] +PseudoType = Literal[ + "first-line", + "first-letter", + "checkmark", + "before", + "after", + "picker-icon", + "interest-hint", + "marker", + "backdrop", + "column", + "selection", + "search-text", + "target-text", + "spelling-error", + "grammar-error", + "highlight", + "first-line-inherited", + "scroll-marker", + "scroll-marker-group", + "scroll-button", + "scrollbar", + "scrollbar-thumb", + "scrollbar-button", + "scrollbar-track", + "scrollbar-track-piece", + "scrollbar-corner", + "resizer", + "input-list-button", + "view-transition", + "view-transition-group", + "view-transition-image-pair", + "view-transition-group-children", + "view-transition-old", + "view-transition-new", + "placeholder", + "file-selector-button", + "details-content", + "picker", + "permission-icon", + "overscroll-area-parent", + "overscroll-client-area", +] """Pseudo element type.""" - ShadowRootType = Literal["user-agent", "open", "closed"] """Shadow root type.""" - CompatibilityMode = Literal["QuirksMode", "LimitedQuirksMode", "NoQuirksMode"] """Document compatibility mode.""" - PhysicalAxes = Literal["Horizontal", "Vertical", "Both"] """ContainerSelector physical axes""" - LogicalAxes = Literal["Inline", "Block", "Both"] """ContainerSelector logical axes""" - ScrollOrientation = Literal["horizontal", "vertical"] """Physical scroll orientation""" - class Node(TypedDict): """DOM interaction is implemented in terms of mirror objects that represent the actual DOM nodes. -DOMNode is a base node mirror type.""" + DOMNode is a base node mirror type.""" nodeId: "NodeId" """Node identifier that is passed into the rest of the DOM messages as the `nodeId`. Backend @@ -135,7 +168,7 @@ class Node(TypedDict): compatibilityMode: "NotRequired[CompatibilityMode]" assignedSlot: "NotRequired[BackendNode]" isScrollable: "NotRequired[bool]" - + affectedByStartingStyles: "NotRequired[bool]" class DetachedElementInfo(TypedDict): @@ -145,7 +178,6 @@ class DetachedElementInfo(TypedDict): retainedNodeIds: "List[NodeId]" - class RGBA(TypedDict): """A structure holding an RGBA color.""" @@ -159,12 +191,10 @@ class RGBA(TypedDict): """The alpha component, in the [0-1] range (default: 1).""" - Quad = List[float] """An array of quad vertices, x immediately followed by y for each point, points clock-wise.""" - class BoxModel(TypedDict): """Box model.""" @@ -184,7 +214,6 @@ class BoxModel(TypedDict): """Shape outside coordinates""" - class ShapeOutsideInfo(TypedDict): """CSS Shape Outside details.""" @@ -196,7 +225,6 @@ class ShapeOutsideInfo(TypedDict): """Margin shape bounds""" - class Rect(TypedDict): """Rectangle.""" @@ -210,7 +238,6 @@ class Rect(TypedDict): """Rectangle height""" - class CSSComputedStyleProperty(TypedDict): name: "str" """Computed style property name.""" diff --git a/cdp_use/cdp/domdebugger/commands.py b/cdp_use/cdp/domdebugger/commands.py index e580988..2ed7666 100644 --- a/cdp_use/cdp/domdebugger/commands.py +++ b/cdp_use/cdp/domdebugger/commands.py @@ -16,6 +16,7 @@ from .types import DOMBreakpointType from .types import EventListener + class GetEventListenersParameters(TypedDict): objectId: "RemoteObjectId" """Identifier of the object to return listeners for.""" @@ -32,7 +33,6 @@ class GetEventListenersReturns(TypedDict): """Array of relevant listeners.""" - class RemoveDOMBreakpointParameters(TypedDict): nodeId: "NodeId" """Identifier of the node to remove breakpoint from.""" @@ -40,9 +40,6 @@ class RemoveDOMBreakpointParameters(TypedDict): """Type of the breakpoint to remove.""" - - - class RemoveEventListenerBreakpointParameters(TypedDict): eventName: "str" """Event name.""" @@ -50,33 +47,21 @@ class RemoveEventListenerBreakpointParameters(TypedDict): """EventTarget interface name.""" - - - class RemoveInstrumentationBreakpointParameters(TypedDict): eventName: "str" """Instrumentation name to stop on.""" - - - class RemoveXHRBreakpointParameters(TypedDict): url: "str" """Resource URL substring.""" - - - class SetBreakOnCSPViolationParameters(TypedDict): violationTypes: "List[CSPViolationType]" """CSP Violations to stop upon.""" - - - class SetDOMBreakpointParameters(TypedDict): nodeId: "NodeId" """Identifier of the node to set breakpoint on.""" @@ -84,9 +69,6 @@ class SetDOMBreakpointParameters(TypedDict): """Type of the operation to stop upon.""" - - - class SetEventListenerBreakpointParameters(TypedDict): eventName: "str" """DOM Event name to stop on (any DOM event will do).""" @@ -95,19 +77,11 @@ class SetEventListenerBreakpointParameters(TypedDict): EventTarget.""" - - - class SetInstrumentationBreakpointParameters(TypedDict): eventName: "str" """Instrumentation name to stop on.""" - - - class SetXHRBreakpointParameters(TypedDict): url: "str" """Resource URL substring. All XHRs having this substring in the URL will get stopped upon.""" - - diff --git a/cdp_use/cdp/domdebugger/events.py b/cdp_use/cdp/domdebugger/events.py index 57ec0d9..a5f93d8 100644 --- a/cdp_use/cdp/domdebugger/events.py +++ b/cdp_use/cdp/domdebugger/events.py @@ -5,4 +5,4 @@ """CDP DOMDebugger Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/domdebugger/library.py b/cdp_use/cdp/domdebugger/library.py index bd57287..ea008f3 100644 --- a/cdp_use/cdp/domdebugger/library.py +++ b/cdp_use/cdp/domdebugger/library.py @@ -22,10 +22,11 @@ from .commands import SetInstrumentationBreakpointParameters from .commands import SetXHRBreakpointParameters + class DOMDebuggerClient: """Client for DOMDebugger domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getEventListeners( @@ -34,11 +35,14 @@ async def getEventListeners( session_id: Optional[str] = None, ) -> "GetEventListenersReturns": """Returns event listeners of the given object.""" - return cast("GetEventListenersReturns", await self._client.send_raw( - method="DOMDebugger.getEventListeners", - params=params, - session_id=session_id, - )) + return cast( + "GetEventListenersReturns", + await self._client.send_raw( + method="DOMDebugger.getEventListeners", + params=params, + session_id=session_id, + ), + ) async def removeDOMBreakpoint( self, @@ -46,11 +50,14 @@ async def removeDOMBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes DOM breakpoint that was set using `setDOMBreakpoint`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.removeDOMBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.removeDOMBreakpoint", + params=params, + session_id=session_id, + ), + ) async def removeEventListenerBreakpoint( self, @@ -58,11 +65,14 @@ async def removeEventListenerBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes breakpoint on particular DOM event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.removeEventListenerBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.removeEventListenerBreakpoint", + params=params, + session_id=session_id, + ), + ) async def removeInstrumentationBreakpoint( self, @@ -70,11 +80,14 @@ async def removeInstrumentationBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes breakpoint on particular native event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.removeInstrumentationBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.removeInstrumentationBreakpoint", + params=params, + session_id=session_id, + ), + ) async def removeXHRBreakpoint( self, @@ -82,11 +95,14 @@ async def removeXHRBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes breakpoint from XMLHttpRequest.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.removeXHRBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.removeXHRBreakpoint", + params=params, + session_id=session_id, + ), + ) async def setBreakOnCSPViolation( self, @@ -94,11 +110,14 @@ async def setBreakOnCSPViolation( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets breakpoint on particular CSP violations.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.setBreakOnCSPViolation", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.setBreakOnCSPViolation", + params=params, + session_id=session_id, + ), + ) async def setDOMBreakpoint( self, @@ -106,11 +125,14 @@ async def setDOMBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets breakpoint on particular operation with DOM.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.setDOMBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.setDOMBreakpoint", + params=params, + session_id=session_id, + ), + ) async def setEventListenerBreakpoint( self, @@ -118,11 +140,14 @@ async def setEventListenerBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets breakpoint on particular DOM event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.setEventListenerBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.setEventListenerBreakpoint", + params=params, + session_id=session_id, + ), + ) async def setInstrumentationBreakpoint( self, @@ -130,11 +155,14 @@ async def setInstrumentationBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets breakpoint on particular native event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.setInstrumentationBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.setInstrumentationBreakpoint", + params=params, + session_id=session_id, + ), + ) async def setXHRBreakpoint( self, @@ -142,10 +170,11 @@ async def setXHRBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets breakpoint on XMLHttpRequest.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMDebugger.setXHRBreakpoint", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMDebugger.setXHRBreakpoint", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/domdebugger/registration.py b/cdp_use/cdp/domdebugger/registration.py index 2969461..62d3615 100644 --- a/cdp_use/cdp/domdebugger/registration.py +++ b/cdp_use/cdp/domdebugger/registration.py @@ -5,4 +5,4 @@ """CDP DOMDebugger Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/domdebugger/types.py b/cdp_use/cdp/domdebugger/types.py index 071bfd0..6fb989d 100644 --- a/cdp_use/cdp/domdebugger/types.py +++ b/cdp_use/cdp/domdebugger/types.py @@ -18,12 +18,10 @@ """DOM breakpoint type.""" - CSPViolationType = Literal["trustedtype-sink-violation", "trustedtype-policy-violation"] """CSP Violation type.""" - class EventListener(TypedDict): """Object event listener.""" diff --git a/cdp_use/cdp/domsnapshot/commands.py b/cdp_use/cdp/domsnapshot/commands.py index f861b34..77506fb 100644 --- a/cdp_use/cdp/domsnapshot/commands.py +++ b/cdp_use/cdp/domsnapshot/commands.py @@ -15,6 +15,7 @@ from .types import DocumentSnapshot from .types import LayoutTreeNode + class GetSnapshotParameters(TypedDict): computedStyleWhitelist: "List[str]" """Whitelist of computed styles to return.""" @@ -35,7 +36,6 @@ class GetSnapshotReturns(TypedDict): """Whitelisted ComputedStyle properties for each node in the layout tree.""" - class CaptureSnapshotParameters(TypedDict): computedStyles: "List[str]" """Whitelist of computed styles to return.""" diff --git a/cdp_use/cdp/domsnapshot/events.py b/cdp_use/cdp/domsnapshot/events.py index b26db9e..716618a 100644 --- a/cdp_use/cdp/domsnapshot/events.py +++ b/cdp_use/cdp/domsnapshot/events.py @@ -5,4 +5,4 @@ """CDP DOMSnapshot Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/domsnapshot/library.py b/cdp_use/cdp/domsnapshot/library.py index f24bb76..1ed61e4 100644 --- a/cdp_use/cdp/domsnapshot/library.py +++ b/cdp_use/cdp/domsnapshot/library.py @@ -15,10 +15,11 @@ from .commands import GetSnapshotParameters from .commands import GetSnapshotReturns + class DOMSnapshotClient: """Client for DOMSnapshot domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -27,11 +28,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables DOM snapshot agent for the given page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMSnapshot.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMSnapshot.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -39,11 +43,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables DOM snapshot agent for the given page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMSnapshot.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMSnapshot.enable", + params=params, + session_id=session_id, + ), + ) async def getSnapshot( self, @@ -51,14 +58,17 @@ async def getSnapshot( session_id: Optional[str] = None, ) -> "GetSnapshotReturns": """Returns a document snapshot, including the full DOM tree of the root node (including iframes, -template contents, and imported documents) in a flattened array, as well as layout and -white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is -flattened.""" - return cast("GetSnapshotReturns", await self._client.send_raw( - method="DOMSnapshot.getSnapshot", - params=params, - session_id=session_id, - )) + template contents, and imported documents) in a flattened array, as well as layout and + white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is + flattened.""" + return cast( + "GetSnapshotReturns", + await self._client.send_raw( + method="DOMSnapshot.getSnapshot", + params=params, + session_id=session_id, + ), + ) async def captureSnapshot( self, @@ -66,13 +76,14 @@ async def captureSnapshot( session_id: Optional[str] = None, ) -> "CaptureSnapshotReturns": """Returns a document snapshot, including the full DOM tree of the root node (including iframes, -template contents, and imported documents) in a flattened array, as well as layout and -white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is -flattened.""" - return cast("CaptureSnapshotReturns", await self._client.send_raw( - method="DOMSnapshot.captureSnapshot", - params=params, - session_id=session_id, - )) - - + template contents, and imported documents) in a flattened array, as well as layout and + white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is + flattened.""" + return cast( + "CaptureSnapshotReturns", + await self._client.send_raw( + method="DOMSnapshot.captureSnapshot", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/domsnapshot/registration.py b/cdp_use/cdp/domsnapshot/registration.py index b4f0f79..87219e8 100644 --- a/cdp_use/cdp/domsnapshot/registration.py +++ b/cdp_use/cdp/domsnapshot/registration.py @@ -5,4 +5,4 @@ """CDP DOMSnapshot Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/domsnapshot/types.py b/cdp_use/cdp/domsnapshot/types.py index a0b2297..560891a 100644 --- a/cdp_use/cdp/domsnapshot/types.py +++ b/cdp_use/cdp/domsnapshot/types.py @@ -17,6 +17,7 @@ from ..domdebugger.types import EventListener from ..page.types import FrameId + class DOMNode(TypedDict): """A Node in the DOM tree.""" @@ -83,10 +84,9 @@ class DOMNode(TypedDict): scrollOffsetY: "NotRequired[float]" - class InlineTextBox(TypedDict): """Details of post layout rendered text positions. The exact layout should not be regarded as -stable and may change between versions.""" + stable and may change between versions.""" boundingBox: "Rect" """The bounding box in document coordinates. Note that scroll offset of the document is ignored.""" @@ -98,7 +98,6 @@ class InlineTextBox(TypedDict): represented as a surrogate pair in UTF-16 have length 2.""" - class LayoutTreeNode(TypedDict): """Details of an element in the DOM tree with a LayoutObject.""" @@ -120,7 +119,6 @@ class LayoutTreeNode(TypedDict): """Set to true to indicate the element begins a new stacking context.""" - class ComputedStyle(TypedDict): """A subset of the full ComputedStyle as defined by the request whitelist.""" @@ -128,7 +126,6 @@ class ComputedStyle(TypedDict): """Name/value pairs of computed style properties.""" - class NameValue(TypedDict): """A name/value pair.""" @@ -138,17 +135,14 @@ class NameValue(TypedDict): """Attribute/property value.""" - StringIndex = int """Index of the string in the strings table.""" - ArrayOfStrings = List[StringIndex] """Index of the string in the strings table.""" - class RareStringData(TypedDict): """Data that is only present on rare nodes.""" @@ -156,22 +150,18 @@ class RareStringData(TypedDict): value: "List[StringIndex]" - class RareBooleanData(TypedDict): index: "List[int]" - class RareIntegerData(TypedDict): index: "List[int]" value: "List[int]" - Rectangle = List[float] - class DocumentSnapshot(TypedDict): """Document snapshot.""" @@ -207,7 +197,6 @@ class DocumentSnapshot(TypedDict): """Document content height.""" - class NodeTreeSnapshot(TypedDict, total=False): """Table containing nodes.""" @@ -250,7 +239,6 @@ class NodeTreeSnapshot(TypedDict, total=False): """The url of the script (if any) that generates this node.""" - class LayoutTreeSnapshot(TypedDict): """Table of details of an element in the DOM tree with a LayoutObject.""" @@ -280,10 +268,9 @@ class LayoutTreeSnapshot(TypedDict): """The list of computed text opacities.""" - class TextBoxSnapshot(TypedDict): """Table of details of the post layout rendered text positions. The exact layout should not be regarded as -stable and may change between versions.""" + stable and may change between versions.""" layoutIndex: "List[int]" """Index of the layout tree node that owns this box collection.""" diff --git a/cdp_use/cdp/domstorage/commands.py b/cdp_use/cdp/domstorage/commands.py index 603ce6c..aae2f2e 100644 --- a/cdp_use/cdp/domstorage/commands.py +++ b/cdp_use/cdp/domstorage/commands.py @@ -13,13 +13,11 @@ from .types import Item from .types import StorageId + class ClearParameters(TypedDict): storageId: "StorageId" - - - class GetDOMStorageItemsParameters(TypedDict): storageId: "StorageId" @@ -28,18 +26,12 @@ class GetDOMStorageItemsReturns(TypedDict): entries: "List[Item]" - class RemoveDOMStorageItemParameters(TypedDict): storageId: "StorageId" key: "str" - - - class SetDOMStorageItemParameters(TypedDict): storageId: "StorageId" key: "str" value: "str" - - diff --git a/cdp_use/cdp/domstorage/events.py b/cdp_use/cdp/domstorage/events.py index 52a6e1b..c97d161 100644 --- a/cdp_use/cdp/domstorage/events.py +++ b/cdp_use/cdp/domstorage/events.py @@ -11,19 +11,18 @@ if TYPE_CHECKING: from .types import StorageId + class DomStorageItemAddedEvent(TypedDict): storageId: "StorageId" key: "str" newValue: "str" - class DomStorageItemRemovedEvent(TypedDict): storageId: "StorageId" key: "str" - class DomStorageItemUpdatedEvent(TypedDict): storageId: "StorageId" key: "str" @@ -31,6 +30,5 @@ class DomStorageItemUpdatedEvent(TypedDict): newValue: "str" - class DomStorageItemsClearedEvent(TypedDict): storageId: "StorageId" diff --git a/cdp_use/cdp/domstorage/library.py b/cdp_use/cdp/domstorage/library.py index badbf7c..895963c 100644 --- a/cdp_use/cdp/domstorage/library.py +++ b/cdp_use/cdp/domstorage/library.py @@ -16,10 +16,11 @@ from .commands import RemoveDOMStorageItemParameters from .commands import SetDOMStorageItemParameters + class DOMStorageClient: """Client for DOMStorage domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def clear( @@ -27,11 +28,14 @@ async def clear( params: "ClearParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMStorage.clear", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMStorage.clear", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -39,11 +43,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables storage tracking, prevents storage events from being sent to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMStorage.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMStorage.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -51,43 +58,53 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables storage tracking, storage events will now be delivered to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMStorage.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMStorage.enable", + params=params, + session_id=session_id, + ), + ) async def getDOMStorageItems( self, params: "GetDOMStorageItemsParameters", session_id: Optional[str] = None, ) -> "GetDOMStorageItemsReturns": - return cast("GetDOMStorageItemsReturns", await self._client.send_raw( - method="DOMStorage.getDOMStorageItems", - params=params, - session_id=session_id, - )) + return cast( + "GetDOMStorageItemsReturns", + await self._client.send_raw( + method="DOMStorage.getDOMStorageItems", + params=params, + session_id=session_id, + ), + ) async def removeDOMStorageItem( self, params: "RemoveDOMStorageItemParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMStorage.removeDOMStorageItem", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMStorage.removeDOMStorageItem", + params=params, + session_id=session_id, + ), + ) async def setDOMStorageItem( self, params: "SetDOMStorageItemParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="DOMStorage.setDOMStorageItem", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="DOMStorage.setDOMStorageItem", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/domstorage/registration.py b/cdp_use/cdp/domstorage/registration.py index ed32722..47b200d 100644 --- a/cdp_use/cdp/domstorage/registration.py +++ b/cdp_use/cdp/domstorage/registration.py @@ -10,22 +10,28 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import DomStorageItemAddedEvent, DomStorageItemRemovedEvent, DomStorageItemUpdatedEvent, DomStorageItemsClearedEvent + from .events import ( + DomStorageItemAddedEvent, + DomStorageItemRemovedEvent, + DomStorageItemUpdatedEvent, + DomStorageItemsClearedEvent, + ) + class DOMStorageRegistration: """Event registration interface for DOMStorage domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "DOMStorage" def domStorageItemAdded( self, - callback: Callable[['DomStorageItemAddedEvent', Optional[str]], None], + callback: Callable[["DomStorageItemAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for domStorageItemAdded events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,11 +40,11 @@ def domStorageItemAdded( def domStorageItemRemoved( self, - callback: Callable[['DomStorageItemRemovedEvent', Optional[str]], None], + callback: Callable[["DomStorageItemRemovedEvent", Optional[str]], None], ) -> None: """ Register a callback for domStorageItemRemoved events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -47,11 +53,11 @@ def domStorageItemRemoved( def domStorageItemUpdated( self, - callback: Callable[['DomStorageItemUpdatedEvent', Optional[str]], None], + callback: Callable[["DomStorageItemUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for domStorageItemUpdated events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -60,14 +66,13 @@ def domStorageItemUpdated( def domStorageItemsCleared( self, - callback: Callable[['DomStorageItemsClearedEvent', Optional[str]], None], + callback: Callable[["DomStorageItemsClearedEvent", Optional[str]], None], ) -> None: """ Register a callback for domStorageItemsCleared events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("DOMStorage.domStorageItemsCleared", callback) - diff --git a/cdp_use/cdp/domstorage/types.py b/cdp_use/cdp/domstorage/types.py index 56aef04..3e87bd5 100644 --- a/cdp_use/cdp/domstorage/types.py +++ b/cdp_use/cdp/domstorage/types.py @@ -10,7 +10,6 @@ SerializedStorageKey = str - class StorageId(TypedDict): """DOM Storage identifier.""" @@ -22,6 +21,5 @@ class StorageId(TypedDict): """Whether the storage is local storage (not session storage).""" - Item = List[str] """DOM Storage item.""" diff --git a/cdp_use/cdp/emulation/commands.py b/cdp_use/cdp/emulation/commands.py index b4623d4..e482849 100644 --- a/cdp_use/cdp/emulation/commands.py +++ b/cdp_use/cdp/emulation/commands.py @@ -31,53 +31,38 @@ from .types import VirtualTimePolicy from .types import WorkAreaInsets + class CanEmulateReturns(TypedDict): result: "bool" """True if emulation is supported.""" - class SetFocusEmulationEnabledParameters(TypedDict): enabled: "bool" """Whether to enable to disable focus emulation.""" - - - class SetAutoDarkModeOverrideParameters(TypedDict, total=False): enabled: "bool" """Whether to enable or disable automatic dark mode. If not specified, any existing override will be cleared.""" - - - class SetCPUThrottlingRateParameters(TypedDict): rate: "float" """Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).""" - - - class SetDefaultBackgroundColorOverrideParameters(TypedDict, total=False): color: "RGBA" """RGBA of the default background color. If not specified, any existing override will be cleared.""" - - - class SetSafeAreaInsetsOverrideParameters(TypedDict): insets: "SafeAreaInsets" - - - class SetDeviceMetricsOverrideParameters(TypedDict): width: "int" """Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.""" @@ -115,39 +100,24 @@ class SetDeviceMetricsOverrideParameters(TypedDict): Deprecated, use Emulation.setDevicePostureOverride.""" - - - class SetDevicePostureOverrideParameters(TypedDict): posture: "DevicePosture" - - - class SetDisplayFeaturesOverrideParameters(TypedDict): features: "List[DisplayFeature]" - - - class SetScrollbarsHiddenParameters(TypedDict): hidden: "bool" """Whether scrollbars should be always hidden.""" - - - class SetDocumentCookieDisabledParameters(TypedDict): disabled: "bool" """Whether document.coookie API should be disabled.""" - - - class SetEmitTouchEventsForMouseParameters(TypedDict): enabled: "bool" """Whether touch emulation based on mouse input should be enabled.""" @@ -155,9 +125,6 @@ class SetEmitTouchEventsForMouseParameters(TypedDict): """Touch/gesture events configuration. Default: current platform.""" - - - class SetEmulatedMediaParameters(TypedDict, total=False): media: "str" """Media type to emulate. Empty string disables the override.""" @@ -165,25 +132,16 @@ class SetEmulatedMediaParameters(TypedDict, total=False): """Media features to emulate.""" - - - class SetEmulatedVisionDeficiencyParameters(TypedDict): type: "str" """Vision deficiency to emulate. Order: best-effort emulations come first, followed by any physiologically accurate emulations for medically recognized color vision deficiencies.""" - - - class SetEmulatedOSTextScaleParameters(TypedDict, total=False): scale: "float" - - - class SetGeolocationOverrideParameters(TypedDict, total=False): latitude: "float" """Mock latitude""" @@ -201,9 +159,6 @@ class SetGeolocationOverrideParameters(TypedDict, total=False): """Mock speed""" - - - class GetOverriddenSensorInformationParameters(TypedDict): type: "SensorType" @@ -212,50 +167,34 @@ class GetOverriddenSensorInformationReturns(TypedDict): requestedSamplingFrequency: "float" - class SetSensorOverrideEnabledParameters(TypedDict): enabled: "bool" type: "SensorType" metadata: "NotRequired[SensorMetadata]" - - - class SetSensorOverrideReadingsParameters(TypedDict): type: "SensorType" reading: "SensorReading" - - - class SetPressureSourceOverrideEnabledParameters(TypedDict): enabled: "bool" source: "PressureSource" metadata: "NotRequired[PressureMetadata]" - - - class SetPressureStateOverrideParameters(TypedDict): source: "PressureSource" state: "PressureState" - - - class SetPressureDataOverrideParameters(TypedDict): source: "PressureSource" state: "PressureState" ownContributionEstimate: "NotRequired[float]" - - - class SetIdleOverrideParameters(TypedDict): isUserActive: "bool" """Mock isUserActive""" @@ -263,33 +202,21 @@ class SetIdleOverrideParameters(TypedDict): """Mock isScreenUnlocked""" - - - class SetNavigatorOverridesParameters(TypedDict): platform: "str" """The platform navigator.platform should return.""" - - - class SetPageScaleFactorParameters(TypedDict): pageScaleFactor: "float" """Page scale factor.""" - - - class SetScriptExecutionDisabledParameters(TypedDict): value: "bool" """Whether script execution should be disabled in the page.""" - - - class SetTouchEmulationEnabledParameters(TypedDict): enabled: "bool" """Whether the touch event emulation should be enabled.""" @@ -297,9 +224,6 @@ class SetTouchEmulationEnabledParameters(TypedDict): """Maximum touch points supported. Defaults to one.""" - - - class SetVirtualTimePolicyParameters(TypedDict): policy: "VirtualTimePolicy" budget: "NotRequired[float]" @@ -317,16 +241,12 @@ class SetVirtualTimePolicyReturns(TypedDict): """Absolute timestamp at which virtual time was first enabled (up time in milliseconds).""" - class SetLocaleOverrideParameters(TypedDict, total=False): locale: "str" """ICU style C locale (e.g. \"en_US\"). If not specified or empty, disables the override and restores default host system locale.""" - - - class SetTimezoneOverrideParameters(TypedDict): timezoneId: "str" """The timezone identifier. List of supported timezones: @@ -334,9 +254,6 @@ class SetTimezoneOverrideParameters(TypedDict): If empty, disables the override and restores default host system timezone.""" - - - class SetVisibleSizeParameters(TypedDict): width: "int" """Frame width (DIP).""" @@ -344,33 +261,21 @@ class SetVisibleSizeParameters(TypedDict): """Frame height (DIP).""" - - - class SetDisabledImageTypesParameters(TypedDict): imageTypes: "List[DisabledImageType]" """Image types to disable.""" - - - class SetDataSaverOverrideParameters(TypedDict, total=False): dataSaverEnabled: "bool" """Override value. Omitting the parameter disables the override.""" - - - class SetHardwareConcurrencyOverrideParameters(TypedDict): hardwareConcurrency: "int" """Hardware concurrency to report""" - - - class SetUserAgentOverrideParameters(TypedDict): userAgent: "str" """User agent to use.""" @@ -382,31 +287,21 @@ class SetUserAgentOverrideParameters(TypedDict): """To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData""" - - - class SetAutomationOverrideParameters(TypedDict): enabled: "bool" """Whether the override should be enabled.""" - - - class SetSmallViewportHeightDifferenceOverrideParameters(TypedDict): difference: "int" """This will cause an element of size 100svh to be `difference` pixels smaller than an element of size 100lvh.""" - - - class GetScreenInfosReturns(TypedDict): screenInfos: "List[ScreenInfo]" - class AddScreenParameters(TypedDict): left: "int" """Offset of the left edge of the screen in pixels.""" @@ -434,8 +329,5 @@ class AddScreenReturns(TypedDict): screenInfo: "ScreenInfo" - class RemoveScreenParameters(TypedDict): screenId: "ScreenId" - - diff --git a/cdp_use/cdp/emulation/events.py b/cdp_use/cdp/emulation/events.py index d5b9185..df775e3 100644 --- a/cdp_use/cdp/emulation/events.py +++ b/cdp_use/cdp/emulation/events.py @@ -7,5 +7,7 @@ from typing_extensions import TypedDict """Notification sent after the virtual time budget for the current VirtualTimePolicy has run out.""" + + class VirtualTimeBudgetExpiredEvent(TypedDict): pass diff --git a/cdp_use/cdp/emulation/library.py b/cdp_use/cdp/emulation/library.py index 81f8ea0..5132b6a 100644 --- a/cdp_use/cdp/emulation/library.py +++ b/cdp_use/cdp/emulation/library.py @@ -54,10 +54,11 @@ from .commands import SetVirtualTimePolicyReturns from .commands import SetVisibleSizeParameters + class EmulationClient: """Client for Emulation domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def canEmulate( @@ -66,11 +67,14 @@ async def canEmulate( session_id: Optional[str] = None, ) -> "CanEmulateReturns": """Tells whether emulation is supported.""" - return cast("CanEmulateReturns", await self._client.send_raw( - method="Emulation.canEmulate", - params=params, - session_id=session_id, - )) + return cast( + "CanEmulateReturns", + await self._client.send_raw( + method="Emulation.canEmulate", + params=params, + session_id=session_id, + ), + ) async def clearDeviceMetricsOverride( self, @@ -78,11 +82,14 @@ async def clearDeviceMetricsOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the overridden device metrics.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.clearDeviceMetricsOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.clearDeviceMetricsOverride", + params=params, + session_id=session_id, + ), + ) async def clearGeolocationOverride( self, @@ -90,11 +97,14 @@ async def clearGeolocationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the overridden Geolocation Position and Error.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.clearGeolocationOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.clearGeolocationOverride", + params=params, + session_id=session_id, + ), + ) async def resetPageScaleFactor( self, @@ -102,11 +112,14 @@ async def resetPageScaleFactor( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that page scale factor is reset to initial values.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.resetPageScaleFactor", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.resetPageScaleFactor", + params=params, + session_id=session_id, + ), + ) async def setFocusEmulationEnabled( self, @@ -114,11 +127,14 @@ async def setFocusEmulationEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables or disables simulating a focused and active page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setFocusEmulationEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setFocusEmulationEnabled", + params=params, + session_id=session_id, + ), + ) async def setAutoDarkModeOverride( self, @@ -126,11 +142,14 @@ async def setAutoDarkModeOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Automatically render all web contents using a dark theme.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setAutoDarkModeOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setAutoDarkModeOverride", + params=params, + session_id=session_id, + ), + ) async def setCPUThrottlingRate( self, @@ -138,11 +157,14 @@ async def setCPUThrottlingRate( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables CPU throttling to emulate slow CPUs.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setCPUThrottlingRate", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setCPUThrottlingRate", + params=params, + session_id=session_id, + ), + ) async def setDefaultBackgroundColorOverride( self, @@ -150,12 +172,15 @@ async def setDefaultBackgroundColorOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets or clears an override of the default background color of the frame. This override is used -if the content does not specify one.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDefaultBackgroundColorOverride", - params=params, - session_id=session_id, - )) + if the content does not specify one.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDefaultBackgroundColorOverride", + params=params, + session_id=session_id, + ), + ) async def setSafeAreaInsetsOverride( self, @@ -163,12 +188,15 @@ async def setSafeAreaInsetsOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the values for env(safe-area-inset-*) and env(safe-area-max-inset-*). Unset values will cause the -respective variables to be undefined, even if previously overridden.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setSafeAreaInsetsOverride", - params=params, - session_id=session_id, - )) + respective variables to be undefined, even if previously overridden.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setSafeAreaInsetsOverride", + params=params, + session_id=session_id, + ), + ) async def setDeviceMetricsOverride( self, @@ -176,13 +204,16 @@ async def setDeviceMetricsOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the values of device screen dimensions (window.screen.width, window.screen.height, -window.innerWidth, window.innerHeight, and \"device-width\"/\"device-height\"-related CSS media -query results).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDeviceMetricsOverride", - params=params, - session_id=session_id, - )) + window.innerWidth, window.innerHeight, and \"device-width\"/\"device-height\"-related CSS media + query results).""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDeviceMetricsOverride", + params=params, + session_id=session_id, + ), + ) async def setDevicePostureOverride( self, @@ -190,12 +221,15 @@ async def setDevicePostureOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Start reporting the given posture value to the Device Posture API. -This override can also be set in setDeviceMetricsOverride().""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDevicePostureOverride", - params=params, - session_id=session_id, - )) + This override can also be set in setDeviceMetricsOverride().""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDevicePostureOverride", + params=params, + session_id=session_id, + ), + ) async def clearDevicePostureOverride( self, @@ -203,14 +237,17 @@ async def clearDevicePostureOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears a device posture override set with either setDeviceMetricsOverride() -or setDevicePostureOverride() and starts using posture information from the -platform again. -Does nothing if no override is set.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.clearDevicePostureOverride", - params=params, - session_id=session_id, - )) + or setDevicePostureOverride() and starts using posture information from the + platform again. + Does nothing if no override is set.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.clearDevicePostureOverride", + params=params, + session_id=session_id, + ), + ) async def setDisplayFeaturesOverride( self, @@ -218,12 +255,15 @@ async def setDisplayFeaturesOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Start using the given display features to pupulate the Viewport Segments API. -This override can also be set in setDeviceMetricsOverride().""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDisplayFeaturesOverride", - params=params, - session_id=session_id, - )) + This override can also be set in setDeviceMetricsOverride().""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDisplayFeaturesOverride", + params=params, + session_id=session_id, + ), + ) async def clearDisplayFeaturesOverride( self, @@ -231,47 +271,59 @@ async def clearDisplayFeaturesOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the display features override set with either setDeviceMetricsOverride() -or setDisplayFeaturesOverride() and starts using display features from the -platform again. -Does nothing if no override is set.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.clearDisplayFeaturesOverride", - params=params, - session_id=session_id, - )) + or setDisplayFeaturesOverride() and starts using display features from the + platform again. + Does nothing if no override is set.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.clearDisplayFeaturesOverride", + params=params, + session_id=session_id, + ), + ) async def setScrollbarsHidden( self, params: "SetScrollbarsHiddenParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setScrollbarsHidden", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setScrollbarsHidden", + params=params, + session_id=session_id, + ), + ) async def setDocumentCookieDisabled( self, params: "SetDocumentCookieDisabledParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDocumentCookieDisabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDocumentCookieDisabled", + params=params, + session_id=session_id, + ), + ) async def setEmitTouchEventsForMouse( self, params: "SetEmitTouchEventsForMouseParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setEmitTouchEventsForMouse", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setEmitTouchEventsForMouse", + params=params, + session_id=session_id, + ), + ) async def setEmulatedMedia( self, @@ -279,11 +331,14 @@ async def setEmulatedMedia( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Emulates the given media type or media feature for CSS media queries.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setEmulatedMedia", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setEmulatedMedia", + params=params, + session_id=session_id, + ), + ) async def setEmulatedVisionDeficiency( self, @@ -291,11 +346,14 @@ async def setEmulatedVisionDeficiency( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Emulates the given vision deficiency.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setEmulatedVisionDeficiency", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setEmulatedVisionDeficiency", + params=params, + session_id=session_id, + ), + ) async def setEmulatedOSTextScale( self, @@ -303,11 +361,14 @@ async def setEmulatedOSTextScale( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Emulates the given OS text scale.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setEmulatedOSTextScale", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setEmulatedOSTextScale", + params=params, + session_id=session_id, + ), + ) async def setGeolocationOverride( self, @@ -315,23 +376,29 @@ async def setGeolocationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the Geolocation Position or Error. Omitting latitude, longitude or -accuracy emulates position unavailable.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setGeolocationOverride", - params=params, - session_id=session_id, - )) + accuracy emulates position unavailable.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setGeolocationOverride", + params=params, + session_id=session_id, + ), + ) async def getOverriddenSensorInformation( self, params: "GetOverriddenSensorInformationParameters", session_id: Optional[str] = None, ) -> "GetOverriddenSensorInformationReturns": - return cast("GetOverriddenSensorInformationReturns", await self._client.send_raw( - method="Emulation.getOverriddenSensorInformation", - params=params, - session_id=session_id, - )) + return cast( + "GetOverriddenSensorInformationReturns", + await self._client.send_raw( + method="Emulation.getOverriddenSensorInformation", + params=params, + session_id=session_id, + ), + ) async def setSensorOverrideEnabled( self, @@ -339,15 +406,18 @@ async def setSensorOverrideEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides a platform sensor of a given type. If |enabled| is true, calls to -Sensor.start() will use a virtual sensor as backend rather than fetching -data from a real hardware sensor. Otherwise, existing virtual -sensor-backend Sensor objects will fire an error event and new calls to -Sensor.start() will attempt to use a real sensor instead.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setSensorOverrideEnabled", - params=params, - session_id=session_id, - )) + Sensor.start() will use a virtual sensor as backend rather than fetching + data from a real hardware sensor. Otherwise, existing virtual + sensor-backend Sensor objects will fire an error event and new calls to + Sensor.start() will attempt to use a real sensor instead.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setSensorOverrideEnabled", + params=params, + session_id=session_id, + ), + ) async def setSensorOverrideReadings( self, @@ -355,12 +425,15 @@ async def setSensorOverrideReadings( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Updates the sensor readings reported by a sensor type previously overridden -by setSensorOverrideEnabled.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setSensorOverrideReadings", - params=params, - session_id=session_id, - )) + by setSensorOverrideEnabled.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setSensorOverrideReadings", + params=params, + session_id=session_id, + ), + ) async def setPressureSourceOverrideEnabled( self, @@ -368,14 +441,17 @@ async def setPressureSourceOverrideEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides a pressure source of a given type, as used by the Compute -Pressure API, so that updates to PressureObserver.observe() are provided -via setPressureStateOverride instead of being retrieved from -platform-provided telemetry data.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setPressureSourceOverrideEnabled", - params=params, - session_id=session_id, - )) + Pressure API, so that updates to PressureObserver.observe() are provided + via setPressureStateOverride instead of being retrieved from + platform-provided telemetry data.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setPressureSourceOverrideEnabled", + params=params, + session_id=session_id, + ), + ) async def setPressureStateOverride( self, @@ -383,14 +459,17 @@ async def setPressureStateOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """TODO: OBSOLETE: To remove when setPressureDataOverride is merged. -Provides a given pressure state that will be processed and eventually be -delivered to PressureObserver users. |source| must have been previously -overridden by setPressureSourceOverrideEnabled.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setPressureStateOverride", - params=params, - session_id=session_id, - )) + Provides a given pressure state that will be processed and eventually be + delivered to PressureObserver users. |source| must have been previously + overridden by setPressureSourceOverrideEnabled.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setPressureStateOverride", + params=params, + session_id=session_id, + ), + ) async def setPressureDataOverride( self, @@ -398,13 +477,16 @@ async def setPressureDataOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Provides a given pressure data set that will be processed and eventually be -delivered to PressureObserver users. |source| must have been previously -overridden by setPressureSourceOverrideEnabled.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setPressureDataOverride", - params=params, - session_id=session_id, - )) + delivered to PressureObserver users. |source| must have been previously + overridden by setPressureSourceOverrideEnabled.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setPressureDataOverride", + params=params, + session_id=session_id, + ), + ) async def setIdleOverride( self, @@ -412,11 +494,14 @@ async def setIdleOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the Idle state.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setIdleOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setIdleOverride", + params=params, + session_id=session_id, + ), + ) async def clearIdleOverride( self, @@ -424,11 +509,14 @@ async def clearIdleOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears Idle state overrides.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.clearIdleOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.clearIdleOverride", + params=params, + session_id=session_id, + ), + ) async def setNavigatorOverrides( self, @@ -436,11 +524,14 @@ async def setNavigatorOverrides( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides value returned by the javascript navigator object.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setNavigatorOverrides", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setNavigatorOverrides", + params=params, + session_id=session_id, + ), + ) async def setPageScaleFactor( self, @@ -448,11 +539,14 @@ async def setPageScaleFactor( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets a specified page scale factor.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setPageScaleFactor", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setPageScaleFactor", + params=params, + session_id=session_id, + ), + ) async def setScriptExecutionDisabled( self, @@ -460,11 +554,14 @@ async def setScriptExecutionDisabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Switches script execution in the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setScriptExecutionDisabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setScriptExecutionDisabled", + params=params, + session_id=session_id, + ), + ) async def setTouchEmulationEnabled( self, @@ -472,11 +569,14 @@ async def setTouchEmulationEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables touch on platforms which do not support them.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setTouchEmulationEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setTouchEmulationEnabled", + params=params, + session_id=session_id, + ), + ) async def setVirtualTimePolicy( self, @@ -484,12 +584,15 @@ async def setVirtualTimePolicy( session_id: Optional[str] = None, ) -> "SetVirtualTimePolicyReturns": """Turns on virtual time for all frames (replacing real-time with a synthetic time source) and sets -the current virtual time policy. Note this supersedes any previous time budget.""" - return cast("SetVirtualTimePolicyReturns", await self._client.send_raw( - method="Emulation.setVirtualTimePolicy", - params=params, - session_id=session_id, - )) + the current virtual time policy. Note this supersedes any previous time budget.""" + return cast( + "SetVirtualTimePolicyReturns", + await self._client.send_raw( + method="Emulation.setVirtualTimePolicy", + params=params, + session_id=session_id, + ), + ) async def setLocaleOverride( self, @@ -497,11 +600,14 @@ async def setLocaleOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides default host system locale with the specified one.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setLocaleOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setLocaleOverride", + params=params, + session_id=session_id, + ), + ) async def setTimezoneOverride( self, @@ -509,11 +615,14 @@ async def setTimezoneOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides default host system timezone with the specified one.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setTimezoneOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setTimezoneOverride", + params=params, + session_id=session_id, + ), + ) async def setVisibleSize( self, @@ -521,24 +630,30 @@ async def setVisibleSize( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Resizes the frame/viewport of the page. Note that this does not affect the frame's container -(e.g. browser window). Can be used to produce screenshots of the specified size. Not supported -on Android.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setVisibleSize", - params=params, - session_id=session_id, - )) + (e.g. browser window). Can be used to produce screenshots of the specified size. Not supported + on Android.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setVisibleSize", + params=params, + session_id=session_id, + ), + ) async def setDisabledImageTypes( self, params: "SetDisabledImageTypesParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDisabledImageTypes", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDisabledImageTypes", + params=params, + session_id=session_id, + ), + ) async def setDataSaverOverride( self, @@ -546,22 +661,28 @@ async def setDataSaverOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Override the value of navigator.connection.saveData""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setDataSaverOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setDataSaverOverride", + params=params, + session_id=session_id, + ), + ) async def setHardwareConcurrencyOverride( self, params: "SetHardwareConcurrencyOverrideParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setHardwareConcurrencyOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setHardwareConcurrencyOverride", + params=params, + session_id=session_id, + ), + ) async def setUserAgentOverride( self, @@ -569,12 +690,15 @@ async def setUserAgentOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Allows overriding user agent with the given string. -`userAgentMetadata` must be set for Client Hint headers to be sent.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setUserAgentOverride", - params=params, - session_id=session_id, - )) + `userAgentMetadata` must be set for Client Hint headers to be sent.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setUserAgentOverride", + params=params, + session_id=session_id, + ), + ) async def setAutomationOverride( self, @@ -582,11 +706,14 @@ async def setAutomationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Allows overriding the automation flag.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setAutomationOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setAutomationOverride", + params=params, + session_id=session_id, + ), + ) async def setSmallViewportHeightDifferenceOverride( self, @@ -594,12 +721,15 @@ async def setSmallViewportHeightDifferenceOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Allows overriding the difference between the small and large viewport sizes, which determine the -value of the `svh` and `lvh` unit, respectively. Only supported for top-level frames.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.setSmallViewportHeightDifferenceOverride", - params=params, - session_id=session_id, - )) + value of the `svh` and `lvh` unit, respectively. Only supported for top-level frames.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.setSmallViewportHeightDifferenceOverride", + params=params, + session_id=session_id, + ), + ) async def getScreenInfos( self, @@ -607,11 +737,14 @@ async def getScreenInfos( session_id: Optional[str] = None, ) -> "GetScreenInfosReturns": """Returns device's screen configuration.""" - return cast("GetScreenInfosReturns", await self._client.send_raw( - method="Emulation.getScreenInfos", - params=params, - session_id=session_id, - )) + return cast( + "GetScreenInfosReturns", + await self._client.send_raw( + method="Emulation.getScreenInfos", + params=params, + session_id=session_id, + ), + ) async def addScreen( self, @@ -619,11 +752,14 @@ async def addScreen( session_id: Optional[str] = None, ) -> "AddScreenReturns": """Add a new screen to the device. Only supported in headless mode.""" - return cast("AddScreenReturns", await self._client.send_raw( - method="Emulation.addScreen", - params=params, - session_id=session_id, - )) + return cast( + "AddScreenReturns", + await self._client.send_raw( + method="Emulation.addScreen", + params=params, + session_id=session_id, + ), + ) async def removeScreen( self, @@ -631,10 +767,11 @@ async def removeScreen( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Remove screen from the device. Only supported in headless mode.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Emulation.removeScreen", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Emulation.removeScreen", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/emulation/registration.py b/cdp_use/cdp/emulation/registration.py index b7f935d..dee632d 100644 --- a/cdp_use/cdp/emulation/registration.py +++ b/cdp_use/cdp/emulation/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import VirtualTimeBudgetExpiredEvent + class EmulationRegistration: """Event registration interface for Emulation domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Emulation" def virtualTimeBudgetExpired( self, - callback: Callable[['VirtualTimeBudgetExpiredEvent', Optional[str]], None], + callback: Callable[["VirtualTimeBudgetExpiredEvent", Optional[str]], None], ) -> None: """ Register a callback for virtualTimeBudgetExpired events. - + Notification sent after the virtual time budget for the current VirtualTimePolicy has run out. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Emulation.virtualTimeBudgetExpired", callback) - diff --git a/cdp_use/cdp/emulation/types.py b/cdp_use/cdp/emulation/types.py index e07061e..6cf76dd 100644 --- a/cdp_use/cdp/emulation/types.py +++ b/cdp_use/cdp/emulation/types.py @@ -8,6 +8,7 @@ from typing_extensions import Literal from typing_extensions import NotRequired, TypedDict + class SafeAreaInsets(TypedDict, total=False): top: "int" """Overrides safe-area-inset-top.""" @@ -27,7 +28,6 @@ class SafeAreaInsets(TypedDict, total=False): """Overrides safe-area-max-inset-right.""" - class ScreenOrientation(TypedDict): """Screen orientation.""" @@ -37,7 +37,6 @@ class ScreenOrientation(TypedDict): """Orientation angle.""" - class DisplayFeature(TypedDict): orientation: "str" """Orientation of a display feature in relation to screen""" @@ -50,19 +49,16 @@ class DisplayFeature(TypedDict): A display feature that only splits content will have a 0 mask_length.""" - class DevicePosture(TypedDict): type: "str" """Current posture of the device""" - class MediaFeature(TypedDict): name: "str" value: "str" - VirtualTimePolicy = Literal["advance", "pause", "pauseIfNetworkFetchesPending"] """advance: If the scheduler runs out of immediate work, the virtual time base may fast forward to allow the next delayed task (if any) to run; pause: The virtual time base may not advance; @@ -70,7 +66,6 @@ class MediaFeature(TypedDict): resource fetches.""" - class UserAgentBrandVersion(TypedDict): """Used to specify User Agent Client Hints to emulate. See https://wicg.github.io/ua-client-hints""" @@ -78,10 +73,9 @@ class UserAgentBrandVersion(TypedDict): version: "str" - class UserAgentMetadata(TypedDict): """Used to specify User Agent Client Hints to emulate. See https://wicg.github.io/ua-client-hints -Missing optional values will be filled in by the target with what it would normally use.""" + Missing optional values will be filled in by the target with what it would normally use.""" brands: "NotRequired[List[UserAgentBrandVersion]]" """Brands appearing in Sec-CH-UA.""" @@ -100,32 +94,36 @@ class UserAgentMetadata(TypedDict): See https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factors""" - -SensorType = Literal["absolute-orientation", "accelerometer", "ambient-light", "gravity", "gyroscope", "linear-acceleration", "magnetometer", "relative-orientation"] +SensorType = Literal[ + "absolute-orientation", + "accelerometer", + "ambient-light", + "gravity", + "gyroscope", + "linear-acceleration", + "magnetometer", + "relative-orientation", +] """Used to specify sensor types to emulate. See https://w3c.github.io/sensors/#automation for more information.""" - class SensorMetadata(TypedDict, total=False): available: "bool" minimumFrequency: "float" maximumFrequency: "float" - class SensorReadingSingle(TypedDict): value: "float" - class SensorReadingXYZ(TypedDict): x: "float" y: "float" z: "float" - class SensorReadingQuaternion(TypedDict): x: "float" y: "float" @@ -133,27 +131,22 @@ class SensorReadingQuaternion(TypedDict): w: "float" - class SensorReading(TypedDict, total=False): single: "SensorReadingSingle" xyz: "SensorReadingXYZ" quaternion: "SensorReadingQuaternion" - PressureSource = Literal["cpu"] - PressureState = Literal["nominal", "fair", "serious", "critical"] - class PressureMetadata(TypedDict, total=False): available: "bool" - class WorkAreaInsets(TypedDict, total=False): top: "int" """Work area top inset in pixels. Default is 0;""" @@ -165,14 +158,12 @@ class WorkAreaInsets(TypedDict, total=False): """Work area right inset in pixels. Default is 0;""" - ScreenId = str - class ScreenInfo(TypedDict): """Screen information similar to the one returned by window.getScreenDetails() method, -see https://w3c.github.io/window-management/#screendetailed.""" + see https://w3c.github.io/window-management/#screendetailed.""" left: "int" """Offset of the left edge of the screen.""" @@ -208,6 +199,5 @@ class ScreenInfo(TypedDict): """Specifies the unique identifier of the screen.""" - DisabledImageType = Literal["avif", "webp"] """Enum of image types that can be disabled.""" diff --git a/cdp_use/cdp/eventbreakpoints/commands.py b/cdp_use/cdp/eventbreakpoints/commands.py index dd8ebb8..b8f51ef 100644 --- a/cdp_use/cdp/eventbreakpoints/commands.py +++ b/cdp_use/cdp/eventbreakpoints/commands.py @@ -6,16 +6,12 @@ from typing_extensions import TypedDict + class SetInstrumentationBreakpointParameters(TypedDict): eventName: "str" """Instrumentation name to stop on.""" - - - class RemoveInstrumentationBreakpointParameters(TypedDict): eventName: "str" """Instrumentation name to stop on.""" - - diff --git a/cdp_use/cdp/eventbreakpoints/events.py b/cdp_use/cdp/eventbreakpoints/events.py index 91b010d..1b41f31 100644 --- a/cdp_use/cdp/eventbreakpoints/events.py +++ b/cdp_use/cdp/eventbreakpoints/events.py @@ -5,4 +5,4 @@ """CDP EventBreakpoints Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/eventbreakpoints/library.py b/cdp_use/cdp/eventbreakpoints/library.py index 0ec7551..93f1b47 100644 --- a/cdp_use/cdp/eventbreakpoints/library.py +++ b/cdp_use/cdp/eventbreakpoints/library.py @@ -13,10 +13,11 @@ from .commands import RemoveInstrumentationBreakpointParameters from .commands import SetInstrumentationBreakpointParameters + class EventBreakpointsClient: """Client for EventBreakpoints domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def setInstrumentationBreakpoint( @@ -25,11 +26,14 @@ async def setInstrumentationBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets breakpoint on particular native event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="EventBreakpoints.setInstrumentationBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="EventBreakpoints.setInstrumentationBreakpoint", + params=params, + session_id=session_id, + ), + ) async def removeInstrumentationBreakpoint( self, @@ -37,11 +41,14 @@ async def removeInstrumentationBreakpoint( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes breakpoint on particular native event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="EventBreakpoints.removeInstrumentationBreakpoint", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="EventBreakpoints.removeInstrumentationBreakpoint", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -49,10 +56,11 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes all breakpoints""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="EventBreakpoints.disable", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="EventBreakpoints.disable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/eventbreakpoints/registration.py b/cdp_use/cdp/eventbreakpoints/registration.py index b13e707..5a4417e 100644 --- a/cdp_use/cdp/eventbreakpoints/registration.py +++ b/cdp_use/cdp/eventbreakpoints/registration.py @@ -5,4 +5,4 @@ """CDP EventBreakpoints Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/eventbreakpoints/types.py b/cdp_use/cdp/eventbreakpoints/types.py index 48667fd..46782a3 100644 --- a/cdp_use/cdp/eventbreakpoints/types.py +++ b/cdp_use/cdp/eventbreakpoints/types.py @@ -5,4 +5,4 @@ """CDP EventBreakpoints Domain Types""" -# No types defined for this domain \ No newline at end of file +# No types defined for this domain diff --git a/cdp_use/cdp/extensions/commands.py b/cdp_use/cdp/extensions/commands.py index c2e0a19..5c19be5 100644 --- a/cdp_use/cdp/extensions/commands.py +++ b/cdp_use/cdp/extensions/commands.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: from .types import StorageArea + class LoadUnpackedParameters(TypedDict): path: "str" """Absolute file path.""" @@ -22,15 +23,11 @@ class LoadUnpackedReturns(TypedDict): """Extension id.""" - class UninstallParameters(TypedDict): id: "str" """Extension id.""" - - - class GetStorageItemsParameters(TypedDict): id: "str" """ID of extension.""" @@ -44,7 +41,6 @@ class GetStorageItemsReturns(TypedDict): data: "Dict[str, Any]" - class RemoveStorageItemsParameters(TypedDict): id: "str" """ID of extension.""" @@ -54,9 +50,6 @@ class RemoveStorageItemsParameters(TypedDict): """Keys to remove.""" - - - class ClearStorageItemsParameters(TypedDict): id: "str" """ID of extension.""" @@ -64,9 +57,6 @@ class ClearStorageItemsParameters(TypedDict): """StorageArea to remove data from.""" - - - class SetStorageItemsParameters(TypedDict): id: "str" """ID of extension.""" @@ -74,5 +64,3 @@ class SetStorageItemsParameters(TypedDict): """StorageArea to set data in.""" values: "Dict[str, Any]" """Values to set.""" - - diff --git a/cdp_use/cdp/extensions/events.py b/cdp_use/cdp/extensions/events.py index 671889f..c41efbf 100644 --- a/cdp_use/cdp/extensions/events.py +++ b/cdp_use/cdp/extensions/events.py @@ -5,4 +5,4 @@ """CDP Extensions Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/extensions/library.py b/cdp_use/cdp/extensions/library.py index 78c5c83..2aefc46 100644 --- a/cdp_use/cdp/extensions/library.py +++ b/cdp_use/cdp/extensions/library.py @@ -19,10 +19,11 @@ from .commands import SetStorageItemsParameters from .commands import UninstallParameters + class ExtensionsClient: """Client for Extensions domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def loadUnpacked( @@ -31,15 +32,18 @@ async def loadUnpacked( session_id: Optional[str] = None, ) -> "LoadUnpackedReturns": """Installs an unpacked extension from the filesystem similar to ---load-extension CLI flags. Returns extension ID once the extension -has been installed. Available if the client is connected using the ---remote-debugging-pipe flag and the --enable-unsafe-extension-debugging -flag is set.""" - return cast("LoadUnpackedReturns", await self._client.send_raw( - method="Extensions.loadUnpacked", - params=params, - session_id=session_id, - )) + --load-extension CLI flags. Returns extension ID once the extension + has been installed. Available if the client is connected using the + --remote-debugging-pipe flag and the --enable-unsafe-extension-debugging + flag is set.""" + return cast( + "LoadUnpackedReturns", + await self._client.send_raw( + method="Extensions.loadUnpacked", + params=params, + session_id=session_id, + ), + ) async def uninstall( self, @@ -47,13 +51,16 @@ async def uninstall( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Uninstalls an unpacked extension (others not supported) from the profile. -Available if the client is connected using the --remote-debugging-pipe flag -and the --enable-unsafe-extension-debugging.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Extensions.uninstall", - params=params, - session_id=session_id, - )) + Available if the client is connected using the --remote-debugging-pipe flag + and the --enable-unsafe-extension-debugging.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Extensions.uninstall", + params=params, + session_id=session_id, + ), + ) async def getStorageItems( self, @@ -61,12 +68,15 @@ async def getStorageItems( session_id: Optional[str] = None, ) -> "GetStorageItemsReturns": """Gets data from extension storage in the given `storageArea`. If `keys` is -specified, these are used to filter the result.""" - return cast("GetStorageItemsReturns", await self._client.send_raw( - method="Extensions.getStorageItems", - params=params, - session_id=session_id, - )) + specified, these are used to filter the result.""" + return cast( + "GetStorageItemsReturns", + await self._client.send_raw( + method="Extensions.getStorageItems", + params=params, + session_id=session_id, + ), + ) async def removeStorageItems( self, @@ -74,11 +84,14 @@ async def removeStorageItems( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes `keys` from extension storage in the given `storageArea`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Extensions.removeStorageItems", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Extensions.removeStorageItems", + params=params, + session_id=session_id, + ), + ) async def clearStorageItems( self, @@ -86,11 +99,14 @@ async def clearStorageItems( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears extension storage in the given `storageArea`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Extensions.clearStorageItems", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Extensions.clearStorageItems", + params=params, + session_id=session_id, + ), + ) async def setStorageItems( self, @@ -98,11 +114,12 @@ async def setStorageItems( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets `values` in extension storage in the given `storageArea`. The provided `values` -will be merged with existing values in the storage area.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Extensions.setStorageItems", - params=params, - session_id=session_id, - )) - - + will be merged with existing values in the storage area.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Extensions.setStorageItems", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/extensions/registration.py b/cdp_use/cdp/extensions/registration.py index 7c3f76e..c694246 100644 --- a/cdp_use/cdp/extensions/registration.py +++ b/cdp_use/cdp/extensions/registration.py @@ -5,4 +5,4 @@ """CDP Extensions Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/fedcm/commands.py b/cdp_use/cdp/fedcm/commands.py index 9277ad2..e6b7244 100644 --- a/cdp_use/cdp/fedcm/commands.py +++ b/cdp_use/cdp/fedcm/commands.py @@ -12,6 +12,7 @@ from .types import AccountUrlType from .types import DialogButton + class EnableParameters(TypedDict, total=False): disableRejectionDelay: "bool" """Allows callers to disable the promise rejection delay that would @@ -19,36 +20,22 @@ class EnableParameters(TypedDict, total=False): (step 4 of https://fedidcg.github.io/FedCM/#browser-api-rp-sign-in)""" - - - class SelectAccountParameters(TypedDict): dialogId: "str" accountIndex: "int" - - - class ClickDialogButtonParameters(TypedDict): dialogId: "str" dialogButton: "DialogButton" - - - class OpenUrlParameters(TypedDict): dialogId: "str" accountIndex: "int" accountUrlType: "AccountUrlType" - - - class DismissDialogParameters(TypedDict): dialogId: "str" triggerCooldown: "NotRequired[bool]" - - diff --git a/cdp_use/cdp/fedcm/events.py b/cdp_use/cdp/fedcm/events.py index f18c962..eca6f25 100644 --- a/cdp_use/cdp/fedcm/events.py +++ b/cdp_use/cdp/fedcm/events.py @@ -13,6 +13,7 @@ from .types import Account from .types import DialogType + class DialogShownEvent(TypedDict): dialogId: "str" dialogType: "DialogType" @@ -23,8 +24,9 @@ class DialogShownEvent(TypedDict): subtitle: "NotRequired[str]" - """Triggered when a dialog is closed, either by user action, JS abort, or a command below.""" + + class DialogClosedEvent(TypedDict): dialogId: "str" diff --git a/cdp_use/cdp/fedcm/library.py b/cdp_use/cdp/fedcm/library.py index 07ccb98..45aa084 100644 --- a/cdp_use/cdp/fedcm/library.py +++ b/cdp_use/cdp/fedcm/library.py @@ -16,10 +16,11 @@ from .commands import OpenUrlParameters from .commands import SelectAccountParameters + class FedCmClient: """Client for FedCm domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -27,66 +28,84 @@ async def enable( params: Optional["EnableParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.disable", + params=params, + session_id=session_id, + ), + ) async def selectAccount( self, params: "SelectAccountParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.selectAccount", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.selectAccount", + params=params, + session_id=session_id, + ), + ) async def clickDialogButton( self, params: "ClickDialogButtonParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.clickDialogButton", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.clickDialogButton", + params=params, + session_id=session_id, + ), + ) async def openUrl( self, params: "OpenUrlParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.openUrl", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.openUrl", + params=params, + session_id=session_id, + ), + ) async def dismissDialog( self, params: "DismissDialogParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.dismissDialog", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.dismissDialog", + params=params, + session_id=session_id, + ), + ) async def resetCooldown( self, @@ -94,11 +113,12 @@ async def resetCooldown( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Resets the cooldown time, if any, to allow the next FedCM call to show -a dialog even if one was recently dismissed by the user.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="FedCm.resetCooldown", - params=params, - session_id=session_id, - )) - - + a dialog even if one was recently dismissed by the user.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="FedCm.resetCooldown", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/fedcm/registration.py b/cdp_use/cdp/fedcm/registration.py index 2406ff8..a6a6720 100644 --- a/cdp_use/cdp/fedcm/registration.py +++ b/cdp_use/cdp/fedcm/registration.py @@ -12,20 +12,21 @@ from ..registry import EventRegistry from .events import DialogClosedEvent, DialogShownEvent + class FedCmRegistration: """Event registration interface for FedCm domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "FedCm" def dialogShown( self, - callback: Callable[['DialogShownEvent', Optional[str]], None], + callback: Callable[["DialogShownEvent", Optional[str]], None], ) -> None: """ Register a callback for dialogShown events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,17 +35,16 @@ def dialogShown( def dialogClosed( self, - callback: Callable[['DialogClosedEvent', Optional[str]], None], + callback: Callable[["DialogClosedEvent", Optional[str]], None], ) -> None: """ - Register a callback for dialogClosed events. - - Triggered when a dialog is closed, either by user action, JS abort, -or a command below. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for dialogClosed events. + + Triggered when a dialog is closed, either by user action, JS abort, + or a command below. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("FedCm.dialogClosed", callback) - diff --git a/cdp_use/cdp/fedcm/types.py b/cdp_use/cdp/fedcm/types.py index 6b9c766..3327c98 100644 --- a/cdp_use/cdp/fedcm/types.py +++ b/cdp_use/cdp/fedcm/types.py @@ -12,22 +12,18 @@ whether this account has ever been used to sign in to this RP before.""" - DialogType = Literal["AccountChooser", "AutoReauthn", "ConfirmIdpLogin", "Error"] """The types of FedCM dialogs.""" - DialogButton = Literal["ConfirmIdpLoginContinue", "ErrorGotIt", "ErrorMoreDetails"] """The buttons on the FedCM dialog.""" - AccountUrlType = Literal["TermsOfService", "PrivacyPolicy"] """The URLs that each account has""" - class Account(TypedDict): """Corresponds to IdentityRequestAccount""" diff --git a/cdp_use/cdp/fetch/commands.py b/cdp_use/cdp/fetch/commands.py index 080a881..265161f 100644 --- a/cdp_use/cdp/fetch/commands.py +++ b/cdp_use/cdp/fetch/commands.py @@ -17,6 +17,7 @@ from .types import RequestId from .types import RequestPattern + class EnableParameters(TypedDict, total=False): patterns: "List[RequestPattern]" """If specified, only requests matching any of these patterns will produce @@ -27,9 +28,6 @@ class EnableParameters(TypedDict, total=False): expecting a call to continueWithAuth.""" - - - class FailRequestParameters(TypedDict): requestId: "RequestId" """An id the client received in requestPaused event.""" @@ -37,9 +35,6 @@ class FailRequestParameters(TypedDict): """Causes the request to fail with the given reason.""" - - - class FulfillRequestParameters(TypedDict): requestId: "RequestId" """An id the client received in requestPaused event.""" @@ -61,9 +56,6 @@ class FulfillRequestParameters(TypedDict): If absent, a standard phrase matching responseCode is used.""" - - - class ContinueRequestParameters(TypedDict): requestId: "RequestId" """An id the client received in requestPaused event.""" @@ -81,9 +73,6 @@ class ContinueRequestParameters(TypedDict): """If set, overrides response interception behavior for this request.""" - - - class ContinueWithAuthParameters(TypedDict): requestId: "RequestId" """An id the client received in authRequired event.""" @@ -91,9 +80,6 @@ class ContinueWithAuthParameters(TypedDict): """Response to with an authChallenge.""" - - - class ContinueResponseParameters(TypedDict): requestId: "RequestId" """An id the client received in requestPaused event.""" @@ -111,9 +97,6 @@ class ContinueResponseParameters(TypedDict): over the protocol as text. (Encoded as a base64 string when passed over JSON)""" - - - class GetResponseBodyParameters(TypedDict): requestId: "RequestId" """Identifier for the intercepted request to get body for.""" @@ -126,7 +109,6 @@ class GetResponseBodyReturns(TypedDict): """True, if content was sent as base64.""" - class TakeResponseBodyAsStreamParameters(TypedDict): requestId: "RequestId" diff --git a/cdp_use/cdp/fetch/events.py b/cdp_use/cdp/fetch/events.py index c73f310..416a731 100644 --- a/cdp_use/cdp/fetch/events.py +++ b/cdp_use/cdp/fetch/events.py @@ -30,6 +30,8 @@ of `responseStatusCode` (which is one of 301, 302, 303, 307, 308) along with presence of the `location` header. Requests resulting from a redirect will have `redirectedRequestId` field set.""" + + class RequestPausedEvent(TypedDict): requestId: "RequestId" """Each request the page makes will have a unique id.""" @@ -55,9 +57,10 @@ class RequestPausedEvent(TypedDict): has caused the redirect.""" - """Issued when the domain is enabled with handleAuthRequests set to true. The request is paused until client responds with continueWithAuth.""" + + class AuthRequiredEvent(TypedDict): requestId: "RequestId" """Each request the page makes will have a unique id.""" diff --git a/cdp_use/cdp/fetch/library.py b/cdp_use/cdp/fetch/library.py index 3b19a5c..ef20d95 100644 --- a/cdp_use/cdp/fetch/library.py +++ b/cdp_use/cdp/fetch/library.py @@ -21,10 +21,11 @@ from .commands import TakeResponseBodyAsStreamParameters from .commands import TakeResponseBodyAsStreamReturns + class FetchClient: """Client for Fetch domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -33,11 +34,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables the fetch domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -45,12 +49,15 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables issuing of requestPaused events. A request will be paused until client -calls one of failRequest, fulfillRequest or continueRequest/continueWithAuth.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.enable", - params=params, - session_id=session_id, - )) + calls one of failRequest, fulfillRequest or continueRequest/continueWithAuth.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.enable", + params=params, + session_id=session_id, + ), + ) async def failRequest( self, @@ -58,11 +65,14 @@ async def failRequest( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Causes the request to fail with specified reason.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.failRequest", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.failRequest", + params=params, + session_id=session_id, + ), + ) async def fulfillRequest( self, @@ -70,11 +80,14 @@ async def fulfillRequest( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Provides response to the request.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.fulfillRequest", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.fulfillRequest", + params=params, + session_id=session_id, + ), + ) async def continueRequest( self, @@ -82,11 +95,14 @@ async def continueRequest( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Continues the request, optionally modifying some of its parameters.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.continueRequest", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.continueRequest", + params=params, + session_id=session_id, + ), + ) async def continueWithAuth( self, @@ -94,11 +110,14 @@ async def continueWithAuth( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Continues a request supplying authChallengeResponse following authRequired event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.continueWithAuth", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.continueWithAuth", + params=params, + session_id=session_id, + ), + ) async def continueResponse( self, @@ -106,13 +125,16 @@ async def continueResponse( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Continues loading of the paused response, optionally modifying the -response headers. If either responseCode or headers are modified, all of them -must be present.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Fetch.continueResponse", - params=params, - session_id=session_id, - )) + response headers. If either responseCode or headers are modified, all of them + must be present.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Fetch.continueResponse", + params=params, + session_id=session_id, + ), + ) async def getResponseBody( self, @@ -120,20 +142,23 @@ async def getResponseBody( session_id: Optional[str] = None, ) -> "GetResponseBodyReturns": """Causes the body of the response to be received from the server and -returned as a single string. May only be issued for a request that -is paused in the Response stage and is mutually exclusive with -takeResponseBodyForInterceptionAsStream. Calling other methods that -affect the request or disabling fetch domain before body is received -results in an undefined behavior. -Note that the response body is not available for redirects. Requests -paused in the _redirect received_ state may be differentiated by -`responseCode` and presence of `location` response header, see -comments to `requestPaused` for details.""" - return cast("GetResponseBodyReturns", await self._client.send_raw( - method="Fetch.getResponseBody", - params=params, - session_id=session_id, - )) + returned as a single string. May only be issued for a request that + is paused in the Response stage and is mutually exclusive with + takeResponseBodyForInterceptionAsStream. Calling other methods that + affect the request or disabling fetch domain before body is received + results in an undefined behavior. + Note that the response body is not available for redirects. Requests + paused in the _redirect received_ state may be differentiated by + `responseCode` and presence of `location` response header, see + comments to `requestPaused` for details.""" + return cast( + "GetResponseBodyReturns", + await self._client.send_raw( + method="Fetch.getResponseBody", + params=params, + session_id=session_id, + ), + ) async def takeResponseBodyAsStream( self, @@ -141,19 +166,20 @@ async def takeResponseBodyAsStream( session_id: Optional[str] = None, ) -> "TakeResponseBodyAsStreamReturns": """Returns a handle to the stream representing the response body. -The request must be paused in the HeadersReceived stage. -Note that after this command the request can't be continued -as is -- client either needs to cancel it or to provide the -response body. -The stream only supports sequential read, IO.read will fail if the position -is specified. -This method is mutually exclusive with getResponseBody. -Calling other methods that affect the request or disabling fetch -domain before body is received results in an undefined behavior.""" - return cast("TakeResponseBodyAsStreamReturns", await self._client.send_raw( - method="Fetch.takeResponseBodyAsStream", - params=params, - session_id=session_id, - )) - - + The request must be paused in the HeadersReceived stage. + Note that after this command the request can't be continued + as is -- client either needs to cancel it or to provide the + response body. + The stream only supports sequential read, IO.read will fail if the position + is specified. + This method is mutually exclusive with getResponseBody. + Calling other methods that affect the request or disabling fetch + domain before body is received results in an undefined behavior.""" + return cast( + "TakeResponseBodyAsStreamReturns", + await self._client.send_raw( + method="Fetch.takeResponseBodyAsStream", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/fetch/registration.py b/cdp_use/cdp/fetch/registration.py index d0d3bf1..bdf9bac 100644 --- a/cdp_use/cdp/fetch/registration.py +++ b/cdp_use/cdp/fetch/registration.py @@ -12,51 +12,51 @@ from ..registry import EventRegistry from .events import AuthRequiredEvent, RequestPausedEvent + class FetchRegistration: """Event registration interface for Fetch domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Fetch" def requestPaused( self, - callback: Callable[['RequestPausedEvent', Optional[str]], None], + callback: Callable[["RequestPausedEvent", Optional[str]], None], ) -> None: """ - Register a callback for requestPaused events. - - Issued when the domain is enabled and the request URL matches the -specified filter. The request is paused until the client responds -with one of continueRequest, failRequest or fulfillRequest. -The stage of the request can be determined by presence of responseErrorReason -and responseStatusCode -- the request is at the response stage if either -of these fields is present and in the request stage otherwise. -Redirect responses and subsequent requests are reported similarly to regular -responses and requests. Redirect responses may be distinguished by the value -of `responseStatusCode` (which is one of 301, 302, 303, 307, 308) along with -presence of the `location` header. Requests resulting from a redirect will -have `redirectedRequestId` field set. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for requestPaused events. + + Issued when the domain is enabled and the request URL matches the + specified filter. The request is paused until the client responds + with one of continueRequest, failRequest or fulfillRequest. + The stage of the request can be determined by presence of responseErrorReason + and responseStatusCode -- the request is at the response stage if either + of these fields is present and in the request stage otherwise. + Redirect responses and subsequent requests are reported similarly to regular + responses and requests. Redirect responses may be distinguished by the value + of `responseStatusCode` (which is one of 301, 302, 303, 307, 308) along with + presence of the `location` header. Requests resulting from a redirect will + have `redirectedRequestId` field set. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Fetch.requestPaused", callback) def authRequired( self, - callback: Callable[['AuthRequiredEvent', Optional[str]], None], + callback: Callable[["AuthRequiredEvent", Optional[str]], None], ) -> None: """ - Register a callback for authRequired events. - - Issued when the domain is enabled with handleAuthRequests set to true. -The request is paused until client responds with continueWithAuth. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for authRequired events. + + Issued when the domain is enabled with handleAuthRequests set to true. + The request is paused until client responds with continueWithAuth. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Fetch.authRequired", callback) - diff --git a/cdp_use/cdp/fetch/types.py b/cdp_use/cdp/fetch/types.py index 76bd0ef..5f0d187 100644 --- a/cdp_use/cdp/fetch/types.py +++ b/cdp_use/cdp/fetch/types.py @@ -18,14 +18,12 @@ a network request.""" - RequestStage = Literal["Request", "Response"] """Stages of the request to handle. Request will intercept before the request is sent. Response will intercept after the response is received (but before response body is received).""" - class RequestPattern(TypedDict, total=False): urlPattern: "str" """Wildcards (`'*'` -> zero or more, `'?'` -> exactly one) are allowed. Escape character is @@ -36,7 +34,6 @@ class RequestPattern(TypedDict, total=False): """Stage at which to begin intercepting requests. Default is Request.""" - class HeaderEntry(TypedDict): """Response HTTP header entry""" @@ -44,7 +41,6 @@ class HeaderEntry(TypedDict): value: "str" - class AuthChallenge(TypedDict): """Authorization challenge for HTTP status code 401 or 407.""" @@ -58,7 +54,6 @@ class AuthChallenge(TypedDict): """The realm of the challenge. May be empty.""" - class AuthChallengeResponse(TypedDict): """Response to an AuthChallenge.""" diff --git a/cdp_use/cdp/filesystem/commands.py b/cdp_use/cdp/filesystem/commands.py index f72dd5a..ad15596 100644 --- a/cdp_use/cdp/filesystem/commands.py +++ b/cdp_use/cdp/filesystem/commands.py @@ -12,6 +12,7 @@ from .types import BucketFileSystemLocator from .types import Directory + class GetDirectoryParameters(TypedDict): bucketFileSystemLocator: "BucketFileSystemLocator" diff --git a/cdp_use/cdp/filesystem/events.py b/cdp_use/cdp/filesystem/events.py index 151578d..1c38fed 100644 --- a/cdp_use/cdp/filesystem/events.py +++ b/cdp_use/cdp/filesystem/events.py @@ -5,4 +5,4 @@ """CDP FileSystem Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/filesystem/library.py b/cdp_use/cdp/filesystem/library.py index f8bbacf..2db3243 100644 --- a/cdp_use/cdp/filesystem/library.py +++ b/cdp_use/cdp/filesystem/library.py @@ -13,10 +13,11 @@ from .commands import GetDirectoryParameters from .commands import GetDirectoryReturns + class FileSystemClient: """Client for FileSystem domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getDirectory( @@ -24,10 +25,11 @@ async def getDirectory( params: "GetDirectoryParameters", session_id: Optional[str] = None, ) -> "GetDirectoryReturns": - return cast("GetDirectoryReturns", await self._client.send_raw( - method="FileSystem.getDirectory", - params=params, - session_id=session_id, - )) - - + return cast( + "GetDirectoryReturns", + await self._client.send_raw( + method="FileSystem.getDirectory", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/filesystem/registration.py b/cdp_use/cdp/filesystem/registration.py index 71157df..770506b 100644 --- a/cdp_use/cdp/filesystem/registration.py +++ b/cdp_use/cdp/filesystem/registration.py @@ -5,4 +5,4 @@ """CDP FileSystem Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/filesystem/types.py b/cdp_use/cdp/filesystem/types.py index 0a1e07d..8db5593 100644 --- a/cdp_use/cdp/filesystem/types.py +++ b/cdp_use/cdp/filesystem/types.py @@ -13,6 +13,7 @@ from ..network.types import TimeSinceEpoch from ..storage.types import SerializedStorageKey + class File(TypedDict): name: "str" lastModified: "TimeSinceEpoch" @@ -22,7 +23,6 @@ class File(TypedDict): type: "str" - class Directory(TypedDict): name: "str" nestedDirectories: "List[str]" @@ -30,7 +30,6 @@ class Directory(TypedDict): """Files that are directly nested under this directory.""" - class BucketFileSystemLocator(TypedDict): storageKey: "SerializedStorageKey" """Storage key""" diff --git a/cdp_use/cdp/headlessexperimental/commands.py b/cdp_use/cdp/headlessexperimental/commands.py index 6e9fc3d..4c5092e 100644 --- a/cdp_use/cdp/headlessexperimental/commands.py +++ b/cdp_use/cdp/headlessexperimental/commands.py @@ -11,6 +11,7 @@ if TYPE_CHECKING: from .types import ScreenshotParams + class BeginFrameParameters(TypedDict, total=False): frameTimeTicks: "float" """Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, diff --git a/cdp_use/cdp/headlessexperimental/events.py b/cdp_use/cdp/headlessexperimental/events.py index 1019b1c..1e44333 100644 --- a/cdp_use/cdp/headlessexperimental/events.py +++ b/cdp_use/cdp/headlessexperimental/events.py @@ -5,4 +5,4 @@ """CDP HeadlessExperimental Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/headlessexperimental/library.py b/cdp_use/cdp/headlessexperimental/library.py index b20bce5..21de146 100644 --- a/cdp_use/cdp/headlessexperimental/library.py +++ b/cdp_use/cdp/headlessexperimental/library.py @@ -13,10 +13,11 @@ from .commands import BeginFrameParameters from .commands import BeginFrameReturns + class HeadlessExperimentalClient: """Client for HeadlessExperimental domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def beginFrame( @@ -25,14 +26,17 @@ async def beginFrame( session_id: Optional[str] = None, ) -> "BeginFrameReturns": """Sends a BeginFrame to the target and returns when the frame was completed. Optionally captures a -screenshot from the resulting frame. Requires that the target was created with enabled -BeginFrameControl. Designed for use with --run-all-compositor-stages-before-draw, see also -https://goo.gle/chrome-headless-rendering for more background.""" - return cast("BeginFrameReturns", await self._client.send_raw( - method="HeadlessExperimental.beginFrame", - params=params, - session_id=session_id, - )) + screenshot from the resulting frame. Requires that the target was created with enabled + BeginFrameControl. Designed for use with --run-all-compositor-stages-before-draw, see also + https://goo.gle/chrome-headless-rendering for more background.""" + return cast( + "BeginFrameReturns", + await self._client.send_raw( + method="HeadlessExperimental.beginFrame", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -40,11 +44,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables headless events for the target.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeadlessExperimental.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeadlessExperimental.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -52,10 +59,11 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables headless events for the target.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeadlessExperimental.enable", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeadlessExperimental.enable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/headlessexperimental/registration.py b/cdp_use/cdp/headlessexperimental/registration.py index c7ed910..43190e8 100644 --- a/cdp_use/cdp/headlessexperimental/registration.py +++ b/cdp_use/cdp/headlessexperimental/registration.py @@ -5,4 +5,4 @@ """CDP HeadlessExperimental Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/headlessexperimental/types.py b/cdp_use/cdp/headlessexperimental/types.py index a5ab082..ab06c1b 100644 --- a/cdp_use/cdp/headlessexperimental/types.py +++ b/cdp_use/cdp/headlessexperimental/types.py @@ -6,6 +6,7 @@ from typing_extensions import TypedDict + class ScreenshotParams(TypedDict, total=False): """Encoding options for a screenshot.""" diff --git a/cdp_use/cdp/heapprofiler/commands.py b/cdp_use/cdp/heapprofiler/commands.py index a50409b..7007360 100644 --- a/cdp_use/cdp/heapprofiler/commands.py +++ b/cdp_use/cdp/heapprofiler/commands.py @@ -14,14 +14,12 @@ from .types import HeapSnapshotObjectId from .types import SamplingHeapProfile + class AddInspectedHeapObjectParameters(TypedDict): heapObjectId: "HeapSnapshotObjectId" """Heap snapshot object id to be accessible by means of $x command line API.""" - - - class GetHeapObjectIdParameters(TypedDict): objectId: "RemoteObjectId" """Identifier of the object to get heap object id for.""" @@ -32,7 +30,6 @@ class GetHeapObjectIdReturns(TypedDict): """Id of the heap snapshot object corresponding to the passed remote object id.""" - class GetObjectByHeapObjectIdParameters(TypedDict): objectId: "HeapSnapshotObjectId" objectGroup: "NotRequired[str]" @@ -44,17 +41,17 @@ class GetObjectByHeapObjectIdReturns(TypedDict): """Evaluation result.""" - class GetSamplingProfileReturns(TypedDict): profile: "SamplingHeapProfile" """Return the sampling profile being collected.""" - class StartSamplingParameters(TypedDict, total=False): samplingInterval: "float" """Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes.""" + stackDepth: "float" + """Maximum stack depth. The default value is 128.""" includeObjectsCollectedByMajorGC: "bool" """By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or @@ -73,22 +70,15 @@ class StartSamplingParameters(TypedDict, total=False): for minimal GC activity.""" - - - class StartTrackingHeapObjectsParameters(TypedDict, total=False): trackAllocations: "bool" - - - class StopSamplingReturns(TypedDict): profile: "SamplingHeapProfile" """Recorded sampling heap profile.""" - class StopTrackingHeapObjectsParameters(TypedDict, total=False): reportProgress: "bool" """If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken @@ -101,9 +91,6 @@ class StopTrackingHeapObjectsParameters(TypedDict, total=False): """If true, exposes internals of the snapshot.""" - - - class TakeHeapSnapshotParameters(TypedDict, total=False): reportProgress: "bool" """If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken.""" @@ -114,5 +101,3 @@ class TakeHeapSnapshotParameters(TypedDict, total=False): """If true, numerical values are included in the snapshot""" exposeInternals: "bool" """If true, exposes internals of the snapshot.""" - - diff --git a/cdp_use/cdp/heapprofiler/events.py b/cdp_use/cdp/heapprofiler/events.py index 8171229..a7fdb99 100644 --- a/cdp_use/cdp/heapprofiler/events.py +++ b/cdp_use/cdp/heapprofiler/events.py @@ -7,12 +7,14 @@ from typing import List from typing_extensions import NotRequired, TypedDict + class AddHeapSnapshotChunkEvent(TypedDict): chunk: "str" - """If heap objects tracking has been started then backend may send update for one or more fragments""" + + class HeapStatsUpdateEvent(TypedDict): statsUpdate: "List[int]" """An array of triplets. Each triplet describes a fragment. The first integer is the fragment @@ -20,22 +22,21 @@ class HeapStatsUpdateEvent(TypedDict): a total size of the objects for the fragment.""" - """If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event.""" + + class LastSeenObjectIdEvent(TypedDict): lastSeenObjectId: "int" timestamp: "float" - class ReportHeapSnapshotProgressEvent(TypedDict): done: "int" total: "int" finished: "NotRequired[bool]" - class ResetProfilesEvent(TypedDict): pass diff --git a/cdp_use/cdp/heapprofiler/library.py b/cdp_use/cdp/heapprofiler/library.py index 10ecdff..3080f4f 100644 --- a/cdp_use/cdp/heapprofiler/library.py +++ b/cdp_use/cdp/heapprofiler/library.py @@ -22,10 +22,11 @@ from .commands import StopTrackingHeapObjectsParameters from .commands import TakeHeapSnapshotParameters + class HeapProfilerClient: """Client for HeapProfiler domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def addInspectedHeapObject( @@ -34,132 +35,166 @@ async def addInspectedHeapObject( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables console to refer to the node with given id via $x (see Command Line API for more details -$x functions).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.addInspectedHeapObject", - params=params, - session_id=session_id, - )) + $x functions).""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.addInspectedHeapObject", + params=params, + session_id=session_id, + ), + ) async def collectGarbage( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.collectGarbage", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.collectGarbage", + params=params, + session_id=session_id, + ), + ) async def disable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.enable", + params=params, + session_id=session_id, + ), + ) async def getHeapObjectId( self, params: "GetHeapObjectIdParameters", session_id: Optional[str] = None, ) -> "GetHeapObjectIdReturns": - return cast("GetHeapObjectIdReturns", await self._client.send_raw( - method="HeapProfiler.getHeapObjectId", - params=params, - session_id=session_id, - )) + return cast( + "GetHeapObjectIdReturns", + await self._client.send_raw( + method="HeapProfiler.getHeapObjectId", + params=params, + session_id=session_id, + ), + ) async def getObjectByHeapObjectId( self, params: "GetObjectByHeapObjectIdParameters", session_id: Optional[str] = None, ) -> "GetObjectByHeapObjectIdReturns": - return cast("GetObjectByHeapObjectIdReturns", await self._client.send_raw( - method="HeapProfiler.getObjectByHeapObjectId", - params=params, - session_id=session_id, - )) + return cast( + "GetObjectByHeapObjectIdReturns", + await self._client.send_raw( + method="HeapProfiler.getObjectByHeapObjectId", + params=params, + session_id=session_id, + ), + ) async def getSamplingProfile( self, params: None = None, session_id: Optional[str] = None, ) -> "GetSamplingProfileReturns": - return cast("GetSamplingProfileReturns", await self._client.send_raw( - method="HeapProfiler.getSamplingProfile", - params=params, - session_id=session_id, - )) + return cast( + "GetSamplingProfileReturns", + await self._client.send_raw( + method="HeapProfiler.getSamplingProfile", + params=params, + session_id=session_id, + ), + ) async def startSampling( self, params: Optional["StartSamplingParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.startSampling", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.startSampling", + params=params, + session_id=session_id, + ), + ) async def startTrackingHeapObjects( self, params: Optional["StartTrackingHeapObjectsParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.startTrackingHeapObjects", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.startTrackingHeapObjects", + params=params, + session_id=session_id, + ), + ) async def stopSampling( self, params: None = None, session_id: Optional[str] = None, ) -> "StopSamplingReturns": - return cast("StopSamplingReturns", await self._client.send_raw( - method="HeapProfiler.stopSampling", - params=params, - session_id=session_id, - )) + return cast( + "StopSamplingReturns", + await self._client.send_raw( + method="HeapProfiler.stopSampling", + params=params, + session_id=session_id, + ), + ) async def stopTrackingHeapObjects( self, params: Optional["StopTrackingHeapObjectsParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.stopTrackingHeapObjects", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.stopTrackingHeapObjects", + params=params, + session_id=session_id, + ), + ) async def takeHeapSnapshot( self, params: Optional["TakeHeapSnapshotParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="HeapProfiler.takeHeapSnapshot", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="HeapProfiler.takeHeapSnapshot", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/heapprofiler/registration.py b/cdp_use/cdp/heapprofiler/registration.py index 9d0facb..d9671f4 100644 --- a/cdp_use/cdp/heapprofiler/registration.py +++ b/cdp_use/cdp/heapprofiler/registration.py @@ -10,22 +10,29 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import AddHeapSnapshotChunkEvent, HeapStatsUpdateEvent, LastSeenObjectIdEvent, ReportHeapSnapshotProgressEvent, ResetProfilesEvent + from .events import ( + AddHeapSnapshotChunkEvent, + HeapStatsUpdateEvent, + LastSeenObjectIdEvent, + ReportHeapSnapshotProgressEvent, + ResetProfilesEvent, + ) + class HeapProfilerRegistration: """Event registration interface for HeapProfiler domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "HeapProfiler" def addHeapSnapshotChunk( self, - callback: Callable[['AddHeapSnapshotChunkEvent', Optional[str]], None], + callback: Callable[["AddHeapSnapshotChunkEvent", Optional[str]], None], ) -> None: """ Register a callback for addHeapSnapshotChunk events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,13 +41,13 @@ def addHeapSnapshotChunk( def heapStatsUpdate( self, - callback: Callable[['HeapStatsUpdateEvent', Optional[str]], None], + callback: Callable[["HeapStatsUpdateEvent", Optional[str]], None], ) -> None: """ Register a callback for heapStatsUpdate events. - + If heap objects tracking has been started then backend may send update for one or more fragments - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -49,28 +56,28 @@ def heapStatsUpdate( def lastSeenObjectId( self, - callback: Callable[['LastSeenObjectIdEvent', Optional[str]], None], + callback: Callable[["LastSeenObjectIdEvent", Optional[str]], None], ) -> None: """ - Register a callback for lastSeenObjectId events. - - If heap objects tracking has been started then backend regularly sends a current value for last -seen object id and corresponding timestamp. If the were changes in the heap since last event -then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for lastSeenObjectId events. + + If heap objects tracking has been started then backend regularly sends a current value for last + seen object id and corresponding timestamp. If the were changes in the heap since last event + then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("HeapProfiler.lastSeenObjectId", callback) def reportHeapSnapshotProgress( self, - callback: Callable[['ReportHeapSnapshotProgressEvent', Optional[str]], None], + callback: Callable[["ReportHeapSnapshotProgressEvent", Optional[str]], None], ) -> None: """ Register a callback for reportHeapSnapshotProgress events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -79,14 +86,13 @@ def reportHeapSnapshotProgress( def resetProfiles( self, - callback: Callable[['ResetProfilesEvent', Optional[str]], None], + callback: Callable[["ResetProfilesEvent", Optional[str]], None], ) -> None: """ Register a callback for resetProfiles events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("HeapProfiler.resetProfiles", callback) - diff --git a/cdp_use/cdp/heapprofiler/types.py b/cdp_use/cdp/heapprofiler/types.py index 02ce8c3..20db807 100644 --- a/cdp_use/cdp/heapprofiler/types.py +++ b/cdp_use/cdp/heapprofiler/types.py @@ -16,7 +16,6 @@ """Heap snapshot object id.""" - class SamplingHeapProfileNode(TypedDict): """Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.""" @@ -30,7 +29,6 @@ class SamplingHeapProfileNode(TypedDict): """Child nodes.""" - class SamplingHeapProfileSample(TypedDict): """A single sample from a sampling profile.""" @@ -43,7 +41,6 @@ class SamplingHeapProfileSample(TypedDict): between startSampling and stopSampling.""" - class SamplingHeapProfile(TypedDict): """Sampling profile.""" diff --git a/cdp_use/cdp/indexeddb/commands.py b/cdp_use/cdp/indexeddb/commands.py index 5dd38d4..975279e 100644 --- a/cdp_use/cdp/indexeddb/commands.py +++ b/cdp_use/cdp/indexeddb/commands.py @@ -15,6 +15,7 @@ from .types import DatabaseWithObjectStores from .types import KeyRange + class ClearObjectStoreParameters(TypedDict): securityOrigin: "NotRequired[str]" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. @@ -29,9 +30,6 @@ class ClearObjectStoreParameters(TypedDict): """Object store name.""" - - - class DeleteDatabaseParameters(TypedDict): securityOrigin: "NotRequired[str]" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. @@ -44,9 +42,6 @@ class DeleteDatabaseParameters(TypedDict): """Database name.""" - - - class DeleteObjectStoreEntriesParameters(TypedDict): securityOrigin: "NotRequired[str]" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. @@ -61,9 +56,6 @@ class DeleteObjectStoreEntriesParameters(TypedDict): """Range of entry keys to delete""" - - - class RequestDataParameters(TypedDict): securityOrigin: "NotRequired[str]" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. @@ -76,8 +68,8 @@ class RequestDataParameters(TypedDict): """Database name.""" objectStoreName: "str" """Object store name.""" - indexName: "str" - """Index name, empty string for object store data requests.""" + indexName: "NotRequired[str]" + """Index name. If not specified, it performs an object store data request.""" skipCount: "int" """Number of records to skip.""" pageSize: "int" @@ -93,7 +85,6 @@ class RequestDataReturns(TypedDict): """If true, there are more entries to fetch in the given range.""" - class GetMetadataParameters(TypedDict): securityOrigin: "NotRequired[str]" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. @@ -117,7 +108,6 @@ class GetMetadataReturns(TypedDict): is true.""" - class RequestDatabaseParameters(TypedDict): securityOrigin: "NotRequired[str]" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. @@ -135,7 +125,6 @@ class RequestDatabaseReturns(TypedDict): """Database with an array of object stores.""" - class RequestDatabaseNamesParameters(TypedDict, total=False): securityOrigin: "str" """At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. diff --git a/cdp_use/cdp/indexeddb/events.py b/cdp_use/cdp/indexeddb/events.py index c826a23..97089b1 100644 --- a/cdp_use/cdp/indexeddb/events.py +++ b/cdp_use/cdp/indexeddb/events.py @@ -5,4 +5,4 @@ """CDP IndexedDB Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/indexeddb/library.py b/cdp_use/cdp/indexeddb/library.py index 895dce3..2f5f47d 100644 --- a/cdp_use/cdp/indexeddb/library.py +++ b/cdp_use/cdp/indexeddb/library.py @@ -22,10 +22,11 @@ from .commands import RequestDatabaseParameters from .commands import RequestDatabaseReturns + class IndexedDBClient: """Client for IndexedDB domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def clearObjectStore( @@ -34,11 +35,14 @@ async def clearObjectStore( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears all entries from an object store.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="IndexedDB.clearObjectStore", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="IndexedDB.clearObjectStore", + params=params, + session_id=session_id, + ), + ) async def deleteDatabase( self, @@ -46,11 +50,14 @@ async def deleteDatabase( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes a database.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="IndexedDB.deleteDatabase", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="IndexedDB.deleteDatabase", + params=params, + session_id=session_id, + ), + ) async def deleteObjectStoreEntries( self, @@ -58,11 +65,14 @@ async def deleteObjectStoreEntries( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Delete a range of entries from an object store""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="IndexedDB.deleteObjectStoreEntries", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="IndexedDB.deleteObjectStoreEntries", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -70,11 +80,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables events from backend.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="IndexedDB.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="IndexedDB.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -82,11 +95,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables events from backend.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="IndexedDB.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="IndexedDB.enable", + params=params, + session_id=session_id, + ), + ) async def requestData( self, @@ -94,11 +110,14 @@ async def requestData( session_id: Optional[str] = None, ) -> "RequestDataReturns": """Requests data from object store or index.""" - return cast("RequestDataReturns", await self._client.send_raw( - method="IndexedDB.requestData", - params=params, - session_id=session_id, - )) + return cast( + "RequestDataReturns", + await self._client.send_raw( + method="IndexedDB.requestData", + params=params, + session_id=session_id, + ), + ) async def getMetadata( self, @@ -106,11 +125,14 @@ async def getMetadata( session_id: Optional[str] = None, ) -> "GetMetadataReturns": """Gets metadata of an object store.""" - return cast("GetMetadataReturns", await self._client.send_raw( - method="IndexedDB.getMetadata", - params=params, - session_id=session_id, - )) + return cast( + "GetMetadataReturns", + await self._client.send_raw( + method="IndexedDB.getMetadata", + params=params, + session_id=session_id, + ), + ) async def requestDatabase( self, @@ -118,11 +140,14 @@ async def requestDatabase( session_id: Optional[str] = None, ) -> "RequestDatabaseReturns": """Requests database with given name in given frame.""" - return cast("RequestDatabaseReturns", await self._client.send_raw( - method="IndexedDB.requestDatabase", - params=params, - session_id=session_id, - )) + return cast( + "RequestDatabaseReturns", + await self._client.send_raw( + method="IndexedDB.requestDatabase", + params=params, + session_id=session_id, + ), + ) async def requestDatabaseNames( self, @@ -130,10 +155,11 @@ async def requestDatabaseNames( session_id: Optional[str] = None, ) -> "RequestDatabaseNamesReturns": """Requests database names for given security origin.""" - return cast("RequestDatabaseNamesReturns", await self._client.send_raw( - method="IndexedDB.requestDatabaseNames", - params=params, - session_id=session_id, - )) - - + return cast( + "RequestDatabaseNamesReturns", + await self._client.send_raw( + method="IndexedDB.requestDatabaseNames", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/indexeddb/registration.py b/cdp_use/cdp/indexeddb/registration.py index 344fc20..8a4dfa0 100644 --- a/cdp_use/cdp/indexeddb/registration.py +++ b/cdp_use/cdp/indexeddb/registration.py @@ -5,4 +5,4 @@ """CDP IndexedDB Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/indexeddb/types.py b/cdp_use/cdp/indexeddb/types.py index 8d5ca76..a9e7543 100644 --- a/cdp_use/cdp/indexeddb/types.py +++ b/cdp_use/cdp/indexeddb/types.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: from ..runtime.types import RemoteObject + class DatabaseWithObjectStores(TypedDict): """Database with an array of object stores.""" @@ -24,7 +25,6 @@ class DatabaseWithObjectStores(TypedDict): """Object stores in this database.""" - class ObjectStore(TypedDict): """Object store.""" @@ -38,7 +38,6 @@ class ObjectStore(TypedDict): """Indexes in this object store.""" - class ObjectStoreIndex(TypedDict): """Object store index.""" @@ -52,7 +51,6 @@ class ObjectStoreIndex(TypedDict): """If true, index allows multiple entries for a key.""" - class Key(TypedDict): """Key.""" @@ -68,7 +66,6 @@ class Key(TypedDict): """Array value.""" - class KeyRange(TypedDict): """Key range.""" @@ -82,7 +79,6 @@ class KeyRange(TypedDict): """If true upper bound is open.""" - class DataEntry(TypedDict): """Data entry.""" @@ -94,7 +90,6 @@ class DataEntry(TypedDict): """Value object.""" - class KeyPath(TypedDict): """Key path.""" diff --git a/cdp_use/cdp/input/commands.py b/cdp_use/cdp/input/commands.py index e712c91..80650d6 100644 --- a/cdp_use/cdp/input/commands.py +++ b/cdp_use/cdp/input/commands.py @@ -16,6 +16,7 @@ from .types import TimeSinceEpoch from .types import TouchPoint + class DispatchDragEventParameters(TypedDict): type: "str" """Type of the drag event.""" @@ -30,9 +31,6 @@ class DispatchDragEventParameters(TypedDict): (default: 0).""" - - - class DispatchKeyEventParameters(TypedDict): type: "str" """Type of the key event.""" @@ -73,17 +71,11 @@ class DispatchKeyEventParameters(TypedDict): See https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h for valid command names.""" - - - class InsertTextParameters(TypedDict): text: "str" """The text to insert.""" - - - class ImeSetCompositionParameters(TypedDict): text: "str" """The text to insert""" @@ -97,9 +89,6 @@ class ImeSetCompositionParameters(TypedDict): """replacement end""" - - - class DispatchMouseEventParameters(TypedDict): type: "str" """Type of the mouse event.""" @@ -138,9 +127,6 @@ class DispatchMouseEventParameters(TypedDict): """Pointer type (default: \"mouse\").""" - - - class DispatchTouchEventParameters(TypedDict): type: "str" """Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while @@ -156,9 +142,6 @@ class DispatchTouchEventParameters(TypedDict): """Time at which the event occurred.""" - - - class EmulateTouchFromMouseEventParameters(TypedDict): type: "str" """Type of the mouse event.""" @@ -181,24 +164,15 @@ class EmulateTouchFromMouseEventParameters(TypedDict): """Number of times the mouse button was clicked (default: 0).""" - - - class SetIgnoreInputEventsParameters(TypedDict): ignore: "bool" """Ignores input events processing when set to true.""" - - - class SetInterceptDragsParameters(TypedDict): enabled: "bool" - - - class SynthesizePinchGestureParameters(TypedDict): x: "float" """X coordinate of the start of the gesture in CSS pixels.""" @@ -213,9 +187,6 @@ class SynthesizePinchGestureParameters(TypedDict): for the preferred input type).""" - - - class SynthesizeScrollGestureParameters(TypedDict): x: "float" """X coordinate of the start of the gesture in CSS pixels.""" @@ -246,9 +217,6 @@ class SynthesizeScrollGestureParameters(TypedDict): """The name of the interaction markers to generate, if not empty (default: \"\").""" - - - class SynthesizeTapGestureParameters(TypedDict): x: "float" """X coordinate of the start of the gesture in CSS pixels.""" @@ -261,5 +229,3 @@ class SynthesizeTapGestureParameters(TypedDict): gestureSourceType: "NotRequired[GestureSourceType]" """Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type).""" - - diff --git a/cdp_use/cdp/input/events.py b/cdp_use/cdp/input/events.py index 4bb9a73..efcbf25 100644 --- a/cdp_use/cdp/input/events.py +++ b/cdp_use/cdp/input/events.py @@ -13,5 +13,7 @@ """Emitted only when `Input.setInterceptDrags` is enabled. Use this data with `Input.dispatchDragEvent` to restore normal drag and drop behavior.""" + + class DragInterceptedEvent(TypedDict): data: "DragData" diff --git a/cdp_use/cdp/input/library.py b/cdp_use/cdp/input/library.py index f02da06..0ee48e1 100644 --- a/cdp_use/cdp/input/library.py +++ b/cdp_use/cdp/input/library.py @@ -23,10 +23,11 @@ from .commands import SynthesizeScrollGestureParameters from .commands import SynthesizeTapGestureParameters + class InputClient: """Client for Input domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def dispatchDragEvent( @@ -35,11 +36,14 @@ async def dispatchDragEvent( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Dispatches a drag event into the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.dispatchDragEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.dispatchDragEvent", + params=params, + session_id=session_id, + ), + ) async def dispatchKeyEvent( self, @@ -47,11 +51,14 @@ async def dispatchKeyEvent( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Dispatches a key event to the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.dispatchKeyEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.dispatchKeyEvent", + params=params, + session_id=session_id, + ), + ) async def insertText( self, @@ -59,12 +66,15 @@ async def insertText( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """This method emulates inserting text that doesn't come from a key press, -for example an emoji keyboard or an IME.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.insertText", - params=params, - session_id=session_id, - )) + for example an emoji keyboard or an IME.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.insertText", + params=params, + session_id=session_id, + ), + ) async def imeSetComposition( self, @@ -72,13 +82,16 @@ async def imeSetComposition( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """This method sets the current candidate text for IME. -Use imeCommitComposition to commit the final text. -Use imeSetComposition with empty string as text to cancel composition.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.imeSetComposition", - params=params, - session_id=session_id, - )) + Use imeCommitComposition to commit the final text. + Use imeSetComposition with empty string as text to cancel composition.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.imeSetComposition", + params=params, + session_id=session_id, + ), + ) async def dispatchMouseEvent( self, @@ -86,11 +99,14 @@ async def dispatchMouseEvent( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Dispatches a mouse event to the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.dispatchMouseEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.dispatchMouseEvent", + params=params, + session_id=session_id, + ), + ) async def dispatchTouchEvent( self, @@ -98,11 +114,14 @@ async def dispatchTouchEvent( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Dispatches a touch event to the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.dispatchTouchEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.dispatchTouchEvent", + params=params, + session_id=session_id, + ), + ) async def cancelDragging( self, @@ -110,11 +129,14 @@ async def cancelDragging( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Cancels any active dragging in the page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.cancelDragging", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.cancelDragging", + params=params, + session_id=session_id, + ), + ) async def emulateTouchFromMouseEvent( self, @@ -122,11 +144,14 @@ async def emulateTouchFromMouseEvent( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Emulates touch event from the mouse event parameters.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.emulateTouchFromMouseEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.emulateTouchFromMouseEvent", + params=params, + session_id=session_id, + ), + ) async def setIgnoreInputEvents( self, @@ -134,11 +159,14 @@ async def setIgnoreInputEvents( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Ignores input events (useful while auditing page).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.setIgnoreInputEvents", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.setIgnoreInputEvents", + params=params, + session_id=session_id, + ), + ) async def setInterceptDrags( self, @@ -146,12 +174,15 @@ async def setInterceptDrags( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Prevents default drag and drop behavior and instead emits `Input.dragIntercepted` events. -Drag and drop behavior can be directly controlled via `Input.dispatchDragEvent`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.setInterceptDrags", - params=params, - session_id=session_id, - )) + Drag and drop behavior can be directly controlled via `Input.dispatchDragEvent`.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.setInterceptDrags", + params=params, + session_id=session_id, + ), + ) async def synthesizePinchGesture( self, @@ -159,11 +190,14 @@ async def synthesizePinchGesture( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Synthesizes a pinch gesture over a time period by issuing appropriate touch events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.synthesizePinchGesture", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.synthesizePinchGesture", + params=params, + session_id=session_id, + ), + ) async def synthesizeScrollGesture( self, @@ -171,11 +205,14 @@ async def synthesizeScrollGesture( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Synthesizes a scroll gesture over a time period by issuing appropriate touch events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.synthesizeScrollGesture", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.synthesizeScrollGesture", + params=params, + session_id=session_id, + ), + ) async def synthesizeTapGesture( self, @@ -183,10 +220,11 @@ async def synthesizeTapGesture( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Synthesizes a tap gesture over a time period by issuing appropriate touch events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Input.synthesizeTapGesture", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Input.synthesizeTapGesture", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/input/registration.py b/cdp_use/cdp/input/registration.py index 945ed30..bbcc826 100644 --- a/cdp_use/cdp/input/registration.py +++ b/cdp_use/cdp/input/registration.py @@ -12,26 +12,26 @@ from ..registry import EventRegistry from .events import DragInterceptedEvent + class InputRegistration: """Event registration interface for Input domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Input" def dragIntercepted( self, - callback: Callable[['DragInterceptedEvent', Optional[str]], None], + callback: Callable[["DragInterceptedEvent", Optional[str]], None], ) -> None: """ - Register a callback for dragIntercepted events. - - Emitted only when `Input.setInterceptDrags` is enabled. Use this data with `Input.dispatchDragEvent` to -restore normal drag and drop behavior. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for dragIntercepted events. + + Emitted only when `Input.setInterceptDrags` is enabled. Use this data with `Input.dispatchDragEvent` to + restore normal drag and drop behavior. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Input.dragIntercepted", callback) - diff --git a/cdp_use/cdp/input/types.py b/cdp_use/cdp/input/types.py index 54f09d9..6db141b 100644 --- a/cdp_use/cdp/input/types.py +++ b/cdp_use/cdp/input/types.py @@ -8,6 +8,7 @@ from typing_extensions import Literal from typing_extensions import NotRequired, TypedDict + class TouchPoint(TypedDict): x: "float" """X coordinate of the event relative to the main frame's viewport in CSS pixels.""" @@ -34,20 +35,16 @@ class TouchPoint(TypedDict): """Identifier used to track touch sources between events, must be unique within an event.""" - GestureSourceType = Literal["default", "touch", "mouse"] - MouseButton = Literal["none", "left", "middle", "right", "back", "forward"] - TimeSinceEpoch = float """UTC time in seconds, counted from January 1, 1970.""" - class DragDataItem(TypedDict): mimeType: "str" """Mime type of the dragged data.""" @@ -61,7 +58,6 @@ class DragDataItem(TypedDict): == \"text/html\".""" - class DragData(TypedDict): items: "List[DragDataItem]" files: "NotRequired[List[str]]" diff --git a/cdp_use/cdp/inspector/commands.py b/cdp_use/cdp/inspector/commands.py index 761bffc..bbcaa03 100644 --- a/cdp_use/cdp/inspector/commands.py +++ b/cdp_use/cdp/inspector/commands.py @@ -5,4 +5,4 @@ """CDP Inspector Domain Commands""" -# No commands defined for this domain \ No newline at end of file +# No commands defined for this domain diff --git a/cdp_use/cdp/inspector/events.py b/cdp_use/cdp/inspector/events.py index b133d95..6630f9a 100644 --- a/cdp_use/cdp/inspector/events.py +++ b/cdp_use/cdp/inspector/events.py @@ -7,18 +7,29 @@ from typing_extensions import TypedDict """Fired when remote debugging connection is about to be terminated. Contains detach reason.""" + + class DetachedEvent(TypedDict): reason: "str" """The reason why connection has been terminated.""" - """Fired when debugging target has crashed""" + + class TargetCrashedEvent(TypedDict): pass - """Fired when debugging target has reloaded after crash""" + + class TargetReloadedAfterCrashEvent(TypedDict): pass + + +"""Fired on worker targets when main worker script and any imported scripts have been evaluated.""" + + +class WorkerScriptLoadedEvent(TypedDict): + pass diff --git a/cdp_use/cdp/inspector/library.py b/cdp_use/cdp/inspector/library.py index 4d29ffe..b5f5365 100644 --- a/cdp_use/cdp/inspector/library.py +++ b/cdp_use/cdp/inspector/library.py @@ -11,10 +11,11 @@ if TYPE_CHECKING: from ...client import CDPClient + class InspectorClient: """Client for Inspector domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -23,11 +24,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables inspector domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Inspector.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Inspector.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -35,10 +39,11 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables inspector domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Inspector.enable", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Inspector.enable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/inspector/registration.py b/cdp_use/cdp/inspector/registration.py index 377d1a1..d01734e 100644 --- a/cdp_use/cdp/inspector/registration.py +++ b/cdp_use/cdp/inspector/registration.py @@ -10,24 +10,30 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import DetachedEvent, TargetCrashedEvent, TargetReloadedAfterCrashEvent + from .events import ( + DetachedEvent, + TargetCrashedEvent, + TargetReloadedAfterCrashEvent, + WorkerScriptLoadedEvent, + ) + class InspectorRegistration: """Event registration interface for Inspector domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Inspector" def detached( self, - callback: Callable[['DetachedEvent', Optional[str]], None], + callback: Callable[["DetachedEvent", Optional[str]], None], ) -> None: """ Register a callback for detached events. - + Fired when remote debugging connection is about to be terminated. Contains detach reason. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -36,13 +42,13 @@ def detached( def targetCrashed( self, - callback: Callable[['TargetCrashedEvent', Optional[str]], None], + callback: Callable[["TargetCrashedEvent", Optional[str]], None], ) -> None: """ Register a callback for targetCrashed events. - + Fired when debugging target has crashed - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -51,16 +57,30 @@ def targetCrashed( def targetReloadedAfterCrash( self, - callback: Callable[['TargetReloadedAfterCrashEvent', Optional[str]], None], + callback: Callable[["TargetReloadedAfterCrashEvent", Optional[str]], None], ) -> None: """ Register a callback for targetReloadedAfterCrash events. - + Fired when debugging target has reloaded after crash - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Inspector.targetReloadedAfterCrash", callback) + def workerScriptLoaded( + self, + callback: Callable[["WorkerScriptLoadedEvent", Optional[str]], None], + ) -> None: + """ + Register a callback for workerScriptLoaded events. + + Fired on worker targets when main worker script and any imported scripts have been evaluated. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("Inspector.workerScriptLoaded", callback) diff --git a/cdp_use/cdp/inspector/types.py b/cdp_use/cdp/inspector/types.py index f15d846..3c78d01 100644 --- a/cdp_use/cdp/inspector/types.py +++ b/cdp_use/cdp/inspector/types.py @@ -5,4 +5,4 @@ """CDP Inspector Domain Types""" -# No types defined for this domain \ No newline at end of file +# No types defined for this domain diff --git a/cdp_use/cdp/io/commands.py b/cdp_use/cdp/io/commands.py index b90708c..112a62d 100644 --- a/cdp_use/cdp/io/commands.py +++ b/cdp_use/cdp/io/commands.py @@ -12,14 +12,12 @@ from ..runtime.types import RemoteObjectId from .types import StreamHandle + class CloseParameters(TypedDict): handle: "StreamHandle" """Handle of the stream to close.""" - - - class ReadParameters(TypedDict): handle: "StreamHandle" """Handle of the stream to read.""" @@ -39,7 +37,6 @@ class ReadReturns(TypedDict): """Set if the end-of-file condition occurred while reading.""" - class ResolveBlobParameters(TypedDict): objectId: "RemoteObjectId" """Object id of a Blob object wrapper.""" diff --git a/cdp_use/cdp/io/events.py b/cdp_use/cdp/io/events.py index 746cf62..04adbe0 100644 --- a/cdp_use/cdp/io/events.py +++ b/cdp_use/cdp/io/events.py @@ -5,4 +5,4 @@ """CDP IO Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/io/library.py b/cdp_use/cdp/io/library.py index fab9e2f..86c1786 100644 --- a/cdp_use/cdp/io/library.py +++ b/cdp_use/cdp/io/library.py @@ -16,10 +16,11 @@ from .commands import ResolveBlobParameters from .commands import ResolveBlobReturns + class IOClient: """Client for IO domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def close( @@ -28,11 +29,14 @@ async def close( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Close the stream, discard any temporary backing storage.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="IO.close", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="IO.close", + params=params, + session_id=session_id, + ), + ) async def read( self, @@ -40,11 +44,14 @@ async def read( session_id: Optional[str] = None, ) -> "ReadReturns": """Read a chunk of the stream""" - return cast("ReadReturns", await self._client.send_raw( - method="IO.read", - params=params, - session_id=session_id, - )) + return cast( + "ReadReturns", + await self._client.send_raw( + method="IO.read", + params=params, + session_id=session_id, + ), + ) async def resolveBlob( self, @@ -52,10 +59,11 @@ async def resolveBlob( session_id: Optional[str] = None, ) -> "ResolveBlobReturns": """Return UUID of Blob object specified by a remote object id.""" - return cast("ResolveBlobReturns", await self._client.send_raw( - method="IO.resolveBlob", - params=params, - session_id=session_id, - )) - - + return cast( + "ResolveBlobReturns", + await self._client.send_raw( + method="IO.resolveBlob", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/io/registration.py b/cdp_use/cdp/io/registration.py index 9c27ba1..9418cfe 100644 --- a/cdp_use/cdp/io/registration.py +++ b/cdp_use/cdp/io/registration.py @@ -5,4 +5,4 @@ """CDP IO Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/io/types.py b/cdp_use/cdp/io/types.py index 084f697..7ae4f0c 100644 --- a/cdp_use/cdp/io/types.py +++ b/cdp_use/cdp/io/types.py @@ -4,7 +4,6 @@ """CDP IO Domain Types""" - StreamHandle = str """This is either obtained from another method or specified as `blob:` where `` is an UUID of a Blob.""" diff --git a/cdp_use/cdp/layertree/commands.py b/cdp_use/cdp/layertree/commands.py index 30d6123..340061f 100644 --- a/cdp_use/cdp/layertree/commands.py +++ b/cdp_use/cdp/layertree/commands.py @@ -16,6 +16,7 @@ from .types import PictureTile from .types import SnapshotId + class CompositingReasonsParameters(TypedDict): layerId: "LayerId" """The id of the layer for which we want to get the reasons it was composited.""" @@ -28,7 +29,6 @@ class CompositingReasonsReturns(TypedDict): """A list of strings specifying reason IDs for the given layer to become composited.""" - class LoadSnapshotParameters(TypedDict): tiles: "List[PictureTile]" """An array of tiles composing the snapshot.""" @@ -39,7 +39,6 @@ class LoadSnapshotReturns(TypedDict): """The id of the snapshot.""" - class MakeSnapshotParameters(TypedDict): layerId: "LayerId" """The id of the layer.""" @@ -50,7 +49,6 @@ class MakeSnapshotReturns(TypedDict): """The id of the layer snapshot.""" - class ProfileSnapshotParameters(TypedDict): snapshotId: "SnapshotId" """The id of the layer snapshot.""" @@ -67,15 +65,11 @@ class ProfileSnapshotReturns(TypedDict): """The array of paint profiles, one per run.""" - class ReleaseSnapshotParameters(TypedDict): snapshotId: "SnapshotId" """The id of the layer snapshot.""" - - - class ReplaySnapshotParameters(TypedDict): snapshotId: "SnapshotId" """The id of the layer snapshot.""" @@ -92,7 +86,6 @@ class ReplaySnapshotReturns(TypedDict): """A data: URL for resulting image.""" - class SnapshotCommandLogParameters(TypedDict): snapshotId: "SnapshotId" """The id of the layer snapshot.""" diff --git a/cdp_use/cdp/layertree/events.py b/cdp_use/cdp/layertree/events.py index c442403..3744f2a 100644 --- a/cdp_use/cdp/layertree/events.py +++ b/cdp_use/cdp/layertree/events.py @@ -14,6 +14,7 @@ from .types import Layer from .types import LayerId + class LayerPaintedEvent(TypedDict): layerId: "LayerId" """The id of the painted layer.""" @@ -21,7 +22,6 @@ class LayerPaintedEvent(TypedDict): """Clip rectangle.""" - class LayerTreeDidChangeEvent(TypedDict, total=False): layers: "List[Layer]" """Layer tree, absent if not in the compositing mode.""" diff --git a/cdp_use/cdp/layertree/library.py b/cdp_use/cdp/layertree/library.py index ac23ee8..cfe704c 100644 --- a/cdp_use/cdp/layertree/library.py +++ b/cdp_use/cdp/layertree/library.py @@ -24,10 +24,11 @@ from .commands import SnapshotCommandLogParameters from .commands import SnapshotCommandLogReturns + class LayerTreeClient: """Client for LayerTree domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def compositingReasons( @@ -36,11 +37,14 @@ async def compositingReasons( session_id: Optional[str] = None, ) -> "CompositingReasonsReturns": """Provides the reasons why the given layer was composited.""" - return cast("CompositingReasonsReturns", await self._client.send_raw( - method="LayerTree.compositingReasons", - params=params, - session_id=session_id, - )) + return cast( + "CompositingReasonsReturns", + await self._client.send_raw( + method="LayerTree.compositingReasons", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -48,11 +52,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables compositing tree inspection.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="LayerTree.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="LayerTree.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -60,11 +67,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables compositing tree inspection.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="LayerTree.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="LayerTree.enable", + params=params, + session_id=session_id, + ), + ) async def loadSnapshot( self, @@ -72,11 +82,14 @@ async def loadSnapshot( session_id: Optional[str] = None, ) -> "LoadSnapshotReturns": """Returns the snapshot identifier.""" - return cast("LoadSnapshotReturns", await self._client.send_raw( - method="LayerTree.loadSnapshot", - params=params, - session_id=session_id, - )) + return cast( + "LoadSnapshotReturns", + await self._client.send_raw( + method="LayerTree.loadSnapshot", + params=params, + session_id=session_id, + ), + ) async def makeSnapshot( self, @@ -84,22 +97,28 @@ async def makeSnapshot( session_id: Optional[str] = None, ) -> "MakeSnapshotReturns": """Returns the layer snapshot identifier.""" - return cast("MakeSnapshotReturns", await self._client.send_raw( - method="LayerTree.makeSnapshot", - params=params, - session_id=session_id, - )) + return cast( + "MakeSnapshotReturns", + await self._client.send_raw( + method="LayerTree.makeSnapshot", + params=params, + session_id=session_id, + ), + ) async def profileSnapshot( self, params: "ProfileSnapshotParameters", session_id: Optional[str] = None, ) -> "ProfileSnapshotReturns": - return cast("ProfileSnapshotReturns", await self._client.send_raw( - method="LayerTree.profileSnapshot", - params=params, - session_id=session_id, - )) + return cast( + "ProfileSnapshotReturns", + await self._client.send_raw( + method="LayerTree.profileSnapshot", + params=params, + session_id=session_id, + ), + ) async def releaseSnapshot( self, @@ -107,11 +126,14 @@ async def releaseSnapshot( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Releases layer snapshot captured by the back-end.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="LayerTree.releaseSnapshot", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="LayerTree.releaseSnapshot", + params=params, + session_id=session_id, + ), + ) async def replaySnapshot( self, @@ -119,11 +141,14 @@ async def replaySnapshot( session_id: Optional[str] = None, ) -> "ReplaySnapshotReturns": """Replays the layer snapshot and returns the resulting bitmap.""" - return cast("ReplaySnapshotReturns", await self._client.send_raw( - method="LayerTree.replaySnapshot", - params=params, - session_id=session_id, - )) + return cast( + "ReplaySnapshotReturns", + await self._client.send_raw( + method="LayerTree.replaySnapshot", + params=params, + session_id=session_id, + ), + ) async def snapshotCommandLog( self, @@ -131,10 +156,11 @@ async def snapshotCommandLog( session_id: Optional[str] = None, ) -> "SnapshotCommandLogReturns": """Replays the layer snapshot and returns canvas log.""" - return cast("SnapshotCommandLogReturns", await self._client.send_raw( - method="LayerTree.snapshotCommandLog", - params=params, - session_id=session_id, - )) - - + return cast( + "SnapshotCommandLogReturns", + await self._client.send_raw( + method="LayerTree.snapshotCommandLog", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/layertree/registration.py b/cdp_use/cdp/layertree/registration.py index 7fbad78..d9beea2 100644 --- a/cdp_use/cdp/layertree/registration.py +++ b/cdp_use/cdp/layertree/registration.py @@ -12,20 +12,21 @@ from ..registry import EventRegistry from .events import LayerPaintedEvent, LayerTreeDidChangeEvent + class LayerTreeRegistration: """Event registration interface for LayerTree domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "LayerTree" def layerPainted( self, - callback: Callable[['LayerPaintedEvent', Optional[str]], None], + callback: Callable[["LayerPaintedEvent", Optional[str]], None], ) -> None: """ Register a callback for layerPainted events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,14 +35,13 @@ def layerPainted( def layerTreeDidChange( self, - callback: Callable[['LayerTreeDidChangeEvent', Optional[str]], None], + callback: Callable[["LayerTreeDidChangeEvent", Optional[str]], None], ) -> None: """ Register a callback for layerTreeDidChange events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("LayerTree.layerTreeDidChange", callback) - diff --git a/cdp_use/cdp/layertree/types.py b/cdp_use/cdp/layertree/types.py index 4d41833..714d70d 100644 --- a/cdp_use/cdp/layertree/types.py +++ b/cdp_use/cdp/layertree/types.py @@ -17,12 +17,10 @@ """Unique Layer identifier.""" - SnapshotId = str """Unique snapshot identifier.""" - class ScrollRect(TypedDict): """Rectangle where scrolling happens on the main thread.""" @@ -32,7 +30,6 @@ class ScrollRect(TypedDict): """Reason for rectangle to force scrolling on the main thread""" - class StickyPositionConstraint(TypedDict): """Sticky position constraints.""" @@ -46,7 +43,6 @@ class StickyPositionConstraint(TypedDict): """The nearest sticky layer that shifts the containing block""" - class PictureTile(TypedDict): """Serialized fragment of layer picture along with its offset within the layer.""" @@ -58,7 +54,6 @@ class PictureTile(TypedDict): """Base64-encoded snapshot data. (Encoded as a base64 string when passed over JSON)""" - class Layer(TypedDict): """Information about a compositing layer.""" @@ -97,6 +92,5 @@ class Layer(TypedDict): """Sticky position constraint information""" - PaintProfile = List[float] """Array of timings, one per paint step.""" diff --git a/cdp_use/cdp/library.py b/cdp_use/cdp/library.py index ed14529..1d6d9a2 100644 --- a/cdp_use/cdp/library.py +++ b/cdp_use/cdp/library.py @@ -9,225 +9,279 @@ if TYPE_CHECKING: from ..client import CDPClient + class CDPLibrary: """Main CDP library with domain-specific clients.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client # Console domain from .console.library import ConsoleClient + self.Console = ConsoleClient(client) # Debugger domain from .debugger.library import DebuggerClient + self.Debugger = DebuggerClient(client) # HeapProfiler domain from .heapprofiler.library import HeapProfilerClient + self.HeapProfiler = HeapProfilerClient(client) # Profiler domain from .profiler.library import ProfilerClient + self.Profiler = ProfilerClient(client) # Runtime domain from .runtime.library import RuntimeClient + self.Runtime = RuntimeClient(client) # Schema domain from .schema.library import SchemaClient + self.Schema = SchemaClient(client) # Accessibility domain from .accessibility.library import AccessibilityClient + self.Accessibility = AccessibilityClient(client) # Animation domain from .animation.library import AnimationClient + self.Animation = AnimationClient(client) # Audits domain from .audits.library import AuditsClient + self.Audits = AuditsClient(client) # Autofill domain from .autofill.library import AutofillClient + self.Autofill = AutofillClient(client) # BackgroundService domain from .backgroundservice.library import BackgroundServiceClient + self.BackgroundService = BackgroundServiceClient(client) # BluetoothEmulation domain from .bluetoothemulation.library import BluetoothEmulationClient + self.BluetoothEmulation = BluetoothEmulationClient(client) # Browser domain from .browser.library import BrowserClient + self.Browser = BrowserClient(client) # CSS domain from .css.library import CSSClient + self.CSS = CSSClient(client) # CacheStorage domain from .cachestorage.library import CacheStorageClient + self.CacheStorage = CacheStorageClient(client) # Cast domain from .cast.library import CastClient + self.Cast = CastClient(client) # DOM domain from .dom.library import DOMClient + self.DOM = DOMClient(client) # DOMDebugger domain from .domdebugger.library import DOMDebuggerClient + self.DOMDebugger = DOMDebuggerClient(client) # DOMSnapshot domain from .domsnapshot.library import DOMSnapshotClient + self.DOMSnapshot = DOMSnapshotClient(client) # DOMStorage domain from .domstorage.library import DOMStorageClient + self.DOMStorage = DOMStorageClient(client) # DeviceAccess domain from .deviceaccess.library import DeviceAccessClient + self.DeviceAccess = DeviceAccessClient(client) # DeviceOrientation domain from .deviceorientation.library import DeviceOrientationClient + self.DeviceOrientation = DeviceOrientationClient(client) # Emulation domain from .emulation.library import EmulationClient + self.Emulation = EmulationClient(client) # EventBreakpoints domain from .eventbreakpoints.library import EventBreakpointsClient + self.EventBreakpoints = EventBreakpointsClient(client) # Extensions domain from .extensions.library import ExtensionsClient + self.Extensions = ExtensionsClient(client) # FedCm domain from .fedcm.library import FedCmClient + self.FedCm = FedCmClient(client) # Fetch domain from .fetch.library import FetchClient + self.Fetch = FetchClient(client) # FileSystem domain from .filesystem.library import FileSystemClient + self.FileSystem = FileSystemClient(client) # HeadlessExperimental domain from .headlessexperimental.library import HeadlessExperimentalClient + self.HeadlessExperimental = HeadlessExperimentalClient(client) # IO domain from .io.library import IOClient + self.IO = IOClient(client) # IndexedDB domain from .indexeddb.library import IndexedDBClient + self.IndexedDB = IndexedDBClient(client) # Input domain from .input.library import InputClient + self.Input = InputClient(client) # Inspector domain from .inspector.library import InspectorClient + self.Inspector = InspectorClient(client) # LayerTree domain from .layertree.library import LayerTreeClient + self.LayerTree = LayerTreeClient(client) # Log domain from .log.library import LogClient + self.Log = LogClient(client) # Media domain from .media.library import MediaClient + self.Media = MediaClient(client) # Memory domain from .memory.library import MemoryClient + self.Memory = MemoryClient(client) # Network domain from .network.library import NetworkClient + self.Network = NetworkClient(client) # Overlay domain from .overlay.library import OverlayClient + self.Overlay = OverlayClient(client) # PWA domain from .pwa.library import PWAClient + self.PWA = PWAClient(client) # Page domain from .page.library import PageClient + self.Page = PageClient(client) # Performance domain from .performance.library import PerformanceClient + self.Performance = PerformanceClient(client) # PerformanceTimeline domain from .performancetimeline.library import PerformanceTimelineClient + self.PerformanceTimeline = PerformanceTimelineClient(client) # Preload domain from .preload.library import PreloadClient + self.Preload = PreloadClient(client) # Security domain from .security.library import SecurityClient + self.Security = SecurityClient(client) # ServiceWorker domain from .serviceworker.library import ServiceWorkerClient + self.ServiceWorker = ServiceWorkerClient(client) # Storage domain from .storage.library import StorageClient + self.Storage = StorageClient(client) # SystemInfo domain from .systeminfo.library import SystemInfoClient + self.SystemInfo = SystemInfoClient(client) # Target domain from .target.library import TargetClient + self.Target = TargetClient(client) # Tethering domain from .tethering.library import TetheringClient + self.Tethering = TetheringClient(client) # Tracing domain from .tracing.library import TracingClient + self.Tracing = TracingClient(client) # WebAudio domain from .webaudio.library import WebAudioClient + self.WebAudio = WebAudioClient(client) # WebAuthn domain from .webauthn.library import WebAuthnClient + self.WebAuthn = WebAuthnClient(client) # BrowserUse domain from .browseruse.library import BrowserUseClient - self.BrowserUse = BrowserUseClient(client) + self.BrowserUse = BrowserUseClient(client) diff --git a/cdp_use/cdp/log/commands.py b/cdp_use/cdp/log/commands.py index acb9be2..c8c9b9d 100644 --- a/cdp_use/cdp/log/commands.py +++ b/cdp_use/cdp/log/commands.py @@ -12,8 +12,7 @@ if TYPE_CHECKING: from .types import ViolationSetting + class StartViolationsReportParameters(TypedDict): config: "List[ViolationSetting]" """Configuration for violations.""" - - diff --git a/cdp_use/cdp/log/events.py b/cdp_use/cdp/log/events.py index b99751b..c23baa9 100644 --- a/cdp_use/cdp/log/events.py +++ b/cdp_use/cdp/log/events.py @@ -12,6 +12,8 @@ from .types import LogEntry """Issued when new message was logged.""" + + class EntryAddedEvent(TypedDict): entry: "LogEntry" """The entry.""" diff --git a/cdp_use/cdp/log/library.py b/cdp_use/cdp/log/library.py index 05ee22d..2626a73 100644 --- a/cdp_use/cdp/log/library.py +++ b/cdp_use/cdp/log/library.py @@ -12,10 +12,11 @@ from ...client import CDPClient from .commands import StartViolationsReportParameters + class LogClient: """Client for Log domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def clear( @@ -24,11 +25,14 @@ async def clear( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the log.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Log.clear", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Log.clear", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -36,11 +40,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables log domain, prevents further log entries from being reported to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Log.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Log.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -48,12 +55,15 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables log domain, sends the entries collected so far to the client by means of the -`entryAdded` notification.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Log.enable", - params=params, - session_id=session_id, - )) + `entryAdded` notification.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Log.enable", + params=params, + session_id=session_id, + ), + ) async def startViolationsReport( self, @@ -61,11 +71,14 @@ async def startViolationsReport( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """start violation reporting.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Log.startViolationsReport", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Log.startViolationsReport", + params=params, + session_id=session_id, + ), + ) async def stopViolationsReport( self, @@ -73,10 +86,11 @@ async def stopViolationsReport( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stop violation reporting.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Log.stopViolationsReport", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Log.stopViolationsReport", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/log/registration.py b/cdp_use/cdp/log/registration.py index 9eb6223..6e798e7 100644 --- a/cdp_use/cdp/log/registration.py +++ b/cdp_use/cdp/log/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import EntryAddedEvent + class LogRegistration: """Event registration interface for Log domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Log" def entryAdded( self, - callback: Callable[['EntryAddedEvent', Optional[str]], None], + callback: Callable[["EntryAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for entryAdded events. - + Issued when new message was logged. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Log.entryAdded", callback) - diff --git a/cdp_use/cdp/log/types.py b/cdp_use/cdp/log/types.py index 811188e..38f26bd 100644 --- a/cdp_use/cdp/log/types.py +++ b/cdp_use/cdp/log/types.py @@ -15,6 +15,7 @@ from ..runtime.types import StackTrace from ..runtime.types import Timestamp + class LogEntry(TypedDict): """Log entry.""" @@ -41,7 +42,6 @@ class LogEntry(TypedDict): """Call arguments.""" - class ViolationSetting(TypedDict): """Violation configuration setting.""" diff --git a/cdp_use/cdp/media/commands.py b/cdp_use/cdp/media/commands.py index 7d6e12d..11e4828 100644 --- a/cdp_use/cdp/media/commands.py +++ b/cdp_use/cdp/media/commands.py @@ -5,4 +5,4 @@ """CDP Media Domain Commands""" -# No commands defined for this domain \ No newline at end of file +# No commands defined for this domain diff --git a/cdp_use/cdp/media/events.py b/cdp_use/cdp/media/events.py index 1c893cb..70a5fa2 100644 --- a/cdp_use/cdp/media/events.py +++ b/cdp_use/cdp/media/events.py @@ -19,36 +19,42 @@ """This can be called multiple times, and can be used to set / override / remove player properties. A null propValue indicates removal.""" + + class PlayerPropertiesChangedEvent(TypedDict): playerId: "PlayerId" properties: "List[PlayerProperty]" - """Send events as a list, allowing them to be batched on the browser for less congestion. If batched, events must ALWAYS be in chronological order.""" + + class PlayerEventsAddedEvent(TypedDict): playerId: "PlayerId" events: "List[PlayerEvent]" - """Send a list of any messages that need to be delivered.""" + + class PlayerMessagesLoggedEvent(TypedDict): playerId: "PlayerId" messages: "List[PlayerMessage]" - """Send a list of any errors that need to be delivered.""" + + class PlayerErrorsRaisedEvent(TypedDict): playerId: "PlayerId" errors: "List[PlayerError]" - """Called whenever a player is created, or when a new agent joins and receives a list of active players. If an agent is restored, it will receive one event for each active player.""" + + class PlayerCreatedEvent(TypedDict): player: "Player" diff --git a/cdp_use/cdp/media/library.py b/cdp_use/cdp/media/library.py index d9c819c..dd8a681 100644 --- a/cdp_use/cdp/media/library.py +++ b/cdp_use/cdp/media/library.py @@ -11,10 +11,11 @@ if TYPE_CHECKING: from ...client import CDPClient + class MediaClient: """Client for Media domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -23,11 +24,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables the Media domain""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Media.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Media.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -35,10 +39,11 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables the Media domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Media.disable", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Media.disable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/media/registration.py b/cdp_use/cdp/media/registration.py index 93d94b9..e6ecd9d 100644 --- a/cdp_use/cdp/media/registration.py +++ b/cdp_use/cdp/media/registration.py @@ -10,56 +10,63 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import PlayerCreatedEvent, PlayerErrorsRaisedEvent, PlayerEventsAddedEvent, PlayerMessagesLoggedEvent, PlayerPropertiesChangedEvent + from .events import ( + PlayerCreatedEvent, + PlayerErrorsRaisedEvent, + PlayerEventsAddedEvent, + PlayerMessagesLoggedEvent, + PlayerPropertiesChangedEvent, + ) + class MediaRegistration: """Event registration interface for Media domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Media" def playerPropertiesChanged( self, - callback: Callable[['PlayerPropertiesChangedEvent', Optional[str]], None], + callback: Callable[["PlayerPropertiesChangedEvent", Optional[str]], None], ) -> None: """ - Register a callback for playerPropertiesChanged events. - - This can be called multiple times, and can be used to set / override / -remove player properties. A null propValue indicates removal. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for playerPropertiesChanged events. + + This can be called multiple times, and can be used to set / override / + remove player properties. A null propValue indicates removal. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Media.playerPropertiesChanged", callback) def playerEventsAdded( self, - callback: Callable[['PlayerEventsAddedEvent', Optional[str]], None], + callback: Callable[["PlayerEventsAddedEvent", Optional[str]], None], ) -> None: """ - Register a callback for playerEventsAdded events. - - Send events as a list, allowing them to be batched on the browser for less -congestion. If batched, events must ALWAYS be in chronological order. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for playerEventsAdded events. + + Send events as a list, allowing them to be batched on the browser for less + congestion. If batched, events must ALWAYS be in chronological order. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Media.playerEventsAdded", callback) def playerMessagesLogged( self, - callback: Callable[['PlayerMessagesLoggedEvent', Optional[str]], None], + callback: Callable[["PlayerMessagesLoggedEvent", Optional[str]], None], ) -> None: """ Register a callback for playerMessagesLogged events. - + Send a list of any messages that need to be delivered. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -68,13 +75,13 @@ def playerMessagesLogged( def playerErrorsRaised( self, - callback: Callable[['PlayerErrorsRaisedEvent', Optional[str]], None], + callback: Callable[["PlayerErrorsRaisedEvent", Optional[str]], None], ) -> None: """ Register a callback for playerErrorsRaised events. - + Send a list of any errors that need to be delivered. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -83,18 +90,17 @@ def playerErrorsRaised( def playerCreated( self, - callback: Callable[['PlayerCreatedEvent', Optional[str]], None], + callback: Callable[["PlayerCreatedEvent", Optional[str]], None], ) -> None: """ - Register a callback for playerCreated events. - - Called whenever a player is created, or when a new agent joins and receives -a list of active players. If an agent is restored, it will receive one -event for each active player. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for playerCreated events. + + Called whenever a player is created, or when a new agent joins and receives + a list of active players. If an agent is restored, it will receive one + event for each active player. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Media.playerCreated", callback) - diff --git a/cdp_use/cdp/media/types.py b/cdp_use/cdp/media/types.py index 800468b..e7bd4e0 100644 --- a/cdp_use/cdp/media/types.py +++ b/cdp_use/cdp/media/types.py @@ -16,14 +16,12 @@ """Players will get an ID that is unique within the agent context.""" - Timestamp = float - class PlayerMessage(TypedDict): """Have one type per entry in MediaLogRecord::Type -Corresponds to kMessage""" + Corresponds to kMessage""" level: "str" """Keep in sync with MediaLogMessageLevel @@ -38,7 +36,6 @@ class PlayerMessage(TypedDict): message: "str" - class PlayerProperty(TypedDict): """Corresponds to kMediaPropertyChange""" @@ -46,7 +43,6 @@ class PlayerProperty(TypedDict): value: "str" - class PlayerEvent(TypedDict): """Corresponds to kMediaEventTriggered""" @@ -54,16 +50,14 @@ class PlayerEvent(TypedDict): value: "str" - class PlayerErrorSourceLocation(TypedDict): """Represents logged source line numbers reported in an error. -NOTE: file and line are from chromium c++ implementation code, not js.""" + NOTE: file and line are from chromium c++ implementation code, not js.""" file: "str" line: "int" - class PlayerError(TypedDict): """Corresponds to kMediaError""" @@ -80,7 +74,6 @@ class PlayerError(TypedDict): """Extra data attached to an error, such as an HRESULT, Video Codec, etc.""" - class Player(TypedDict): playerId: "PlayerId" domNodeId: "NotRequired[BackendNodeId]" diff --git a/cdp_use/cdp/memory/commands.py b/cdp_use/cdp/memory/commands.py index f50feaf..f59459b 100644 --- a/cdp_use/cdp/memory/commands.py +++ b/cdp_use/cdp/memory/commands.py @@ -14,35 +14,28 @@ from .types import PressureLevel from .types import SamplingProfile + class GetDOMCountersReturns(TypedDict): documents: "int" nodes: "int" jsEventListeners: "int" - class GetDOMCountersForLeakDetectionReturns(TypedDict): counters: "List[DOMCounter]" """DOM object counters.""" - class SetPressureNotificationsSuppressedParameters(TypedDict): suppressed: "bool" """If true, memory pressure notifications will be suppressed.""" - - - class SimulatePressureNotificationParameters(TypedDict): level: "PressureLevel" """Memory pressure level of the notification.""" - - - class StartSamplingParameters(TypedDict, total=False): samplingInterval: "int" """Average number of bytes between samples.""" @@ -50,18 +43,13 @@ class StartSamplingParameters(TypedDict, total=False): """Do not randomize intervals between samples.""" - - - class GetAllTimeSamplingProfileReturns(TypedDict): profile: "SamplingProfile" - class GetBrowserSamplingProfileReturns(TypedDict): profile: "SamplingProfile" - class GetSamplingProfileReturns(TypedDict): profile: "SamplingProfile" diff --git a/cdp_use/cdp/memory/events.py b/cdp_use/cdp/memory/events.py index 1065b7f..813fd58 100644 --- a/cdp_use/cdp/memory/events.py +++ b/cdp_use/cdp/memory/events.py @@ -5,4 +5,4 @@ """CDP Memory Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/memory/library.py b/cdp_use/cdp/memory/library.py index 9297e82..6a6684c 100644 --- a/cdp_use/cdp/memory/library.py +++ b/cdp_use/cdp/memory/library.py @@ -19,10 +19,11 @@ from .commands import SimulatePressureNotificationParameters from .commands import StartSamplingParameters + class MemoryClient: """Client for Memory domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getDOMCounters( @@ -31,11 +32,14 @@ async def getDOMCounters( session_id: Optional[str] = None, ) -> "GetDOMCountersReturns": """Retruns current DOM object counters.""" - return cast("GetDOMCountersReturns", await self._client.send_raw( - method="Memory.getDOMCounters", - params=params, - session_id=session_id, - )) + return cast( + "GetDOMCountersReturns", + await self._client.send_raw( + method="Memory.getDOMCounters", + params=params, + session_id=session_id, + ), + ) async def getDOMCountersForLeakDetection( self, @@ -43,11 +47,14 @@ async def getDOMCountersForLeakDetection( session_id: Optional[str] = None, ) -> "GetDOMCountersForLeakDetectionReturns": """Retruns DOM object counters after preparing renderer for leak detection.""" - return cast("GetDOMCountersForLeakDetectionReturns", await self._client.send_raw( - method="Memory.getDOMCountersForLeakDetection", - params=params, - session_id=session_id, - )) + return cast( + "GetDOMCountersForLeakDetectionReturns", + await self._client.send_raw( + method="Memory.getDOMCountersForLeakDetection", + params=params, + session_id=session_id, + ), + ) async def prepareForLeakDetection( self, @@ -55,12 +62,15 @@ async def prepareForLeakDetection( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Prepares for leak detection by terminating workers, stopping spellcheckers, -dropping non-essential internal caches, running garbage collections, etc.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Memory.prepareForLeakDetection", - params=params, - session_id=session_id, - )) + dropping non-essential internal caches, running garbage collections, etc.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Memory.prepareForLeakDetection", + params=params, + session_id=session_id, + ), + ) async def forciblyPurgeJavaScriptMemory( self, @@ -68,11 +78,14 @@ async def forciblyPurgeJavaScriptMemory( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulate OomIntervention by purging V8 memory.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Memory.forciblyPurgeJavaScriptMemory", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Memory.forciblyPurgeJavaScriptMemory", + params=params, + session_id=session_id, + ), + ) async def setPressureNotificationsSuppressed( self, @@ -80,11 +93,14 @@ async def setPressureNotificationsSuppressed( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable/disable suppressing memory pressure notifications in all processes.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Memory.setPressureNotificationsSuppressed", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Memory.setPressureNotificationsSuppressed", + params=params, + session_id=session_id, + ), + ) async def simulatePressureNotification( self, @@ -92,11 +108,14 @@ async def simulatePressureNotification( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Simulate a memory pressure notification in all processes.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Memory.simulatePressureNotification", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Memory.simulatePressureNotification", + params=params, + session_id=session_id, + ), + ) async def startSampling( self, @@ -104,11 +123,14 @@ async def startSampling( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Start collecting native memory profile.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Memory.startSampling", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Memory.startSampling", + params=params, + session_id=session_id, + ), + ) async def stopSampling( self, @@ -116,11 +138,14 @@ async def stopSampling( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stop collecting native memory profile.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Memory.stopSampling", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Memory.stopSampling", + params=params, + session_id=session_id, + ), + ) async def getAllTimeSamplingProfile( self, @@ -128,12 +153,15 @@ async def getAllTimeSamplingProfile( session_id: Optional[str] = None, ) -> "GetAllTimeSamplingProfileReturns": """Retrieve native memory allocations profile -collected since renderer process startup.""" - return cast("GetAllTimeSamplingProfileReturns", await self._client.send_raw( - method="Memory.getAllTimeSamplingProfile", - params=params, - session_id=session_id, - )) + collected since renderer process startup.""" + return cast( + "GetAllTimeSamplingProfileReturns", + await self._client.send_raw( + method="Memory.getAllTimeSamplingProfile", + params=params, + session_id=session_id, + ), + ) async def getBrowserSamplingProfile( self, @@ -141,12 +169,15 @@ async def getBrowserSamplingProfile( session_id: Optional[str] = None, ) -> "GetBrowserSamplingProfileReturns": """Retrieve native memory allocations profile -collected since browser process startup.""" - return cast("GetBrowserSamplingProfileReturns", await self._client.send_raw( - method="Memory.getBrowserSamplingProfile", - params=params, - session_id=session_id, - )) + collected since browser process startup.""" + return cast( + "GetBrowserSamplingProfileReturns", + await self._client.send_raw( + method="Memory.getBrowserSamplingProfile", + params=params, + session_id=session_id, + ), + ) async def getSamplingProfile( self, @@ -154,11 +185,12 @@ async def getSamplingProfile( session_id: Optional[str] = None, ) -> "GetSamplingProfileReturns": """Retrieve native memory allocations profile collected since last -`startSampling` call.""" - return cast("GetSamplingProfileReturns", await self._client.send_raw( - method="Memory.getSamplingProfile", - params=params, - session_id=session_id, - )) - - + `startSampling` call.""" + return cast( + "GetSamplingProfileReturns", + await self._client.send_raw( + method="Memory.getSamplingProfile", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/memory/registration.py b/cdp_use/cdp/memory/registration.py index e316684..7a95724 100644 --- a/cdp_use/cdp/memory/registration.py +++ b/cdp_use/cdp/memory/registration.py @@ -5,4 +5,4 @@ """CDP Memory Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/memory/types.py b/cdp_use/cdp/memory/types.py index 28522fd..9ef3a3b 100644 --- a/cdp_use/cdp/memory/types.py +++ b/cdp_use/cdp/memory/types.py @@ -12,7 +12,6 @@ """Memory pressure level.""" - class SamplingProfileNode(TypedDict): """Heap profile sample.""" @@ -24,7 +23,6 @@ class SamplingProfileNode(TypedDict): """Execution stack at the point of allocation.""" - class SamplingProfile(TypedDict): """Array of heap profile samples.""" @@ -32,7 +30,6 @@ class SamplingProfile(TypedDict): modules: "List[Module]" - class Module(TypedDict): """Executable module information""" @@ -47,7 +44,6 @@ class Module(TypedDict): """Size of the module in bytes.""" - class DOMCounter(TypedDict): """DOM object counter data.""" diff --git a/cdp_use/cdp/network/commands.py b/cdp_use/cdp/network/commands.py index 81045ff..d9ebd82 100644 --- a/cdp_use/cdp/network/commands.py +++ b/cdp_use/cdp/network/commands.py @@ -15,6 +15,7 @@ from ..io.types import StreamHandle from ..page.types import FrameId from .types import AuthChallengeResponse + from .types import BlockPattern from .types import ConnectionType from .types import ContentEncoding from .types import Cookie @@ -26,46 +27,35 @@ from .types import ErrorReason from .types import Headers from .types import InterceptionId - from .types import IpProxyStatus from .types import LoadNetworkResourceOptions from .types import LoadNetworkResourcePageResult + from .types import NetworkConditions from .types import RequestId from .types import RequestPattern from .types import SecurityIsolationStatus from .types import TimeSinceEpoch -class GetIPProtectionProxyStatusReturns(TypedDict): - status: "IpProxyStatus" - """Whether IP proxy is available""" - - class SetAcceptedEncodingsParameters(TypedDict): encodings: "List[ContentEncoding]" """List of accepted content encodings.""" - - - class CanClearBrowserCacheReturns(TypedDict): result: "bool" """True if browser cache can be cleared.""" - class CanClearBrowserCookiesReturns(TypedDict): result: "bool" """True if browser cookies can be cleared.""" - class CanEmulateNetworkConditionsReturns(TypedDict): result: "bool" """True if emulation of network conditions is supported.""" - class ContinueInterceptedRequestParameters(TypedDict): interceptionId: "InterceptionId" errorReason: "NotRequired[ErrorReason]" @@ -90,9 +80,6 @@ class ContinueInterceptedRequestParameters(TypedDict): """Response to a requestIntercepted with an authChallenge. Must not be set otherwise.""" - - - class DeleteCookiesParameters(TypedDict): name: "str" """Name of the cookies to remove.""" @@ -108,9 +95,6 @@ class DeleteCookiesParameters(TypedDict): all partition key attributes match the cookie partition key attribute.""" - - - class EmulateNetworkConditionsParameters(TypedDict): offline: "bool" """True to emulate internet disconnection.""" @@ -130,7 +114,32 @@ class EmulateNetworkConditionsParameters(TypedDict): """WebRTC packetReordering feature.""" +class EmulateNetworkConditionsByRuleParameters(TypedDict): + offline: "bool" + """True to emulate internet disconnection.""" + matchedNetworkConditions: "List[NetworkConditions]" + """Configure conditions for matching requests. If multiple entries match a request, the first entry wins. Global +conditions can be configured by leaving the urlPattern for the conditions empty. These global conditions are +also applied for throttling of p2p connections.""" + + +class EmulateNetworkConditionsByRuleReturns(TypedDict): + ruleIds: "List[str]" + """An id for each entry in matchedNetworkConditions. The id will be included in the requestWillBeSentExtraInfo for +requests affected by a rule.""" + +class OverrideNetworkStateParameters(TypedDict): + offline: "bool" + """True to emulate internet disconnection.""" + latency: "float" + """Minimum latency from request sent to response headers received (ms).""" + downloadThroughput: "float" + """Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.""" + uploadThroughput: "float" + """Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling.""" + connectionType: "NotRequired[ConnectionType]" + """Connection type if known.""" class EnableParameters(TypedDict, total=False): @@ -142,9 +151,10 @@ class EnableParameters(TypedDict, total=False): """Longest post body size (in bytes) that would be included in requestWillBeSent notification""" reportDirectSocketTraffic: "bool" """Whether DirectSocket chunk send/receive events should be reported.""" - - - + enableDurableMessages: "bool" + """Enable storing response bodies outside of renderer, so that these survive +a cross-process navigation. Requires maxTotalBufferSize to be set. +Currently defaults to false.""" class GetAllCookiesReturns(TypedDict): @@ -152,7 +162,6 @@ class GetAllCookiesReturns(TypedDict): """Array of cookie objects.""" - class GetCertificateParameters(TypedDict): origin: "str" """Origin to get certificate for.""" @@ -162,7 +171,6 @@ class GetCertificateReturns(TypedDict): tableNames: "List[str]" - class GetCookiesParameters(TypedDict, total=False): urls: "List[str]" """The list of URLs for which applicable cookies will be fetched. @@ -175,7 +183,6 @@ class GetCookiesReturns(TypedDict): """Array of cookie objects.""" - class GetResponseBodyParameters(TypedDict): requestId: "RequestId" """Identifier of the network request to get content for.""" @@ -188,7 +195,6 @@ class GetResponseBodyReturns(TypedDict): """True, if content was sent as base64.""" - class GetRequestPostDataParameters(TypedDict): requestId: "RequestId" """Identifier of the network request to get content for.""" @@ -199,7 +205,6 @@ class GetRequestPostDataReturns(TypedDict): """Request body string, omitting files from multipart requests""" - class GetResponseBodyForInterceptionParameters(TypedDict): interceptionId: "InterceptionId" """Identifier for the intercepted request to get body for.""" @@ -212,7 +217,6 @@ class GetResponseBodyForInterceptionReturns(TypedDict): """True, if content was sent as base64.""" - class TakeResponseBodyForInterceptionAsStreamParameters(TypedDict): interceptionId: "InterceptionId" @@ -221,15 +225,11 @@ class TakeResponseBodyForInterceptionAsStreamReturns(TypedDict): stream: "StreamHandle" - class ReplayXHRParameters(TypedDict): requestId: "RequestId" """Identifier of XHR to replay.""" - - - class SearchInResponseBodyParameters(TypedDict): requestId: "RequestId" """Identifier of the network response to search.""" @@ -246,31 +246,24 @@ class SearchInResponseBodyReturns(TypedDict): """List of search matches.""" - -class SetBlockedURLsParameters(TypedDict): +class SetBlockedURLsParameters(TypedDict, total=False): + urlPatterns: "List[BlockPattern]" + """Patterns to match in the order in which they are given. These patterns +also take precedence over any wildcard patterns defined in `urls`.""" urls: "List[str]" """URL patterns to block. Wildcards ('*') are allowed.""" - - - class SetBypassServiceWorkerParameters(TypedDict): bypass: "bool" """Bypass service worker and load from network.""" - - - class SetCacheDisabledParameters(TypedDict): cacheDisabled: "bool" """Cache disabled state.""" - - - class SetCookieParameters(TypedDict): name: "str" """Cookie name.""" @@ -310,40 +303,27 @@ class SetCookieReturns(TypedDict): """Always set to true. If an error occurs, the response indicates protocol error.""" - class SetCookiesParameters(TypedDict): cookies: "List[CookieParam]" """Cookies to be set.""" - - - class SetExtraHTTPHeadersParameters(TypedDict): headers: "Headers" """Map with extra HTTP headers.""" - - - class SetAttachDebugStackParameters(TypedDict): enabled: "bool" """Whether to attach a page script stack for debugging purpose.""" - - - class SetRequestInterceptionParameters(TypedDict): patterns: "List[RequestPattern]" """Requests matching any of these patterns will be forwarded and wait for the corresponding continueInterceptedRequest call.""" - - - class SetUserAgentOverrideParameters(TypedDict): userAgent: "str" """User agent to use.""" @@ -355,9 +335,6 @@ class SetUserAgentOverrideParameters(TypedDict): """To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData""" - - - class StreamResourceContentParameters(TypedDict): requestId: "RequestId" """Identifier of the request to stream.""" @@ -368,7 +345,6 @@ class StreamResourceContentReturns(TypedDict): """Data that has been buffered until streaming is enabled. (Encoded as a base64 string when passed over JSON)""" - class GetSecurityIsolationStatusParameters(TypedDict, total=False): frameId: "FrameId" """If no frameId is provided, the status of the target is provided.""" @@ -378,15 +354,11 @@ class GetSecurityIsolationStatusReturns(TypedDict): status: "SecurityIsolationStatus" - class EnableReportingApiParameters(TypedDict): enable: "bool" """Whether to enable or disable events for the Reporting API""" - - - class LoadNetworkResourceParameters(TypedDict): frameId: "NotRequired[FrameId]" """Frame id to get the resource for. Mandatory for frame targets, and @@ -401,7 +373,6 @@ class LoadNetworkResourceReturns(TypedDict): resource: "LoadNetworkResourcePageResult" - class SetCookieControlsParameters(TypedDict): enableThirdPartyCookieRestriction: "bool" """Whether 3pc restriction is enabled.""" @@ -409,5 +380,3 @@ class SetCookieControlsParameters(TypedDict): """Whether 3pc grace period exception should be enabled; false by default.""" disableThirdPartyCookieHeuristics: "bool" """Whether 3pc heuristics exceptions should be enabled; false by default.""" - - diff --git a/cdp_use/cdp/network/events.py b/cdp_use/cdp/network/events.py index 4eddf8d..10eeae9 100644 --- a/cdp_use/cdp/network/events.py +++ b/cdp_use/cdp/network/events.py @@ -45,6 +45,8 @@ from .types import WebSocketResponse """Fired when data chunk was received over the network.""" + + class DataReceivedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -58,8 +60,9 @@ class DataReceivedEvent(TypedDict): """Data that was received. (Encoded as a base64 string when passed over JSON)""" - """Fired when EventSource message is received.""" + + class EventSourceMessageReceivedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -73,8 +76,9 @@ class EventSourceMessageReceivedEvent(TypedDict): """Message content.""" - """Fired when HTTP request has failed to load.""" + + class LoadingFailedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -92,8 +96,9 @@ class LoadingFailedEvent(TypedDict): """The reason why loading was blocked by CORS, if any.""" - """Fired when HTTP request has finished loading.""" + + class LoadingFinishedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -103,10 +108,11 @@ class LoadingFinishedEvent(TypedDict): """Total number of bytes received for this request.""" - """Details of an intercepted HTTP request, which must be either allowed, blocked, modified or mocked. Deprecated, use Fetch.requestPaused instead.""" + + class RequestInterceptedEvent(TypedDict): interceptionId: "InterceptionId" """Each request the page makes will have a unique id, however if any redirects are encountered @@ -141,15 +147,17 @@ class RequestInterceptedEvent(TypedDict): this requestId will be the same as the requestId present in the requestWillBeSent event.""" - """Fired if request ended up loading from cache.""" + + class RequestServedFromCacheEvent(TypedDict): requestId: "RequestId" """Request identifier.""" - """Fired when page is about to send HTTP request.""" + + class RequestWillBeSentEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -179,8 +187,9 @@ class RequestWillBeSentEvent(TypedDict): """Whether the request is initiated by a user gesture. Defaults to false.""" - """Fired when resource loading priority is changed""" + + class ResourceChangedPriorityEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -190,8 +199,9 @@ class ResourceChangedPriorityEvent(TypedDict): """Timestamp.""" - """Fired when a signed exchange was received over the network""" + + class SignedExchangeReceivedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -199,8 +209,9 @@ class SignedExchangeReceivedEvent(TypedDict): """Information about the signed exchange response.""" - """Fired when HTTP response is available.""" + + class ResponseReceivedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -219,8 +230,9 @@ class ResponseReceivedEvent(TypedDict): """Frame identifier.""" - """Fired when WebSocket is closed.""" + + class WebSocketClosedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -228,8 +240,9 @@ class WebSocketClosedEvent(TypedDict): """Timestamp.""" - """Fired upon WebSocket creation.""" + + class WebSocketCreatedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -239,8 +252,9 @@ class WebSocketCreatedEvent(TypedDict): """Request initiator.""" - """Fired when WebSocket message error occurs.""" + + class WebSocketFrameErrorEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -250,8 +264,9 @@ class WebSocketFrameErrorEvent(TypedDict): """WebSocket error message.""" - """Fired when WebSocket message is received.""" + + class WebSocketFrameReceivedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -261,8 +276,9 @@ class WebSocketFrameReceivedEvent(TypedDict): """WebSocket response data.""" - """Fired when WebSocket message is sent.""" + + class WebSocketFrameSentEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -272,8 +288,9 @@ class WebSocketFrameSentEvent(TypedDict): """WebSocket response data.""" - """Fired when WebSocket handshake response becomes available.""" + + class WebSocketHandshakeResponseReceivedEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -283,8 +300,9 @@ class WebSocketHandshakeResponseReceivedEvent(TypedDict): """WebSocket response data.""" - """Fired when WebSocket is about to initiate handshake.""" + + class WebSocketWillSendHandshakeRequestEvent(TypedDict): requestId: "RequestId" """Request identifier.""" @@ -296,8 +314,9 @@ class WebSocketWillSendHandshakeRequestEvent(TypedDict): """WebSocket request data.""" - """Fired upon WebTransport creation.""" + + class WebTransportCreatedEvent(TypedDict): transportId: "RequestId" """WebTransport identifier.""" @@ -309,8 +328,9 @@ class WebTransportCreatedEvent(TypedDict): """Request initiator.""" - """Fired when WebTransport handshake is finished.""" + + class WebTransportConnectionEstablishedEvent(TypedDict): transportId: "RequestId" """WebTransport identifier.""" @@ -318,8 +338,9 @@ class WebTransportConnectionEstablishedEvent(TypedDict): """Timestamp.""" - """Fired when WebTransport is disposed.""" + + class WebTransportClosedEvent(TypedDict): transportId: "RequestId" """WebTransport identifier.""" @@ -327,8 +348,9 @@ class WebTransportClosedEvent(TypedDict): """Timestamp.""" - """Fired upon direct_socket.TCPSocket creation.""" + + class DirectTCPSocketCreatedEvent(TypedDict): identifier: "RequestId" remoteAddr: "str" @@ -339,8 +361,9 @@ class DirectTCPSocketCreatedEvent(TypedDict): initiator: "NotRequired[Initiator]" - """Fired when direct_socket.TCPSocket connection is opened.""" + + class DirectTCPSocketOpenedEvent(TypedDict): identifier: "RequestId" remoteAddr: "str" @@ -352,39 +375,54 @@ class DirectTCPSocketOpenedEvent(TypedDict): """Expected to be unsigned integer.""" - """Fired when direct_socket.TCPSocket is aborted.""" + + class DirectTCPSocketAbortedEvent(TypedDict): identifier: "RequestId" errorMessage: "str" timestamp: "MonotonicTime" - """Fired when direct_socket.TCPSocket is closed.""" + + class DirectTCPSocketClosedEvent(TypedDict): identifier: "RequestId" timestamp: "MonotonicTime" - """Fired when data is sent to tcp direct socket stream.""" + + class DirectTCPSocketChunkSentEvent(TypedDict): identifier: "RequestId" data: "str" timestamp: "MonotonicTime" - """Fired when data is received from tcp direct socket stream.""" + + class DirectTCPSocketChunkReceivedEvent(TypedDict): identifier: "RequestId" data: "str" timestamp: "MonotonicTime" +class DirectUDPSocketJoinedMulticastGroupEvent(TypedDict): + identifier: "RequestId" + IPAddress: "str" + + +class DirectUDPSocketLeftMulticastGroupEvent(TypedDict): + identifier: "RequestId" + IPAddress: "str" + """Fired upon direct_socket.UDPSocket creation.""" + + class DirectUDPSocketCreatedEvent(TypedDict): identifier: "RequestId" options: "DirectUDPSocketOptions" @@ -392,8 +430,9 @@ class DirectUDPSocketCreatedEvent(TypedDict): initiator: "NotRequired[Initiator]" - """Fired when direct_socket.UDPSocket connection is opened.""" + + class DirectUDPSocketOpenedEvent(TypedDict): identifier: "RequestId" localAddr: "str" @@ -405,42 +444,47 @@ class DirectUDPSocketOpenedEvent(TypedDict): """Expected to be unsigned integer.""" - """Fired when direct_socket.UDPSocket is aborted.""" + + class DirectUDPSocketAbortedEvent(TypedDict): identifier: "RequestId" errorMessage: "str" timestamp: "MonotonicTime" - """Fired when direct_socket.UDPSocket is closed.""" + + class DirectUDPSocketClosedEvent(TypedDict): identifier: "RequestId" timestamp: "MonotonicTime" - """Fired when message is sent to udp direct socket stream.""" + + class DirectUDPSocketChunkSentEvent(TypedDict): identifier: "RequestId" message: "DirectUDPMessage" timestamp: "MonotonicTime" - """Fired when message is received from udp direct socket stream.""" + + class DirectUDPSocketChunkReceivedEvent(TypedDict): identifier: "RequestId" message: "DirectUDPMessage" timestamp: "MonotonicTime" - """Fired when additional information about a requestWillBeSent event is available from the network stack. Not every requestWillBeSent event will have an additional requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent or requestWillBeSentExtraInfo will be fired first for the same request.""" + + class RequestWillBeSentExtraInfoEvent(TypedDict): requestId: "RequestId" """Request identifier. Used to match this information to an existing requestWillBeSent event.""" @@ -455,12 +499,16 @@ class RequestWillBeSentExtraInfoEvent(TypedDict): """The client security state set for the request.""" siteHasCookieInOtherPartition: "NotRequired[bool]" """Whether the site has partitioned cookies stored in a partition different than the current one.""" - + appliedNetworkConditionsId: "NotRequired[str]" + """The network conditions id if this request was affected by network conditions configured via +emulateNetworkConditionsByRule.""" """Fired when additional information about a responseReceived event is available from the network stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for it, and responseReceivedExtraInfo may be fired before or after responseReceived.""" + + class ResponseReceivedExtraInfoEvent(TypedDict): requestId: "RequestId" """Request identifier. Used to match this information to another responseReceived event.""" @@ -493,10 +541,11 @@ class ResponseReceivedExtraInfoEvent(TypedDict): the response with the corresponding reason.""" - """Fired when 103 Early Hints headers is received in addition to the common response. Not every responseReceived event will have an responseReceivedEarlyHints fired. Only one responseReceivedEarlyHints may be fired for eached responseReceived event.""" + + class ResponseReceivedEarlyHintsEvent(TypedDict): requestId: "RequestId" """Request identifier. Used to match this information to another responseReceived event.""" @@ -507,11 +556,12 @@ class ResponseReceivedEarlyHintsEvent(TypedDict): See also `headersText` that contains verbatim text for HTTP/1.*.""" - """Fired exactly once for each Trust Token operation. Depending on the type of the operation and whether the operation succeeded or failed, the event is fired before the corresponding request was sent or after the response was received.""" + + class TrustTokenOperationDoneEvent(TypedDict): status: "str" """Detailed success or error status of the operation. @@ -528,73 +578,25 @@ class TrustTokenOperationDoneEvent(TypedDict): """The number of obtained Trust Tokens on a successful \"Issuance\" operation.""" - """Fired once security policy has been updated.""" -class PolicyUpdatedEvent(TypedDict): - pass - - - -"""Fired once when parsing the .wbn file has succeeded. -The event contains the information about the web bundle contents.""" -class SubresourceWebBundleMetadataReceivedEvent(TypedDict): - requestId: "RequestId" - """Request identifier. Used to match this information to another event.""" - urls: "List[str]" - """A list of URLs of resources in the subresource Web Bundle.""" - -"""Fired once when parsing the .wbn file has failed.""" -class SubresourceWebBundleMetadataErrorEvent(TypedDict): - requestId: "RequestId" - """Request identifier. Used to match this information to another event.""" - errorMessage: "str" - """Error message""" - - - -"""Fired when handling requests for resources within a .wbn file. -Note: this will only be fired for resources that are requested by the webpage.""" -class SubresourceWebBundleInnerResponseParsedEvent(TypedDict): - innerRequestId: "RequestId" - """Request identifier of the subresource request""" - innerRequestURL: "str" - """URL of the subresource resource.""" - bundleRequestId: "NotRequired[RequestId]" - """Bundle request identifier. Used to match this information to another event. -This made be absent in case when the instrumentation was enabled only -after webbundle was parsed.""" - - - -"""Fired when request for resources within a .wbn file failed.""" -class SubresourceWebBundleInnerResponseErrorEvent(TypedDict): - innerRequestId: "RequestId" - """Request identifier of the subresource request""" - innerRequestURL: "str" - """URL of the subresource resource.""" - errorMessage: "str" - """Error message""" - bundleRequestId: "NotRequired[RequestId]" - """Bundle request identifier. Used to match this information to another event. -This made be absent in case when the instrumentation was enabled only -after webbundle was parsed.""" - +class PolicyUpdatedEvent(TypedDict): + pass """Is sent whenever a new report is added. And after 'enableReportingApi' for all existing reports.""" + + class ReportingApiReportAddedEvent(TypedDict): report: "ReportingApiReport" - class ReportingApiReportUpdatedEvent(TypedDict): report: "ReportingApiReport" - class ReportingApiEndpointsChangedForOriginEvent(TypedDict): origin: "str" """Origin of the document(s) which configured the endpoints.""" diff --git a/cdp_use/cdp/network/library.py b/cdp_use/cdp/network/library.py index bb33a3a..95ad85b 100644 --- a/cdp_use/cdp/network/library.py +++ b/cdp_use/cdp/network/library.py @@ -15,6 +15,8 @@ from .commands import CanEmulateNetworkConditionsReturns from .commands import ContinueInterceptedRequestParameters from .commands import DeleteCookiesParameters + from .commands import EmulateNetworkConditionsByRuleParameters + from .commands import EmulateNetworkConditionsByRuleReturns from .commands import EmulateNetworkConditionsParameters from .commands import EnableParameters from .commands import EnableReportingApiParameters @@ -23,7 +25,6 @@ from .commands import GetCertificateReturns from .commands import GetCookiesParameters from .commands import GetCookiesReturns - from .commands import GetIPProtectionProxyStatusReturns from .commands import GetRequestPostDataParameters from .commands import GetRequestPostDataReturns from .commands import GetResponseBodyForInterceptionParameters @@ -34,6 +35,7 @@ from .commands import GetSecurityIsolationStatusReturns from .commands import LoadNetworkResourceParameters from .commands import LoadNetworkResourceReturns + from .commands import OverrideNetworkStateParameters from .commands import ReplayXHRParameters from .commands import SearchInResponseBodyParameters from .commands import SearchInResponseBodyReturns @@ -54,36 +56,27 @@ from .commands import TakeResponseBodyForInterceptionAsStreamParameters from .commands import TakeResponseBodyForInterceptionAsStreamReturns + class NetworkClient: """Client for Network domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client - async def getIPProtectionProxyStatus( - self, - params: None = None, - session_id: Optional[str] = None, - ) -> "GetIPProtectionProxyStatusReturns": - """Returns enum representing if IP Proxy of requests is available -or reason it is not active.""" - return cast("GetIPProtectionProxyStatusReturns", await self._client.send_raw( - method="Network.getIPProtectionProxyStatus", - params=params, - session_id=session_id, - )) - async def setAcceptedEncodings( self, params: "SetAcceptedEncodingsParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets a list of content encodings that will be accepted. Empty list means no encoding is accepted.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setAcceptedEncodings", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setAcceptedEncodings", + params=params, + session_id=session_id, + ), + ) async def clearAcceptedEncodingsOverride( self, @@ -91,11 +84,14 @@ async def clearAcceptedEncodingsOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears accepted encodings set by setAcceptedEncodings""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.clearAcceptedEncodingsOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.clearAcceptedEncodingsOverride", + params=params, + session_id=session_id, + ), + ) async def canClearBrowserCache( self, @@ -103,11 +99,14 @@ async def canClearBrowserCache( session_id: Optional[str] = None, ) -> "CanClearBrowserCacheReturns": """Tells whether clearing browser cache is supported.""" - return cast("CanClearBrowserCacheReturns", await self._client.send_raw( - method="Network.canClearBrowserCache", - params=params, - session_id=session_id, - )) + return cast( + "CanClearBrowserCacheReturns", + await self._client.send_raw( + method="Network.canClearBrowserCache", + params=params, + session_id=session_id, + ), + ) async def canClearBrowserCookies( self, @@ -115,11 +114,14 @@ async def canClearBrowserCookies( session_id: Optional[str] = None, ) -> "CanClearBrowserCookiesReturns": """Tells whether clearing browser cookies is supported.""" - return cast("CanClearBrowserCookiesReturns", await self._client.send_raw( - method="Network.canClearBrowserCookies", - params=params, - session_id=session_id, - )) + return cast( + "CanClearBrowserCookiesReturns", + await self._client.send_raw( + method="Network.canClearBrowserCookies", + params=params, + session_id=session_id, + ), + ) async def canEmulateNetworkConditions( self, @@ -127,11 +129,14 @@ async def canEmulateNetworkConditions( session_id: Optional[str] = None, ) -> "CanEmulateNetworkConditionsReturns": """Tells whether emulation of network conditions is supported.""" - return cast("CanEmulateNetworkConditionsReturns", await self._client.send_raw( - method="Network.canEmulateNetworkConditions", - params=params, - session_id=session_id, - )) + return cast( + "CanEmulateNetworkConditionsReturns", + await self._client.send_raw( + method="Network.canEmulateNetworkConditions", + params=params, + session_id=session_id, + ), + ) async def clearBrowserCache( self, @@ -139,11 +144,14 @@ async def clearBrowserCache( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears browser cache.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.clearBrowserCache", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.clearBrowserCache", + params=params, + session_id=session_id, + ), + ) async def clearBrowserCookies( self, @@ -151,11 +159,14 @@ async def clearBrowserCookies( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears browser cookies.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.clearBrowserCookies", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.clearBrowserCookies", + params=params, + session_id=session_id, + ), + ) async def continueInterceptedRequest( self, @@ -163,15 +174,18 @@ async def continueInterceptedRequest( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Response to Network.requestIntercepted which either modifies the request to continue with any -modifications, or blocks it, or completes it with the provided response bytes. If a network -fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted -event will be sent with the same InterceptionId. -Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.continueInterceptedRequest", - params=params, - session_id=session_id, - )) + modifications, or blocks it, or completes it with the provided response bytes. If a network + fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted + event will be sent with the same InterceptionId. + Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.continueInterceptedRequest", + params=params, + session_id=session_id, + ), + ) async def deleteCookies( self, @@ -179,11 +193,14 @@ async def deleteCookies( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes browser cookies with matching name and url or domain/path/partitionKey pair.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.deleteCookies", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.deleteCookies", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -191,23 +208,62 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables network tracking, prevents network events from being sent to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.disable", + params=params, + session_id=session_id, + ), + ) async def emulateNetworkConditions( self, params: "EmulateNetworkConditionsParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - """Activates emulation of network conditions.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.emulateNetworkConditions", - params=params, - session_id=session_id, - )) + """Activates emulation of network conditions. This command is deprecated in favor of the emulateNetworkConditionsByRule + and overrideNetworkState commands, which can be used together to the same effect.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.emulateNetworkConditions", + params=params, + session_id=session_id, + ), + ) + + async def emulateNetworkConditionsByRule( + self, + params: "EmulateNetworkConditionsByRuleParameters", + session_id: Optional[str] = None, + ) -> "EmulateNetworkConditionsByRuleReturns": + """Activates emulation of network conditions for individual requests using URL match patterns. Unlike the deprecated + Network.emulateNetworkConditions this method does not affect `navigator` state. Use Network.overrideNetworkState to + explicitly modify `navigator` behavior.""" + return cast( + "EmulateNetworkConditionsByRuleReturns", + await self._client.send_raw( + method="Network.emulateNetworkConditionsByRule", + params=params, + session_id=session_id, + ), + ) + + async def overrideNetworkState( + self, + params: "OverrideNetworkStateParameters", + session_id: Optional[str] = None, + ) -> "Dict[str, Any]": + """Override the state of navigator.onLine and navigator.connection.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.overrideNetworkState", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -215,11 +271,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables network tracking, network events will now be delivered to the client.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.enable", + params=params, + session_id=session_id, + ), + ) async def getAllCookies( self, @@ -227,13 +286,16 @@ async def getAllCookies( session_id: Optional[str] = None, ) -> "GetAllCookiesReturns": """Returns all browser cookies. Depending on the backend support, will return detailed cookie -information in the `cookies` field. -Deprecated. Use Storage.getCookies instead.""" - return cast("GetAllCookiesReturns", await self._client.send_raw( - method="Network.getAllCookies", - params=params, - session_id=session_id, - )) + information in the `cookies` field. + Deprecated. Use Storage.getCookies instead.""" + return cast( + "GetAllCookiesReturns", + await self._client.send_raw( + method="Network.getAllCookies", + params=params, + session_id=session_id, + ), + ) async def getCertificate( self, @@ -241,11 +303,14 @@ async def getCertificate( session_id: Optional[str] = None, ) -> "GetCertificateReturns": """Returns the DER-encoded certificate.""" - return cast("GetCertificateReturns", await self._client.send_raw( - method="Network.getCertificate", - params=params, - session_id=session_id, - )) + return cast( + "GetCertificateReturns", + await self._client.send_raw( + method="Network.getCertificate", + params=params, + session_id=session_id, + ), + ) async def getCookies( self, @@ -253,12 +318,15 @@ async def getCookies( session_id: Optional[str] = None, ) -> "GetCookiesReturns": """Returns all browser cookies for the current URL. Depending on the backend support, will return -detailed cookie information in the `cookies` field.""" - return cast("GetCookiesReturns", await self._client.send_raw( - method="Network.getCookies", - params=params, - session_id=session_id, - )) + detailed cookie information in the `cookies` field.""" + return cast( + "GetCookiesReturns", + await self._client.send_raw( + method="Network.getCookies", + params=params, + session_id=session_id, + ), + ) async def getResponseBody( self, @@ -266,11 +334,14 @@ async def getResponseBody( session_id: Optional[str] = None, ) -> "GetResponseBodyReturns": """Returns content served for the given request.""" - return cast("GetResponseBodyReturns", await self._client.send_raw( - method="Network.getResponseBody", - params=params, - session_id=session_id, - )) + return cast( + "GetResponseBodyReturns", + await self._client.send_raw( + method="Network.getResponseBody", + params=params, + session_id=session_id, + ), + ) async def getRequestPostData( self, @@ -278,11 +349,14 @@ async def getRequestPostData( session_id: Optional[str] = None, ) -> "GetRequestPostDataReturns": """Returns post data sent with the request. Returns an error when no data was sent with the request.""" - return cast("GetRequestPostDataReturns", await self._client.send_raw( - method="Network.getRequestPostData", - params=params, - session_id=session_id, - )) + return cast( + "GetRequestPostDataReturns", + await self._client.send_raw( + method="Network.getRequestPostData", + params=params, + session_id=session_id, + ), + ) async def getResponseBodyForInterception( self, @@ -290,11 +364,14 @@ async def getResponseBodyForInterception( session_id: Optional[str] = None, ) -> "GetResponseBodyForInterceptionReturns": """Returns content served for the given currently intercepted request.""" - return cast("GetResponseBodyForInterceptionReturns", await self._client.send_raw( - method="Network.getResponseBodyForInterception", - params=params, - session_id=session_id, - )) + return cast( + "GetResponseBodyForInterceptionReturns", + await self._client.send_raw( + method="Network.getResponseBodyForInterception", + params=params, + session_id=session_id, + ), + ) async def takeResponseBodyForInterceptionAsStream( self, @@ -302,14 +379,17 @@ async def takeResponseBodyForInterceptionAsStream( session_id: Optional[str] = None, ) -> "TakeResponseBodyForInterceptionAsStreamReturns": """Returns a handle to the stream representing the response body. Note that after this command, -the intercepted request can't be continued as is -- you either need to cancel it or to provide -the response body. The stream only supports sequential read, IO.read will fail if the position -is specified.""" - return cast("TakeResponseBodyForInterceptionAsStreamReturns", await self._client.send_raw( - method="Network.takeResponseBodyForInterceptionAsStream", - params=params, - session_id=session_id, - )) + the intercepted request can't be continued as is -- you either need to cancel it or to provide + the response body. The stream only supports sequential read, IO.read will fail if the position + is specified.""" + return cast( + "TakeResponseBodyForInterceptionAsStreamReturns", + await self._client.send_raw( + method="Network.takeResponseBodyForInterceptionAsStream", + params=params, + session_id=session_id, + ), + ) async def replayXHR( self, @@ -317,13 +397,16 @@ async def replayXHR( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """This method sends a new XMLHttpRequest which is identical to the original one. The following -parameters should be identical: method, url, async, request body, extra headers, withCredentials -attribute, user, password.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.replayXHR", - params=params, - session_id=session_id, - )) + parameters should be identical: method, url, async, request body, extra headers, withCredentials + attribute, user, password.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.replayXHR", + params=params, + session_id=session_id, + ), + ) async def searchInResponseBody( self, @@ -331,23 +414,29 @@ async def searchInResponseBody( session_id: Optional[str] = None, ) -> "SearchInResponseBodyReturns": """Searches for given string in response content.""" - return cast("SearchInResponseBodyReturns", await self._client.send_raw( - method="Network.searchInResponseBody", - params=params, - session_id=session_id, - )) + return cast( + "SearchInResponseBodyReturns", + await self._client.send_raw( + method="Network.searchInResponseBody", + params=params, + session_id=session_id, + ), + ) async def setBlockedURLs( self, - params: "SetBlockedURLsParameters", + params: Optional["SetBlockedURLsParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Blocks URLs from loading.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setBlockedURLs", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setBlockedURLs", + params=params, + session_id=session_id, + ), + ) async def setBypassServiceWorker( self, @@ -355,11 +444,14 @@ async def setBypassServiceWorker( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Toggles ignoring of service worker for each request.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setBypassServiceWorker", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setBypassServiceWorker", + params=params, + session_id=session_id, + ), + ) async def setCacheDisabled( self, @@ -367,11 +459,14 @@ async def setCacheDisabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Toggles ignoring cache for each request. If `true`, cache will not be used.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setCacheDisabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setCacheDisabled", + params=params, + session_id=session_id, + ), + ) async def setCookie( self, @@ -379,11 +474,14 @@ async def setCookie( session_id: Optional[str] = None, ) -> "SetCookieReturns": """Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.""" - return cast("SetCookieReturns", await self._client.send_raw( - method="Network.setCookie", - params=params, - session_id=session_id, - )) + return cast( + "SetCookieReturns", + await self._client.send_raw( + method="Network.setCookie", + params=params, + session_id=session_id, + ), + ) async def setCookies( self, @@ -391,11 +489,14 @@ async def setCookies( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets given cookies.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setCookies", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setCookies", + params=params, + session_id=session_id, + ), + ) async def setExtraHTTPHeaders( self, @@ -403,11 +504,14 @@ async def setExtraHTTPHeaders( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Specifies whether to always send extra HTTP headers with the requests from this page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setExtraHTTPHeaders", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setExtraHTTPHeaders", + params=params, + session_id=session_id, + ), + ) async def setAttachDebugStack( self, @@ -415,11 +519,14 @@ async def setAttachDebugStack( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Specifies whether to attach a page script stack id in requests""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setAttachDebugStack", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setAttachDebugStack", + params=params, + session_id=session_id, + ), + ) async def setRequestInterception( self, @@ -427,12 +534,15 @@ async def setRequestInterception( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets the requests to intercept that match the provided patterns and optionally resource types. -Deprecated, please use Fetch.enable instead.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setRequestInterception", - params=params, - session_id=session_id, - )) + Deprecated, please use Fetch.enable instead.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setRequestInterception", + params=params, + session_id=session_id, + ), + ) async def setUserAgentOverride( self, @@ -440,11 +550,14 @@ async def setUserAgentOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Allows overriding user agent with the given string.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setUserAgentOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setUserAgentOverride", + params=params, + session_id=session_id, + ), + ) async def streamResourceContent( self, @@ -452,12 +565,15 @@ async def streamResourceContent( session_id: Optional[str] = None, ) -> "StreamResourceContentReturns": """Enables streaming of the response for the given requestId. -If enabled, the dataReceived event contains the data that was received during streaming.""" - return cast("StreamResourceContentReturns", await self._client.send_raw( - method="Network.streamResourceContent", - params=params, - session_id=session_id, - )) + If enabled, the dataReceived event contains the data that was received during streaming.""" + return cast( + "StreamResourceContentReturns", + await self._client.send_raw( + method="Network.streamResourceContent", + params=params, + session_id=session_id, + ), + ) async def getSecurityIsolationStatus( self, @@ -465,11 +581,14 @@ async def getSecurityIsolationStatus( session_id: Optional[str] = None, ) -> "GetSecurityIsolationStatusReturns": """Returns information about the COEP/COOP isolation status.""" - return cast("GetSecurityIsolationStatusReturns", await self._client.send_raw( - method="Network.getSecurityIsolationStatus", - params=params, - session_id=session_id, - )) + return cast( + "GetSecurityIsolationStatusReturns", + await self._client.send_raw( + method="Network.getSecurityIsolationStatus", + params=params, + session_id=session_id, + ), + ) async def enableReportingApi( self, @@ -477,12 +596,15 @@ async def enableReportingApi( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables tracking for the Reporting API, events generated by the Reporting API will now be delivered to the client. -Enabling triggers 'reportingApiReportAdded' for all existing reports.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.enableReportingApi", - params=params, - session_id=session_id, - )) + Enabling triggers 'reportingApiReportAdded' for all existing reports.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.enableReportingApi", + params=params, + session_id=session_id, + ), + ) async def loadNetworkResource( self, @@ -490,11 +612,14 @@ async def loadNetworkResource( session_id: Optional[str] = None, ) -> "LoadNetworkResourceReturns": """Fetches the resource and returns the content.""" - return cast("LoadNetworkResourceReturns", await self._client.send_raw( - method="Network.loadNetworkResource", - params=params, - session_id=session_id, - )) + return cast( + "LoadNetworkResourceReturns", + await self._client.send_raw( + method="Network.loadNetworkResource", + params=params, + session_id=session_id, + ), + ) async def setCookieControls( self, @@ -502,11 +627,12 @@ async def setCookieControls( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets Controls for third-party cookie access -Page reload is required before the new cookie behavior will be observed""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Network.setCookieControls", - params=params, - session_id=session_id, - )) - - + Page reload is required before the new cookie behavior will be observed""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Network.setCookieControls", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/network/registration.py b/cdp_use/cdp/network/registration.py index 41efa9a..0c9184e 100644 --- a/cdp_use/cdp/network/registration.py +++ b/cdp_use/cdp/network/registration.py @@ -11,68 +11,67 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - DataReceivedEvent, - DirectTCPSocketAbortedEvent, - DirectTCPSocketChunkReceivedEvent, - DirectTCPSocketChunkSentEvent, - DirectTCPSocketClosedEvent, - DirectTCPSocketCreatedEvent, - DirectTCPSocketOpenedEvent, - DirectUDPSocketAbortedEvent, - DirectUDPSocketChunkReceivedEvent, - DirectUDPSocketChunkSentEvent, - DirectUDPSocketClosedEvent, - DirectUDPSocketCreatedEvent, - DirectUDPSocketOpenedEvent, - EventSourceMessageReceivedEvent, - LoadingFailedEvent, - LoadingFinishedEvent, - PolicyUpdatedEvent, - ReportingApiEndpointsChangedForOriginEvent, - ReportingApiReportAddedEvent, - ReportingApiReportUpdatedEvent, - RequestInterceptedEvent, - RequestServedFromCacheEvent, - RequestWillBeSentEvent, - RequestWillBeSentExtraInfoEvent, - ResourceChangedPriorityEvent, - ResponseReceivedEarlyHintsEvent, - ResponseReceivedEvent, - ResponseReceivedExtraInfoEvent, - SignedExchangeReceivedEvent, - SubresourceWebBundleInnerResponseErrorEvent, - SubresourceWebBundleInnerResponseParsedEvent, - SubresourceWebBundleMetadataErrorEvent, - SubresourceWebBundleMetadataReceivedEvent, - TrustTokenOperationDoneEvent, - WebSocketClosedEvent, - WebSocketCreatedEvent, - WebSocketFrameErrorEvent, - WebSocketFrameReceivedEvent, - WebSocketFrameSentEvent, - WebSocketHandshakeResponseReceivedEvent, - WebSocketWillSendHandshakeRequestEvent, - WebTransportClosedEvent, - WebTransportConnectionEstablishedEvent, - WebTransportCreatedEvent -) + DataReceivedEvent, + DirectTCPSocketAbortedEvent, + DirectTCPSocketChunkReceivedEvent, + DirectTCPSocketChunkSentEvent, + DirectTCPSocketClosedEvent, + DirectTCPSocketCreatedEvent, + DirectTCPSocketOpenedEvent, + DirectUDPSocketAbortedEvent, + DirectUDPSocketChunkReceivedEvent, + DirectUDPSocketChunkSentEvent, + DirectUDPSocketClosedEvent, + DirectUDPSocketCreatedEvent, + DirectUDPSocketJoinedMulticastGroupEvent, + DirectUDPSocketLeftMulticastGroupEvent, + DirectUDPSocketOpenedEvent, + EventSourceMessageReceivedEvent, + LoadingFailedEvent, + LoadingFinishedEvent, + PolicyUpdatedEvent, + ReportingApiEndpointsChangedForOriginEvent, + ReportingApiReportAddedEvent, + ReportingApiReportUpdatedEvent, + RequestInterceptedEvent, + RequestServedFromCacheEvent, + RequestWillBeSentEvent, + RequestWillBeSentExtraInfoEvent, + ResourceChangedPriorityEvent, + ResponseReceivedEarlyHintsEvent, + ResponseReceivedEvent, + ResponseReceivedExtraInfoEvent, + SignedExchangeReceivedEvent, + TrustTokenOperationDoneEvent, + WebSocketClosedEvent, + WebSocketCreatedEvent, + WebSocketFrameErrorEvent, + WebSocketFrameReceivedEvent, + WebSocketFrameSentEvent, + WebSocketHandshakeResponseReceivedEvent, + WebSocketWillSendHandshakeRequestEvent, + WebTransportClosedEvent, + WebTransportConnectionEstablishedEvent, + WebTransportCreatedEvent, + ) + class NetworkRegistration: """Event registration interface for Network domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Network" def dataReceived( self, - callback: Callable[['DataReceivedEvent', Optional[str]], None], + callback: Callable[["DataReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for dataReceived events. - + Fired when data chunk was received over the network. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -81,13 +80,13 @@ def dataReceived( def eventSourceMessageReceived( self, - callback: Callable[['EventSourceMessageReceivedEvent', Optional[str]], None], + callback: Callable[["EventSourceMessageReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for eventSourceMessageReceived events. - + Fired when EventSource message is received. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -96,13 +95,13 @@ def eventSourceMessageReceived( def loadingFailed( self, - callback: Callable[['LoadingFailedEvent', Optional[str]], None], + callback: Callable[["LoadingFailedEvent", Optional[str]], None], ) -> None: """ Register a callback for loadingFailed events. - + Fired when HTTP request has failed to load. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -111,13 +110,13 @@ def loadingFailed( def loadingFinished( self, - callback: Callable[['LoadingFinishedEvent', Optional[str]], None], + callback: Callable[["LoadingFinishedEvent", Optional[str]], None], ) -> None: """ Register a callback for loadingFinished events. - + Fired when HTTP request has finished loading. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -126,30 +125,30 @@ def loadingFinished( def requestIntercepted( self, - callback: Callable[['RequestInterceptedEvent', Optional[str]], None], + callback: Callable[["RequestInterceptedEvent", Optional[str]], None], ) -> None: """ - Register a callback for requestIntercepted events. - - Details of an intercepted HTTP request, which must be either allowed, blocked, modified or -mocked. -Deprecated, use Fetch.requestPaused instead. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for requestIntercepted events. + + Details of an intercepted HTTP request, which must be either allowed, blocked, modified or + mocked. + Deprecated, use Fetch.requestPaused instead. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Network.requestIntercepted", callback) def requestServedFromCache( self, - callback: Callable[['RequestServedFromCacheEvent', Optional[str]], None], + callback: Callable[["RequestServedFromCacheEvent", Optional[str]], None], ) -> None: """ Register a callback for requestServedFromCache events. - + Fired if request ended up loading from cache. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -158,13 +157,13 @@ def requestServedFromCache( def requestWillBeSent( self, - callback: Callable[['RequestWillBeSentEvent', Optional[str]], None], + callback: Callable[["RequestWillBeSentEvent", Optional[str]], None], ) -> None: """ Register a callback for requestWillBeSent events. - + Fired when page is about to send HTTP request. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -173,13 +172,13 @@ def requestWillBeSent( def resourceChangedPriority( self, - callback: Callable[['ResourceChangedPriorityEvent', Optional[str]], None], + callback: Callable[["ResourceChangedPriorityEvent", Optional[str]], None], ) -> None: """ Register a callback for resourceChangedPriority events. - + Fired when resource loading priority is changed - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -188,13 +187,13 @@ def resourceChangedPriority( def signedExchangeReceived( self, - callback: Callable[['SignedExchangeReceivedEvent', Optional[str]], None], + callback: Callable[["SignedExchangeReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for signedExchangeReceived events. - + Fired when a signed exchange was received over the network - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -203,13 +202,13 @@ def signedExchangeReceived( def responseReceived( self, - callback: Callable[['ResponseReceivedEvent', Optional[str]], None], + callback: Callable[["ResponseReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for responseReceived events. - + Fired when HTTP response is available. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -218,13 +217,13 @@ def responseReceived( def webSocketClosed( self, - callback: Callable[['WebSocketClosedEvent', Optional[str]], None], + callback: Callable[["WebSocketClosedEvent", Optional[str]], None], ) -> None: """ Register a callback for webSocketClosed events. - + Fired when WebSocket is closed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -233,13 +232,13 @@ def webSocketClosed( def webSocketCreated( self, - callback: Callable[['WebSocketCreatedEvent', Optional[str]], None], + callback: Callable[["WebSocketCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for webSocketCreated events. - + Fired upon WebSocket creation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -248,13 +247,13 @@ def webSocketCreated( def webSocketFrameError( self, - callback: Callable[['WebSocketFrameErrorEvent', Optional[str]], None], + callback: Callable[["WebSocketFrameErrorEvent", Optional[str]], None], ) -> None: """ Register a callback for webSocketFrameError events. - + Fired when WebSocket message error occurs. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -263,13 +262,13 @@ def webSocketFrameError( def webSocketFrameReceived( self, - callback: Callable[['WebSocketFrameReceivedEvent', Optional[str]], None], + callback: Callable[["WebSocketFrameReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for webSocketFrameReceived events. - + Fired when WebSocket message is received. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -278,13 +277,13 @@ def webSocketFrameReceived( def webSocketFrameSent( self, - callback: Callable[['WebSocketFrameSentEvent', Optional[str]], None], + callback: Callable[["WebSocketFrameSentEvent", Optional[str]], None], ) -> None: """ Register a callback for webSocketFrameSent events. - + Fired when WebSocket message is sent. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -293,13 +292,15 @@ def webSocketFrameSent( def webSocketHandshakeResponseReceived( self, - callback: Callable[['WebSocketHandshakeResponseReceivedEvent', Optional[str]], None], + callback: Callable[ + ["WebSocketHandshakeResponseReceivedEvent", Optional[str]], None + ], ) -> None: """ Register a callback for webSocketHandshakeResponseReceived events. - + Fired when WebSocket handshake response becomes available. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -308,13 +309,15 @@ def webSocketHandshakeResponseReceived( def webSocketWillSendHandshakeRequest( self, - callback: Callable[['WebSocketWillSendHandshakeRequestEvent', Optional[str]], None], + callback: Callable[ + ["WebSocketWillSendHandshakeRequestEvent", Optional[str]], None + ], ) -> None: """ Register a callback for webSocketWillSendHandshakeRequest events. - + Fired when WebSocket is about to initiate handshake. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -323,13 +326,13 @@ def webSocketWillSendHandshakeRequest( def webTransportCreated( self, - callback: Callable[['WebTransportCreatedEvent', Optional[str]], None], + callback: Callable[["WebTransportCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for webTransportCreated events. - + Fired upon WebTransport creation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -338,13 +341,15 @@ def webTransportCreated( def webTransportConnectionEstablished( self, - callback: Callable[['WebTransportConnectionEstablishedEvent', Optional[str]], None], + callback: Callable[ + ["WebTransportConnectionEstablishedEvent", Optional[str]], None + ], ) -> None: """ Register a callback for webTransportConnectionEstablished events. - + Fired when WebTransport handshake is finished. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -353,13 +358,13 @@ def webTransportConnectionEstablished( def webTransportClosed( self, - callback: Callable[['WebTransportClosedEvent', Optional[str]], None], + callback: Callable[["WebTransportClosedEvent", Optional[str]], None], ) -> None: """ Register a callback for webTransportClosed events. - + Fired when WebTransport is disposed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -368,13 +373,13 @@ def webTransportClosed( def directTCPSocketCreated( self, - callback: Callable[['DirectTCPSocketCreatedEvent', Optional[str]], None], + callback: Callable[["DirectTCPSocketCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for directTCPSocketCreated events. - + Fired upon direct_socket.TCPSocket creation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -383,13 +388,13 @@ def directTCPSocketCreated( def directTCPSocketOpened( self, - callback: Callable[['DirectTCPSocketOpenedEvent', Optional[str]], None], + callback: Callable[["DirectTCPSocketOpenedEvent", Optional[str]], None], ) -> None: """ Register a callback for directTCPSocketOpened events. - + Fired when direct_socket.TCPSocket connection is opened. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -398,13 +403,13 @@ def directTCPSocketOpened( def directTCPSocketAborted( self, - callback: Callable[['DirectTCPSocketAbortedEvent', Optional[str]], None], + callback: Callable[["DirectTCPSocketAbortedEvent", Optional[str]], None], ) -> None: """ Register a callback for directTCPSocketAborted events. - + Fired when direct_socket.TCPSocket is aborted. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -413,13 +418,13 @@ def directTCPSocketAborted( def directTCPSocketClosed( self, - callback: Callable[['DirectTCPSocketClosedEvent', Optional[str]], None], + callback: Callable[["DirectTCPSocketClosedEvent", Optional[str]], None], ) -> None: """ Register a callback for directTCPSocketClosed events. - + Fired when direct_socket.TCPSocket is closed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -428,13 +433,13 @@ def directTCPSocketClosed( def directTCPSocketChunkSent( self, - callback: Callable[['DirectTCPSocketChunkSentEvent', Optional[str]], None], + callback: Callable[["DirectTCPSocketChunkSentEvent", Optional[str]], None], ) -> None: """ Register a callback for directTCPSocketChunkSent events. - + Fired when data is sent to tcp direct socket stream. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -443,28 +448,58 @@ def directTCPSocketChunkSent( def directTCPSocketChunkReceived( self, - callback: Callable[['DirectTCPSocketChunkReceivedEvent', Optional[str]], None], + callback: Callable[["DirectTCPSocketChunkReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for directTCPSocketChunkReceived events. - + Fired when data is received from tcp direct socket stream. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Network.directTCPSocketChunkReceived", callback) + def directUDPSocketJoinedMulticastGroup( + self, + callback: Callable[ + ["DirectUDPSocketJoinedMulticastGroupEvent", Optional[str]], None + ], + ) -> None: + """ + Register a callback for directUDPSocketJoinedMulticastGroup events. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("Network.directUDPSocketJoinedMulticastGroup", callback) + + def directUDPSocketLeftMulticastGroup( + self, + callback: Callable[ + ["DirectUDPSocketLeftMulticastGroupEvent", Optional[str]], None + ], + ) -> None: + """ + Register a callback for directUDPSocketLeftMulticastGroup events. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. + """ + self._registry.register("Network.directUDPSocketLeftMulticastGroup", callback) + def directUDPSocketCreated( self, - callback: Callable[['DirectUDPSocketCreatedEvent', Optional[str]], None], + callback: Callable[["DirectUDPSocketCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for directUDPSocketCreated events. - + Fired upon direct_socket.UDPSocket creation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -473,13 +508,13 @@ def directUDPSocketCreated( def directUDPSocketOpened( self, - callback: Callable[['DirectUDPSocketOpenedEvent', Optional[str]], None], + callback: Callable[["DirectUDPSocketOpenedEvent", Optional[str]], None], ) -> None: """ Register a callback for directUDPSocketOpened events. - + Fired when direct_socket.UDPSocket connection is opened. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -488,13 +523,13 @@ def directUDPSocketOpened( def directUDPSocketAborted( self, - callback: Callable[['DirectUDPSocketAbortedEvent', Optional[str]], None], + callback: Callable[["DirectUDPSocketAbortedEvent", Optional[str]], None], ) -> None: """ Register a callback for directUDPSocketAborted events. - + Fired when direct_socket.UDPSocket is aborted. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -503,13 +538,13 @@ def directUDPSocketAborted( def directUDPSocketClosed( self, - callback: Callable[['DirectUDPSocketClosedEvent', Optional[str]], None], + callback: Callable[["DirectUDPSocketClosedEvent", Optional[str]], None], ) -> None: """ Register a callback for directUDPSocketClosed events. - + Fired when direct_socket.UDPSocket is closed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -518,13 +553,13 @@ def directUDPSocketClosed( def directUDPSocketChunkSent( self, - callback: Callable[['DirectUDPSocketChunkSentEvent', Optional[str]], None], + callback: Callable[["DirectUDPSocketChunkSentEvent", Optional[str]], None], ) -> None: """ Register a callback for directUDPSocketChunkSent events. - + Fired when message is sent to udp direct socket stream. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -533,13 +568,13 @@ def directUDPSocketChunkSent( def directUDPSocketChunkReceived( self, - callback: Callable[['DirectUDPSocketChunkReceivedEvent', Optional[str]], None], + callback: Callable[["DirectUDPSocketChunkReceivedEvent", Optional[str]], None], ) -> None: """ Register a callback for directUDPSocketChunkReceived events. - + Fired when message is received from udp direct socket stream. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -548,174 +583,112 @@ def directUDPSocketChunkReceived( def requestWillBeSentExtraInfo( self, - callback: Callable[['RequestWillBeSentExtraInfoEvent', Optional[str]], None], + callback: Callable[["RequestWillBeSentExtraInfoEvent", Optional[str]], None], ) -> None: """ - Register a callback for requestWillBeSentExtraInfo events. - - Fired when additional information about a requestWillBeSent event is available from the -network stack. Not every requestWillBeSent event will have an additional -requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent -or requestWillBeSentExtraInfo will be fired first for the same request. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for requestWillBeSentExtraInfo events. + + Fired when additional information about a requestWillBeSent event is available from the + network stack. Not every requestWillBeSent event will have an additional + requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent + or requestWillBeSentExtraInfo will be fired first for the same request. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Network.requestWillBeSentExtraInfo", callback) def responseReceivedExtraInfo( self, - callback: Callable[['ResponseReceivedExtraInfoEvent', Optional[str]], None], + callback: Callable[["ResponseReceivedExtraInfoEvent", Optional[str]], None], ) -> None: """ - Register a callback for responseReceivedExtraInfo events. - - Fired when additional information about a responseReceived event is available from the network -stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for -it, and responseReceivedExtraInfo may be fired before or after responseReceived. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for responseReceivedExtraInfo events. + + Fired when additional information about a responseReceived event is available from the network + stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for + it, and responseReceivedExtraInfo may be fired before or after responseReceived. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Network.responseReceivedExtraInfo", callback) def responseReceivedEarlyHints( self, - callback: Callable[['ResponseReceivedEarlyHintsEvent', Optional[str]], None], + callback: Callable[["ResponseReceivedEarlyHintsEvent", Optional[str]], None], ) -> None: """ - Register a callback for responseReceivedEarlyHints events. - - Fired when 103 Early Hints headers is received in addition to the common response. -Not every responseReceived event will have an responseReceivedEarlyHints fired. -Only one responseReceivedEarlyHints may be fired for eached responseReceived event. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for responseReceivedEarlyHints events. + + Fired when 103 Early Hints headers is received in addition to the common response. + Not every responseReceived event will have an responseReceivedEarlyHints fired. + Only one responseReceivedEarlyHints may be fired for eached responseReceived event. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Network.responseReceivedEarlyHints", callback) def trustTokenOperationDone( self, - callback: Callable[['TrustTokenOperationDoneEvent', Optional[str]], None], + callback: Callable[["TrustTokenOperationDoneEvent", Optional[str]], None], ) -> None: """ - Register a callback for trustTokenOperationDone events. - - Fired exactly once for each Trust Token operation. Depending on -the type of the operation and whether the operation succeeded or -failed, the event is fired before the corresponding request was sent -or after the response was received. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for trustTokenOperationDone events. + + Fired exactly once for each Trust Token operation. Depending on + the type of the operation and whether the operation succeeded or + failed, the event is fired before the corresponding request was sent + or after the response was received. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Network.trustTokenOperationDone", callback) def policyUpdated( self, - callback: Callable[['PolicyUpdatedEvent', Optional[str]], None], + callback: Callable[["PolicyUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for policyUpdated events. - - Fired once security policy has been updated. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. - """ - self._registry.register("Network.policyUpdated", callback) - def subresourceWebBundleMetadataReceived( - self, - callback: Callable[['SubresourceWebBundleMetadataReceivedEvent', Optional[str]], None], - ) -> None: - """ - Register a callback for subresourceWebBundleMetadataReceived events. - - Fired once when parsing the .wbn file has succeeded. -The event contains the information about the web bundle contents. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. - """ - self._registry.register("Network.subresourceWebBundleMetadataReceived", callback) + Fired once security policy has been updated. - def subresourceWebBundleMetadataError( - self, - callback: Callable[['SubresourceWebBundleMetadataErrorEvent', Optional[str]], None], - ) -> None: - """ - Register a callback for subresourceWebBundleMetadataError events. - - Fired once when parsing the .wbn file has failed. - Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ - self._registry.register("Network.subresourceWebBundleMetadataError", callback) + self._registry.register("Network.policyUpdated", callback) - def subresourceWebBundleInnerResponseParsed( + def reportingApiReportAdded( self, - callback: Callable[['SubresourceWebBundleInnerResponseParsedEvent', Optional[str]], None], + callback: Callable[["ReportingApiReportAddedEvent", Optional[str]], None], ) -> None: """ - Register a callback for subresourceWebBundleInnerResponseParsed events. - - Fired when handling requests for resources within a .wbn file. -Note: this will only be fired for resources that are requested by the webpage. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. - """ - self._registry.register("Network.subresourceWebBundleInnerResponseParsed", callback) + Register a callback for reportingApiReportAdded events. - def subresourceWebBundleInnerResponseError( - self, - callback: Callable[['SubresourceWebBundleInnerResponseErrorEvent', Optional[str]], None], - ) -> None: - """ - Register a callback for subresourceWebBundleInnerResponseError events. - - Fired when request for resources within a .wbn file failed. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. - """ - self._registry.register("Network.subresourceWebBundleInnerResponseError", callback) + Is sent whenever a new report is added. + And after 'enableReportingApi' for all existing reports. - def reportingApiReportAdded( - self, - callback: Callable[['ReportingApiReportAddedEvent', Optional[str]], None], - ) -> None: - """ - Register a callback for reportingApiReportAdded events. - - Is sent whenever a new report is added. -And after 'enableReportingApi' for all existing reports. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Network.reportingApiReportAdded", callback) def reportingApiReportUpdated( self, - callback: Callable[['ReportingApiReportUpdatedEvent', Optional[str]], None], + callback: Callable[["ReportingApiReportUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for reportingApiReportUpdated events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -724,14 +697,17 @@ def reportingApiReportUpdated( def reportingApiEndpointsChangedForOrigin( self, - callback: Callable[['ReportingApiEndpointsChangedForOriginEvent', Optional[str]], None], + callback: Callable[ + ["ReportingApiEndpointsChangedForOriginEvent", Optional[str]], None + ], ) -> None: """ Register a callback for reportingApiEndpointsChangedForOrigin events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ - self._registry.register("Network.reportingApiEndpointsChangedForOrigin", callback) - + self._registry.register( + "Network.reportingApiEndpointsChangedForOrigin", callback + ) diff --git a/cdp_use/cdp/network/types.py b/cdp_use/cdp/network/types.py index eb9c87f..02e212a 100644 --- a/cdp_use/cdp/network/types.py +++ b/cdp_use/cdp/network/types.py @@ -17,72 +17,105 @@ from ..security.types import MixedContentType from ..security.types import SecurityState -ResourceType = Literal["Document", "Stylesheet", "Image", "Media", "Font", "Script", "TextTrack", "XHR", "Fetch", "Prefetch", "EventSource", "WebSocket", "Manifest", "SignedExchange", "Ping", "CSPViolationReport", "Preflight", "FedCM", "Other"] +ResourceType = Literal[ + "Document", + "Stylesheet", + "Image", + "Media", + "Font", + "Script", + "TextTrack", + "XHR", + "Fetch", + "Prefetch", + "EventSource", + "WebSocket", + "Manifest", + "SignedExchange", + "Ping", + "CSPViolationReport", + "Preflight", + "FedCM", + "Other", +] """Resource type as it was perceived by the rendering engine.""" - LoaderId = str """Unique loader identifier.""" - RequestId = str """Unique network request identifier. Note that this does not identify individual HTTP requests that are part of a network request.""" - InterceptionId = str """Unique intercepted request identifier.""" - -ErrorReason = Literal["Failed", "Aborted", "TimedOut", "AccessDenied", "ConnectionClosed", "ConnectionReset", "ConnectionRefused", "ConnectionAborted", "ConnectionFailed", "NameNotResolved", "InternetDisconnected", "AddressUnreachable", "BlockedByClient", "BlockedByResponse"] +ErrorReason = Literal[ + "Failed", + "Aborted", + "TimedOut", + "AccessDenied", + "ConnectionClosed", + "ConnectionReset", + "ConnectionRefused", + "ConnectionAborted", + "ConnectionFailed", + "NameNotResolved", + "InternetDisconnected", + "AddressUnreachable", + "BlockedByClient", + "BlockedByResponse", +] """Network level fetch failure reason.""" - TimeSinceEpoch = float """UTC time in seconds, counted from January 1, 1970.""" - MonotonicTime = float """Monotonically increasing time in seconds since an arbitrary point in the past.""" - class Headers(TypedDict): """Request / response headers as keys / values of JSON object.""" - -ConnectionType = Literal["none", "cellular2g", "cellular3g", "cellular4g", "bluetooth", "ethernet", "wifi", "wimax", "other"] +ConnectionType = Literal[ + "none", + "cellular2g", + "cellular3g", + "cellular4g", + "bluetooth", + "ethernet", + "wifi", + "wimax", + "other", +] """The underlying connection technology that the browser is supposedly using.""" - CookieSameSite = Literal["Strict", "Lax", "None"] """Represents the cookie's 'SameSite' status: https://tools.ietf.org/html/draft-west-first-party-cookies""" - CookiePriority = Literal["Low", "Medium", "High"] """Represents the cookie's 'Priority' status: https://tools.ietf.org/html/draft-west-cookie-priority-00""" - CookieSourceScheme = Literal["Unset", "NonSecure", "Secure"] """Represents the source scheme of the origin that originally set the cookie. A value of "Unset" allows protocol clients to emulate legacy cookie scope for the scheme. This is a temporary ability and it will be removed in the future.""" - class ResourceTiming(TypedDict): """Timing information for the request.""" @@ -131,19 +164,16 @@ class ResourceTiming(TypedDict): """Finished receiving response headers.""" - ResourcePriority = Literal["VeryLow", "Low", "Medium", "High", "VeryHigh"] """Loading priority of a resource request.""" - class PostDataEntry(TypedDict, total=False): """Post data entry for HTTP request""" bytes: "str" - class Request(TypedDict): """HTTP request data.""" @@ -176,7 +206,8 @@ class Request(TypedDict): isSameSite: "NotRequired[bool]" """True if this resource request is considered to be the 'same site' as the request corresponding to the main frame.""" - + isAdRelated: "NotRequired[bool]" + """True when the resource request is ad-related.""" class SignedCertificateTimestamp(TypedDict): @@ -201,7 +232,6 @@ class SignedCertificateTimestamp(TypedDict): """Signature data.""" - class SecurityDetails(TypedDict): """Security details about a request.""" @@ -239,43 +269,86 @@ class SecurityDetails(TypedDict): """Whether the connection used Encrypted ClientHello""" - CertificateTransparencyCompliance = Literal["unknown", "not-compliant", "compliant"] """Whether the request complied with Certificate Transparency policy.""" - -BlockedReason = Literal["other", "csp", "mixed-content", "origin", "inspector", "integrity", "subresource-filter", "content-type", "coep-frame-resource-needs-coep-header", "coop-sandboxed-iframe-cannot-navigate-to-coop-page", "corp-not-same-origin", "corp-not-same-origin-after-defaulted-to-same-origin-by-coep", "corp-not-same-origin-after-defaulted-to-same-origin-by-dip", "corp-not-same-origin-after-defaulted-to-same-origin-by-coep-and-dip", "corp-not-same-site", "sri-message-signature-mismatch"] +BlockedReason = Literal[ + "other", + "csp", + "mixed-content", + "origin", + "inspector", + "integrity", + "subresource-filter", + "content-type", + "coep-frame-resource-needs-coep-header", + "coop-sandboxed-iframe-cannot-navigate-to-coop-page", + "corp-not-same-origin", + "corp-not-same-origin-after-defaulted-to-same-origin-by-coep", + "corp-not-same-origin-after-defaulted-to-same-origin-by-dip", + "corp-not-same-origin-after-defaulted-to-same-origin-by-coep-and-dip", + "corp-not-same-site", + "sri-message-signature-mismatch", +] """The reason why request was blocked.""" - -IpProxyStatus = Literal["Available", "FeatureNotEnabled", "MaskedDomainListNotEnabled", "MaskedDomainListNotPopulated", "AuthTokensUnavailable", "Unavailable", "BypassedByDevTools"] -"""Sets Controls for IP Proxy of requests. -Page reload is required before the new behavior will be observed.""" - - - -CorsError = Literal["DisallowedByMode", "InvalidResponse", "WildcardOriginNotAllowed", "MissingAllowOriginHeader", "MultipleAllowOriginValues", "InvalidAllowOriginValue", "AllowOriginMismatch", "InvalidAllowCredentials", "CorsDisabledScheme", "PreflightInvalidStatus", "PreflightDisallowedRedirect", "PreflightWildcardOriginNotAllowed", "PreflightMissingAllowOriginHeader", "PreflightMultipleAllowOriginValues", "PreflightInvalidAllowOriginValue", "PreflightAllowOriginMismatch", "PreflightInvalidAllowCredentials", "PreflightMissingAllowExternal", "PreflightInvalidAllowExternal", "PreflightMissingAllowPrivateNetwork", "PreflightInvalidAllowPrivateNetwork", "InvalidAllowMethodsPreflightResponse", "InvalidAllowHeadersPreflightResponse", "MethodDisallowedByPreflightResponse", "HeaderDisallowedByPreflightResponse", "RedirectContainsCredentials", "InsecurePrivateNetwork", "InvalidPrivateNetworkAccess", "UnexpectedPrivateNetworkAccess", "NoCorsRedirectModeNotFollow", "PreflightMissingPrivateNetworkAccessId", "PreflightMissingPrivateNetworkAccessName", "PrivateNetworkAccessPermissionUnavailable", "PrivateNetworkAccessPermissionDenied", "LocalNetworkAccessPermissionDenied"] +CorsError = Literal[ + "DisallowedByMode", + "InvalidResponse", + "WildcardOriginNotAllowed", + "MissingAllowOriginHeader", + "MultipleAllowOriginValues", + "InvalidAllowOriginValue", + "AllowOriginMismatch", + "InvalidAllowCredentials", + "CorsDisabledScheme", + "PreflightInvalidStatus", + "PreflightDisallowedRedirect", + "PreflightWildcardOriginNotAllowed", + "PreflightMissingAllowOriginHeader", + "PreflightMultipleAllowOriginValues", + "PreflightInvalidAllowOriginValue", + "PreflightAllowOriginMismatch", + "PreflightInvalidAllowCredentials", + "PreflightMissingAllowExternal", + "PreflightInvalidAllowExternal", + "PreflightMissingAllowPrivateNetwork", + "PreflightInvalidAllowPrivateNetwork", + "InvalidAllowMethodsPreflightResponse", + "InvalidAllowHeadersPreflightResponse", + "MethodDisallowedByPreflightResponse", + "HeaderDisallowedByPreflightResponse", + "RedirectContainsCredentials", + "InsecurePrivateNetwork", + "InvalidPrivateNetworkAccess", + "UnexpectedPrivateNetworkAccess", + "NoCorsRedirectModeNotFollow", + "PreflightMissingPrivateNetworkAccessId", + "PreflightMissingPrivateNetworkAccessName", + "PrivateNetworkAccessPermissionUnavailable", + "PrivateNetworkAccessPermissionDenied", + "LocalNetworkAccessPermissionDenied", +] """The reason why request was blocked.""" - class CorsErrorStatus(TypedDict): corsError: "CorsError" failedParameter: "str" - -ServiceWorkerResponseSource = Literal["cache-storage", "http-cache", "fallback-code", "network"] +ServiceWorkerResponseSource = Literal[ + "cache-storage", "http-cache", "fallback-code", "network" +] """Source of serviceworker response.""" - class TrustTokenParams(TypedDict): """Determines what type of Trust Token operation is executed and -depending on the type, some additional parameters. The values -are specified in third_party/blink/renderer/core/fetch/trust_token.idl.""" + depending on the type, some additional parameters. The values + are specified in third_party/blink/renderer/core/fetch/trust_token.idl.""" operation: "TrustTokenOperationType" refreshPolicy: "str" @@ -286,21 +359,32 @@ class TrustTokenParams(TypedDict): records.""" - TrustTokenOperationType = Literal["Issuance", "Redemption", "Signing"] - -AlternateProtocolUsage = Literal["alternativeJobWonWithoutRace", "alternativeJobWonRace", "mainJobWonRace", "mappingMissing", "broken", "dnsAlpnH3JobWonWithoutRace", "dnsAlpnH3JobWonRace", "unspecifiedReason"] +AlternateProtocolUsage = Literal[ + "alternativeJobWonWithoutRace", + "alternativeJobWonRace", + "mainJobWonRace", + "mappingMissing", + "broken", + "dnsAlpnH3JobWonWithoutRace", + "dnsAlpnH3JobWonRace", + "unspecifiedReason", +] """The reason why Chrome uses a specific transport protocol for HTTP semantics.""" - -ServiceWorkerRouterSource = Literal["network", "cache", "fetch-event", "race-network-and-fetch-handler", "race-network-and-cache"] +ServiceWorkerRouterSource = Literal[ + "network", + "cache", + "fetch-event", + "race-network-and-fetch-handler", + "race-network-and-cache", +] """Source of service worker router.""" - class ServiceWorkerRouterInfo(TypedDict, total=False): ruleIdMatched: "int" """ID of the rule matched. If there is a matched rule, this field will @@ -312,7 +396,6 @@ class ServiceWorkerRouterInfo(TypedDict, total=False): """The actual router source used.""" - class Response(TypedDict): """HTTP response data.""" @@ -373,10 +456,6 @@ class Response(TypedDict): """Security state of the request resource.""" securityDetails: "NotRequired[SecurityDetails]" """Security details for the request.""" - isIpProtectionUsed: "NotRequired[bool]" - """Indicates whether the request was sent through IP Protection proxies. If -set to true, the request used the IP Protection privacy feature.""" - class WebSocketRequest(TypedDict): @@ -386,7 +465,6 @@ class WebSocketRequest(TypedDict): """HTTP request headers.""" - class WebSocketResponse(TypedDict): """WebSocket response data.""" @@ -404,7 +482,6 @@ class WebSocketResponse(TypedDict): """HTTP request headers text.""" - class WebSocketFrame(TypedDict): """WebSocket message data. This represents an entire WebSocket message, not just a fragmented frame as the name suggests.""" @@ -418,7 +495,6 @@ class WebSocketFrame(TypedDict): If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data.""" - class CachedResource(TypedDict): """Information about the cached resource.""" @@ -432,7 +508,6 @@ class CachedResource(TypedDict): """Cached response body size.""" - class Initiator(TypedDict): """Information about the request initiator.""" @@ -453,10 +528,9 @@ class Initiator(TypedDict): """Set if another request triggered this request (e.g. preflight).""" - class CookiePartitionKey(TypedDict): """cookiePartitionKey object -The representation of the components of the key that are created by the cookiePartitionKey class contained in net/cookies/cookie_partition_key.h.""" + The representation of the components of the key that are created by the cookiePartitionKey class contained in net/cookies/cookie_partition_key.h.""" topLevelSite: "str" """The site of the top-level URL the browser was visiting at the start @@ -465,7 +539,6 @@ class CookiePartitionKey(TypedDict): """Indicates if the cookie has any ancestors that are cross-site to the topLevelSite.""" - class Cookie(TypedDict): """Cookie object""" @@ -478,7 +551,10 @@ class Cookie(TypedDict): path: "str" """Cookie path.""" expires: "float" - """Cookie expiration date as the number of seconds since the UNIX epoch.""" + """Cookie expiration date as the number of seconds since the UNIX epoch. +The value is set to -1 if the expiry date is not set. +The value can be null for values that cannot be represented in +JSON (±Inf).""" size: "int" """Cookie size.""" httpOnly: "bool" @@ -505,22 +581,73 @@ class Cookie(TypedDict): """True if cookie partition key is opaque.""" - -SetCookieBlockedReason = Literal["SecureOnly", "SameSiteStrict", "SameSiteLax", "SameSiteUnspecifiedTreatedAsLax", "SameSiteNoneInsecure", "UserPreferences", "ThirdPartyPhaseout", "ThirdPartyBlockedInFirstPartySet", "SyntaxError", "SchemeNotSupported", "OverwriteSecure", "InvalidDomain", "InvalidPrefix", "UnknownError", "SchemefulSameSiteStrict", "SchemefulSameSiteLax", "SchemefulSameSiteUnspecifiedTreatedAsLax", "SamePartyFromCrossPartyContext", "SamePartyConflictsWithOtherAttributes", "NameValuePairExceedsMaxSize", "DisallowedCharacter", "NoCookieContent"] +SetCookieBlockedReason = Literal[ + "SecureOnly", + "SameSiteStrict", + "SameSiteLax", + "SameSiteUnspecifiedTreatedAsLax", + "SameSiteNoneInsecure", + "UserPreferences", + "ThirdPartyPhaseout", + "ThirdPartyBlockedInFirstPartySet", + "SyntaxError", + "SchemeNotSupported", + "OverwriteSecure", + "InvalidDomain", + "InvalidPrefix", + "UnknownError", + "SchemefulSameSiteStrict", + "SchemefulSameSiteLax", + "SchemefulSameSiteUnspecifiedTreatedAsLax", + "SamePartyFromCrossPartyContext", + "SamePartyConflictsWithOtherAttributes", + "NameValuePairExceedsMaxSize", + "DisallowedCharacter", + "NoCookieContent", +] """Types of reasons why a cookie may not be stored from a response.""" - -CookieBlockedReason = Literal["SecureOnly", "NotOnPath", "DomainMismatch", "SameSiteStrict", "SameSiteLax", "SameSiteUnspecifiedTreatedAsLax", "SameSiteNoneInsecure", "UserPreferences", "ThirdPartyPhaseout", "ThirdPartyBlockedInFirstPartySet", "UnknownError", "SchemefulSameSiteStrict", "SchemefulSameSiteLax", "SchemefulSameSiteUnspecifiedTreatedAsLax", "SamePartyFromCrossPartyContext", "NameValuePairExceedsMaxSize", "PortMismatch", "SchemeMismatch", "AnonymousContext"] +CookieBlockedReason = Literal[ + "SecureOnly", + "NotOnPath", + "DomainMismatch", + "SameSiteStrict", + "SameSiteLax", + "SameSiteUnspecifiedTreatedAsLax", + "SameSiteNoneInsecure", + "UserPreferences", + "ThirdPartyPhaseout", + "ThirdPartyBlockedInFirstPartySet", + "UnknownError", + "SchemefulSameSiteStrict", + "SchemefulSameSiteLax", + "SchemefulSameSiteUnspecifiedTreatedAsLax", + "SamePartyFromCrossPartyContext", + "NameValuePairExceedsMaxSize", + "PortMismatch", + "SchemeMismatch", + "AnonymousContext", +] """Types of reasons why a cookie may not be sent with a request.""" - -CookieExemptionReason = Literal["None", "UserSetting", "TPCDMetadata", "TPCDDeprecationTrial", "TopLevelTPCDDeprecationTrial", "TPCDHeuristics", "EnterprisePolicy", "StorageAccess", "TopLevelStorageAccess", "Scheme", "SameSiteNoneCookiesInSandbox"] +CookieExemptionReason = Literal[ + "None", + "UserSetting", + "TPCDMetadata", + "TPCDDeprecationTrial", + "TopLevelTPCDDeprecationTrial", + "TPCDHeuristics", + "EnterprisePolicy", + "StorageAccess", + "TopLevelStorageAccess", + "Scheme", + "SameSiteNoneCookiesInSandbox", +] """Types of reasons why a cookie should have been blocked by 3PCD but is exempted for the request.""" - class BlockedSetCookieWithReason(TypedDict): """A cookie which was not stored from a response with the corresponding reason.""" @@ -535,10 +662,9 @@ class BlockedSetCookieWithReason(TypedDict): errors.""" - class ExemptedSetCookieWithReason(TypedDict): """A cookie should have been blocked by 3PCD but is exempted and stored from a response with the -corresponding reason. A cookie could only have at most one exemption reason.""" + corresponding reason. A cookie could only have at most one exemption reason.""" exemptionReason: "CookieExemptionReason" """The reason the cookie was exempted.""" @@ -548,10 +674,9 @@ class ExemptedSetCookieWithReason(TypedDict): """The cookie object representing the cookie.""" - class AssociatedCookie(TypedDict): """A cookie associated with the request which may or may not be sent with it. -Includes the cookies itself and reasons for blocking or exemption.""" + Includes the cookies itself and reasons for blocking or exemption.""" cookie: "Cookie" """The cookie object representing the cookie which was not sent.""" @@ -562,7 +687,6 @@ class AssociatedCookie(TypedDict): only have at most one exemption reason.""" - class CookieParam(TypedDict): """Cookie parameter object""" @@ -599,7 +723,6 @@ class CookieParam(TypedDict): """Cookie partition key. If not set, the cookie will be set as not partitioned.""" - class AuthChallenge(TypedDict): """Authorization challenge for HTTP status code 401 or 407.""" @@ -613,7 +736,6 @@ class AuthChallenge(TypedDict): """The realm of the challenge. May be empty.""" - class AuthChallengeResponse(TypedDict): """Response to an AuthChallenge.""" @@ -629,13 +751,11 @@ class AuthChallengeResponse(TypedDict): ProvideCredentials.""" - InterceptionStage = Literal["Request", "HeadersReceived"] """Stages of the interception to begin intercepting. Request will intercept before the request is sent. Response will intercept after the response is received.""" - class RequestPattern(TypedDict, total=False): """Request pattern for interception.""" @@ -648,10 +768,9 @@ class RequestPattern(TypedDict, total=False): """Stage at which to begin intercepting requests. Default is Request.""" - class SignedExchangeSignature(TypedDict): """Information about a signed exchange signature. -https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#rfc.section.3.1""" + https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#rfc.section.3.1""" label: "str" """Signed exchange signature label.""" @@ -673,10 +792,9 @@ class SignedExchangeSignature(TypedDict): """The encoded certificates.""" - class SignedExchangeHeader(TypedDict): """Information about a signed exchange header. -https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cbor-representation""" + https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cbor-representation""" requestUrl: "str" """Signed exchange request URL.""" @@ -690,12 +808,17 @@ class SignedExchangeHeader(TypedDict): """Signed exchange header integrity hash in the form of `sha256-`.""" - -SignedExchangeErrorField = Literal["signatureSig", "signatureIntegrity", "signatureCertUrl", "signatureCertSha256", "signatureValidityUrl", "signatureTimestamps"] +SignedExchangeErrorField = Literal[ + "signatureSig", + "signatureIntegrity", + "signatureCertUrl", + "signatureCertSha256", + "signatureValidityUrl", + "signatureTimestamps", +] """Field type for a signed exchange related error.""" - class SignedExchangeError(TypedDict): """Information about a signed exchange response.""" @@ -707,7 +830,6 @@ class SignedExchangeError(TypedDict): """The field which caused the error.""" - class SignedExchangeInfo(TypedDict): """Information about a signed exchange response.""" @@ -724,14 +846,41 @@ class SignedExchangeInfo(TypedDict): """Errors occurred while handling the signed exchange.""" - ContentEncoding = Literal["deflate", "gzip", "br", "zstd"] """List of content encodings supported by the backend.""" +class NetworkConditions(TypedDict): + urlPattern: "str" + """Only matching requests will be affected by these conditions. Patterns use the URLPattern constructor string +syntax (https://urlpattern.spec.whatwg.org/) and must be absolute. If the pattern is empty, all requests are +matched (including p2p connections).""" + latency: "float" + """Minimum latency from request sent to response headers received (ms).""" + downloadThroughput: "float" + """Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.""" + uploadThroughput: "float" + """Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling.""" + connectionType: "NotRequired[ConnectionType]" + """Connection type if known.""" + packetLoss: "NotRequired[float]" + """WebRTC packet loss (percent, 0-100). 0 disables packet loss emulation, 100 drops all the packets.""" + packetQueueLength: "NotRequired[int]" + """WebRTC packet queue length (packet). 0 removes any queue length limitations.""" + packetReordering: "NotRequired[bool]" + """WebRTC packetReordering feature.""" + + +class BlockPattern(TypedDict): + urlPattern: "str" + """URL pattern to match. Patterns use the URLPattern constructor string syntax +(https://urlpattern.spec.whatwg.org/) and must be absolute. Example: `*://*:*/*.css`.""" + block: "bool" + """Whether or not to block the pattern. If false, a matching request will not be blocked even if it matches a later +`BlockPattern`.""" -DirectSocketDnsQueryType = Literal["ipv4", "ipv6"] +DirectSocketDnsQueryType = Literal["ipv4", "ipv6"] class DirectTCPSocketOptions(TypedDict): @@ -746,7 +895,6 @@ class DirectTCPSocketOptions(TypedDict): dnsQueryType: "NotRequired[DirectSocketDnsQueryType]" - class DirectUDPSocketOptions(TypedDict, total=False): remoteAddr: "str" remotePort: "int" @@ -759,7 +907,10 @@ class DirectUDPSocketOptions(TypedDict, total=False): """Expected to be unsigned integer.""" receiveBufferSize: "float" """Expected to be unsigned integer.""" - + multicastLoopback: "bool" + multicastTimeToLive: "int" + """Unsigned int 8.""" + multicastAllowAddressSharing: "bool" class DirectUDPMessage(TypedDict): @@ -771,15 +922,18 @@ class DirectUDPMessage(TypedDict): Expected to be unsigned integer.""" - -PrivateNetworkRequestPolicy = Literal["Allow", "BlockFromInsecureToMorePrivate", "WarnFromInsecureToMorePrivate", "PreflightBlock", "PreflightWarn", "PermissionBlock", "PermissionWarn"] - +PrivateNetworkRequestPolicy = Literal[ + "Allow", + "BlockFromInsecureToMorePrivate", + "WarnFromInsecureToMorePrivate", + "PermissionBlock", + "PermissionWarn", +] IPAddressSpace = Literal["Loopback", "Local", "Public", "Unknown"] - class ConnectTiming(TypedDict): requestTime: "float" """Timing's requestTime is a baseline in seconds, while the other numbers are ticks in @@ -787,16 +941,21 @@ class ConnectTiming(TypedDict): the same request (but not for redirected requests).""" - class ClientSecurityState(TypedDict): initiatorIsSecureContext: "bool" initiatorIPAddressSpace: "IPAddressSpace" privateNetworkRequestPolicy: "PrivateNetworkRequestPolicy" - -CrossOriginOpenerPolicyValue = Literal["SameOrigin", "SameOriginAllowPopups", "RestrictProperties", "UnsafeNone", "SameOriginPlusCoep", "RestrictPropertiesPlusCoep", "NoopenerAllowPopups"] - +CrossOriginOpenerPolicyValue = Literal[ + "SameOrigin", + "SameOriginAllowPopups", + "RestrictProperties", + "UnsafeNone", + "SameOriginPlusCoep", + "RestrictPropertiesPlusCoep", + "NoopenerAllowPopups", +] class CrossOriginOpenerPolicyStatus(TypedDict): @@ -806,11 +965,9 @@ class CrossOriginOpenerPolicyStatus(TypedDict): reportOnlyReportingEndpoint: "NotRequired[str]" - CrossOriginEmbedderPolicyValue = Literal["None", "Credentialless", "RequireCorp"] - class CrossOriginEmbedderPolicyStatus(TypedDict): value: "CrossOriginEmbedderPolicyValue" reportOnlyValue: "CrossOriginEmbedderPolicyValue" @@ -818,34 +975,28 @@ class CrossOriginEmbedderPolicyStatus(TypedDict): reportOnlyReportingEndpoint: "NotRequired[str]" - ContentSecurityPolicySource = Literal["HTTP", "Meta"] - class ContentSecurityPolicyStatus(TypedDict): effectiveDirectives: "str" isEnforced: "bool" source: "ContentSecurityPolicySource" - class SecurityIsolationStatus(TypedDict, total=False): coop: "CrossOriginOpenerPolicyStatus" coep: "CrossOriginEmbedderPolicyStatus" csp: "List[ContentSecurityPolicyStatus]" - ReportStatus = Literal["Queued", "Pending", "MarkedForRemoval", "Success"] """The status of a Reporting API report.""" - ReportId = str - class ReportingApiReport(TypedDict): """An object representing a report generated by the Reporting API.""" @@ -866,7 +1017,6 @@ class ReportingApiReport(TypedDict): status: "ReportStatus" - class ReportingApiEndpoint(TypedDict): url: "str" """The URL of the endpoint to which reports may be delivered.""" @@ -874,7 +1024,6 @@ class ReportingApiEndpoint(TypedDict): """Name of the endpoint group.""" - class LoadNetworkResourcePageResult(TypedDict): """An object providing the result of a network resource load.""" @@ -889,10 +1038,9 @@ class LoadNetworkResourcePageResult(TypedDict): """Response headers.""" - class LoadNetworkResourceOptions(TypedDict): """An options object that may be extended later to better support CORS, -CORB and streaming.""" + CORB and streaming.""" disableCache: "bool" includeCredentials: "bool" diff --git a/cdp_use/cdp/overlay/commands.py b/cdp_use/cdp/overlay/commands.py index e30550b..9c097fe 100644 --- a/cdp_use/cdp/overlay/commands.py +++ b/cdp_use/cdp/overlay/commands.py @@ -28,6 +28,7 @@ from .types import SourceOrderConfig from .types import WindowControlsOverlayConfig + class GetHighlightObjectForTestParameters(TypedDict): nodeId: "NodeId" """Id of the node to get highlight object for.""" @@ -46,7 +47,6 @@ class GetHighlightObjectForTestReturns(TypedDict): """Highlight data for the node.""" - class GetGridHighlightObjectsForTestParameters(TypedDict): nodeIds: "List[NodeId]" """Ids of the node to get highlight object for.""" @@ -57,7 +57,6 @@ class GetGridHighlightObjectsForTestReturns(TypedDict): """Grid Highlight data for the node ids provided.""" - class GetSourceOrderHighlightObjectForTestParameters(TypedDict): nodeId: "NodeId" """Id of the node to highlight.""" @@ -68,7 +67,6 @@ class GetSourceOrderHighlightObjectForTestReturns(TypedDict): """Source order highlight data for the node id provided.""" - class HighlightFrameParameters(TypedDict): frameId: "FrameId" """Identifier of the frame to highlight.""" @@ -78,9 +76,6 @@ class HighlightFrameParameters(TypedDict): """The content box highlight outline color (default: transparent).""" - - - class HighlightNodeParameters(TypedDict): highlightConfig: "HighlightConfig" """A descriptor for the highlight appearance.""" @@ -94,9 +89,6 @@ class HighlightNodeParameters(TypedDict): """Selectors to highlight relevant nodes.""" - - - class HighlightQuadParameters(TypedDict): quad: "Quad" """Quad to highlight""" @@ -106,9 +98,6 @@ class HighlightQuadParameters(TypedDict): """The highlight outline color (default: transparent).""" - - - class HighlightRectParameters(TypedDict): x: "int" """X coordinate""" @@ -124,9 +113,6 @@ class HighlightRectParameters(TypedDict): """The highlight outline color (default: transparent).""" - - - class HighlightSourceOrderParameters(TypedDict): sourceOrderConfig: "SourceOrderConfig" """A descriptor for the appearance of the overlay drawing.""" @@ -138,9 +124,6 @@ class HighlightSourceOrderParameters(TypedDict): """JavaScript object id of the node to be highlighted.""" - - - class SetInspectModeParameters(TypedDict): mode: "InspectMode" """Set an inspection mode.""" @@ -149,138 +132,85 @@ class SetInspectModeParameters(TypedDict): == false`.""" - - - class SetShowAdHighlightsParameters(TypedDict): show: "bool" """True for showing ad highlights""" - - - class SetPausedInDebuggerMessageParameters(TypedDict, total=False): message: "str" """The message to display, also triggers resume and step over controls.""" - - - class SetShowDebugBordersParameters(TypedDict): show: "bool" """True for showing debug borders""" - - - class SetShowFPSCounterParameters(TypedDict): show: "bool" """True for showing the FPS counter""" - - - class SetShowGridOverlaysParameters(TypedDict): gridNodeHighlightConfigs: "List[GridNodeHighlightConfig]" """An array of node identifiers and descriptors for the highlight appearance.""" - - - class SetShowFlexOverlaysParameters(TypedDict): flexNodeHighlightConfigs: "List[FlexNodeHighlightConfig]" """An array of node identifiers and descriptors for the highlight appearance.""" - - - class SetShowScrollSnapOverlaysParameters(TypedDict): scrollSnapHighlightConfigs: "List[ScrollSnapHighlightConfig]" """An array of node identifiers and descriptors for the highlight appearance.""" - - - class SetShowContainerQueryOverlaysParameters(TypedDict): containerQueryHighlightConfigs: "List[ContainerQueryHighlightConfig]" """An array of node identifiers and descriptors for the highlight appearance.""" - - - class SetShowPaintRectsParameters(TypedDict): result: "bool" """True for showing paint rectangles""" - - - class SetShowLayoutShiftRegionsParameters(TypedDict): result: "bool" """True for showing layout shift regions""" - - - class SetShowScrollBottleneckRectsParameters(TypedDict): show: "bool" """True for showing scroll bottleneck rects""" - - - class SetShowHitTestBordersParameters(TypedDict): show: "bool" """True for showing hit-test borders""" - - - class SetShowWebVitalsParameters(TypedDict): show: "bool" - - - class SetShowViewportSizeOnResizeParameters(TypedDict): show: "bool" """Whether to paint size or not.""" - - - class SetShowHingeParameters(TypedDict, total=False): hingeConfig: "HingeConfig" """hinge data, null means hideHinge""" - - - class SetShowIsolatedElementsParameters(TypedDict): isolatedElementHighlightConfigs: "List[IsolatedElementHighlightConfig]" """An array of node identifiers and descriptors for the highlight appearance.""" - - - class SetShowWindowControlsOverlayParameters(TypedDict, total=False): windowControlsOverlayConfig: "WindowControlsOverlayConfig" """Window Controls Overlay data, null means hide Window Controls Overlay""" - - diff --git a/cdp_use/cdp/overlay/events.py b/cdp_use/cdp/overlay/events.py index e500e11..d747e28 100644 --- a/cdp_use/cdp/overlay/events.py +++ b/cdp_use/cdp/overlay/events.py @@ -15,25 +15,30 @@ """Fired when the node should be inspected. This happens after call to `setInspectMode` or when user manually inspects an element.""" + + class InspectNodeRequestedEvent(TypedDict): backendNodeId: "BackendNodeId" """Id of the node to inspect.""" - """Fired when the node should be highlighted. This happens after call to `setInspectMode`.""" + + class NodeHighlightRequestedEvent(TypedDict): nodeId: "NodeId" - """Fired when user asks to capture screenshot of some area on the page.""" + + class ScreenshotRequestedEvent(TypedDict): viewport: "Viewport" """Viewport to capture, in device independent pixels (dip).""" - """Fired when user cancels the inspect mode.""" + + class InspectModeCanceledEvent(TypedDict): pass diff --git a/cdp_use/cdp/overlay/library.py b/cdp_use/cdp/overlay/library.py index b569f0e..428d8d4 100644 --- a/cdp_use/cdp/overlay/library.py +++ b/cdp_use/cdp/overlay/library.py @@ -40,10 +40,11 @@ from .commands import SetShowWebVitalsParameters from .commands import SetShowWindowControlsOverlayParameters + class OverlayClient: """Client for Overlay domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -52,11 +53,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -64,11 +68,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.enable", + params=params, + session_id=session_id, + ), + ) async def getHighlightObjectForTest( self, @@ -76,11 +83,14 @@ async def getHighlightObjectForTest( session_id: Optional[str] = None, ) -> "GetHighlightObjectForTestReturns": """For testing.""" - return cast("GetHighlightObjectForTestReturns", await self._client.send_raw( - method="Overlay.getHighlightObjectForTest", - params=params, - session_id=session_id, - )) + return cast( + "GetHighlightObjectForTestReturns", + await self._client.send_raw( + method="Overlay.getHighlightObjectForTest", + params=params, + session_id=session_id, + ), + ) async def getGridHighlightObjectsForTest( self, @@ -88,11 +98,14 @@ async def getGridHighlightObjectsForTest( session_id: Optional[str] = None, ) -> "GetGridHighlightObjectsForTestReturns": """For Persistent Grid testing.""" - return cast("GetGridHighlightObjectsForTestReturns", await self._client.send_raw( - method="Overlay.getGridHighlightObjectsForTest", - params=params, - session_id=session_id, - )) + return cast( + "GetGridHighlightObjectsForTestReturns", + await self._client.send_raw( + method="Overlay.getGridHighlightObjectsForTest", + params=params, + session_id=session_id, + ), + ) async def getSourceOrderHighlightObjectForTest( self, @@ -100,11 +113,14 @@ async def getSourceOrderHighlightObjectForTest( session_id: Optional[str] = None, ) -> "GetSourceOrderHighlightObjectForTestReturns": """For Source Order Viewer testing.""" - return cast("GetSourceOrderHighlightObjectForTestReturns", await self._client.send_raw( - method="Overlay.getSourceOrderHighlightObjectForTest", - params=params, - session_id=session_id, - )) + return cast( + "GetSourceOrderHighlightObjectForTestReturns", + await self._client.send_raw( + method="Overlay.getSourceOrderHighlightObjectForTest", + params=params, + session_id=session_id, + ), + ) async def hideHighlight( self, @@ -112,11 +128,14 @@ async def hideHighlight( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Hides any highlight.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.hideHighlight", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.hideHighlight", + params=params, + session_id=session_id, + ), + ) async def highlightFrame( self, @@ -124,14 +143,17 @@ async def highlightFrame( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights owner element of the frame with given id. -Deprecated: Doesn't work reliably and cannot be fixed due to process -separation (the owner node might be in a different process). Determine -the owner node in the client and use highlightNode.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.highlightFrame", - params=params, - session_id=session_id, - )) + Deprecated: Doesn't work reliably and cannot be fixed due to process + separation (the owner node might be in a different process). Determine + the owner node in the client and use highlightNode.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.highlightFrame", + params=params, + session_id=session_id, + ), + ) async def highlightNode( self, @@ -139,12 +161,15 @@ async def highlightNode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights DOM node with given id or with the given JavaScript object wrapper. Either nodeId or -objectId must be specified.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.highlightNode", - params=params, - session_id=session_id, - )) + objectId must be specified.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.highlightNode", + params=params, + session_id=session_id, + ), + ) async def highlightQuad( self, @@ -152,11 +177,14 @@ async def highlightQuad( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights given quad. Coordinates are absolute with respect to the main frame viewport.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.highlightQuad", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.highlightQuad", + params=params, + session_id=session_id, + ), + ) async def highlightRect( self, @@ -164,14 +192,17 @@ async def highlightRect( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport. -Issue: the method does not handle device pixel ratio (DPR) correctly. -The coordinates currently have to be adjusted by the client -if DPR is not 1 (see crbug.com/437807128).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.highlightRect", - params=params, - session_id=session_id, - )) + Issue: the method does not handle device pixel ratio (DPR) correctly. + The coordinates currently have to be adjusted by the client + if DPR is not 1 (see crbug.com/437807128).""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.highlightRect", + params=params, + session_id=session_id, + ), + ) async def highlightSourceOrder( self, @@ -179,12 +210,15 @@ async def highlightSourceOrder( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights the source order of the children of the DOM node with given id or with the given -JavaScript object wrapper. Either nodeId or objectId must be specified.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.highlightSourceOrder", - params=params, - session_id=session_id, - )) + JavaScript object wrapper. Either nodeId or objectId must be specified.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.highlightSourceOrder", + params=params, + session_id=session_id, + ), + ) async def setInspectMode( self, @@ -192,12 +226,15 @@ async def setInspectMode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. -Backend then generates 'inspectNodeRequested' event upon element selection.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setInspectMode", - params=params, - session_id=session_id, - )) + Backend then generates 'inspectNodeRequested' event upon element selection.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setInspectMode", + params=params, + session_id=session_id, + ), + ) async def setShowAdHighlights( self, @@ -205,22 +242,28 @@ async def setShowAdHighlights( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlights owner element of all frames detected to be ads.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowAdHighlights", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowAdHighlights", + params=params, + session_id=session_id, + ), + ) async def setPausedInDebuggerMessage( self, params: Optional["SetPausedInDebuggerMessageParameters"] = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setPausedInDebuggerMessage", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setPausedInDebuggerMessage", + params=params, + session_id=session_id, + ), + ) async def setShowDebugBorders( self, @@ -228,11 +271,14 @@ async def setShowDebugBorders( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that backend shows debug borders on layers""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowDebugBorders", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowDebugBorders", + params=params, + session_id=session_id, + ), + ) async def setShowFPSCounter( self, @@ -240,11 +286,14 @@ async def setShowFPSCounter( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that backend shows the FPS counter""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowFPSCounter", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowFPSCounter", + params=params, + session_id=session_id, + ), + ) async def setShowGridOverlays( self, @@ -252,44 +301,56 @@ async def setShowGridOverlays( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Highlight multiple elements with the CSS Grid overlay.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowGridOverlays", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowGridOverlays", + params=params, + session_id=session_id, + ), + ) async def setShowFlexOverlays( self, params: "SetShowFlexOverlaysParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowFlexOverlays", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowFlexOverlays", + params=params, + session_id=session_id, + ), + ) async def setShowScrollSnapOverlays( self, params: "SetShowScrollSnapOverlaysParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowScrollSnapOverlays", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowScrollSnapOverlays", + params=params, + session_id=session_id, + ), + ) async def setShowContainerQueryOverlays( self, params: "SetShowContainerQueryOverlaysParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowContainerQueryOverlays", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowContainerQueryOverlays", + params=params, + session_id=session_id, + ), + ) async def setShowPaintRects( self, @@ -297,11 +358,14 @@ async def setShowPaintRects( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that backend shows paint rectangles""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowPaintRects", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowPaintRects", + params=params, + session_id=session_id, + ), + ) async def setShowLayoutShiftRegions( self, @@ -309,11 +373,14 @@ async def setShowLayoutShiftRegions( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that backend shows layout shift regions""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowLayoutShiftRegions", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowLayoutShiftRegions", + params=params, + session_id=session_id, + ), + ) async def setShowScrollBottleneckRects( self, @@ -321,11 +388,14 @@ async def setShowScrollBottleneckRects( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests that backend shows scroll bottleneck rects""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowScrollBottleneckRects", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowScrollBottleneckRects", + params=params, + session_id=session_id, + ), + ) async def setShowHitTestBorders( self, @@ -333,11 +403,14 @@ async def setShowHitTestBorders( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deprecated, no longer has any effect.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowHitTestBorders", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowHitTestBorders", + params=params, + session_id=session_id, + ), + ) async def setShowWebVitals( self, @@ -345,11 +418,14 @@ async def setShowWebVitals( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deprecated, no longer has any effect.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowWebVitals", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowWebVitals", + params=params, + session_id=session_id, + ), + ) async def setShowViewportSizeOnResize( self, @@ -357,11 +433,14 @@ async def setShowViewportSizeOnResize( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Paints viewport size upon main frame resize.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowViewportSizeOnResize", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowViewportSizeOnResize", + params=params, + session_id=session_id, + ), + ) async def setShowHinge( self, @@ -369,11 +448,14 @@ async def setShowHinge( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Add a dual screen device hinge""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowHinge", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowHinge", + params=params, + session_id=session_id, + ), + ) async def setShowIsolatedElements( self, @@ -381,11 +463,14 @@ async def setShowIsolatedElements( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Show elements in isolation mode with overlays.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowIsolatedElements", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowIsolatedElements", + params=params, + session_id=session_id, + ), + ) async def setShowWindowControlsOverlay( self, @@ -393,10 +478,11 @@ async def setShowWindowControlsOverlay( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Show Window Controls Overlay for PWA""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Overlay.setShowWindowControlsOverlay", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Overlay.setShowWindowControlsOverlay", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/overlay/registration.py b/cdp_use/cdp/overlay/registration.py index 9d727ca..09e4f59 100644 --- a/cdp_use/cdp/overlay/registration.py +++ b/cdp_use/cdp/overlay/registration.py @@ -10,40 +10,46 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import InspectModeCanceledEvent, InspectNodeRequestedEvent, NodeHighlightRequestedEvent, ScreenshotRequestedEvent + from .events import ( + InspectModeCanceledEvent, + InspectNodeRequestedEvent, + NodeHighlightRequestedEvent, + ScreenshotRequestedEvent, + ) + class OverlayRegistration: """Event registration interface for Overlay domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Overlay" def inspectNodeRequested( self, - callback: Callable[['InspectNodeRequestedEvent', Optional[str]], None], + callback: Callable[["InspectNodeRequestedEvent", Optional[str]], None], ) -> None: """ - Register a callback for inspectNodeRequested events. - - Fired when the node should be inspected. This happens after call to `setInspectMode` or when -user manually inspects an element. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for inspectNodeRequested events. + + Fired when the node should be inspected. This happens after call to `setInspectMode` or when + user manually inspects an element. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Overlay.inspectNodeRequested", callback) def nodeHighlightRequested( self, - callback: Callable[['NodeHighlightRequestedEvent', Optional[str]], None], + callback: Callable[["NodeHighlightRequestedEvent", Optional[str]], None], ) -> None: """ Register a callback for nodeHighlightRequested events. - + Fired when the node should be highlighted. This happens after call to `setInspectMode`. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -52,13 +58,13 @@ def nodeHighlightRequested( def screenshotRequested( self, - callback: Callable[['ScreenshotRequestedEvent', Optional[str]], None], + callback: Callable[["ScreenshotRequestedEvent", Optional[str]], None], ) -> None: """ Register a callback for screenshotRequested events. - + Fired when user asks to capture screenshot of some area on the page. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -67,16 +73,15 @@ def screenshotRequested( def inspectModeCanceled( self, - callback: Callable[['InspectModeCanceledEvent', Optional[str]], None], + callback: Callable[["InspectModeCanceledEvent", Optional[str]], None], ) -> None: """ Register a callback for inspectModeCanceled events. - + Fired when user cancels the inspect mode. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Overlay.inspectModeCanceled", callback) - diff --git a/cdp_use/cdp/overlay/types.py b/cdp_use/cdp/overlay/types.py index 8af691d..cbd2677 100644 --- a/cdp_use/cdp/overlay/types.py +++ b/cdp_use/cdp/overlay/types.py @@ -14,6 +14,7 @@ from ..dom.types import RGBA from ..dom.types import Rect + class SourceOrderConfig(TypedDict): """Configuration data for drawing the source order of an elements children.""" @@ -23,7 +24,6 @@ class SourceOrderConfig(TypedDict): """the color to outline the child elements in.""" - class GridHighlightConfig(TypedDict, total=False): """Configuration data for the highlighting of Grid elements.""" @@ -69,7 +69,6 @@ class GridHighlightConfig(TypedDict, total=False): """The grid container background color (Default: transparent).""" - class FlexContainerHighlightConfig(TypedDict, total=False): """Configuration data for the highlighting of Flex container elements.""" @@ -91,7 +90,6 @@ class FlexContainerHighlightConfig(TypedDict, total=False): """Style of the self-alignment line (align-items).""" - class FlexItemHighlightConfig(TypedDict, total=False): """Configuration data for the highlighting of Flex item elements.""" @@ -103,7 +101,6 @@ class FlexItemHighlightConfig(TypedDict, total=False): """Style of the arrow representing if the item grew or shrank""" - class LineStyle(TypedDict, total=False): """Style information for drawing a line.""" @@ -113,7 +110,6 @@ class LineStyle(TypedDict, total=False): """The line pattern (default: solid)""" - class BoxStyle(TypedDict, total=False): """Style information for drawing a box.""" @@ -123,11 +119,9 @@ class BoxStyle(TypedDict, total=False): """The hatching color for the box (default: transparent)""" - ContrastAlgorithm = Literal["aa", "aaa", "apca"] - class HighlightConfig(TypedDict, total=False): """Configuration data for the highlighting of page elements.""" @@ -171,11 +165,9 @@ class HighlightConfig(TypedDict, total=False): """The container query container highlight configuration (default: all transparent).""" - ColorFormat = Literal["rgb", "hsl", "hwb", "hex"] - class GridNodeHighlightConfig(TypedDict): """Configurations for Persistent Grid Highlight""" @@ -185,7 +177,6 @@ class GridNodeHighlightConfig(TypedDict): """Identifier of the node to highlight.""" - class FlexNodeHighlightConfig(TypedDict): flexContainerHighlightConfig: "FlexContainerHighlightConfig" """A descriptor for the highlight appearance of flex containers.""" @@ -193,7 +184,6 @@ class FlexNodeHighlightConfig(TypedDict): """Identifier of the node to highlight.""" - class ScrollSnapContainerHighlightConfig(TypedDict, total=False): snapportBorder: "LineStyle" """The style of the snapport border (default: transparent)""" @@ -205,7 +195,6 @@ class ScrollSnapContainerHighlightConfig(TypedDict, total=False): """The padding highlight fill color (default: transparent).""" - class ScrollSnapHighlightConfig(TypedDict): scrollSnapContainerHighlightConfig: "ScrollSnapContainerHighlightConfig" """A descriptor for the highlight appearance of scroll snap containers.""" @@ -213,7 +202,6 @@ class ScrollSnapHighlightConfig(TypedDict): """Identifier of the node to highlight.""" - class HingeConfig(TypedDict): """Configuration for dual screen hinge""" @@ -225,7 +213,6 @@ class HingeConfig(TypedDict): """The content box highlight outline color (default: transparent).""" - class WindowControlsOverlayConfig(TypedDict): """Configuration for Window Controls Overlay""" @@ -237,7 +224,6 @@ class WindowControlsOverlayConfig(TypedDict): """The theme color defined in app manifest.""" - class ContainerQueryHighlightConfig(TypedDict): containerQueryContainerHighlightConfig: "ContainerQueryContainerHighlightConfig" """A descriptor for the highlight appearance of container query containers.""" @@ -245,7 +231,6 @@ class ContainerQueryHighlightConfig(TypedDict): """Identifier of the container node to highlight.""" - class ContainerQueryContainerHighlightConfig(TypedDict, total=False): containerBorder: "LineStyle" """The style of the container border.""" @@ -253,7 +238,6 @@ class ContainerQueryContainerHighlightConfig(TypedDict, total=False): """The style of the descendants' borders.""" - class IsolatedElementHighlightConfig(TypedDict): isolationModeHighlightConfig: "IsolationModeHighlightConfig" """A descriptor for the highlight appearance of an element in isolation mode.""" @@ -261,7 +245,6 @@ class IsolatedElementHighlightConfig(TypedDict): """Identifier of the isolated element to highlight.""" - class IsolationModeHighlightConfig(TypedDict, total=False): resizerColor: "RGBA" """The fill color of the resizers (default: transparent).""" @@ -271,5 +254,6 @@ class IsolationModeHighlightConfig(TypedDict, total=False): """The fill color for the mask covering non-isolated elements (default: transparent).""" - -InspectMode = Literal["searchForNode", "searchForUAShadowDOM", "captureAreaScreenshot", "none"] +InspectMode = Literal[ + "searchForNode", "searchForUAShadowDOM", "captureAreaScreenshot", "none" +] diff --git a/cdp_use/cdp/page/commands.py b/cdp_use/cdp/page/commands.py index a42be01..2b3bd00 100644 --- a/cdp_use/cdp/page/commands.py +++ b/cdp_use/cdp/page/commands.py @@ -38,6 +38,7 @@ from .types import VisualViewport from .types import WebAppManifest + class AddScriptToEvaluateOnLoadParameters(TypedDict): scriptSource: "str" @@ -47,7 +48,6 @@ class AddScriptToEvaluateOnLoadReturns(TypedDict): """Identifier of the added script.""" - class AddScriptToEvaluateOnNewDocumentParameters(TypedDict): source: "str" worldName: "NotRequired[str]" @@ -67,7 +67,6 @@ class AddScriptToEvaluateOnNewDocumentReturns(TypedDict): """Identifier of the added script.""" - class CaptureScreenshotParameters(TypedDict, total=False): format: "str" """Image compression format (defaults to png).""" @@ -88,7 +87,6 @@ class CaptureScreenshotReturns(TypedDict): """Base64-encoded image data. (Encoded as a base64 string when passed over JSON)""" - class CaptureSnapshotParameters(TypedDict, total=False): format: "str" """Format (defaults to mhtml).""" @@ -99,7 +97,6 @@ class CaptureSnapshotReturns(TypedDict): """Serialized page data.""" - class CreateIsolatedWorldParameters(TypedDict): frameId: "FrameId" """Id of the frame in which the isolated world should be created.""" @@ -115,7 +112,6 @@ class CreateIsolatedWorldReturns(TypedDict): """Execution context of the isolated world.""" - class DeleteCookieParameters(TypedDict): cookieName: "str" """Name of the cookie to remove.""" @@ -123,18 +119,12 @@ class DeleteCookieParameters(TypedDict): """URL to match cooke domain and path.""" - - - class EnableParameters(TypedDict, total=False): enableFileChooserOpenedEvent: "bool" """If true, the `Page.fileChooserOpened` event will be emitted regardless of the state set by `Page.setInterceptFileChooserDialog` command (default: false).""" - - - class GetAppManifestParameters(TypedDict, total=False): manifestId: "str" @@ -150,17 +140,14 @@ class GetAppManifestReturns(TypedDict): manifest: "WebAppManifest" - class GetInstallabilityErrorsReturns(TypedDict): installabilityErrors: "List[InstallabilityError]" - class GetManifestIconsReturns(TypedDict): primaryIcon: "str" - class GetAppIdReturns(TypedDict): appId: "str" """App id, either from manifest's id attribute or computed from start_url""" @@ -168,7 +155,6 @@ class GetAppIdReturns(TypedDict): """Recommendation for manifest's id attribute to match current id computed from start_url""" - class GetAdScriptAncestryParameters(TypedDict): frameId: "FrameId" @@ -182,13 +168,11 @@ class GetAdScriptAncestryReturns(TypedDict): script). Only sent if frame is labelled as an ad and ids are available.""" - class GetFrameTreeReturns(TypedDict): frameTree: "FrameTree" """Present frame tree structure.""" - class GetLayoutMetricsReturns(TypedDict): layoutViewport: "LayoutViewport" """Deprecated metrics relating to the layout viewport. Is in device pixels. Use `cssLayoutViewport` instead.""" @@ -204,7 +188,6 @@ class GetLayoutMetricsReturns(TypedDict): """Size of scrollable area in CSS pixels.""" - class GetNavigationHistoryReturns(TypedDict): currentIndex: "int" """Index of the current navigation history entry.""" @@ -212,7 +195,6 @@ class GetNavigationHistoryReturns(TypedDict): """Array of navigation history entries.""" - class GetResourceContentParameters(TypedDict): frameId: "FrameId" """Frame id to get resource for.""" @@ -227,13 +209,11 @@ class GetResourceContentReturns(TypedDict): """True, if content was served as base64.""" - class GetResourceTreeReturns(TypedDict): frameTree: "FrameResourceTree" """Present frame / resource tree structure.""" - class HandleJavaScriptDialogParameters(TypedDict): accept: "bool" """Whether to accept or dismiss the dialog.""" @@ -242,9 +222,6 @@ class HandleJavaScriptDialogParameters(TypedDict): dialog.""" - - - class NavigateParameters(TypedDict): url: "str" """URL to navigate the page to.""" @@ -270,15 +247,11 @@ class NavigateReturns(TypedDict): """Whether the navigation resulted in a download.""" - class NavigateToHistoryEntryParameters(TypedDict): entryId: "int" """Unique id of the entry to navigate to.""" - - - class PrintToPDFParameters(TypedDict, total=False): landscape: "bool" """Paper orientation. Defaults to false.""" @@ -339,7 +312,6 @@ class PrintToPDFReturns(TypedDict): """A handle of the stream that holds resulting PDF data.""" - class ReloadParameters(TypedDict, total=False): ignoreCache: "bool" """If true, browser cache is ignored (as if the user pressed Shift+refresh).""" @@ -352,31 +324,19 @@ class ReloadParameters(TypedDict, total=False): reloading an unintended target in case there's a racing navigation.""" - - - class RemoveScriptToEvaluateOnLoadParameters(TypedDict): identifier: "ScriptIdentifier" - - - class RemoveScriptToEvaluateOnNewDocumentParameters(TypedDict): identifier: "ScriptIdentifier" - - - class ScreencastFrameAckParameters(TypedDict): sessionId: "int" """Frame number.""" - - - class SearchInResourceParameters(TypedDict): frameId: "FrameId" """Frame id for resource to search in.""" @@ -395,23 +355,16 @@ class SearchInResourceReturns(TypedDict): """List of search matches.""" - class SetAdBlockingEnabledParameters(TypedDict): enabled: "bool" """Whether to block ads.""" - - - class SetBypassCSPParameters(TypedDict): enabled: "bool" """Whether to bypass page CSP.""" - - - class GetPermissionsPolicyStateParameters(TypedDict): frameId: "FrameId" @@ -420,7 +373,6 @@ class GetPermissionsPolicyStateReturns(TypedDict): states: "List[PermissionsPolicyFeatureState]" - class GetOriginTrialsParameters(TypedDict): frameId: "FrameId" @@ -429,7 +381,6 @@ class GetOriginTrialsReturns(TypedDict): originTrials: "List[OriginTrial]" - class SetDeviceMetricsOverrideParameters(TypedDict): width: "int" """Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.""" @@ -458,9 +409,6 @@ class SetDeviceMetricsOverrideParameters(TypedDict): """The viewport dimensions and scale. If not set, the override is cleared.""" - - - class SetDeviceOrientationOverrideParameters(TypedDict): alpha: "float" """Mock alpha""" @@ -470,9 +418,6 @@ class SetDeviceOrientationOverrideParameters(TypedDict): """Mock gamma""" - - - class SetFontFamiliesParameters(TypedDict): fontFamilies: "FontFamilies" """Specifies font families to set. If a font family is not specified, it won't be changed.""" @@ -480,17 +425,11 @@ class SetFontFamiliesParameters(TypedDict): """Specifies font families to set for individual scripts.""" - - - class SetFontSizesParameters(TypedDict): fontSizes: "FontSizes" """Specifies font sizes to set. If a font size is not specified, it won't be changed.""" - - - class SetDocumentContentParameters(TypedDict): frameId: "FrameId" """Frame id to set HTML for.""" @@ -498,9 +437,6 @@ class SetDocumentContentParameters(TypedDict): """HTML content to set.""" - - - class SetDownloadBehaviorParameters(TypedDict): behavior: "str" """Whether to allow all or deny all download requests, or use default Chrome behavior if @@ -509,9 +445,6 @@ class SetDownloadBehaviorParameters(TypedDict): """The default path to save downloaded files to. This is required if behavior is set to 'allow'""" - - - class SetGeolocationOverrideParameters(TypedDict, total=False): latitude: "float" """Mock latitude""" @@ -521,17 +454,11 @@ class SetGeolocationOverrideParameters(TypedDict, total=False): """Mock accuracy""" - - - class SetLifecycleEventsEnabledParameters(TypedDict): enabled: "bool" """If true, starts emitting lifecycle events.""" - - - class SetTouchEmulationEnabledParameters(TypedDict): enabled: "bool" """Whether the touch event emulation should be enabled.""" @@ -539,9 +466,6 @@ class SetTouchEmulationEnabledParameters(TypedDict): """Touch/gesture events configuration. Default: current platform.""" - - - class StartScreencastParameters(TypedDict, total=False): format: "str" """Image compression format.""" @@ -555,47 +479,29 @@ class StartScreencastParameters(TypedDict, total=False): """Send every n-th frame.""" - - - class SetWebLifecycleStateParameters(TypedDict): state: "str" """Target lifecycle state""" - - - class ProduceCompilationCacheParameters(TypedDict): scripts: "List[CompilationCacheParams]" - - - class AddCompilationCacheParameters(TypedDict): url: "str" data: "str" """Base64-encoded data (Encoded as a base64 string when passed over JSON)""" - - - class SetSPCTransactionModeParameters(TypedDict): mode: "str" - - - class SetRPHRegistrationModeParameters(TypedDict): mode: "str" - - - class GenerateTestReportParameters(TypedDict): message: "str" """Message to be displayed in the report.""" @@ -603,9 +509,6 @@ class GenerateTestReportParameters(TypedDict): """Specifies the endpoint group to deliver the report to.""" - - - class SetInterceptFileChooserDialogParameters(TypedDict): enabled: "bool" cancel: "NotRequired[bool]" @@ -614,10 +517,17 @@ class SetInterceptFileChooserDialogParameters(TypedDict): (default: false).""" - - - class SetPrerenderingAllowedParameters(TypedDict): isAllowed: "bool" +class GetAnnotatedPageContentParameters(TypedDict, total=False): + includeActionableInformation: "bool" + """Whether to include actionable information. Defaults to true.""" + + +class GetAnnotatedPageContentReturns(TypedDict): + content: "str" + """The annotated page content as a base64 encoded protobuf. +The format is defined by the `AnnotatedPageContent` message in +components/optimization_guide/proto/features/common_quality_data.proto (Encoded as a base64 string when passed over JSON)""" diff --git a/cdp_use/cdp/page/events.py b/cdp_use/cdp/page/events.py index 305b03c..2168950 100644 --- a/cdp_use/cdp/page/events.py +++ b/cdp_use/cdp/page/events.py @@ -24,12 +24,14 @@ from .types import NavigationType from .types import ScreencastFrameMetadata + class DomContentEventFiredEvent(TypedDict): timestamp: "MonotonicTime" - """Emitted only when `page.interceptFileChooser` is enabled.""" + + class FileChooserOpenedEvent(TypedDict): frameId: "FrameId" """Id of the frame containing input node.""" @@ -39,8 +41,9 @@ class FileChooserOpenedEvent(TypedDict): """Input node id. Only present for file choosers opened via an `` element.""" - """Fired when frame has been attached to its parent.""" + + class FrameAttachedEvent(TypedDict): frameId: "FrameId" """Id of the frame that has been attached.""" @@ -50,50 +53,53 @@ class FrameAttachedEvent(TypedDict): """JavaScript stack trace of when frame was attached, only set if frame initiated from script.""" - """Fired when frame no longer has a scheduled navigation.""" + + class FrameClearedScheduledNavigationEvent(TypedDict): frameId: "FrameId" """Id of the frame that has cleared its scheduled navigation.""" - """Fired when frame has been detached from its parent.""" + + class FrameDetachedEvent(TypedDict): frameId: "FrameId" """Id of the frame that has been detached.""" reason: "str" - """Fired before frame subtree is detached. Emitted before any frame of the subtree is actually detached.""" + + class FrameSubtreeWillBeDetachedEvent(TypedDict): frameId: "FrameId" """Id of the frame that is the root of the subtree that will be detached.""" - """Fired once navigation of the frame has completed. Frame is now associated with the new loader.""" + + class FrameNavigatedEvent(TypedDict): frame: "Frame" """Frame object.""" type: "NavigationType" - """Fired when opening document to write to.""" + + class DocumentOpenedEvent(TypedDict): frame: "Frame" """Frame object.""" - class FrameResizedEvent(TypedDict): pass - """Fired when a navigation starts. This event is fired for both renderer-initiated and browser-initiated navigations. For renderer-initiated navigations, the event is fired after `frameRequestedNavigation`. @@ -101,6 +107,8 @@ class FrameResizedEvent(TypedDict): can be fired for a single navigation, for example, when a same-document navigation becomes a cross-document navigation (such as in the case of a frameset).""" + + class FrameStartedNavigatingEvent(TypedDict): frameId: "FrameId" """ID of the frame that is being navigated.""" @@ -114,9 +122,10 @@ class FrameStartedNavigatingEvent(TypedDict): navigationType: "str" - """Fired when a renderer-initiated navigation is requested. Navigation may still be cancelled after the event is issued.""" + + class FrameRequestedNavigationEvent(TypedDict): frameId: "FrameId" """Id of the frame that is being navigated.""" @@ -128,8 +137,9 @@ class FrameRequestedNavigationEvent(TypedDict): """The disposition for the navigation.""" - """Fired when frame schedules a potential navigation.""" + + class FrameScheduledNavigationEvent(TypedDict): frameId: "FrameId" """Id of the frame that has scheduled a navigation.""" @@ -142,23 +152,26 @@ class FrameScheduledNavigationEvent(TypedDict): """The destination URL for the scheduled navigation.""" - """Fired when frame has started loading.""" + + class FrameStartedLoadingEvent(TypedDict): frameId: "FrameId" """Id of the frame that has started loading.""" - """Fired when frame has stopped loading.""" + + class FrameStoppedLoadingEvent(TypedDict): frameId: "FrameId" """Id of the frame that has stopped loading.""" - """Fired when page is about to start a download. Deprecated. Use Browser.downloadWillBegin instead.""" + + class DownloadWillBeginEvent(TypedDict): frameId: "FrameId" """Id of the frame that caused download to begin.""" @@ -170,9 +183,10 @@ class DownloadWillBeginEvent(TypedDict): """Suggested file name of the resource (the actual name of the file saved on disk may differ).""" - """Fired when download makes progress. Last call has |done| == true. Deprecated. Use Browser.downloadProgress instead.""" + + class DownloadProgressEvent(TypedDict): guid: "str" """Global unique identifier of the download.""" @@ -184,21 +198,24 @@ class DownloadProgressEvent(TypedDict): """Download status.""" - """Fired when interstitial page was hidden""" + + class InterstitialHiddenEvent(TypedDict): pass - """Fired when interstitial page was shown""" + + class InterstitialShownEvent(TypedDict): pass - """Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) has been closed.""" + + class JavascriptDialogClosedEvent(TypedDict): frameId: "FrameId" """Frame id.""" @@ -208,9 +225,10 @@ class JavascriptDialogClosedEvent(TypedDict): """User input in case of prompt.""" - """Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) is about to open.""" + + class JavascriptDialogOpeningEvent(TypedDict): url: "str" """Frame url.""" @@ -228,9 +246,10 @@ class JavascriptDialogOpeningEvent(TypedDict): """Default dialog prompt.""" - """Fired for lifecycle events (navigation, load, paint, etc) in the current target (including local frames).""" + + class LifecycleEventEvent(TypedDict): frameId: "FrameId" """Id of the frame.""" @@ -240,11 +259,12 @@ class LifecycleEventEvent(TypedDict): timestamp: "MonotonicTime" - """Fired for failed bfcache history navigations if BackForwardCache feature is enabled. Do not assume any ordering with the Page.frameNavigated event. This event is fired only for main-frame history navigation where the document changes (non-same-document navigations), when bfcache navigation fails.""" + + class BackForwardCacheNotUsedEvent(TypedDict): loaderId: "LoaderId" """The loader id for the associated navigation.""" @@ -252,17 +272,19 @@ class BackForwardCacheNotUsedEvent(TypedDict): """The frame id of the associated frame.""" notRestoredExplanations: "List[BackForwardCacheNotRestoredExplanation]" """Array of reasons why the page could not be cached. This must not be empty.""" - notRestoredExplanationsTree: "NotRequired[BackForwardCacheNotRestoredExplanationTree]" + notRestoredExplanationsTree: ( + "NotRequired[BackForwardCacheNotRestoredExplanationTree]" + ) """Tree structure of reasons why the page could not be cached for each frame.""" - class LoadEventFiredEvent(TypedDict): timestamp: "MonotonicTime" - """Fired when same-document navigation happens, e.g. due to history API usage or anchor navigation.""" + + class NavigatedWithinDocumentEvent(TypedDict): frameId: "FrameId" """Id of the frame.""" @@ -272,8 +294,9 @@ class NavigatedWithinDocumentEvent(TypedDict): """Navigation type""" - """Compressed image data requested by the `startScreencast`.""" + + class ScreencastFrameEvent(TypedDict): data: "str" """Base64-encoded compressed image. (Encoded as a base64 string when passed over JSON)""" @@ -283,16 +306,18 @@ class ScreencastFrameEvent(TypedDict): """Frame number.""" - """Fired when the page with currently enabled screencast was shown or hidden `.""" + + class ScreencastVisibilityChangedEvent(TypedDict): visible: "bool" """True if the page is visible.""" - """Fired when a new window is going to be opened, via window.open(), link click, form submission, etc.""" + + class WindowOpenEvent(TypedDict): url: "str" """The URL for the new window.""" @@ -304,8 +329,9 @@ class WindowOpenEvent(TypedDict): """Whether or not it was triggered by user gesture.""" - """Issued for every compilation cache generated.""" + + class CompilationCacheProducedEvent(TypedDict): url: "str" data: "str" diff --git a/cdp_use/cdp/page/library.py b/cdp_use/cdp/page/library.py index c35c745..cf3349a 100644 --- a/cdp_use/cdp/page/library.py +++ b/cdp_use/cdp/page/library.py @@ -26,6 +26,8 @@ from .commands import GenerateTestReportParameters from .commands import GetAdScriptAncestryParameters from .commands import GetAdScriptAncestryReturns + from .commands import GetAnnotatedPageContentParameters + from .commands import GetAnnotatedPageContentReturns from .commands import GetAppIdReturns from .commands import GetAppManifestParameters from .commands import GetAppManifestReturns @@ -72,10 +74,11 @@ from .commands import SetWebLifecycleStateParameters from .commands import StartScreencastParameters + class PageClient: """Client for Page domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def addScriptToEvaluateOnLoad( @@ -84,11 +87,14 @@ async def addScriptToEvaluateOnLoad( session_id: Optional[str] = None, ) -> "AddScriptToEvaluateOnLoadReturns": """Deprecated, please use addScriptToEvaluateOnNewDocument instead.""" - return cast("AddScriptToEvaluateOnLoadReturns", await self._client.send_raw( - method="Page.addScriptToEvaluateOnLoad", - params=params, - session_id=session_id, - )) + return cast( + "AddScriptToEvaluateOnLoadReturns", + await self._client.send_raw( + method="Page.addScriptToEvaluateOnLoad", + params=params, + session_id=session_id, + ), + ) async def addScriptToEvaluateOnNewDocument( self, @@ -96,11 +102,14 @@ async def addScriptToEvaluateOnNewDocument( session_id: Optional[str] = None, ) -> "AddScriptToEvaluateOnNewDocumentReturns": """Evaluates given script in every frame upon creation (before loading frame's scripts).""" - return cast("AddScriptToEvaluateOnNewDocumentReturns", await self._client.send_raw( - method="Page.addScriptToEvaluateOnNewDocument", - params=params, - session_id=session_id, - )) + return cast( + "AddScriptToEvaluateOnNewDocumentReturns", + await self._client.send_raw( + method="Page.addScriptToEvaluateOnNewDocument", + params=params, + session_id=session_id, + ), + ) async def bringToFront( self, @@ -108,11 +117,14 @@ async def bringToFront( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Brings page to front (activates tab).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.bringToFront", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.bringToFront", + params=params, + session_id=session_id, + ), + ) async def captureScreenshot( self, @@ -120,11 +132,14 @@ async def captureScreenshot( session_id: Optional[str] = None, ) -> "CaptureScreenshotReturns": """Capture page screenshot.""" - return cast("CaptureScreenshotReturns", await self._client.send_raw( - method="Page.captureScreenshot", - params=params, - session_id=session_id, - )) + return cast( + "CaptureScreenshotReturns", + await self._client.send_raw( + method="Page.captureScreenshot", + params=params, + session_id=session_id, + ), + ) async def captureSnapshot( self, @@ -132,12 +147,15 @@ async def captureSnapshot( session_id: Optional[str] = None, ) -> "CaptureSnapshotReturns": """Returns a snapshot of the page as a string. For MHTML format, the serialization includes -iframes, shadow DOM, external resources, and element-inline styles.""" - return cast("CaptureSnapshotReturns", await self._client.send_raw( - method="Page.captureSnapshot", - params=params, - session_id=session_id, - )) + iframes, shadow DOM, external resources, and element-inline styles.""" + return cast( + "CaptureSnapshotReturns", + await self._client.send_raw( + method="Page.captureSnapshot", + params=params, + session_id=session_id, + ), + ) async def clearDeviceMetricsOverride( self, @@ -145,11 +163,14 @@ async def clearDeviceMetricsOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the overridden device metrics.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.clearDeviceMetricsOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.clearDeviceMetricsOverride", + params=params, + session_id=session_id, + ), + ) async def clearDeviceOrientationOverride( self, @@ -157,11 +178,14 @@ async def clearDeviceOrientationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the overridden Device Orientation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.clearDeviceOrientationOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.clearDeviceOrientationOverride", + params=params, + session_id=session_id, + ), + ) async def clearGeolocationOverride( self, @@ -169,11 +193,14 @@ async def clearGeolocationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears the overridden Geolocation Position and Error.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.clearGeolocationOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.clearGeolocationOverride", + params=params, + session_id=session_id, + ), + ) async def createIsolatedWorld( self, @@ -181,11 +208,14 @@ async def createIsolatedWorld( session_id: Optional[str] = None, ) -> "CreateIsolatedWorldReturns": """Creates an isolated world for the given frame.""" - return cast("CreateIsolatedWorldReturns", await self._client.send_raw( - method="Page.createIsolatedWorld", - params=params, - session_id=session_id, - )) + return cast( + "CreateIsolatedWorldReturns", + await self._client.send_raw( + method="Page.createIsolatedWorld", + params=params, + session_id=session_id, + ), + ) async def deleteCookie( self, @@ -193,11 +223,14 @@ async def deleteCookie( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes browser cookie with given name, domain and path.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.deleteCookie", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.deleteCookie", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -205,11 +238,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables page domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -217,11 +253,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables page domain notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.enable", + params=params, + session_id=session_id, + ), + ) async def getAppManifest( self, @@ -229,26 +268,32 @@ async def getAppManifest( session_id: Optional[str] = None, ) -> "GetAppManifestReturns": """Gets the processed manifest for this current document. - This API always waits for the manifest to be loaded. - If manifestId is provided, and it does not match the manifest of the - current document, this API errors out. - If there is not a loaded page, this API errors out immediately.""" - return cast("GetAppManifestReturns", await self._client.send_raw( - method="Page.getAppManifest", - params=params, - session_id=session_id, - )) + This API always waits for the manifest to be loaded. + If manifestId is provided, and it does not match the manifest of the + current document, this API errors out. + If there is not a loaded page, this API errors out immediately.""" + return cast( + "GetAppManifestReturns", + await self._client.send_raw( + method="Page.getAppManifest", + params=params, + session_id=session_id, + ), + ) async def getInstallabilityErrors( self, params: None = None, session_id: Optional[str] = None, ) -> "GetInstallabilityErrorsReturns": - return cast("GetInstallabilityErrorsReturns", await self._client.send_raw( - method="Page.getInstallabilityErrors", - params=params, - session_id=session_id, - )) + return cast( + "GetInstallabilityErrorsReturns", + await self._client.send_raw( + method="Page.getInstallabilityErrors", + params=params, + session_id=session_id, + ), + ) async def getManifestIcons( self, @@ -256,11 +301,14 @@ async def getManifestIcons( session_id: Optional[str] = None, ) -> "GetManifestIconsReturns": """Deprecated because it's not guaranteed that the returned icon is in fact the one used for PWA installation.""" - return cast("GetManifestIconsReturns", await self._client.send_raw( - method="Page.getManifestIcons", - params=params, - session_id=session_id, - )) + return cast( + "GetManifestIconsReturns", + await self._client.send_raw( + method="Page.getManifestIcons", + params=params, + session_id=session_id, + ), + ) async def getAppId( self, @@ -268,23 +316,29 @@ async def getAppId( session_id: Optional[str] = None, ) -> "GetAppIdReturns": """Returns the unique (PWA) app id. -Only returns values if the feature flag 'WebAppEnableManifestId' is enabled""" - return cast("GetAppIdReturns", await self._client.send_raw( - method="Page.getAppId", - params=params, - session_id=session_id, - )) + Only returns values if the feature flag 'WebAppEnableManifestId' is enabled""" + return cast( + "GetAppIdReturns", + await self._client.send_raw( + method="Page.getAppId", + params=params, + session_id=session_id, + ), + ) async def getAdScriptAncestry( self, params: "GetAdScriptAncestryParameters", session_id: Optional[str] = None, ) -> "GetAdScriptAncestryReturns": - return cast("GetAdScriptAncestryReturns", await self._client.send_raw( - method="Page.getAdScriptAncestry", - params=params, - session_id=session_id, - )) + return cast( + "GetAdScriptAncestryReturns", + await self._client.send_raw( + method="Page.getAdScriptAncestry", + params=params, + session_id=session_id, + ), + ) async def getFrameTree( self, @@ -292,11 +346,14 @@ async def getFrameTree( session_id: Optional[str] = None, ) -> "GetFrameTreeReturns": """Returns present frame tree structure.""" - return cast("GetFrameTreeReturns", await self._client.send_raw( - method="Page.getFrameTree", - params=params, - session_id=session_id, - )) + return cast( + "GetFrameTreeReturns", + await self._client.send_raw( + method="Page.getFrameTree", + params=params, + session_id=session_id, + ), + ) async def getLayoutMetrics( self, @@ -304,11 +361,14 @@ async def getLayoutMetrics( session_id: Optional[str] = None, ) -> "GetLayoutMetricsReturns": """Returns metrics relating to the layouting of the page, such as viewport bounds/scale.""" - return cast("GetLayoutMetricsReturns", await self._client.send_raw( - method="Page.getLayoutMetrics", - params=params, - session_id=session_id, - )) + return cast( + "GetLayoutMetricsReturns", + await self._client.send_raw( + method="Page.getLayoutMetrics", + params=params, + session_id=session_id, + ), + ) async def getNavigationHistory( self, @@ -316,11 +376,14 @@ async def getNavigationHistory( session_id: Optional[str] = None, ) -> "GetNavigationHistoryReturns": """Returns navigation history for the current page.""" - return cast("GetNavigationHistoryReturns", await self._client.send_raw( - method="Page.getNavigationHistory", - params=params, - session_id=session_id, - )) + return cast( + "GetNavigationHistoryReturns", + await self._client.send_raw( + method="Page.getNavigationHistory", + params=params, + session_id=session_id, + ), + ) async def resetNavigationHistory( self, @@ -328,11 +391,14 @@ async def resetNavigationHistory( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Resets navigation history for the current page.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.resetNavigationHistory", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.resetNavigationHistory", + params=params, + session_id=session_id, + ), + ) async def getResourceContent( self, @@ -340,11 +406,14 @@ async def getResourceContent( session_id: Optional[str] = None, ) -> "GetResourceContentReturns": """Returns content of the given resource.""" - return cast("GetResourceContentReturns", await self._client.send_raw( - method="Page.getResourceContent", - params=params, - session_id=session_id, - )) + return cast( + "GetResourceContentReturns", + await self._client.send_raw( + method="Page.getResourceContent", + params=params, + session_id=session_id, + ), + ) async def getResourceTree( self, @@ -352,11 +421,14 @@ async def getResourceTree( session_id: Optional[str] = None, ) -> "GetResourceTreeReturns": """Returns present frame / resource tree structure.""" - return cast("GetResourceTreeReturns", await self._client.send_raw( - method="Page.getResourceTree", - params=params, - session_id=session_id, - )) + return cast( + "GetResourceTreeReturns", + await self._client.send_raw( + method="Page.getResourceTree", + params=params, + session_id=session_id, + ), + ) async def handleJavaScriptDialog( self, @@ -364,11 +436,14 @@ async def handleJavaScriptDialog( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Accepts or dismisses a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.handleJavaScriptDialog", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.handleJavaScriptDialog", + params=params, + session_id=session_id, + ), + ) async def navigate( self, @@ -376,11 +451,14 @@ async def navigate( session_id: Optional[str] = None, ) -> "NavigateReturns": """Navigates current page to the given URL.""" - return cast("NavigateReturns", await self._client.send_raw( - method="Page.navigate", - params=params, - session_id=session_id, - )) + return cast( + "NavigateReturns", + await self._client.send_raw( + method="Page.navigate", + params=params, + session_id=session_id, + ), + ) async def navigateToHistoryEntry( self, @@ -388,11 +466,14 @@ async def navigateToHistoryEntry( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Navigates current page to the given history entry.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.navigateToHistoryEntry", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.navigateToHistoryEntry", + params=params, + session_id=session_id, + ), + ) async def printToPDF( self, @@ -400,11 +481,14 @@ async def printToPDF( session_id: Optional[str] = None, ) -> "PrintToPDFReturns": """Print page as PDF.""" - return cast("PrintToPDFReturns", await self._client.send_raw( - method="Page.printToPDF", - params=params, - session_id=session_id, - )) + return cast( + "PrintToPDFReturns", + await self._client.send_raw( + method="Page.printToPDF", + params=params, + session_id=session_id, + ), + ) async def reload( self, @@ -412,11 +496,14 @@ async def reload( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Reloads given page optionally ignoring the cache.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.reload", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.reload", + params=params, + session_id=session_id, + ), + ) async def removeScriptToEvaluateOnLoad( self, @@ -424,11 +511,14 @@ async def removeScriptToEvaluateOnLoad( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deprecated, please use removeScriptToEvaluateOnNewDocument instead.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.removeScriptToEvaluateOnLoad", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.removeScriptToEvaluateOnLoad", + params=params, + session_id=session_id, + ), + ) async def removeScriptToEvaluateOnNewDocument( self, @@ -436,11 +526,14 @@ async def removeScriptToEvaluateOnNewDocument( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes given script from the list.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.removeScriptToEvaluateOnNewDocument", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.removeScriptToEvaluateOnNewDocument", + params=params, + session_id=session_id, + ), + ) async def screencastFrameAck( self, @@ -448,11 +541,14 @@ async def screencastFrameAck( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Acknowledges that a screencast frame has been received by the frontend.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.screencastFrameAck", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.screencastFrameAck", + params=params, + session_id=session_id, + ), + ) async def searchInResource( self, @@ -460,11 +556,14 @@ async def searchInResource( session_id: Optional[str] = None, ) -> "SearchInResourceReturns": """Searches for given string in resource content.""" - return cast("SearchInResourceReturns", await self._client.send_raw( - method="Page.searchInResource", - params=params, - session_id=session_id, - )) + return cast( + "SearchInResourceReturns", + await self._client.send_raw( + method="Page.searchInResource", + params=params, + session_id=session_id, + ), + ) async def setAdBlockingEnabled( self, @@ -472,11 +571,14 @@ async def setAdBlockingEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable Chrome's experimental ad filter on all sites.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setAdBlockingEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setAdBlockingEnabled", + params=params, + session_id=session_id, + ), + ) async def setBypassCSP( self, @@ -484,11 +586,14 @@ async def setBypassCSP( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable page Content Security Policy by-passing.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setBypassCSP", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setBypassCSP", + params=params, + session_id=session_id, + ), + ) async def getPermissionsPolicyState( self, @@ -496,11 +601,14 @@ async def getPermissionsPolicyState( session_id: Optional[str] = None, ) -> "GetPermissionsPolicyStateReturns": """Get Permissions Policy state on given frame.""" - return cast("GetPermissionsPolicyStateReturns", await self._client.send_raw( - method="Page.getPermissionsPolicyState", - params=params, - session_id=session_id, - )) + return cast( + "GetPermissionsPolicyStateReturns", + await self._client.send_raw( + method="Page.getPermissionsPolicyState", + params=params, + session_id=session_id, + ), + ) async def getOriginTrials( self, @@ -508,11 +616,14 @@ async def getOriginTrials( session_id: Optional[str] = None, ) -> "GetOriginTrialsReturns": """Get Origin Trials on given frame.""" - return cast("GetOriginTrialsReturns", await self._client.send_raw( - method="Page.getOriginTrials", - params=params, - session_id=session_id, - )) + return cast( + "GetOriginTrialsReturns", + await self._client.send_raw( + method="Page.getOriginTrials", + params=params, + session_id=session_id, + ), + ) async def setDeviceMetricsOverride( self, @@ -520,13 +631,16 @@ async def setDeviceMetricsOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the values of device screen dimensions (window.screen.width, window.screen.height, -window.innerWidth, window.innerHeight, and \"device-width\"/\"device-height\"-related CSS media -query results).""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setDeviceMetricsOverride", - params=params, - session_id=session_id, - )) + window.innerWidth, window.innerHeight, and \"device-width\"/\"device-height\"-related CSS media + query results).""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setDeviceMetricsOverride", + params=params, + session_id=session_id, + ), + ) async def setDeviceOrientationOverride( self, @@ -534,11 +648,14 @@ async def setDeviceOrientationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the Device Orientation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setDeviceOrientationOverride", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setDeviceOrientationOverride", + params=params, + session_id=session_id, + ), + ) async def setFontFamilies( self, @@ -546,11 +663,14 @@ async def setFontFamilies( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set generic font families.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setFontFamilies", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setFontFamilies", + params=params, + session_id=session_id, + ), + ) async def setFontSizes( self, @@ -558,11 +678,14 @@ async def setFontSizes( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set default font sizes.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setFontSizes", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setFontSizes", + params=params, + session_id=session_id, + ), + ) async def setDocumentContent( self, @@ -570,11 +693,14 @@ async def setDocumentContent( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets given markup as the document's HTML.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setDocumentContent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setDocumentContent", + params=params, + session_id=session_id, + ), + ) async def setDownloadBehavior( self, @@ -582,11 +708,14 @@ async def setDownloadBehavior( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set the behavior when downloading a file.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setDownloadBehavior", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setDownloadBehavior", + params=params, + session_id=session_id, + ), + ) async def setGeolocationOverride( self, @@ -594,12 +723,15 @@ async def setGeolocationOverride( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position -unavailable.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setGeolocationOverride", - params=params, - session_id=session_id, - )) + unavailable.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setGeolocationOverride", + params=params, + session_id=session_id, + ), + ) async def setLifecycleEventsEnabled( self, @@ -607,11 +739,14 @@ async def setLifecycleEventsEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Controls whether page will emit lifecycle events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setLifecycleEventsEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setLifecycleEventsEnabled", + params=params, + session_id=session_id, + ), + ) async def setTouchEmulationEnabled( self, @@ -619,11 +754,14 @@ async def setTouchEmulationEnabled( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Toggles mouse event-based touch event emulation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setTouchEmulationEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setTouchEmulationEnabled", + params=params, + session_id=session_id, + ), + ) async def startScreencast( self, @@ -631,11 +769,14 @@ async def startScreencast( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Starts sending each frame using the `screencastFrame` event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.startScreencast", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.startScreencast", + params=params, + session_id=session_id, + ), + ) async def stopLoading( self, @@ -643,11 +784,14 @@ async def stopLoading( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Force the page stop all navigations and pending resource fetches.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.stopLoading", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.stopLoading", + params=params, + session_id=session_id, + ), + ) async def crash( self, @@ -655,11 +799,14 @@ async def crash( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Crashes renderer on the IO thread, generates minidumps.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.crash", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.crash", + params=params, + session_id=session_id, + ), + ) async def close( self, @@ -667,11 +814,14 @@ async def close( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Tries to close page, running its beforeunload hooks, if any.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.close", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.close", + params=params, + session_id=session_id, + ), + ) async def setWebLifecycleState( self, @@ -679,13 +829,16 @@ async def setWebLifecycleState( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Tries to update the web lifecycle state of the page. -It will transition the page to the given state according to: -https://github.com/WICG/web-lifecycle/""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setWebLifecycleState", - params=params, - session_id=session_id, - )) + It will transition the page to the given state according to: + https://github.com/WICG/web-lifecycle/""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setWebLifecycleState", + params=params, + session_id=session_id, + ), + ) async def stopScreencast( self, @@ -693,11 +846,14 @@ async def stopScreencast( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stops sending each frame in the `screencastFrame`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.stopScreencast", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.stopScreencast", + params=params, + session_id=session_id, + ), + ) async def produceCompilationCache( self, @@ -705,16 +861,19 @@ async def produceCompilationCache( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Requests backend to produce compilation cache for the specified scripts. -`scripts` are appended to the list of scripts for which the cache -would be produced. The list may be reset during page navigation. -When script with a matching URL is encountered, the cache is optionally -produced upon backend discretion, based on internal heuristics. -See also: `Page.compilationCacheProduced`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.produceCompilationCache", - params=params, - session_id=session_id, - )) + `scripts` are appended to the list of scripts for which the cache + would be produced. The list may be reset during page navigation. + When script with a matching URL is encountered, the cache is optionally + produced upon backend discretion, based on internal heuristics. + See also: `Page.compilationCacheProduced`.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.produceCompilationCache", + params=params, + session_id=session_id, + ), + ) async def addCompilationCache( self, @@ -722,12 +881,15 @@ async def addCompilationCache( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Seeds compilation cache for given url. Compilation cache does not survive -cross-process navigation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.addCompilationCache", - params=params, - session_id=session_id, - )) + cross-process navigation.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.addCompilationCache", + params=params, + session_id=session_id, + ), + ) async def clearCompilationCache( self, @@ -735,11 +897,14 @@ async def clearCompilationCache( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears seeded compilation cache.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.clearCompilationCache", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.clearCompilationCache", + params=params, + session_id=session_id, + ), + ) async def setSPCTransactionMode( self, @@ -747,12 +912,15 @@ async def setSPCTransactionMode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets the Secure Payment Confirmation transaction mode. -https://w3c.github.io/secure-payment-confirmation/#sctn-automation-set-spc-transaction-mode""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setSPCTransactionMode", - params=params, - session_id=session_id, - )) + https://w3c.github.io/secure-payment-confirmation/#sctn-automation-set-spc-transaction-mode""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setSPCTransactionMode", + params=params, + session_id=session_id, + ), + ) async def setRPHRegistrationMode( self, @@ -760,12 +928,15 @@ async def setRPHRegistrationMode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Extensions for Custom Handlers API: -https://html.spec.whatwg.org/multipage/system-state.html#rph-automation""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setRPHRegistrationMode", - params=params, - session_id=session_id, - )) + https://html.spec.whatwg.org/multipage/system-state.html#rph-automation""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setRPHRegistrationMode", + params=params, + session_id=session_id, + ), + ) async def generateTestReport( self, @@ -773,11 +944,14 @@ async def generateTestReport( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Generates a report for testing.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.generateTestReport", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.generateTestReport", + params=params, + session_id=session_id, + ), + ) async def waitForDebugger( self, @@ -785,11 +959,14 @@ async def waitForDebugger( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Pauses page execution. Can be resumed using generic Runtime.runIfWaitingForDebugger.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.waitForDebugger", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.waitForDebugger", + params=params, + session_id=session_id, + ), + ) async def setInterceptFileChooserDialog( self, @@ -797,13 +974,16 @@ async def setInterceptFileChooserDialog( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Intercept file chooser requests and transfer control to protocol clients. -When file chooser interception is enabled, native file chooser dialog is not shown. -Instead, a protocol event `Page.fileChooserOpened` is emitted.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setInterceptFileChooserDialog", - params=params, - session_id=session_id, - )) + When file chooser interception is enabled, native file chooser dialog is not shown. + Instead, a protocol event `Page.fileChooserOpened` is emitted.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setInterceptFileChooserDialog", + params=params, + session_id=session_id, + ), + ) async def setPrerenderingAllowed( self, @@ -812,15 +992,32 @@ async def setPrerenderingAllowed( ) -> "Dict[str, Any]": """Enable/disable prerendering manually. -This command is a short-term solution for https://crbug.com/1440085. -See https://docs.google.com/document/d/12HVmFxYj5Jc-eJr5OmWsa2bqTJsbgGLKI6ZIyx0_wpA -for more details. - -TODO(https://crbug.com/1440085): Remove this once Puppeteer supports tab targets.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Page.setPrerenderingAllowed", - params=params, - session_id=session_id, - )) - - + This command is a short-term solution for https://crbug.com/1440085. + See https://docs.google.com/document/d/12HVmFxYj5Jc-eJr5OmWsa2bqTJsbgGLKI6ZIyx0_wpA + for more details. + + TODO(https://crbug.com/1440085): Remove this once Puppeteer supports tab targets.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Page.setPrerenderingAllowed", + params=params, + session_id=session_id, + ), + ) + + async def getAnnotatedPageContent( + self, + params: Optional["GetAnnotatedPageContentParameters"] = None, + session_id: Optional[str] = None, + ) -> "GetAnnotatedPageContentReturns": + """Get the annotated page content for the main frame. + This is an experimental command that is subject to change.""" + return cast( + "GetAnnotatedPageContentReturns", + await self._client.send_raw( + method="Page.getAnnotatedPageContent", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/page/registration.py b/cdp_use/cdp/page/registration.py index e43569e..de57ef6 100644 --- a/cdp_use/cdp/page/registration.py +++ b/cdp_use/cdp/page/registration.py @@ -11,50 +11,51 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - BackForwardCacheNotUsedEvent, - CompilationCacheProducedEvent, - DocumentOpenedEvent, - DomContentEventFiredEvent, - DownloadProgressEvent, - DownloadWillBeginEvent, - FileChooserOpenedEvent, - FrameAttachedEvent, - FrameClearedScheduledNavigationEvent, - FrameDetachedEvent, - FrameNavigatedEvent, - FrameRequestedNavigationEvent, - FrameResizedEvent, - FrameScheduledNavigationEvent, - FrameStartedLoadingEvent, - FrameStartedNavigatingEvent, - FrameStoppedLoadingEvent, - FrameSubtreeWillBeDetachedEvent, - InterstitialHiddenEvent, - InterstitialShownEvent, - JavascriptDialogClosedEvent, - JavascriptDialogOpeningEvent, - LifecycleEventEvent, - LoadEventFiredEvent, - NavigatedWithinDocumentEvent, - ScreencastFrameEvent, - ScreencastVisibilityChangedEvent, - WindowOpenEvent -) + BackForwardCacheNotUsedEvent, + CompilationCacheProducedEvent, + DocumentOpenedEvent, + DomContentEventFiredEvent, + DownloadProgressEvent, + DownloadWillBeginEvent, + FileChooserOpenedEvent, + FrameAttachedEvent, + FrameClearedScheduledNavigationEvent, + FrameDetachedEvent, + FrameNavigatedEvent, + FrameRequestedNavigationEvent, + FrameResizedEvent, + FrameScheduledNavigationEvent, + FrameStartedLoadingEvent, + FrameStartedNavigatingEvent, + FrameStoppedLoadingEvent, + FrameSubtreeWillBeDetachedEvent, + InterstitialHiddenEvent, + InterstitialShownEvent, + JavascriptDialogClosedEvent, + JavascriptDialogOpeningEvent, + LifecycleEventEvent, + LoadEventFiredEvent, + NavigatedWithinDocumentEvent, + ScreencastFrameEvent, + ScreencastVisibilityChangedEvent, + WindowOpenEvent, + ) + class PageRegistration: """Event registration interface for Page domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Page" def domContentEventFired( self, - callback: Callable[['DomContentEventFiredEvent', Optional[str]], None], + callback: Callable[["DomContentEventFiredEvent", Optional[str]], None], ) -> None: """ Register a callback for domContentEventFired events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -63,13 +64,13 @@ def domContentEventFired( def fileChooserOpened( self, - callback: Callable[['FileChooserOpenedEvent', Optional[str]], None], + callback: Callable[["FileChooserOpenedEvent", Optional[str]], None], ) -> None: """ Register a callback for fileChooserOpened events. - + Emitted only when `page.interceptFileChooser` is enabled. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -78,13 +79,13 @@ def fileChooserOpened( def frameAttached( self, - callback: Callable[['FrameAttachedEvent', Optional[str]], None], + callback: Callable[["FrameAttachedEvent", Optional[str]], None], ) -> None: """ Register a callback for frameAttached events. - + Fired when frame has been attached to its parent. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -93,13 +94,15 @@ def frameAttached( def frameClearedScheduledNavigation( self, - callback: Callable[['FrameClearedScheduledNavigationEvent', Optional[str]], None], + callback: Callable[ + ["FrameClearedScheduledNavigationEvent", Optional[str]], None + ], ) -> None: """ Register a callback for frameClearedScheduledNavigation events. - + Fired when frame no longer has a scheduled navigation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -108,13 +111,13 @@ def frameClearedScheduledNavigation( def frameDetached( self, - callback: Callable[['FrameDetachedEvent', Optional[str]], None], + callback: Callable[["FrameDetachedEvent", Optional[str]], None], ) -> None: """ Register a callback for frameDetached events. - + Fired when frame has been detached from its parent. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -123,29 +126,29 @@ def frameDetached( def frameSubtreeWillBeDetached( self, - callback: Callable[['FrameSubtreeWillBeDetachedEvent', Optional[str]], None], + callback: Callable[["FrameSubtreeWillBeDetachedEvent", Optional[str]], None], ) -> None: """ - Register a callback for frameSubtreeWillBeDetached events. - - Fired before frame subtree is detached. Emitted before any frame of the -subtree is actually detached. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for frameSubtreeWillBeDetached events. + + Fired before frame subtree is detached. Emitted before any frame of the + subtree is actually detached. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.frameSubtreeWillBeDetached", callback) def frameNavigated( self, - callback: Callable[['FrameNavigatedEvent', Optional[str]], None], + callback: Callable[["FrameNavigatedEvent", Optional[str]], None], ) -> None: """ Register a callback for frameNavigated events. - + Fired once navigation of the frame has completed. Frame is now associated with the new loader. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -154,13 +157,13 @@ def frameNavigated( def documentOpened( self, - callback: Callable[['DocumentOpenedEvent', Optional[str]], None], + callback: Callable[["DocumentOpenedEvent", Optional[str]], None], ) -> None: """ Register a callback for documentOpened events. - + Fired when opening document to write to. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -169,11 +172,11 @@ def documentOpened( def frameResized( self, - callback: Callable[['FrameResizedEvent', Optional[str]], None], + callback: Callable[["FrameResizedEvent", Optional[str]], None], ) -> None: """ Register a callback for frameResized events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -182,50 +185,50 @@ def frameResized( def frameStartedNavigating( self, - callback: Callable[['FrameStartedNavigatingEvent', Optional[str]], None], + callback: Callable[["FrameStartedNavigatingEvent", Optional[str]], None], ) -> None: """ - Register a callback for frameStartedNavigating events. - - Fired when a navigation starts. This event is fired for both -renderer-initiated and browser-initiated navigations. For renderer-initiated -navigations, the event is fired after `frameRequestedNavigation`. -Navigation may still be cancelled after the event is issued. Multiple events -can be fired for a single navigation, for example, when a same-document -navigation becomes a cross-document navigation (such as in the case of a -frameset). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for frameStartedNavigating events. + + Fired when a navigation starts. This event is fired for both + renderer-initiated and browser-initiated navigations. For renderer-initiated + navigations, the event is fired after `frameRequestedNavigation`. + Navigation may still be cancelled after the event is issued. Multiple events + can be fired for a single navigation, for example, when a same-document + navigation becomes a cross-document navigation (such as in the case of a + frameset). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.frameStartedNavigating", callback) def frameRequestedNavigation( self, - callback: Callable[['FrameRequestedNavigationEvent', Optional[str]], None], + callback: Callable[["FrameRequestedNavigationEvent", Optional[str]], None], ) -> None: """ - Register a callback for frameRequestedNavigation events. - - Fired when a renderer-initiated navigation is requested. -Navigation may still be cancelled after the event is issued. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for frameRequestedNavigation events. + + Fired when a renderer-initiated navigation is requested. + Navigation may still be cancelled after the event is issued. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.frameRequestedNavigation", callback) def frameScheduledNavigation( self, - callback: Callable[['FrameScheduledNavigationEvent', Optional[str]], None], + callback: Callable[["FrameScheduledNavigationEvent", Optional[str]], None], ) -> None: """ Register a callback for frameScheduledNavigation events. - + Fired when frame schedules a potential navigation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -234,13 +237,13 @@ def frameScheduledNavigation( def frameStartedLoading( self, - callback: Callable[['FrameStartedLoadingEvent', Optional[str]], None], + callback: Callable[["FrameStartedLoadingEvent", Optional[str]], None], ) -> None: """ Register a callback for frameStartedLoading events. - + Fired when frame has started loading. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -249,13 +252,13 @@ def frameStartedLoading( def frameStoppedLoading( self, - callback: Callable[['FrameStoppedLoadingEvent', Optional[str]], None], + callback: Callable[["FrameStoppedLoadingEvent", Optional[str]], None], ) -> None: """ Register a callback for frameStoppedLoading events. - + Fired when frame has stopped loading. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -264,45 +267,45 @@ def frameStoppedLoading( def downloadWillBegin( self, - callback: Callable[['DownloadWillBeginEvent', Optional[str]], None], + callback: Callable[["DownloadWillBeginEvent", Optional[str]], None], ) -> None: """ - Register a callback for downloadWillBegin events. - - Fired when page is about to start a download. -Deprecated. Use Browser.downloadWillBegin instead. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for downloadWillBegin events. + + Fired when page is about to start a download. + Deprecated. Use Browser.downloadWillBegin instead. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.downloadWillBegin", callback) def downloadProgress( self, - callback: Callable[['DownloadProgressEvent', Optional[str]], None], + callback: Callable[["DownloadProgressEvent", Optional[str]], None], ) -> None: """ - Register a callback for downloadProgress events. - - Fired when download makes progress. Last call has |done| == true. -Deprecated. Use Browser.downloadProgress instead. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for downloadProgress events. + + Fired when download makes progress. Last call has |done| == true. + Deprecated. Use Browser.downloadProgress instead. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.downloadProgress", callback) def interstitialHidden( self, - callback: Callable[['InterstitialHiddenEvent', Optional[str]], None], + callback: Callable[["InterstitialHiddenEvent", Optional[str]], None], ) -> None: """ Register a callback for interstitialHidden events. - + Fired when interstitial page was hidden - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -311,13 +314,13 @@ def interstitialHidden( def interstitialShown( self, - callback: Callable[['InterstitialShownEvent', Optional[str]], None], + callback: Callable[["InterstitialShownEvent", Optional[str]], None], ) -> None: """ Register a callback for interstitialShown events. - + Fired when interstitial page was shown - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -326,77 +329,77 @@ def interstitialShown( def javascriptDialogClosed( self, - callback: Callable[['JavascriptDialogClosedEvent', Optional[str]], None], + callback: Callable[["JavascriptDialogClosedEvent", Optional[str]], None], ) -> None: """ - Register a callback for javascriptDialogClosed events. - - Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) has been -closed. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for javascriptDialogClosed events. + + Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) has been + closed. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.javascriptDialogClosed", callback) def javascriptDialogOpening( self, - callback: Callable[['JavascriptDialogOpeningEvent', Optional[str]], None], + callback: Callable[["JavascriptDialogOpeningEvent", Optional[str]], None], ) -> None: """ - Register a callback for javascriptDialogOpening events. - - Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) is about to -open. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for javascriptDialogOpening events. + + Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) is about to + open. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.javascriptDialogOpening", callback) def lifecycleEvent( self, - callback: Callable[['LifecycleEventEvent', Optional[str]], None], + callback: Callable[["LifecycleEventEvent", Optional[str]], None], ) -> None: """ - Register a callback for lifecycleEvent events. - - Fired for lifecycle events (navigation, load, paint, etc) in the current -target (including local frames). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for lifecycleEvent events. + + Fired for lifecycle events (navigation, load, paint, etc) in the current + target (including local frames). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.lifecycleEvent", callback) def backForwardCacheNotUsed( self, - callback: Callable[['BackForwardCacheNotUsedEvent', Optional[str]], None], + callback: Callable[["BackForwardCacheNotUsedEvent", Optional[str]], None], ) -> None: """ - Register a callback for backForwardCacheNotUsed events. - - Fired for failed bfcache history navigations if BackForwardCache feature is enabled. Do -not assume any ordering with the Page.frameNavigated event. This event is fired only for -main-frame history navigation where the document changes (non-same-document navigations), -when bfcache navigation fails. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for backForwardCacheNotUsed events. + + Fired for failed bfcache history navigations if BackForwardCache feature is enabled. Do + not assume any ordering with the Page.frameNavigated event. This event is fired only for + main-frame history navigation where the document changes (non-same-document navigations), + when bfcache navigation fails. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.backForwardCacheNotUsed", callback) def loadEventFired( self, - callback: Callable[['LoadEventFiredEvent', Optional[str]], None], + callback: Callable[["LoadEventFiredEvent", Optional[str]], None], ) -> None: """ Register a callback for loadEventFired events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -405,13 +408,13 @@ def loadEventFired( def navigatedWithinDocument( self, - callback: Callable[['NavigatedWithinDocumentEvent', Optional[str]], None], + callback: Callable[["NavigatedWithinDocumentEvent", Optional[str]], None], ) -> None: """ Register a callback for navigatedWithinDocument events. - + Fired when same-document navigation happens, e.g. due to history API usage or anchor navigation. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -420,13 +423,13 @@ def navigatedWithinDocument( def screencastFrame( self, - callback: Callable[['ScreencastFrameEvent', Optional[str]], None], + callback: Callable[["ScreencastFrameEvent", Optional[str]], None], ) -> None: """ Register a callback for screencastFrame events. - + Compressed image data requested by the `startScreencast`. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -435,13 +438,13 @@ def screencastFrame( def screencastVisibilityChanged( self, - callback: Callable[['ScreencastVisibilityChangedEvent', Optional[str]], None], + callback: Callable[["ScreencastVisibilityChangedEvent", Optional[str]], None], ) -> None: """ Register a callback for screencastVisibilityChanged events. - + Fired when the page with currently enabled screencast was shown or hidden `. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -450,32 +453,31 @@ def screencastVisibilityChanged( def windowOpen( self, - callback: Callable[['WindowOpenEvent', Optional[str]], None], + callback: Callable[["WindowOpenEvent", Optional[str]], None], ) -> None: """ - Register a callback for windowOpen events. - - Fired when a new window is going to be opened, via window.open(), link click, form submission, -etc. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for windowOpen events. + + Fired when a new window is going to be opened, via window.open(), link click, form submission, + etc. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Page.windowOpen", callback) def compilationCacheProduced( self, - callback: Callable[['CompilationCacheProducedEvent', Optional[str]], None], + callback: Callable[["CompilationCacheProducedEvent", Optional[str]], None], ) -> None: """ Register a callback for compilationCacheProduced events. - + Issued for every compilation cache generated. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Page.compilationCacheProduced", callback) - diff --git a/cdp_use/cdp/page/types.py b/cdp_use/cdp/page/types.py index 0b7a0f7..4ea2db8 100644 --- a/cdp_use/cdp/page/types.py +++ b/cdp_use/cdp/page/types.py @@ -21,16 +21,13 @@ """Unique frame identifier.""" - AdFrameType = Literal["none", "child", "root"] """Indicates whether a frame has been identified as an ad.""" - AdFrameExplanation = Literal["ParentIsAd", "CreatedByAdScript", "MatchedBlockingRule"] - class AdFrameStatus(TypedDict): """Indicates whether a frame has been identified as an ad and why.""" @@ -38,10 +35,9 @@ class AdFrameStatus(TypedDict): explanations: "NotRequired[List[AdFrameExplanation]]" - class AdScriptId(TypedDict): """Identifies the script which caused a script or frame to be labelled as an -ad.""" + ad.""" scriptId: "ScriptId" """Script Id of the script which caused a script or frame to be labelled as @@ -50,11 +46,10 @@ class AdScriptId(TypedDict): """Id of scriptId's debugger.""" - class AdScriptAncestry(TypedDict): """Encapsulates the script ancestry and the root script filterlist rule that -caused the frame to be labelled as an ad. Only created when `ancestryChain` -is not empty.""" + caused the frame to be labelled as an ad. Only created when `ancestryChain` + is not empty.""" ancestryChain: "List[AdScriptId]" """A chain of `AdScriptId`s representing the ancestry of an ad script that @@ -67,61 +62,185 @@ class AdScriptAncestry(TypedDict): available.""" - -SecureContextType = Literal["Secure", "SecureLocalhost", "InsecureScheme", "InsecureAncestor"] +SecureContextType = Literal[ + "Secure", "SecureLocalhost", "InsecureScheme", "InsecureAncestor" +] """Indicates whether the frame is a secure context and why it is the case.""" - -CrossOriginIsolatedContextType = Literal["Isolated", "NotIsolated", "NotIsolatedFeatureDisabled"] +CrossOriginIsolatedContextType = Literal[ + "Isolated", "NotIsolated", "NotIsolatedFeatureDisabled" +] """Indicates whether the frame is cross-origin isolated and why it is the case.""" - -GatedAPIFeatures = Literal["SharedArrayBuffers", "SharedArrayBuffersTransferAllowed", "PerformanceMeasureMemory", "PerformanceProfile"] - - - -PermissionsPolicyFeature = Literal["accelerometer", "all-screens-capture", "ambient-light-sensor", "aria-notify", "attribution-reporting", "autoplay", "bluetooth", "browsing-topics", "camera", "captured-surface-control", "ch-dpr", "ch-device-memory", "ch-downlink", "ch-ect", "ch-prefers-color-scheme", "ch-prefers-reduced-motion", "ch-prefers-reduced-transparency", "ch-rtt", "ch-save-data", "ch-ua", "ch-ua-arch", "ch-ua-bitness", "ch-ua-high-entropy-values", "ch-ua-platform", "ch-ua-model", "ch-ua-mobile", "ch-ua-form-factors", "ch-ua-full-version", "ch-ua-full-version-list", "ch-ua-platform-version", "ch-ua-wow64", "ch-viewport-height", "ch-viewport-width", "ch-width", "clipboard-read", "clipboard-write", "compute-pressure", "controlled-frame", "cross-origin-isolated", "deferred-fetch", "deferred-fetch-minimal", "device-attributes", "digital-credentials-create", "digital-credentials-get", "direct-sockets", "direct-sockets-private", "display-capture", "document-domain", "encrypted-media", "execution-while-out-of-viewport", "execution-while-not-rendered", "fenced-unpartitioned-storage-read", "focus-without-user-activation", "fullscreen", "frobulate", "gamepad", "geolocation", "gyroscope", "hid", "identity-credentials-get", "idle-detection", "interest-cohort", "join-ad-interest-group", "keyboard-map", "language-detector", "language-model", "local-fonts", "local-network-access", "magnetometer", "media-playback-while-not-visible", "microphone", "midi", "on-device-speech-recognition", "otp-credentials", "payment", "picture-in-picture", "popins", "private-aggregation", "private-state-token-issuance", "private-state-token-redemption", "publickey-credentials-create", "publickey-credentials-get", "record-ad-auction-events", "rewriter", "run-ad-auction", "screen-wake-lock", "serial", "shared-autofill", "shared-storage", "shared-storage-select-url", "smart-card", "speaker-selection", "storage-access", "sub-apps", "summarizer", "sync-xhr", "translator", "unload", "usb", "usb-unrestricted", "vertical-scroll", "web-app-installation", "web-printing", "web-share", "window-management", "writer", "xr-spatial-tracking"] +GatedAPIFeatures = Literal[ + "SharedArrayBuffers", + "SharedArrayBuffersTransferAllowed", + "PerformanceMeasureMemory", + "PerformanceProfile", +] + + +PermissionsPolicyFeature = Literal[ + "accelerometer", + "all-screens-capture", + "ambient-light-sensor", + "aria-notify", + "attribution-reporting", + "autofill", + "autoplay", + "bluetooth", + "browsing-topics", + "camera", + "captured-surface-control", + "ch-dpr", + "ch-device-memory", + "ch-downlink", + "ch-ect", + "ch-prefers-color-scheme", + "ch-prefers-reduced-motion", + "ch-prefers-reduced-transparency", + "ch-rtt", + "ch-save-data", + "ch-ua", + "ch-ua-arch", + "ch-ua-bitness", + "ch-ua-high-entropy-values", + "ch-ua-platform", + "ch-ua-model", + "ch-ua-mobile", + "ch-ua-form-factors", + "ch-ua-full-version", + "ch-ua-full-version-list", + "ch-ua-platform-version", + "ch-ua-wow64", + "ch-viewport-height", + "ch-viewport-width", + "ch-width", + "clipboard-read", + "clipboard-write", + "compute-pressure", + "controlled-frame", + "cross-origin-isolated", + "deferred-fetch", + "deferred-fetch-minimal", + "device-attributes", + "digital-credentials-create", + "digital-credentials-get", + "direct-sockets", + "direct-sockets-multicast", + "direct-sockets-private", + "display-capture", + "document-domain", + "encrypted-media", + "execution-while-out-of-viewport", + "execution-while-not-rendered", + "fenced-unpartitioned-storage-read", + "focus-without-user-activation", + "fullscreen", + "frobulate", + "gamepad", + "geolocation", + "gyroscope", + "hid", + "identity-credentials-get", + "idle-detection", + "interest-cohort", + "join-ad-interest-group", + "keyboard-map", + "language-detector", + "language-model", + "local-fonts", + "local-network-access", + "magnetometer", + "manual-text", + "media-playback-while-not-visible", + "microphone", + "midi", + "on-device-speech-recognition", + "otp-credentials", + "payment", + "picture-in-picture", + "private-aggregation", + "private-state-token-issuance", + "private-state-token-redemption", + "publickey-credentials-create", + "publickey-credentials-get", + "record-ad-auction-events", + "rewriter", + "run-ad-auction", + "screen-wake-lock", + "serial", + "shared-storage", + "shared-storage-select-url", + "smart-card", + "speaker-selection", + "storage-access", + "sub-apps", + "summarizer", + "sync-xhr", + "translator", + "unload", + "usb", + "usb-unrestricted", + "vertical-scroll", + "web-app-installation", + "web-printing", + "web-share", + "window-management", + "writer", + "xr-spatial-tracking", +] """All Permissions Policy features. This enum should match the one defined in services/network/public/cpp/permissions_policy/permissions_policy_features.json5. LINT.IfChange(PermissionsPolicyFeature)""" - -PermissionsPolicyBlockReason = Literal["Header", "IframeAttribute", "InFencedFrameTree", "InIsolatedApp"] +PermissionsPolicyBlockReason = Literal[ + "Header", "IframeAttribute", "InFencedFrameTree", "InIsolatedApp" +] """Reason for a permissions policy feature to be disabled.""" - class PermissionsPolicyBlockLocator(TypedDict): frameId: "FrameId" blockReason: "PermissionsPolicyBlockReason" - class PermissionsPolicyFeatureState(TypedDict): feature: "PermissionsPolicyFeature" allowed: "bool" locator: "NotRequired[PermissionsPolicyBlockLocator]" - -OriginTrialTokenStatus = Literal["Success", "NotSupported", "Insecure", "Expired", "WrongOrigin", "InvalidSignature", "Malformed", "WrongVersion", "FeatureDisabled", "TokenDisabled", "FeatureDisabledForUser", "UnknownTrial"] +OriginTrialTokenStatus = Literal[ + "Success", + "NotSupported", + "Insecure", + "Expired", + "WrongOrigin", + "InvalidSignature", + "Malformed", + "WrongVersion", + "FeatureDisabled", + "TokenDisabled", + "FeatureDisabledForUser", + "UnknownTrial", +] """Origin Trial(https://www.chromium.org/blink/origin-trials) support. Status for an Origin Trial token.""" - -OriginTrialStatus = Literal["Enabled", "ValidTokenNotProvided", "OSNotSupported", "TrialNotAllowed"] +OriginTrialStatus = Literal[ + "Enabled", "ValidTokenNotProvided", "OSNotSupported", "TrialNotAllowed" +] """Status for an Origin Trial.""" - OriginTrialUsageRestriction = Literal["None", "Subset"] - class OriginTrialToken(TypedDict): origin: "str" matchSubDomains: "bool" @@ -131,7 +250,6 @@ class OriginTrialToken(TypedDict): usageRestriction: "OriginTrialUsageRestriction" - class OriginTrialTokenWithStatus(TypedDict): rawTokenText: "str" parsedToken: "NotRequired[OriginTrialToken]" @@ -140,14 +258,12 @@ class OriginTrialTokenWithStatus(TypedDict): status: "OriginTrialTokenStatus" - class OriginTrial(TypedDict): trialName: "str" status: "OriginTrialStatus" tokensWithStatus: "List[OriginTrialTokenWithStatus]" - class SecurityOriginDetails(TypedDict): """Additional information about the frame document's security origin.""" @@ -157,7 +273,6 @@ class SecurityOriginDetails(TypedDict): 127.0.0.0/8 or IPv6 ::1).""" - class Frame(TypedDict): """Information about the Frame on the page.""" @@ -196,7 +311,6 @@ class Frame(TypedDict): """Indicated which gated APIs / features are available.""" - class FrameResource(TypedDict): """Information about the Resource on the page.""" @@ -216,7 +330,6 @@ class FrameResource(TypedDict): """True if the resource was canceled during loading.""" - class FrameResourceTree(TypedDict): """Information about the Frame hierarchy along with their cached resources.""" @@ -228,7 +341,6 @@ class FrameResourceTree(TypedDict): """Information about frame resources.""" - class FrameTree(TypedDict): """Information about the Frame hierarchy.""" @@ -238,17 +350,28 @@ class FrameTree(TypedDict): """Child frames.""" - ScriptIdentifier = str """Unique script identifier.""" - -TransitionType = Literal["link", "typed", "address_bar", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "auto_toplevel", "form_submit", "reload", "keyword", "keyword_generated", "other"] +TransitionType = Literal[ + "link", + "typed", + "address_bar", + "auto_bookmark", + "auto_subframe", + "manual_subframe", + "generated", + "auto_toplevel", + "form_submit", + "reload", + "keyword", + "keyword_generated", + "other", +] """Transition type.""" - class NavigationEntry(TypedDict): """Navigation history entry.""" @@ -264,7 +387,6 @@ class NavigationEntry(TypedDict): """Transition type.""" - class ScreencastFrameMetadata(TypedDict): """Screencast frame metadata.""" @@ -284,12 +406,10 @@ class ScreencastFrameMetadata(TypedDict): """Frame swap timestamp.""" - DialogType = Literal["alert", "confirm", "prompt", "beforeunload"] """Javascript dialog type.""" - class AppManifestError(TypedDict): """Error while paring app manifest.""" @@ -303,7 +423,6 @@ class AppManifestError(TypedDict): """Error column.""" - class AppManifestParsedProperties(TypedDict): """Parsed app manifest properties.""" @@ -311,7 +430,6 @@ class AppManifestParsedProperties(TypedDict): """Computed scope value""" - class LayoutViewport(TypedDict): """Layout viewport position and dimensions.""" @@ -325,7 +443,6 @@ class LayoutViewport(TypedDict): """Height (CSS pixels), excludes scrollbar if present.""" - class VisualViewport(TypedDict): """Visual viewport position, dimensions, and scale.""" @@ -347,7 +464,6 @@ class VisualViewport(TypedDict): """Page zoom factor (CSS to device independent pixels ratio).""" - class Viewport(TypedDict): """Viewport for capturing screenshot.""" @@ -363,7 +479,6 @@ class Viewport(TypedDict): """Page scale factor.""" - class FontFamilies(TypedDict, total=False): """Generic font families collection.""" @@ -383,7 +498,6 @@ class FontFamilies(TypedDict, total=False): """The math font-family.""" - class ScriptFontFamilies(TypedDict): """Font families collection for a script.""" @@ -393,7 +507,6 @@ class ScriptFontFamilies(TypedDict): """Generic font families collection for the script.""" - class FontSizes(TypedDict, total=False): """Default font sizes.""" @@ -403,15 +516,23 @@ class FontSizes(TypedDict, total=False): """Default fixed font size.""" - -ClientNavigationReason = Literal["anchorClick", "formSubmissionGet", "formSubmissionPost", "httpHeaderRefresh", "initialFrameNavigation", "metaTagRefresh", "other", "pageBlockInterstitial", "reload", "scriptInitiated"] - +ClientNavigationReason = Literal[ + "anchorClick", + "formSubmissionGet", + "formSubmissionPost", + "httpHeaderRefresh", + "initialFrameNavigation", + "metaTagRefresh", + "other", + "pageBlockInterstitial", + "reload", + "scriptInitiated", +] ClientNavigationDisposition = Literal["currentTab", "newTab", "newWindow", "download"] - class InstallabilityErrorArgument(TypedDict): name: "str" """Argument name (e.g. name:'minimum-icon-size-in-pixels').""" @@ -419,7 +540,6 @@ class InstallabilityErrorArgument(TypedDict): """Argument value (e.g. value:'64').""" - class InstallabilityError(TypedDict): """The installability error""" @@ -429,12 +549,19 @@ class InstallabilityError(TypedDict): """The list of error arguments (e.g. {name:'minimum-icon-size-in-pixels', value:'64'}).""" - -ReferrerPolicy = Literal["noReferrer", "noReferrerWhenDowngrade", "origin", "originWhenCrossOrigin", "sameOrigin", "strictOrigin", "strictOriginWhenCrossOrigin", "unsafeUrl"] +ReferrerPolicy = Literal[ + "noReferrer", + "noReferrerWhenDowngrade", + "origin", + "originWhenCrossOrigin", + "sameOrigin", + "strictOrigin", + "strictOriginWhenCrossOrigin", + "unsafeUrl", +] """The referring-policy used for the navigation.""" - class CompilationCacheParams(TypedDict): """Per-script compilation cache parameters for `Page.produceCompilationCache`""" @@ -445,13 +572,11 @@ class CompilationCacheParams(TypedDict): (the actual compilation mode used is upon backend discretion).""" - class FileFilter(TypedDict, total=False): name: "str" accepts: "List[str]" - class FileHandler(TypedDict): action: "str" name: "str" @@ -463,7 +588,6 @@ class FileHandler(TypedDict): other enums below.""" - class ImageResource(TypedDict): """The image definition used in both icon and screenshot.""" @@ -474,24 +598,20 @@ class ImageResource(TypedDict): type: "NotRequired[str]" - class LaunchHandler(TypedDict): clientMode: "str" - class ProtocolHandler(TypedDict): protocol: "str" url: "str" - class RelatedApplication(TypedDict): id: "NotRequired[str]" url: "str" - class ScopeExtension(TypedDict): origin: "str" """Instead of using tuple, this field always returns the serialized string @@ -499,14 +619,12 @@ class ScopeExtension(TypedDict): hasOriginWildcard: "bool" - class Screenshot(TypedDict): image: "ImageResource" formFactor: "str" label: "NotRequired[str]" - class ShareTarget(TypedDict): action: "str" method: "str" @@ -518,13 +636,11 @@ class ShareTarget(TypedDict): files: "NotRequired[List[FileFilter]]" - class Shortcut(TypedDict): name: "str" url: "str" - class WebAppManifest(TypedDict, total=False): backgroundColor: "str" description: "str" @@ -561,22 +677,166 @@ class WebAppManifest(TypedDict, total=False): themeColor: "str" - NavigationType = Literal["Navigation", "BackForwardCacheRestore"] """The type of a frameNavigated event.""" - -BackForwardCacheNotRestoredReason = Literal["NotPrimaryMainFrame", "BackForwardCacheDisabled", "RelatedActiveContentsExist", "HTTPStatusNotOK", "SchemeNotHTTPOrHTTPS", "Loading", "WasGrantedMediaAccess", "DisableForRenderFrameHostCalled", "DomainNotAllowed", "HTTPMethodNotGET", "SubframeIsNavigating", "Timeout", "CacheLimit", "JavaScriptExecution", "RendererProcessKilled", "RendererProcessCrashed", "SchedulerTrackedFeatureUsed", "ConflictingBrowsingInstance", "CacheFlushed", "ServiceWorkerVersionActivation", "SessionRestored", "ServiceWorkerPostMessage", "EnteredBackForwardCacheBeforeServiceWorkerHostAdded", "RenderFrameHostReused_SameSite", "RenderFrameHostReused_CrossSite", "ServiceWorkerClaim", "IgnoreEventAndEvict", "HaveInnerContents", "TimeoutPuttingInCache", "BackForwardCacheDisabledByLowMemory", "BackForwardCacheDisabledByCommandLine", "NetworkRequestDatapipeDrainedAsBytesConsumer", "NetworkRequestRedirected", "NetworkRequestTimeout", "NetworkExceedsBufferLimit", "NavigationCancelledWhileRestoring", "NotMostRecentNavigationEntry", "BackForwardCacheDisabledForPrerender", "UserAgentOverrideDiffers", "ForegroundCacheLimit", "BrowsingInstanceNotSwapped", "BackForwardCacheDisabledForDelegate", "UnloadHandlerExistsInMainFrame", "UnloadHandlerExistsInSubFrame", "ServiceWorkerUnregistration", "CacheControlNoStore", "CacheControlNoStoreCookieModified", "CacheControlNoStoreHTTPOnlyCookieModified", "NoResponseHead", "Unknown", "ActivationNavigationsDisallowedForBug1234857", "ErrorDocument", "FencedFramesEmbedder", "CookieDisabled", "HTTPAuthRequired", "CookieFlushed", "BroadcastChannelOnMessage", "WebViewSettingsChanged", "WebViewJavaScriptObjectChanged", "WebViewMessageListenerInjected", "WebViewSafeBrowsingAllowlistChanged", "WebViewDocumentStartJavascriptChanged", "WebSocket", "WebTransport", "WebRTC", "MainResourceHasCacheControlNoStore", "MainResourceHasCacheControlNoCache", "SubresourceHasCacheControlNoStore", "SubresourceHasCacheControlNoCache", "ContainsPlugins", "DocumentLoaded", "OutstandingNetworkRequestOthers", "RequestedMIDIPermission", "RequestedAudioCapturePermission", "RequestedVideoCapturePermission", "RequestedBackForwardCacheBlockedSensors", "RequestedBackgroundWorkPermission", "BroadcastChannel", "WebXR", "SharedWorker", "SharedWorkerMessage", "WebLocks", "WebHID", "WebShare", "RequestedStorageAccessGrant", "WebNfc", "OutstandingNetworkRequestFetch", "OutstandingNetworkRequestXHR", "AppBanner", "Printing", "WebDatabase", "PictureInPicture", "SpeechRecognizer", "IdleManager", "PaymentManager", "SpeechSynthesis", "KeyboardLock", "WebOTPService", "OutstandingNetworkRequestDirectSocket", "InjectedJavascript", "InjectedStyleSheet", "KeepaliveRequest", "IndexedDBEvent", "Dummy", "JsNetworkRequestReceivedCacheControlNoStoreResource", "WebRTCSticky", "WebTransportSticky", "WebSocketSticky", "SmartCard", "LiveMediaStreamTrack", "UnloadHandler", "ParserAborted", "ContentSecurityHandler", "ContentWebAuthenticationAPI", "ContentFileChooser", "ContentSerial", "ContentFileSystemAccess", "ContentMediaDevicesDispatcherHost", "ContentWebBluetooth", "ContentWebUSB", "ContentMediaSessionService", "ContentScreenReader", "ContentDiscarded", "EmbedderPopupBlockerTabHelper", "EmbedderSafeBrowsingTriggeredPopupBlocker", "EmbedderSafeBrowsingThreatDetails", "EmbedderAppBannerManager", "EmbedderDomDistillerViewerSource", "EmbedderDomDistillerSelfDeletingRequestDelegate", "EmbedderOomInterventionTabHelper", "EmbedderOfflinePage", "EmbedderChromePasswordManagerClientBindCredentialManager", "EmbedderPermissionRequestManager", "EmbedderModalDialog", "EmbedderExtensions", "EmbedderExtensionMessaging", "EmbedderExtensionMessagingForOpenPort", "EmbedderExtensionSentMessageToCachedFrame", "RequestedByWebViewClient", "PostMessageByWebViewClient", "CacheControlNoStoreDeviceBoundSessionTerminated", "CacheLimitPrunedOnModerateMemoryPressure", "CacheLimitPrunedOnCriticalMemoryPressure"] +BackForwardCacheNotRestoredReason = Literal[ + "NotPrimaryMainFrame", + "BackForwardCacheDisabled", + "RelatedActiveContentsExist", + "HTTPStatusNotOK", + "SchemeNotHTTPOrHTTPS", + "Loading", + "WasGrantedMediaAccess", + "DisableForRenderFrameHostCalled", + "DomainNotAllowed", + "HTTPMethodNotGET", + "SubframeIsNavigating", + "Timeout", + "CacheLimit", + "JavaScriptExecution", + "RendererProcessKilled", + "RendererProcessCrashed", + "SchedulerTrackedFeatureUsed", + "ConflictingBrowsingInstance", + "CacheFlushed", + "ServiceWorkerVersionActivation", + "SessionRestored", + "ServiceWorkerPostMessage", + "EnteredBackForwardCacheBeforeServiceWorkerHostAdded", + "RenderFrameHostReused_SameSite", + "RenderFrameHostReused_CrossSite", + "ServiceWorkerClaim", + "IgnoreEventAndEvict", + "HaveInnerContents", + "TimeoutPuttingInCache", + "BackForwardCacheDisabledByLowMemory", + "BackForwardCacheDisabledByCommandLine", + "NetworkRequestDatapipeDrainedAsBytesConsumer", + "NetworkRequestRedirected", + "NetworkRequestTimeout", + "NetworkExceedsBufferLimit", + "NavigationCancelledWhileRestoring", + "NotMostRecentNavigationEntry", + "BackForwardCacheDisabledForPrerender", + "UserAgentOverrideDiffers", + "ForegroundCacheLimit", + "BrowsingInstanceNotSwapped", + "BackForwardCacheDisabledForDelegate", + "UnloadHandlerExistsInMainFrame", + "UnloadHandlerExistsInSubFrame", + "ServiceWorkerUnregistration", + "CacheControlNoStore", + "CacheControlNoStoreCookieModified", + "CacheControlNoStoreHTTPOnlyCookieModified", + "NoResponseHead", + "Unknown", + "ActivationNavigationsDisallowedForBug1234857", + "ErrorDocument", + "FencedFramesEmbedder", + "CookieDisabled", + "HTTPAuthRequired", + "CookieFlushed", + "BroadcastChannelOnMessage", + "WebViewSettingsChanged", + "WebViewJavaScriptObjectChanged", + "WebViewMessageListenerInjected", + "WebViewSafeBrowsingAllowlistChanged", + "WebViewDocumentStartJavascriptChanged", + "WebSocket", + "WebTransport", + "WebRTC", + "MainResourceHasCacheControlNoStore", + "MainResourceHasCacheControlNoCache", + "SubresourceHasCacheControlNoStore", + "SubresourceHasCacheControlNoCache", + "ContainsPlugins", + "DocumentLoaded", + "OutstandingNetworkRequestOthers", + "RequestedMIDIPermission", + "RequestedAudioCapturePermission", + "RequestedVideoCapturePermission", + "RequestedBackForwardCacheBlockedSensors", + "RequestedBackgroundWorkPermission", + "BroadcastChannel", + "WebXR", + "SharedWorker", + "SharedWorkerMessage", + "SharedWorkerWithNoActiveClient", + "WebLocks", + "WebHID", + "WebBluetooth", + "WebShare", + "RequestedStorageAccessGrant", + "WebNfc", + "OutstandingNetworkRequestFetch", + "OutstandingNetworkRequestXHR", + "AppBanner", + "Printing", + "WebDatabase", + "PictureInPicture", + "SpeechRecognizer", + "IdleManager", + "PaymentManager", + "SpeechSynthesis", + "KeyboardLock", + "WebOTPService", + "OutstandingNetworkRequestDirectSocket", + "InjectedJavascript", + "InjectedStyleSheet", + "KeepaliveRequest", + "IndexedDBEvent", + "Dummy", + "JsNetworkRequestReceivedCacheControlNoStoreResource", + "WebRTCUsedWithCCNS", + "WebTransportUsedWithCCNS", + "WebSocketUsedWithCCNS", + "SmartCard", + "LiveMediaStreamTrack", + "UnloadHandler", + "ParserAborted", + "ContentSecurityHandler", + "ContentWebAuthenticationAPI", + "ContentFileChooser", + "ContentSerial", + "ContentFileSystemAccess", + "ContentMediaDevicesDispatcherHost", + "ContentWebBluetooth", + "ContentWebUSB", + "ContentMediaSessionService", + "ContentScreenReader", + "ContentDiscarded", + "EmbedderPopupBlockerTabHelper", + "EmbedderSafeBrowsingTriggeredPopupBlocker", + "EmbedderSafeBrowsingThreatDetails", + "EmbedderAppBannerManager", + "EmbedderDomDistillerViewerSource", + "EmbedderDomDistillerSelfDeletingRequestDelegate", + "EmbedderOomInterventionTabHelper", + "EmbedderOfflinePage", + "EmbedderChromePasswordManagerClientBindCredentialManager", + "EmbedderPermissionRequestManager", + "EmbedderModalDialog", + "EmbedderExtensions", + "EmbedderExtensionMessaging", + "EmbedderExtensionMessagingForOpenPort", + "EmbedderExtensionSentMessageToCachedFrame", + "RequestedByWebViewClient", + "PostMessageByWebViewClient", + "CacheControlNoStoreDeviceBoundSessionTerminated", + "CacheLimitPrunedOnModerateMemoryPressure", + "CacheLimitPrunedOnCriticalMemoryPressure", +] """List of not restored reasons for back-forward cache.""" - -BackForwardCacheNotRestoredReasonType = Literal["SupportPending", "PageSupportNeeded", "Circumstantial"] +BackForwardCacheNotRestoredReasonType = Literal[ + "SupportPending", "PageSupportNeeded", "Circumstantial" +] """Types of not restored reasons for back-forward cache.""" - class BackForwardCacheBlockingDetails(TypedDict): url: "NotRequired[str]" """Url of the file where blockage happened. Optional because of tests.""" @@ -588,7 +848,6 @@ class BackForwardCacheBlockingDetails(TypedDict): """Column number in the script (0-based).""" - class BackForwardCacheNotRestoredExplanation(TypedDict): type: "BackForwardCacheNotRestoredReasonType" """Type of the reason""" @@ -601,7 +860,6 @@ class BackForwardCacheNotRestoredExplanation(TypedDict): details: "NotRequired[List[BackForwardCacheBlockingDetails]]" - class BackForwardCacheNotRestoredExplanationTree(TypedDict): url: "str" """URL of each frame""" diff --git a/cdp_use/cdp/performance/commands.py b/cdp_use/cdp/performance/commands.py index 95784b9..fb1cacd 100644 --- a/cdp_use/cdp/performance/commands.py +++ b/cdp_use/cdp/performance/commands.py @@ -12,22 +12,17 @@ if TYPE_CHECKING: from .types import Metric + class EnableParameters(TypedDict, total=False): timeDomain: "str" """Time domain to use for collecting and reporting duration metrics.""" - - - class SetTimeDomainParameters(TypedDict): timeDomain: "str" """Time domain""" - - - class GetMetricsReturns(TypedDict): metrics: "List[Metric]" """Current values for run-time metrics.""" diff --git a/cdp_use/cdp/performance/events.py b/cdp_use/cdp/performance/events.py index 97043e1..e9e06e8 100644 --- a/cdp_use/cdp/performance/events.py +++ b/cdp_use/cdp/performance/events.py @@ -13,6 +13,8 @@ from .types import Metric """Current values of the metrics.""" + + class MetricsEvent(TypedDict): metrics: "List[Metric]" """Current values of the metrics.""" diff --git a/cdp_use/cdp/performance/library.py b/cdp_use/cdp/performance/library.py index d49b225..f325648 100644 --- a/cdp_use/cdp/performance/library.py +++ b/cdp_use/cdp/performance/library.py @@ -14,10 +14,11 @@ from .commands import GetMetricsReturns from .commands import SetTimeDomainParameters + class PerformanceClient: """Client for Performance domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -26,11 +27,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disable collecting and reporting metrics.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Performance.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Performance.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -38,11 +42,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable collecting and reporting metrics.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Performance.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Performance.enable", + params=params, + session_id=session_id, + ), + ) async def setTimeDomain( self, @@ -50,13 +57,16 @@ async def setTimeDomain( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets time domain to use for collecting and reporting duration metrics. -Note that this must be called before enabling metrics collection. Calling -this method while metrics collection is enabled returns an error.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Performance.setTimeDomain", - params=params, - session_id=session_id, - )) + Note that this must be called before enabling metrics collection. Calling + this method while metrics collection is enabled returns an error.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Performance.setTimeDomain", + params=params, + session_id=session_id, + ), + ) async def getMetrics( self, @@ -64,10 +74,11 @@ async def getMetrics( session_id: Optional[str] = None, ) -> "GetMetricsReturns": """Retrieve current values of run-time metrics.""" - return cast("GetMetricsReturns", await self._client.send_raw( - method="Performance.getMetrics", - params=params, - session_id=session_id, - )) - - + return cast( + "GetMetricsReturns", + await self._client.send_raw( + method="Performance.getMetrics", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/performance/registration.py b/cdp_use/cdp/performance/registration.py index b887f41..30c31a5 100644 --- a/cdp_use/cdp/performance/registration.py +++ b/cdp_use/cdp/performance/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import MetricsEvent + class PerformanceRegistration: """Event registration interface for Performance domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Performance" def metrics( self, - callback: Callable[['MetricsEvent', Optional[str]], None], + callback: Callable[["MetricsEvent", Optional[str]], None], ) -> None: """ Register a callback for metrics events. - + Current values of the metrics. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Performance.metrics", callback) - diff --git a/cdp_use/cdp/performance/types.py b/cdp_use/cdp/performance/types.py index 719ee76..d39380a 100644 --- a/cdp_use/cdp/performance/types.py +++ b/cdp_use/cdp/performance/types.py @@ -6,6 +6,7 @@ from typing_extensions import TypedDict + class Metric(TypedDict): """Run-time execution metric.""" diff --git a/cdp_use/cdp/performancetimeline/commands.py b/cdp_use/cdp/performancetimeline/commands.py index 8f683e5..f236ea4 100644 --- a/cdp_use/cdp/performancetimeline/commands.py +++ b/cdp_use/cdp/performancetimeline/commands.py @@ -7,6 +7,7 @@ from typing import List from typing_extensions import TypedDict + class EnableParameters(TypedDict): eventTypes: "List[str]" """The types of event to report, as specified in @@ -14,5 +15,3 @@ class EnableParameters(TypedDict): The specified filter overrides any previous filters, passing empty filter disables recording. Note that not all types exposed to the web platform are currently supported.""" - - diff --git a/cdp_use/cdp/performancetimeline/events.py b/cdp_use/cdp/performancetimeline/events.py index 2bb2ee8..4dee3d3 100644 --- a/cdp_use/cdp/performancetimeline/events.py +++ b/cdp_use/cdp/performancetimeline/events.py @@ -12,5 +12,7 @@ from .types import TimelineEvent """Sent when a performance timeline event is added. See reportPerformanceTimeline method.""" + + class TimelineEventAddedEvent(TypedDict): event: "TimelineEvent" diff --git a/cdp_use/cdp/performancetimeline/library.py b/cdp_use/cdp/performancetimeline/library.py index 09fd6b2..79bca9a 100644 --- a/cdp_use/cdp/performancetimeline/library.py +++ b/cdp_use/cdp/performancetimeline/library.py @@ -12,10 +12,11 @@ from ...client import CDPClient from .commands import EnableParameters + class PerformanceTimelineClient: """Client for PerformanceTimeline domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -24,11 +25,12 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Previously buffered events would be reported before method returns. -See also: timelineEventAdded""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="PerformanceTimeline.enable", - params=params, - session_id=session_id, - )) - - + See also: timelineEventAdded""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="PerformanceTimeline.enable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/performancetimeline/registration.py b/cdp_use/cdp/performancetimeline/registration.py index 04a642d..79b15e1 100644 --- a/cdp_use/cdp/performancetimeline/registration.py +++ b/cdp_use/cdp/performancetimeline/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import TimelineEventAddedEvent + class PerformanceTimelineRegistration: """Event registration interface for PerformanceTimeline domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "PerformanceTimeline" def timelineEventAdded( self, - callback: Callable[['TimelineEventAddedEvent', Optional[str]], None], + callback: Callable[["TimelineEventAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for timelineEventAdded events. - + Sent when a performance timeline event is added. See reportPerformanceTimeline method. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("PerformanceTimeline.timelineEventAdded", callback) - diff --git a/cdp_use/cdp/performancetimeline/types.py b/cdp_use/cdp/performancetimeline/types.py index 154b6c3..50f0bd4 100644 --- a/cdp_use/cdp/performancetimeline/types.py +++ b/cdp_use/cdp/performancetimeline/types.py @@ -15,6 +15,7 @@ from ..network.types import TimeSinceEpoch from ..page.types import FrameId + class LargestContentfulPaint(TypedDict): """See https://github.com/WICG/LargestContentfulPaint and largest_contentful_paint.idl""" @@ -29,14 +30,12 @@ class LargestContentfulPaint(TypedDict): nodeId: "NotRequired[BackendNodeId]" - class LayoutShiftAttribution(TypedDict): previousRect: "Rect" currentRect: "Rect" nodeId: "NotRequired[BackendNodeId]" - class LayoutShift(TypedDict): """See https://wicg.github.io/layout-instability/#sec-layout-shift and layout_shift.idl""" @@ -47,7 +46,6 @@ class LayoutShift(TypedDict): sources: "List[LayoutShiftAttribution]" - class TimelineEvent(TypedDict): frameId: "FrameId" """Identifies the frame that this event is related to. Empty for non-frame targets.""" diff --git a/cdp_use/cdp/preload/commands.py b/cdp_use/cdp/preload/commands.py index b4ef041..e4fc8c7 100644 --- a/cdp_use/cdp/preload/commands.py +++ b/cdp_use/cdp/preload/commands.py @@ -5,4 +5,4 @@ """CDP Preload Domain Commands""" -# No commands defined for this domain \ No newline at end of file +# No commands defined for this domain diff --git a/cdp_use/cdp/preload/events.py b/cdp_use/cdp/preload/events.py index cad0986..4940b08 100644 --- a/cdp_use/cdp/preload/events.py +++ b/cdp_use/cdp/preload/events.py @@ -24,17 +24,19 @@ from .types import RuleSetId """Upsert. Currently, it is only emitted when a rule set added.""" + + class RuleSetUpdatedEvent(TypedDict): ruleSet: "RuleSet" - class RuleSetRemovedEvent(TypedDict): id: "RuleSetId" - """Fired when a preload enabled state is updated.""" + + class PreloadEnabledStateUpdatedEvent(TypedDict): disabledByPreference: "bool" disabledByDataSaver: "bool" @@ -43,8 +45,9 @@ class PreloadEnabledStateUpdatedEvent(TypedDict): disabledByHoldbackPrerenderSpeculationRules: "bool" - """Fired when a prefetch attempt is updated.""" + + class PrefetchStatusUpdatedEvent(TypedDict): key: "PreloadingAttemptKey" pipelineId: "PreloadPipelineId" @@ -56,8 +59,9 @@ class PrefetchStatusUpdatedEvent(TypedDict): requestId: "RequestId" - """Fired when a prerender attempt is updated.""" + + class PrerenderStatusUpdatedEvent(TypedDict): key: "PreloadingAttemptKey" pipelineId: "PreloadPipelineId" @@ -69,8 +73,9 @@ class PrerenderStatusUpdatedEvent(TypedDict): mismatchedHeaders: "NotRequired[List[PrerenderMismatchedHeaders]]" - """Send a list of sources for all preloading attempts in a document.""" + + class PreloadingAttemptSourcesUpdatedEvent(TypedDict): loaderId: "LoaderId" preloadingAttemptSources: "List[PreloadingAttemptSource]" diff --git a/cdp_use/cdp/preload/library.py b/cdp_use/cdp/preload/library.py index fc55265..a3013f4 100644 --- a/cdp_use/cdp/preload/library.py +++ b/cdp_use/cdp/preload/library.py @@ -11,10 +11,11 @@ if TYPE_CHECKING: from ...client import CDPClient + class PreloadClient: """Client for Preload domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -22,21 +23,25 @@ async def enable( params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Preload.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Preload.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Preload.disable", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Preload.disable", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/preload/registration.py b/cdp_use/cdp/preload/registration.py index 9a2982e..b24d3a5 100644 --- a/cdp_use/cdp/preload/registration.py +++ b/cdp_use/cdp/preload/registration.py @@ -11,30 +11,31 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - PrefetchStatusUpdatedEvent, - PreloadEnabledStateUpdatedEvent, - PreloadingAttemptSourcesUpdatedEvent, - PrerenderStatusUpdatedEvent, - RuleSetRemovedEvent, - RuleSetUpdatedEvent -) + PrefetchStatusUpdatedEvent, + PreloadEnabledStateUpdatedEvent, + PreloadingAttemptSourcesUpdatedEvent, + PrerenderStatusUpdatedEvent, + RuleSetRemovedEvent, + RuleSetUpdatedEvent, + ) + class PreloadRegistration: """Event registration interface for Preload domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Preload" def ruleSetUpdated( self, - callback: Callable[['RuleSetUpdatedEvent', Optional[str]], None], + callback: Callable[["RuleSetUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for ruleSetUpdated events. - + Upsert. Currently, it is only emitted when a rule set added. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -43,11 +44,11 @@ def ruleSetUpdated( def ruleSetRemoved( self, - callback: Callable[['RuleSetRemovedEvent', Optional[str]], None], + callback: Callable[["RuleSetRemovedEvent", Optional[str]], None], ) -> None: """ Register a callback for ruleSetRemoved events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -56,13 +57,13 @@ def ruleSetRemoved( def preloadEnabledStateUpdated( self, - callback: Callable[['PreloadEnabledStateUpdatedEvent', Optional[str]], None], + callback: Callable[["PreloadEnabledStateUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for preloadEnabledStateUpdated events. - + Fired when a preload enabled state is updated. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -71,13 +72,13 @@ def preloadEnabledStateUpdated( def prefetchStatusUpdated( self, - callback: Callable[['PrefetchStatusUpdatedEvent', Optional[str]], None], + callback: Callable[["PrefetchStatusUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for prefetchStatusUpdated events. - + Fired when a prefetch attempt is updated. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -86,13 +87,13 @@ def prefetchStatusUpdated( def prerenderStatusUpdated( self, - callback: Callable[['PrerenderStatusUpdatedEvent', Optional[str]], None], + callback: Callable[["PrerenderStatusUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for prerenderStatusUpdated events. - + Fired when a prerender attempt is updated. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -101,16 +102,17 @@ def prerenderStatusUpdated( def preloadingAttemptSourcesUpdated( self, - callback: Callable[['PreloadingAttemptSourcesUpdatedEvent', Optional[str]], None], + callback: Callable[ + ["PreloadingAttemptSourcesUpdatedEvent", Optional[str]], None + ], ) -> None: """ Register a callback for preloadingAttemptSourcesUpdated events. - + Send a list of sources for all preloading attempts in a document. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Preload.preloadingAttemptSourcesUpdated", callback) - diff --git a/cdp_use/cdp/preload/types.py b/cdp_use/cdp/preload/types.py index fb250ce..bbd8ca3 100644 --- a/cdp_use/cdp/preload/types.py +++ b/cdp_use/cdp/preload/types.py @@ -19,7 +19,6 @@ """Unique id""" - class RuleSet(TypedDict): """Corresponds to SpeculationRuleSet""" @@ -52,33 +51,34 @@ class RuleSet(TypedDict): `errorMessage` is null iff `errorType` is null.""" errorMessage: "NotRequired[str]" """TODO(https://crbug.com/1425354): Replace this property with structured error.""" + tag: "NotRequired[str]" + """For more details, see: +https://github.com/WICG/nav-speculation/blob/main/speculation-rules-tags.md""" - -RuleSetErrorType = Literal["SourceIsNotJsonObject", "InvalidRulesSkipped", "InvalidRulesetLevelTag"] - +RuleSetErrorType = Literal[ + "SourceIsNotJsonObject", "InvalidRulesSkipped", "InvalidRulesetLevelTag" +] -SpeculationAction = Literal["Prefetch", "Prerender"] +SpeculationAction = Literal["Prefetch", "Prerender", "PrerenderUntilScript"] """The type of preloading attempted. It corresponds to mojom::SpeculationAction (although PrefetchWithSubresources is omitted as it isn't being used by clients).""" - SpeculationTargetHint = Literal["Blank", "Self"] """Corresponds to mojom::SpeculationTargetHint. See https://github.com/WICG/nav-speculation/blob/main/triggers.md#window-name-targeting-hints""" - class PreloadingAttemptKey(TypedDict): """A key that identifies a preloading attempt. -The url used is the url specified by the trigger (i.e. the initial URL), and -not the final url that is navigated to. For example, prerendering allows -same-origin main frame navigations during the attempt, but the attempt is -still keyed with the initial URL.""" + The url used is the url specified by the trigger (i.e. the initial URL), and + not the final url that is navigated to. For example, prerendering allows + same-origin main frame navigations during the attempt, but the attempt is + still keyed with the initial URL.""" loaderId: "LoaderId" action: "SpeculationAction" @@ -86,20 +86,18 @@ class PreloadingAttemptKey(TypedDict): targetHint: "NotRequired[SpeculationTargetHint]" - class PreloadingAttemptSource(TypedDict): """Lists sources for a preloading attempt, specifically the ids of rule sets -that had a speculation rule that triggered the attempt, and the -BackendNodeIds of or elements that triggered the -attempt (in the case of attempts triggered by a document rule). It is -possible for multiple rule sets and links to trigger a single attempt.""" + that had a speculation rule that triggered the attempt, and the + BackendNodeIds of or elements that triggered the + attempt (in the case of attempts triggered by a document rule). It is + possible for multiple rule sets and links to trigger a single attempt.""" key: "PreloadingAttemptKey" ruleSetIds: "List[RuleSetId]" nodeIds: "List[BackendNodeId]" - PreloadPipelineId = str """Chrome manages different types of preloads together using a concept of preloading pipeline. For example, if a site uses a @@ -110,24 +108,132 @@ class PreloadingAttemptSource(TypedDict): `PreloadPipelineId`.""" - -PrerenderFinalStatus = Literal["Activated", "Destroyed", "LowEndDevice", "InvalidSchemeRedirect", "InvalidSchemeNavigation", "NavigationRequestBlockedByCsp", "MojoBinderPolicy", "RendererProcessCrashed", "RendererProcessKilled", "Download", "TriggerDestroyed", "NavigationNotCommitted", "NavigationBadHttpStatus", "ClientCertRequested", "NavigationRequestNetworkError", "CancelAllHostsForTesting", "DidFailLoad", "Stop", "SslCertificateError", "LoginAuthRequested", "UaChangeRequiresReload", "BlockedByClient", "AudioOutputDeviceRequested", "MixedContent", "TriggerBackgrounded", "MemoryLimitExceeded", "DataSaverEnabled", "TriggerUrlHasEffectiveUrl", "ActivatedBeforeStarted", "InactivePageRestriction", "StartFailed", "TimeoutBackgrounded", "CrossSiteRedirectInInitialNavigation", "CrossSiteNavigationInInitialNavigation", "SameSiteCrossOriginRedirectNotOptInInInitialNavigation", "SameSiteCrossOriginNavigationNotOptInInInitialNavigation", "ActivationNavigationParameterMismatch", "ActivatedInBackground", "EmbedderHostDisallowed", "ActivationNavigationDestroyedBeforeSuccess", "TabClosedByUserGesture", "TabClosedWithoutUserGesture", "PrimaryMainFrameRendererProcessCrashed", "PrimaryMainFrameRendererProcessKilled", "ActivationFramePolicyNotCompatible", "PreloadingDisabled", "BatterySaverEnabled", "ActivatedDuringMainFrameNavigation", "PreloadingUnsupportedByWebContents", "CrossSiteRedirectInMainFrameNavigation", "CrossSiteNavigationInMainFrameNavigation", "SameSiteCrossOriginRedirectNotOptInInMainFrameNavigation", "SameSiteCrossOriginNavigationNotOptInInMainFrameNavigation", "MemoryPressureOnTrigger", "MemoryPressureAfterTriggered", "PrerenderingDisabledByDevTools", "SpeculationRuleRemoved", "ActivatedWithAuxiliaryBrowsingContexts", "MaxNumOfRunningEagerPrerendersExceeded", "MaxNumOfRunningNonEagerPrerendersExceeded", "MaxNumOfRunningEmbedderPrerendersExceeded", "PrerenderingUrlHasEffectiveUrl", "RedirectedPrerenderingUrlHasEffectiveUrl", "ActivationUrlHasEffectiveUrl", "JavaScriptInterfaceAdded", "JavaScriptInterfaceRemoved", "AllPrerenderingCanceled", "WindowClosed", "SlowNetwork", "OtherPrerenderedPageActivated", "V8OptimizerDisabled", "PrerenderFailedDuringPrefetch", "BrowsingDataRemoved", "PrerenderHostReused"] +PrerenderFinalStatus = Literal[ + "Activated", + "Destroyed", + "LowEndDevice", + "InvalidSchemeRedirect", + "InvalidSchemeNavigation", + "NavigationRequestBlockedByCsp", + "MojoBinderPolicy", + "RendererProcessCrashed", + "RendererProcessKilled", + "Download", + "TriggerDestroyed", + "NavigationNotCommitted", + "NavigationBadHttpStatus", + "ClientCertRequested", + "NavigationRequestNetworkError", + "CancelAllHostsForTesting", + "DidFailLoad", + "Stop", + "SslCertificateError", + "LoginAuthRequested", + "UaChangeRequiresReload", + "BlockedByClient", + "AudioOutputDeviceRequested", + "MixedContent", + "TriggerBackgrounded", + "MemoryLimitExceeded", + "DataSaverEnabled", + "TriggerUrlHasEffectiveUrl", + "ActivatedBeforeStarted", + "InactivePageRestriction", + "StartFailed", + "TimeoutBackgrounded", + "CrossSiteRedirectInInitialNavigation", + "CrossSiteNavigationInInitialNavigation", + "SameSiteCrossOriginRedirectNotOptInInInitialNavigation", + "SameSiteCrossOriginNavigationNotOptInInInitialNavigation", + "ActivationNavigationParameterMismatch", + "ActivatedInBackground", + "EmbedderHostDisallowed", + "ActivationNavigationDestroyedBeforeSuccess", + "TabClosedByUserGesture", + "TabClosedWithoutUserGesture", + "PrimaryMainFrameRendererProcessCrashed", + "PrimaryMainFrameRendererProcessKilled", + "ActivationFramePolicyNotCompatible", + "PreloadingDisabled", + "BatterySaverEnabled", + "ActivatedDuringMainFrameNavigation", + "PreloadingUnsupportedByWebContents", + "CrossSiteRedirectInMainFrameNavigation", + "CrossSiteNavigationInMainFrameNavigation", + "SameSiteCrossOriginRedirectNotOptInInMainFrameNavigation", + "SameSiteCrossOriginNavigationNotOptInInMainFrameNavigation", + "MemoryPressureOnTrigger", + "MemoryPressureAfterTriggered", + "PrerenderingDisabledByDevTools", + "SpeculationRuleRemoved", + "ActivatedWithAuxiliaryBrowsingContexts", + "MaxNumOfRunningEagerPrerendersExceeded", + "MaxNumOfRunningNonEagerPrerendersExceeded", + "MaxNumOfRunningEmbedderPrerendersExceeded", + "PrerenderingUrlHasEffectiveUrl", + "RedirectedPrerenderingUrlHasEffectiveUrl", + "ActivationUrlHasEffectiveUrl", + "JavaScriptInterfaceAdded", + "JavaScriptInterfaceRemoved", + "AllPrerenderingCanceled", + "WindowClosed", + "SlowNetwork", + "OtherPrerenderedPageActivated", + "V8OptimizerDisabled", + "PrerenderFailedDuringPrefetch", + "BrowsingDataRemoved", + "PrerenderHostReused", +] """List of FinalStatus reasons for Prerender2.""" - -PreloadingStatus = Literal["Pending", "Running", "Ready", "Success", "Failure", "NotSupported"] +PreloadingStatus = Literal[ + "Pending", "Running", "Ready", "Success", "Failure", "NotSupported" +] """Preloading status values, see also PreloadingTriggeringOutcome. This status is shared by prefetchStatusUpdated and prerenderStatusUpdated.""" - -PrefetchStatus = Literal["PrefetchAllowed", "PrefetchFailedIneligibleRedirect", "PrefetchFailedInvalidRedirect", "PrefetchFailedMIMENotSupported", "PrefetchFailedNetError", "PrefetchFailedNon2XX", "PrefetchEvictedAfterBrowsingDataRemoved", "PrefetchEvictedAfterCandidateRemoved", "PrefetchEvictedForNewerPrefetch", "PrefetchHeldback", "PrefetchIneligibleRetryAfter", "PrefetchIsPrivacyDecoy", "PrefetchIsStale", "PrefetchNotEligibleBrowserContextOffTheRecord", "PrefetchNotEligibleDataSaverEnabled", "PrefetchNotEligibleExistingProxy", "PrefetchNotEligibleHostIsNonUnique", "PrefetchNotEligibleNonDefaultStoragePartition", "PrefetchNotEligibleSameSiteCrossOriginPrefetchRequiredProxy", "PrefetchNotEligibleSchemeIsNotHttps", "PrefetchNotEligibleUserHasCookies", "PrefetchNotEligibleUserHasServiceWorker", "PrefetchNotEligibleUserHasServiceWorkerNoFetchHandler", "PrefetchNotEligibleRedirectFromServiceWorker", "PrefetchNotEligibleRedirectToServiceWorker", "PrefetchNotEligibleBatterySaverEnabled", "PrefetchNotEligiblePreloadingDisabled", "PrefetchNotFinishedInTime", "PrefetchNotStarted", "PrefetchNotUsedCookiesChanged", "PrefetchProxyNotAvailable", "PrefetchResponseUsed", "PrefetchSuccessfulButNotUsed", "PrefetchNotUsedProbeFailed"] +PrefetchStatus = Literal[ + "PrefetchAllowed", + "PrefetchFailedIneligibleRedirect", + "PrefetchFailedInvalidRedirect", + "PrefetchFailedMIMENotSupported", + "PrefetchFailedNetError", + "PrefetchFailedNon2XX", + "PrefetchEvictedAfterBrowsingDataRemoved", + "PrefetchEvictedAfterCandidateRemoved", + "PrefetchEvictedForNewerPrefetch", + "PrefetchHeldback", + "PrefetchIneligibleRetryAfter", + "PrefetchIsPrivacyDecoy", + "PrefetchIsStale", + "PrefetchNotEligibleBrowserContextOffTheRecord", + "PrefetchNotEligibleDataSaverEnabled", + "PrefetchNotEligibleExistingProxy", + "PrefetchNotEligibleHostIsNonUnique", + "PrefetchNotEligibleNonDefaultStoragePartition", + "PrefetchNotEligibleSameSiteCrossOriginPrefetchRequiredProxy", + "PrefetchNotEligibleSchemeIsNotHttps", + "PrefetchNotEligibleUserHasCookies", + "PrefetchNotEligibleUserHasServiceWorker", + "PrefetchNotEligibleUserHasServiceWorkerNoFetchHandler", + "PrefetchNotEligibleRedirectFromServiceWorker", + "PrefetchNotEligibleRedirectToServiceWorker", + "PrefetchNotEligibleBatterySaverEnabled", + "PrefetchNotEligiblePreloadingDisabled", + "PrefetchNotFinishedInTime", + "PrefetchNotStarted", + "PrefetchNotUsedCookiesChanged", + "PrefetchProxyNotAvailable", + "PrefetchResponseUsed", + "PrefetchSuccessfulButNotUsed", + "PrefetchNotUsedProbeFailed", +] """TODO(https://crbug.com/1384419): revisit the list of PrefetchStatus and filter out the ones that aren't necessary to the developers.""" - class PrerenderMismatchedHeaders(TypedDict): """Information of headers to be displayed when the header mismatch occurred.""" diff --git a/cdp_use/cdp/profiler/commands.py b/cdp_use/cdp/profiler/commands.py index 0ad6242..99f34da 100644 --- a/cdp_use/cdp/profiler/commands.py +++ b/cdp_use/cdp/profiler/commands.py @@ -13,20 +13,17 @@ from .types import Profile from .types import ScriptCoverage + class GetBestEffortCoverageReturns(TypedDict): result: "List[ScriptCoverage]" """Coverage data for the current isolate.""" - class SetSamplingIntervalParameters(TypedDict): interval: "int" """New sampling interval in microseconds.""" - - - class StartPreciseCoverageParameters(TypedDict, total=False): callCount: "bool" """Collect accurate call counts beyond simple 'covered' or 'not covered'.""" @@ -41,13 +38,11 @@ class StartPreciseCoverageReturns(TypedDict): """Monotonically increasing time (in seconds) when the coverage update was taken in the backend.""" - class StopReturns(TypedDict): profile: "Profile" """Recorded profile.""" - class TakePreciseCoverageReturns(TypedDict): result: "List[ScriptCoverage]" """Coverage data for the current isolate.""" diff --git a/cdp_use/cdp/profiler/events.py b/cdp_use/cdp/profiler/events.py index a9c2f68..f8a267d 100644 --- a/cdp_use/cdp/profiler/events.py +++ b/cdp_use/cdp/profiler/events.py @@ -14,6 +14,7 @@ from .types import Profile from .types import ScriptCoverage + class ConsoleProfileFinishedEvent(TypedDict): id: "str" location: "Location" @@ -23,8 +24,9 @@ class ConsoleProfileFinishedEvent(TypedDict): """Profile title passed as an argument to console.profile().""" - """Sent when new profile recording is started using console.profile() call.""" + + class ConsoleProfileStartedEvent(TypedDict): id: "str" location: "Location" @@ -33,11 +35,12 @@ class ConsoleProfileStartedEvent(TypedDict): """Profile title passed as an argument to console.profile().""" - """Reports coverage delta since the last poll (either from an event like this, or from `takePreciseCoverage` for the current isolate. May only be sent if precise code coverage has been started. This event can be trigged by the embedder to, for example, trigger collection of coverage data immediately at a certain point in time.""" + + class PreciseCoverageDeltaUpdateEvent(TypedDict): timestamp: "float" """Monotonically increasing time (in seconds) when the coverage update was taken in the backend.""" diff --git a/cdp_use/cdp/profiler/library.py b/cdp_use/cdp/profiler/library.py index e9b382d..364f986 100644 --- a/cdp_use/cdp/profiler/library.py +++ b/cdp_use/cdp/profiler/library.py @@ -17,10 +17,11 @@ from .commands import StopReturns from .commands import TakePreciseCoverageReturns + class ProfilerClient: """Client for Profiler domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -28,22 +29,28 @@ async def disable( params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Profiler.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Profiler.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Profiler.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Profiler.enable", + params=params, + session_id=session_id, + ), + ) async def getBestEffortCoverage( self, @@ -51,12 +58,15 @@ async def getBestEffortCoverage( session_id: Optional[str] = None, ) -> "GetBestEffortCoverageReturns": """Collect coverage data for the current isolate. The coverage data may be incomplete due to -garbage collection.""" - return cast("GetBestEffortCoverageReturns", await self._client.send_raw( - method="Profiler.getBestEffortCoverage", - params=params, - session_id=session_id, - )) + garbage collection.""" + return cast( + "GetBestEffortCoverageReturns", + await self._client.send_raw( + method="Profiler.getBestEffortCoverage", + params=params, + session_id=session_id, + ), + ) async def setSamplingInterval( self, @@ -64,22 +74,28 @@ async def setSamplingInterval( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Changes CPU profiler sampling interval. Must be called before CPU profiles recording started.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Profiler.setSamplingInterval", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Profiler.setSamplingInterval", + params=params, + session_id=session_id, + ), + ) async def start( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Profiler.start", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Profiler.start", + params=params, + session_id=session_id, + ), + ) async def startPreciseCoverage( self, @@ -87,24 +103,30 @@ async def startPreciseCoverage( session_id: Optional[str] = None, ) -> "StartPreciseCoverageReturns": """Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code -coverage may be incomplete. Enabling prevents running optimized code and resets execution -counters.""" - return cast("StartPreciseCoverageReturns", await self._client.send_raw( - method="Profiler.startPreciseCoverage", - params=params, - session_id=session_id, - )) + coverage may be incomplete. Enabling prevents running optimized code and resets execution + counters.""" + return cast( + "StartPreciseCoverageReturns", + await self._client.send_raw( + method="Profiler.startPreciseCoverage", + params=params, + session_id=session_id, + ), + ) async def stop( self, params: None = None, session_id: Optional[str] = None, ) -> "StopReturns": - return cast("StopReturns", await self._client.send_raw( - method="Profiler.stop", - params=params, - session_id=session_id, - )) + return cast( + "StopReturns", + await self._client.send_raw( + method="Profiler.stop", + params=params, + session_id=session_id, + ), + ) async def stopPreciseCoverage( self, @@ -112,12 +134,15 @@ async def stopPreciseCoverage( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disable precise code coverage. Disabling releases unnecessary execution count records and allows -executing optimized code.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Profiler.stopPreciseCoverage", - params=params, - session_id=session_id, - )) + executing optimized code.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Profiler.stopPreciseCoverage", + params=params, + session_id=session_id, + ), + ) async def takePreciseCoverage( self, @@ -125,11 +150,12 @@ async def takePreciseCoverage( session_id: Optional[str] = None, ) -> "TakePreciseCoverageReturns": """Collect coverage data for the current isolate, and resets execution counters. Precise code -coverage needs to have started.""" - return cast("TakePreciseCoverageReturns", await self._client.send_raw( - method="Profiler.takePreciseCoverage", - params=params, - session_id=session_id, - )) - - + coverage needs to have started.""" + return cast( + "TakePreciseCoverageReturns", + await self._client.send_raw( + method="Profiler.takePreciseCoverage", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/profiler/registration.py b/cdp_use/cdp/profiler/registration.py index 7a3cf39..0e59406 100644 --- a/cdp_use/cdp/profiler/registration.py +++ b/cdp_use/cdp/profiler/registration.py @@ -10,22 +10,27 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import ConsoleProfileFinishedEvent, ConsoleProfileStartedEvent, PreciseCoverageDeltaUpdateEvent + from .events import ( + ConsoleProfileFinishedEvent, + ConsoleProfileStartedEvent, + PreciseCoverageDeltaUpdateEvent, + ) + class ProfilerRegistration: """Event registration interface for Profiler domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Profiler" def consoleProfileFinished( self, - callback: Callable[['ConsoleProfileFinishedEvent', Optional[str]], None], + callback: Callable[["ConsoleProfileFinishedEvent", Optional[str]], None], ) -> None: """ Register a callback for consoleProfileFinished events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,13 +39,13 @@ def consoleProfileFinished( def consoleProfileStarted( self, - callback: Callable[['ConsoleProfileStartedEvent', Optional[str]], None], + callback: Callable[["ConsoleProfileStartedEvent", Optional[str]], None], ) -> None: """ Register a callback for consoleProfileStarted events. - + Sent when new profile recording is started using console.profile() call. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -49,19 +54,18 @@ def consoleProfileStarted( def preciseCoverageDeltaUpdate( self, - callback: Callable[['PreciseCoverageDeltaUpdateEvent', Optional[str]], None], + callback: Callable[["PreciseCoverageDeltaUpdateEvent", Optional[str]], None], ) -> None: """ - Register a callback for preciseCoverageDeltaUpdate events. - - Reports coverage delta since the last poll (either from an event like this, or from -`takePreciseCoverage` for the current isolate. May only be sent if precise code -coverage has been started. This event can be trigged by the embedder to, for example, -trigger collection of coverage data immediately at a certain point in time. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for preciseCoverageDeltaUpdate events. + + Reports coverage delta since the last poll (either from an event like this, or from + `takePreciseCoverage` for the current isolate. May only be sent if precise code + coverage has been started. This event can be trigged by the embedder to, for example, + trigger collection of coverage data immediately at a certain point in time. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Profiler.preciseCoverageDeltaUpdate", callback) - diff --git a/cdp_use/cdp/profiler/types.py b/cdp_use/cdp/profiler/types.py index 9567272..cc75729 100644 --- a/cdp_use/cdp/profiler/types.py +++ b/cdp_use/cdp/profiler/types.py @@ -13,6 +13,7 @@ from ..runtime.types import CallFrame from ..runtime.types import ScriptId + class ProfileNode(TypedDict): """Profile node. Holds callsite information, execution statistics and child nodes.""" @@ -31,7 +32,6 @@ class ProfileNode(TypedDict): """An array of source position ticks.""" - class Profile(TypedDict): """Profile.""" @@ -48,7 +48,6 @@ class Profile(TypedDict): profile startTime.""" - class PositionTickInfo(TypedDict): """Specifies a number of samples attributed to a certain source position.""" @@ -58,7 +57,6 @@ class PositionTickInfo(TypedDict): """Number of samples attributed to the source line.""" - class CoverageRange(TypedDict): """Coverage data for a source range.""" @@ -70,7 +68,6 @@ class CoverageRange(TypedDict): """Collected execution count of the source range.""" - class FunctionCoverage(TypedDict): """Coverage data for a JavaScript function.""" @@ -82,7 +79,6 @@ class FunctionCoverage(TypedDict): """Whether coverage data for this function has block granularity.""" - class ScriptCoverage(TypedDict): """Coverage data for a JavaScript script.""" diff --git a/cdp_use/cdp/pwa/commands.py b/cdp_use/cdp/pwa/commands.py index f255f0f..f30faba 100644 --- a/cdp_use/cdp/pwa/commands.py +++ b/cdp_use/cdp/pwa/commands.py @@ -14,6 +14,7 @@ from .types import DisplayMode from .types import FileHandler + class GetOsAppStateParameters(TypedDict): manifestId: "str" """The id from the webapp's manifest file, commonly it's the url of the @@ -26,7 +27,6 @@ class GetOsAppStateReturns(TypedDict): fileHandlers: "List[FileHandler]" - class InstallParameters(TypedDict): manifestId: "str" installUrlOrBundleUrl: "NotRequired[str]" @@ -34,16 +34,10 @@ class InstallParameters(TypedDict): manifestId.""" - - - class UninstallParameters(TypedDict): manifestId: "str" - - - class LaunchParameters(TypedDict): manifestId: "str" url: "NotRequired[str]" @@ -54,7 +48,6 @@ class LaunchReturns(TypedDict): """ID of the tab target created as a result.""" - class LaunchFilesInAppParameters(TypedDict): manifestId: "str" files: "List[str]" @@ -65,14 +58,10 @@ class LaunchFilesInAppReturns(TypedDict): """IDs of the tab targets created as the result.""" - class OpenCurrentPageInAppParameters(TypedDict): manifestId: "str" - - - class ChangeAppUserSettingsParameters(TypedDict): manifestId: "str" linkCapturing: "NotRequired[bool]" @@ -88,5 +77,3 @@ class ChangeAppUserSettingsParameters(TypedDict): TODO(crbug.com/339453269): Setting this value on ChromeOS is not supported yet.""" displayMode: "NotRequired[DisplayMode]" - - diff --git a/cdp_use/cdp/pwa/events.py b/cdp_use/cdp/pwa/events.py index 6fb7a26..fcf3377 100644 --- a/cdp_use/cdp/pwa/events.py +++ b/cdp_use/cdp/pwa/events.py @@ -5,4 +5,4 @@ """CDP PWA Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/pwa/library.py b/cdp_use/cdp/pwa/library.py index f6f3c69..ae6413e 100644 --- a/cdp_use/cdp/pwa/library.py +++ b/cdp_use/cdp/pwa/library.py @@ -21,10 +21,11 @@ from .commands import OpenCurrentPageInAppParameters from .commands import UninstallParameters + class PWAClient: """Client for PWA domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getOsAppState( @@ -33,11 +34,14 @@ async def getOsAppState( session_id: Optional[str] = None, ) -> "GetOsAppStateReturns": """Returns the following OS state for the given manifest id.""" - return cast("GetOsAppStateReturns", await self._client.send_raw( - method="PWA.getOsAppState", - params=params, - session_id=session_id, - )) + return cast( + "GetOsAppStateReturns", + await self._client.send_raw( + method="PWA.getOsAppState", + params=params, + session_id=session_id, + ), + ) async def install( self, @@ -46,34 +50,38 @@ async def install( ) -> "Dict[str, Any]": """Installs the given manifest identity, optionally using the given installUrlOrBundleUrl -IWA-specific install description: -manifestId corresponds to isolated-app:// + web_package::SignedWebBundleId - -File installation mode: -The installUrlOrBundleUrl can be either file:// or http(s):// pointing -to a signed web bundle (.swbn). In this case SignedWebBundleId must correspond to -The .swbn file's signing key. - -Dev proxy installation mode: -installUrlOrBundleUrl must be http(s):// that serves dev mode IWA. -web_package::SignedWebBundleId must be of type dev proxy. - -The advantage of dev proxy mode is that all changes to IWA -automatically will be reflected in the running app without -reinstallation. - -To generate bundle id for proxy mode: -1. Generate 32 random bytes. -2. Add a specific suffix 0x00 at the end. -3. Encode the entire sequence using Base32 without padding. - -If Chrome is not in IWA dev -mode, the installation will fail, regardless of the state of the allowlist.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="PWA.install", - params=params, - session_id=session_id, - )) + IWA-specific install description: + manifestId corresponds to isolated-app:// + web_package::SignedWebBundleId + + File installation mode: + The installUrlOrBundleUrl can be either file:// or http(s):// pointing + to a signed web bundle (.swbn). In this case SignedWebBundleId must correspond to + The .swbn file's signing key. + + Dev proxy installation mode: + installUrlOrBundleUrl must be http(s):// that serves dev mode IWA. + web_package::SignedWebBundleId must be of type dev proxy. + + The advantage of dev proxy mode is that all changes to IWA + automatically will be reflected in the running app without + reinstallation. + + To generate bundle id for proxy mode: + 1. Generate 32 random bytes. + 2. Add a specific suffix at the end following the documentation + https://github.com/WICG/isolated-web-apps/blob/main/Scheme.md#suffix + 3. Encode the entire sequence using Base32 without padding. + + If Chrome is not in IWA dev + mode, the installation will fail, regardless of the state of the allowlist.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="PWA.install", + params=params, + session_id=session_id, + ), + ) async def uninstall( self, @@ -81,11 +89,14 @@ async def uninstall( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Uninstalls the given manifest_id and closes any opened app windows.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="PWA.uninstall", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="PWA.uninstall", + params=params, + session_id=session_id, + ), + ) async def launch( self, @@ -93,13 +104,16 @@ async def launch( session_id: Optional[str] = None, ) -> "LaunchReturns": """Launches the installed web app, or an url in the same web app instead of the -default start url if it is provided. Returns a page Target.TargetID which -can be used to attach to via Target.attachToTarget or similar APIs.""" - return cast("LaunchReturns", await self._client.send_raw( - method="PWA.launch", - params=params, - session_id=session_id, - )) + default start url if it is provided. Returns a page Target.TargetID which + can be used to attach to via Target.attachToTarget or similar APIs.""" + return cast( + "LaunchReturns", + await self._client.send_raw( + method="PWA.launch", + params=params, + session_id=session_id, + ), + ) async def launchFilesInApp( self, @@ -107,23 +121,26 @@ async def launchFilesInApp( session_id: Optional[str] = None, ) -> "LaunchFilesInAppReturns": """Opens one or more local files from an installed web app identified by its -manifestId. The web app needs to have file handlers registered to process -the files. The API returns one or more page Target.TargetIDs which can be -used to attach to via Target.attachToTarget or similar APIs. -If some files in the parameters cannot be handled by the web app, they will -be ignored. If none of the files can be handled, this API returns an error. -If no files are provided as the parameter, this API also returns an error. - -According to the definition of the file handlers in the manifest file, one -Target.TargetID may represent a page handling one or more files. The order -of the returned Target.TargetIDs is not guaranteed. - -TODO(crbug.com/339454034): Check the existences of the input files.""" - return cast("LaunchFilesInAppReturns", await self._client.send_raw( - method="PWA.launchFilesInApp", - params=params, - session_id=session_id, - )) + manifestId. The web app needs to have file handlers registered to process + the files. The API returns one or more page Target.TargetIDs which can be + used to attach to via Target.attachToTarget or similar APIs. + If some files in the parameters cannot be handled by the web app, they will + be ignored. If none of the files can be handled, this API returns an error. + If no files are provided as the parameter, this API also returns an error. + + According to the definition of the file handlers in the manifest file, one + Target.TargetID may represent a page handling one or more files. The order + of the returned Target.TargetIDs is not guaranteed. + + TODO(crbug.com/339454034): Check the existences of the input files.""" + return cast( + "LaunchFilesInAppReturns", + await self._client.send_raw( + method="PWA.launchFilesInApp", + params=params, + session_id=session_id, + ), + ) async def openCurrentPageInApp( self, @@ -131,13 +148,16 @@ async def openCurrentPageInApp( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Opens the current page in its web app identified by the manifest id, needs -to be called on a page target. This function returns immediately without -waiting for the app to finish loading.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="PWA.openCurrentPageInApp", - params=params, - session_id=session_id, - )) + to be called on a page target. This function returns immediately without + waiting for the app to finish loading.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="PWA.openCurrentPageInApp", + params=params, + session_id=session_id, + ), + ) async def changeAppUserSettings( self, @@ -145,18 +165,19 @@ async def changeAppUserSettings( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Changes user settings of the web app identified by its manifestId. If the -app was not installed, this command returns an error. Unset parameters will -be ignored; unrecognized values will cause an error. - -Unlike the ones defined in the manifest files of the web apps, these -settings are provided by the browser and controlled by the users, they -impact the way the browser handling the web apps. - -See the comment of each parameter.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="PWA.changeAppUserSettings", - params=params, - session_id=session_id, - )) - - + app was not installed, this command returns an error. Unset parameters will + be ignored; unrecognized values will cause an error. + + Unlike the ones defined in the manifest files of the web apps, these + settings are provided by the browser and controlled by the users, they + impact the way the browser handling the web apps. + + See the comment of each parameter.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="PWA.changeAppUserSettings", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/pwa/registration.py b/cdp_use/cdp/pwa/registration.py index 5fd33a6..5c2087e 100644 --- a/cdp_use/cdp/pwa/registration.py +++ b/cdp_use/cdp/pwa/registration.py @@ -5,4 +5,4 @@ """CDP PWA Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/pwa/types.py b/cdp_use/cdp/pwa/types.py index 9a4a0b5..9feea10 100644 --- a/cdp_use/cdp/pwa/types.py +++ b/cdp_use/cdp/pwa/types.py @@ -8,9 +8,10 @@ from typing_extensions import Literal from typing_extensions import TypedDict + class FileHandlerAccept(TypedDict): """The following types are the replica of -https://crsrc.org/c/chrome/browser/web_applications/proto/web_app_os_integration_state.proto;drc=9910d3be894c8f142c977ba1023f30a656bc13fc;l=67""" + https://crsrc.org/c/chrome/browser/web_applications/proto/web_app_os_integration_state.proto;drc=9910d3be894c8f142c977ba1023f30a656bc13fc;l=67""" mediaType: "str" """New name of the mimetype according to @@ -18,13 +19,11 @@ class FileHandlerAccept(TypedDict): fileExtensions: "List[str]" - class FileHandler(TypedDict): action: "str" accepts: "List[FileHandlerAccept]" displayName: "str" - DisplayMode = Literal["standalone", "browser"] """If user prefers opening the app in browser or an app window.""" diff --git a/cdp_use/cdp/registration_library.py b/cdp_use/cdp/registration_library.py index 1cf62fb..48b41dd 100644 --- a/cdp_use/cdp/registration_library.py +++ b/cdp_use/cdp/registration_library.py @@ -9,169 +9,209 @@ if TYPE_CHECKING: from .registry import EventRegistry + class CDPRegistrationLibrary: """Main CDP registration library with domain-specific registration interfaces.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry # Console domain registration from .console.registration import ConsoleRegistration + self.Console = ConsoleRegistration(registry) # Debugger domain registration from .debugger.registration import DebuggerRegistration + self.Debugger = DebuggerRegistration(registry) # HeapProfiler domain registration from .heapprofiler.registration import HeapProfilerRegistration + self.HeapProfiler = HeapProfilerRegistration(registry) # Profiler domain registration from .profiler.registration import ProfilerRegistration + self.Profiler = ProfilerRegistration(registry) # Runtime domain registration from .runtime.registration import RuntimeRegistration + self.Runtime = RuntimeRegistration(registry) # Accessibility domain registration from .accessibility.registration import AccessibilityRegistration + self.Accessibility = AccessibilityRegistration(registry) # Animation domain registration from .animation.registration import AnimationRegistration + self.Animation = AnimationRegistration(registry) # Audits domain registration from .audits.registration import AuditsRegistration + self.Audits = AuditsRegistration(registry) # Autofill domain registration from .autofill.registration import AutofillRegistration + self.Autofill = AutofillRegistration(registry) # BackgroundService domain registration from .backgroundservice.registration import BackgroundServiceRegistration + self.BackgroundService = BackgroundServiceRegistration(registry) # BluetoothEmulation domain registration from .bluetoothemulation.registration import BluetoothEmulationRegistration + self.BluetoothEmulation = BluetoothEmulationRegistration(registry) # Browser domain registration from .browser.registration import BrowserRegistration + self.Browser = BrowserRegistration(registry) # CSS domain registration from .css.registration import CSSRegistration + self.CSS = CSSRegistration(registry) # Cast domain registration from .cast.registration import CastRegistration + self.Cast = CastRegistration(registry) # DOM domain registration from .dom.registration import DOMRegistration + self.DOM = DOMRegistration(registry) # DOMStorage domain registration from .domstorage.registration import DOMStorageRegistration + self.DOMStorage = DOMStorageRegistration(registry) # DeviceAccess domain registration from .deviceaccess.registration import DeviceAccessRegistration + self.DeviceAccess = DeviceAccessRegistration(registry) # Emulation domain registration from .emulation.registration import EmulationRegistration + self.Emulation = EmulationRegistration(registry) # FedCm domain registration from .fedcm.registration import FedCmRegistration + self.FedCm = FedCmRegistration(registry) # Fetch domain registration from .fetch.registration import FetchRegistration + self.Fetch = FetchRegistration(registry) # Input domain registration from .input.registration import InputRegistration + self.Input = InputRegistration(registry) # Inspector domain registration from .inspector.registration import InspectorRegistration + self.Inspector = InspectorRegistration(registry) # LayerTree domain registration from .layertree.registration import LayerTreeRegistration + self.LayerTree = LayerTreeRegistration(registry) # Log domain registration from .log.registration import LogRegistration + self.Log = LogRegistration(registry) # Media domain registration from .media.registration import MediaRegistration + self.Media = MediaRegistration(registry) # Network domain registration from .network.registration import NetworkRegistration + self.Network = NetworkRegistration(registry) # Overlay domain registration from .overlay.registration import OverlayRegistration + self.Overlay = OverlayRegistration(registry) # Page domain registration from .page.registration import PageRegistration + self.Page = PageRegistration(registry) # Performance domain registration from .performance.registration import PerformanceRegistration + self.Performance = PerformanceRegistration(registry) # PerformanceTimeline domain registration from .performancetimeline.registration import PerformanceTimelineRegistration + self.PerformanceTimeline = PerformanceTimelineRegistration(registry) # Preload domain registration from .preload.registration import PreloadRegistration + self.Preload = PreloadRegistration(registry) # Security domain registration from .security.registration import SecurityRegistration + self.Security = SecurityRegistration(registry) # ServiceWorker domain registration from .serviceworker.registration import ServiceWorkerRegistration + self.ServiceWorker = ServiceWorkerRegistration(registry) # Storage domain registration from .storage.registration import StorageRegistration + self.Storage = StorageRegistration(registry) # Target domain registration from .target.registration import TargetRegistration + self.Target = TargetRegistration(registry) # Tethering domain registration from .tethering.registration import TetheringRegistration + self.Tethering = TetheringRegistration(registry) # Tracing domain registration from .tracing.registration import TracingRegistration + self.Tracing = TracingRegistration(registry) # WebAudio domain registration from .webaudio.registration import WebAudioRegistration + self.WebAudio = WebAudioRegistration(registry) # WebAuthn domain registration from .webauthn.registration import WebAuthnRegistration + self.WebAuthn = WebAuthnRegistration(registry) # BrowserUse domain registration from .browseruse.registration import BrowserUseRegistration - self.BrowserUse = BrowserUseRegistration(registry) + self.BrowserUse = BrowserUseRegistration(registry) diff --git a/cdp_use/cdp/registry.py b/cdp_use/cdp/registry.py index baa7348..0ab550b 100644 --- a/cdp_use/cdp/registry.py +++ b/cdp_use/cdp/registry.py @@ -10,6 +10,7 @@ logger = logging.getLogger(__name__) + class EventRegistry: """Central registry for managing CDP event callbacks.""" @@ -23,7 +24,7 @@ def register( ) -> None: """ Register a callback for a specific CDP event method. - + Args: method: The CDP method name (e.g., "Page.frameAttached") callback: Function to call when event occurs. @@ -35,7 +36,7 @@ def register( def unregister(self, method: str) -> None: """ Unregister a callback for a specific CDP event method. - + Args: method: The CDP method name to unregister """ @@ -50,12 +51,12 @@ async def handle_event( ) -> bool: """ Handle an incoming CDP event. - + Args: method: The CDP method name params: The event parameters session_id: Optional session ID - + Returns: True if a handler was found and called, False otherwise """ diff --git a/cdp_use/cdp/runtime/commands.py b/cdp_use/cdp/runtime/commands.py index dbff0dc..99d3ebc 100644 --- a/cdp_use/cdp/runtime/commands.py +++ b/cdp_use/cdp/runtime/commands.py @@ -22,6 +22,7 @@ from .types import SerializationOptions from .types import TimeDelta + class AwaitPromiseParameters(TypedDict): promiseObjectId: "RemoteObjectId" """Identifier of the promise.""" @@ -38,7 +39,6 @@ class AwaitPromiseReturns(TypedDict): """Exception details if stack strace is available.""" - class CallFunctionOnParameters(TypedDict): functionDeclaration: "str" """Declaration of the function to call.""" @@ -88,7 +88,6 @@ class CallFunctionOnReturns(TypedDict): """Exception details.""" - class CompileScriptParameters(TypedDict): expression: "str" """Expression to compile.""" @@ -108,7 +107,6 @@ class CompileScriptReturns(TypedDict): """Exception details.""" - class EvaluateParameters(TypedDict): expression: "str" """Expression to evaluate.""" @@ -169,13 +167,11 @@ class EvaluateReturns(TypedDict): """Exception details.""" - class GetIsolateIdReturns(TypedDict): id: "str" """The isolate id.""" - class GetHeapUsageReturns(TypedDict): usedSize: "float" """Used JavaScript heap size in bytes.""" @@ -187,7 +183,6 @@ class GetHeapUsageReturns(TypedDict): """Size in bytes of backing storage for array buffers and external strings.""" - class GetPropertiesParameters(TypedDict): objectId: "RemoteObjectId" """Identifier of the object to return properties for.""" @@ -214,7 +209,6 @@ class GetPropertiesReturns(TypedDict): """Exception details.""" - class GlobalLexicalScopeNamesParameters(TypedDict, total=False): executionContextId: "ExecutionContextId" """Specifies in which execution context to lookup global scope variables.""" @@ -224,7 +218,6 @@ class GlobalLexicalScopeNamesReturns(TypedDict): names: "List[str]" - class QueryObjectsParameters(TypedDict): prototypeObjectId: "RemoteObjectId" """Identifier of the prototype to return objects for.""" @@ -237,23 +230,16 @@ class QueryObjectsReturns(TypedDict): """Array with objects.""" - class ReleaseObjectParameters(TypedDict): objectId: "RemoteObjectId" """Identifier of the object to release.""" - - - class ReleaseObjectGroupParameters(TypedDict): objectGroup: "str" """Symbolic object group name.""" - - - class RunScriptParameters(TypedDict): scriptId: "ScriptId" """Id of the script to run.""" @@ -283,30 +269,20 @@ class RunScriptReturns(TypedDict): """Exception details.""" - class SetAsyncCallStackDepthParameters(TypedDict): maxDepth: "int" """Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async call stacks (default).""" - - - class SetCustomObjectFormatterEnabledParameters(TypedDict): enabled: "bool" - - - class SetMaxCallStackSizeToCaptureParameters(TypedDict): size: "int" - - - class AddBindingParameters(TypedDict): name: "str" executionContextId: "NotRequired[ExecutionContextId]" @@ -325,16 +301,10 @@ class AddBindingParameters(TypedDict): This parameter is mutually exclusive with `executionContextId`.""" - - - class RemoveBindingParameters(TypedDict): name: "str" - - - class GetExceptionDetailsParameters(TypedDict): errorObjectId: "RemoteObjectId" """The error object for which to resolve the exception details.""" diff --git a/cdp_use/cdp/runtime/events.py b/cdp_use/cdp/runtime/events.py index d047fd7..3b93d7c 100644 --- a/cdp_use/cdp/runtime/events.py +++ b/cdp_use/cdp/runtime/events.py @@ -18,6 +18,8 @@ from .types import Timestamp """Notification is issued every time when binding is called.""" + + class BindingCalledEvent(TypedDict): name: "str" payload: "str" @@ -25,8 +27,9 @@ class BindingCalledEvent(TypedDict): """Identifier of the context where the call was made.""" - """Issued when console API was called.""" + + class ConsoleAPICalledEvent(TypedDict): type: "str" """Type of the call.""" @@ -46,8 +49,9 @@ class ConsoleAPICalledEvent(TypedDict): on named context.""" - """Issued when unhandled exception was revoked.""" + + class ExceptionRevokedEvent(TypedDict): reason: "str" """Reason describing why exception was revoked.""" @@ -55,23 +59,26 @@ class ExceptionRevokedEvent(TypedDict): """The id of revoked exception, as reported in `exceptionThrown`.""" - """Issued when exception was thrown and unhandled.""" + + class ExceptionThrownEvent(TypedDict): timestamp: "Timestamp" """Timestamp of the exception.""" exceptionDetails: "ExceptionDetails" - """Issued when new execution context is created.""" + + class ExecutionContextCreatedEvent(TypedDict): context: "ExecutionContextDescription" """A newly created execution context.""" - """Issued when execution context is destroyed.""" + + class ExecutionContextDestroyedEvent(TypedDict): executionContextId: "ExecutionContextId" """Id of the destroyed context""" @@ -79,15 +86,17 @@ class ExecutionContextDestroyedEvent(TypedDict): """Unique Id of the destroyed context""" - """Issued when all executionContexts were cleared in browser""" + + class ExecutionContextsClearedEvent(TypedDict): pass - """Issued when object should be inspected (for example, as a result of inspect() command line API call).""" + + class InspectRequestedEvent(TypedDict): object: "RemoteObject" hints: "Dict[str, Any]" diff --git a/cdp_use/cdp/runtime/library.py b/cdp_use/cdp/runtime/library.py index 3db0d10..6035506 100644 --- a/cdp_use/cdp/runtime/library.py +++ b/cdp_use/cdp/runtime/library.py @@ -38,10 +38,11 @@ from .commands import SetCustomObjectFormatterEnabledParameters from .commands import SetMaxCallStackSizeToCaptureParameters + class RuntimeClient: """Client for Runtime domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def awaitPromise( @@ -50,11 +51,14 @@ async def awaitPromise( session_id: Optional[str] = None, ) -> "AwaitPromiseReturns": """Add handler to promise with given promise object id.""" - return cast("AwaitPromiseReturns", await self._client.send_raw( - method="Runtime.awaitPromise", - params=params, - session_id=session_id, - )) + return cast( + "AwaitPromiseReturns", + await self._client.send_raw( + method="Runtime.awaitPromise", + params=params, + session_id=session_id, + ), + ) async def callFunctionOn( self, @@ -62,12 +66,15 @@ async def callFunctionOn( session_id: Optional[str] = None, ) -> "CallFunctionOnReturns": """Calls function with given declaration on the given object. Object group of the result is -inherited from the target object.""" - return cast("CallFunctionOnReturns", await self._client.send_raw( - method="Runtime.callFunctionOn", - params=params, - session_id=session_id, - )) + inherited from the target object.""" + return cast( + "CallFunctionOnReturns", + await self._client.send_raw( + method="Runtime.callFunctionOn", + params=params, + session_id=session_id, + ), + ) async def compileScript( self, @@ -75,11 +82,14 @@ async def compileScript( session_id: Optional[str] = None, ) -> "CompileScriptReturns": """Compiles expression.""" - return cast("CompileScriptReturns", await self._client.send_raw( - method="Runtime.compileScript", - params=params, - session_id=session_id, - )) + return cast( + "CompileScriptReturns", + await self._client.send_raw( + method="Runtime.compileScript", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -87,11 +97,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables reporting of execution contexts creation.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.disable", + params=params, + session_id=session_id, + ), + ) async def discardConsoleEntries( self, @@ -99,11 +112,14 @@ async def discardConsoleEntries( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Discards collected exceptions and console API calls.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.discardConsoleEntries", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.discardConsoleEntries", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -111,13 +127,16 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables reporting of execution contexts creation by means of `executionContextCreated` event. -When the reporting gets enabled the event will be sent immediately for each existing execution -context.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.enable", - params=params, - session_id=session_id, - )) + When the reporting gets enabled the event will be sent immediately for each existing execution + context.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.enable", + params=params, + session_id=session_id, + ), + ) async def evaluate( self, @@ -125,11 +144,14 @@ async def evaluate( session_id: Optional[str] = None, ) -> "EvaluateReturns": """Evaluates expression on global object.""" - return cast("EvaluateReturns", await self._client.send_raw( - method="Runtime.evaluate", - params=params, - session_id=session_id, - )) + return cast( + "EvaluateReturns", + await self._client.send_raw( + method="Runtime.evaluate", + params=params, + session_id=session_id, + ), + ) async def getIsolateId( self, @@ -137,11 +159,14 @@ async def getIsolateId( session_id: Optional[str] = None, ) -> "GetIsolateIdReturns": """Returns the isolate id.""" - return cast("GetIsolateIdReturns", await self._client.send_raw( - method="Runtime.getIsolateId", - params=params, - session_id=session_id, - )) + return cast( + "GetIsolateIdReturns", + await self._client.send_raw( + method="Runtime.getIsolateId", + params=params, + session_id=session_id, + ), + ) async def getHeapUsage( self, @@ -149,12 +174,15 @@ async def getHeapUsage( session_id: Optional[str] = None, ) -> "GetHeapUsageReturns": """Returns the JavaScript heap usage. -It is the total usage of the corresponding isolate not scoped to a particular Runtime.""" - return cast("GetHeapUsageReturns", await self._client.send_raw( - method="Runtime.getHeapUsage", - params=params, - session_id=session_id, - )) + It is the total usage of the corresponding isolate not scoped to a particular Runtime.""" + return cast( + "GetHeapUsageReturns", + await self._client.send_raw( + method="Runtime.getHeapUsage", + params=params, + session_id=session_id, + ), + ) async def getProperties( self, @@ -162,12 +190,15 @@ async def getProperties( session_id: Optional[str] = None, ) -> "GetPropertiesReturns": """Returns properties of a given object. Object group of the result is inherited from the target -object.""" - return cast("GetPropertiesReturns", await self._client.send_raw( - method="Runtime.getProperties", - params=params, - session_id=session_id, - )) + object.""" + return cast( + "GetPropertiesReturns", + await self._client.send_raw( + method="Runtime.getProperties", + params=params, + session_id=session_id, + ), + ) async def globalLexicalScopeNames( self, @@ -175,22 +206,28 @@ async def globalLexicalScopeNames( session_id: Optional[str] = None, ) -> "GlobalLexicalScopeNamesReturns": """Returns all let, const and class variables from global scope.""" - return cast("GlobalLexicalScopeNamesReturns", await self._client.send_raw( - method="Runtime.globalLexicalScopeNames", - params=params, - session_id=session_id, - )) + return cast( + "GlobalLexicalScopeNamesReturns", + await self._client.send_raw( + method="Runtime.globalLexicalScopeNames", + params=params, + session_id=session_id, + ), + ) async def queryObjects( self, params: "QueryObjectsParameters", session_id: Optional[str] = None, ) -> "QueryObjectsReturns": - return cast("QueryObjectsReturns", await self._client.send_raw( - method="Runtime.queryObjects", - params=params, - session_id=session_id, - )) + return cast( + "QueryObjectsReturns", + await self._client.send_raw( + method="Runtime.queryObjects", + params=params, + session_id=session_id, + ), + ) async def releaseObject( self, @@ -198,11 +235,14 @@ async def releaseObject( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Releases remote object with given id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.releaseObject", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.releaseObject", + params=params, + session_id=session_id, + ), + ) async def releaseObjectGroup( self, @@ -210,11 +250,14 @@ async def releaseObjectGroup( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Releases all remote objects that belong to a given group.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.releaseObjectGroup", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.releaseObjectGroup", + params=params, + session_id=session_id, + ), + ) async def runIfWaitingForDebugger( self, @@ -222,11 +265,14 @@ async def runIfWaitingForDebugger( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Tells inspected instance to run if it was waiting for debugger to attach.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.runIfWaitingForDebugger", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.runIfWaitingForDebugger", + params=params, + session_id=session_id, + ), + ) async def runScript( self, @@ -234,11 +280,14 @@ async def runScript( session_id: Optional[str] = None, ) -> "RunScriptReturns": """Runs script with given id in a given context.""" - return cast("RunScriptReturns", await self._client.send_raw( - method="Runtime.runScript", - params=params, - session_id=session_id, - )) + return cast( + "RunScriptReturns", + await self._client.send_raw( + method="Runtime.runScript", + params=params, + session_id=session_id, + ), + ) async def setAsyncCallStackDepth( self, @@ -246,33 +295,42 @@ async def setAsyncCallStackDepth( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables or disables async call stacks tracking.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.setAsyncCallStackDepth", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.setAsyncCallStackDepth", + params=params, + session_id=session_id, + ), + ) async def setCustomObjectFormatterEnabled( self, params: "SetCustomObjectFormatterEnabledParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.setCustomObjectFormatterEnabled", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.setCustomObjectFormatterEnabled", + params=params, + session_id=session_id, + ), + ) async def setMaxCallStackSizeToCapture( self, params: "SetMaxCallStackSizeToCaptureParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.setMaxCallStackSizeToCapture", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.setMaxCallStackSizeToCapture", + params=params, + session_id=session_id, + ), + ) async def terminateExecution( self, @@ -280,12 +338,15 @@ async def terminateExecution( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Terminate current or next JavaScript execution. -Will cancel the termination when the outer-most script execution ends.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.terminateExecution", - params=params, - session_id=session_id, - )) + Will cancel the termination when the outer-most script execution ends.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.terminateExecution", + params=params, + session_id=session_id, + ), + ) async def addBinding( self, @@ -293,16 +354,19 @@ async def addBinding( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """If executionContextId is empty, adds binding with the given name on the -global objects of all inspected contexts, including those created later, -bindings survive reloads. -Binding function takes exactly one argument, this argument should be string, -in case of any other input, function throws an exception. -Each binding function call produces Runtime.bindingCalled notification.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.addBinding", - params=params, - session_id=session_id, - )) + global objects of all inspected contexts, including those created later, + bindings survive reloads. + Binding function takes exactly one argument, this argument should be string, + in case of any other input, function throws an exception. + Each binding function call produces Runtime.bindingCalled notification.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.addBinding", + params=params, + session_id=session_id, + ), + ) async def removeBinding( self, @@ -310,12 +374,15 @@ async def removeBinding( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """This method does not remove binding function from global object but -unsubscribes current runtime agent from Runtime.bindingCalled notifications.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Runtime.removeBinding", - params=params, - session_id=session_id, - )) + unsubscribes current runtime agent from Runtime.bindingCalled notifications.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Runtime.removeBinding", + params=params, + session_id=session_id, + ), + ) async def getExceptionDetails( self, @@ -323,14 +390,15 @@ async def getExceptionDetails( session_id: Optional[str] = None, ) -> "GetExceptionDetailsReturns": """This method tries to lookup and populate exception details for a -JavaScript Error object. -Note that the stackTrace portion of the resulting exceptionDetails will -only be populated if the Runtime domain was enabled at the time when the -Error was thrown.""" - return cast("GetExceptionDetailsReturns", await self._client.send_raw( - method="Runtime.getExceptionDetails", - params=params, - session_id=session_id, - )) - - + JavaScript Error object. + Note that the stackTrace portion of the resulting exceptionDetails will + only be populated if the Runtime domain was enabled at the time when the + Error was thrown.""" + return cast( + "GetExceptionDetailsReturns", + await self._client.send_raw( + method="Runtime.getExceptionDetails", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/runtime/registration.py b/cdp_use/cdp/runtime/registration.py index 671a6a6..2c1b5fd 100644 --- a/cdp_use/cdp/runtime/registration.py +++ b/cdp_use/cdp/runtime/registration.py @@ -11,32 +11,33 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - BindingCalledEvent, - ConsoleAPICalledEvent, - ExceptionRevokedEvent, - ExceptionThrownEvent, - ExecutionContextCreatedEvent, - ExecutionContextDestroyedEvent, - ExecutionContextsClearedEvent, - InspectRequestedEvent -) + BindingCalledEvent, + ConsoleAPICalledEvent, + ExceptionRevokedEvent, + ExceptionThrownEvent, + ExecutionContextCreatedEvent, + ExecutionContextDestroyedEvent, + ExecutionContextsClearedEvent, + InspectRequestedEvent, + ) + class RuntimeRegistration: """Event registration interface for Runtime domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Runtime" def bindingCalled( self, - callback: Callable[['BindingCalledEvent', Optional[str]], None], + callback: Callable[["BindingCalledEvent", Optional[str]], None], ) -> None: """ Register a callback for bindingCalled events. - + Notification is issued every time when binding is called. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -45,13 +46,13 @@ def bindingCalled( def consoleAPICalled( self, - callback: Callable[['ConsoleAPICalledEvent', Optional[str]], None], + callback: Callable[["ConsoleAPICalledEvent", Optional[str]], None], ) -> None: """ Register a callback for consoleAPICalled events. - + Issued when console API was called. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -60,13 +61,13 @@ def consoleAPICalled( def exceptionRevoked( self, - callback: Callable[['ExceptionRevokedEvent', Optional[str]], None], + callback: Callable[["ExceptionRevokedEvent", Optional[str]], None], ) -> None: """ Register a callback for exceptionRevoked events. - + Issued when unhandled exception was revoked. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -75,13 +76,13 @@ def exceptionRevoked( def exceptionThrown( self, - callback: Callable[['ExceptionThrownEvent', Optional[str]], None], + callback: Callable[["ExceptionThrownEvent", Optional[str]], None], ) -> None: """ Register a callback for exceptionThrown events. - + Issued when exception was thrown and unhandled. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -90,13 +91,13 @@ def exceptionThrown( def executionContextCreated( self, - callback: Callable[['ExecutionContextCreatedEvent', Optional[str]], None], + callback: Callable[["ExecutionContextCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for executionContextCreated events. - + Issued when new execution context is created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -105,13 +106,13 @@ def executionContextCreated( def executionContextDestroyed( self, - callback: Callable[['ExecutionContextDestroyedEvent', Optional[str]], None], + callback: Callable[["ExecutionContextDestroyedEvent", Optional[str]], None], ) -> None: """ Register a callback for executionContextDestroyed events. - + Issued when execution context is destroyed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -120,13 +121,13 @@ def executionContextDestroyed( def executionContextsCleared( self, - callback: Callable[['ExecutionContextsClearedEvent', Optional[str]], None], + callback: Callable[["ExecutionContextsClearedEvent", Optional[str]], None], ) -> None: """ Register a callback for executionContextsCleared events. - + Issued when all executionContexts were cleared in browser - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -135,17 +136,16 @@ def executionContextsCleared( def inspectRequested( self, - callback: Callable[['InspectRequestedEvent', Optional[str]], None], + callback: Callable[["InspectRequestedEvent", Optional[str]], None], ) -> None: """ - Register a callback for inspectRequested events. - - Issued when object should be inspected (for example, as a result of inspect() command line API -call). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for inspectRequested events. + + Issued when object should be inspected (for example, as a result of inspect() command line API + call). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Runtime.inspectRequested", callback) - diff --git a/cdp_use/cdp/runtime/types.py b/cdp_use/cdp/runtime/types.py index eae4354..7fdb5da 100644 --- a/cdp_use/cdp/runtime/types.py +++ b/cdp_use/cdp/runtime/types.py @@ -11,7 +11,6 @@ """Unique script identifier.""" - class SerializationOptions(TypedDict): """Represents options for serialization. Overrides `generatePreview` and `returnByValue`.""" @@ -24,7 +23,6 @@ class SerializationOptions(TypedDict): Values can be only of type string or integer.""" - class DeepSerializedValue(TypedDict): """Represents deep serialized value.""" @@ -37,18 +35,15 @@ class DeepSerializedValue(TypedDict): per value in the scope of one CDP call.""" - RemoteObjectId = str """Unique object identifier.""" - UnserializableValue = str """Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.""" - class RemoteObject(TypedDict): """Mirror object referencing original JavaScript object.""" @@ -76,7 +71,6 @@ class RemoteObject(TypedDict): customPreview: "NotRequired[CustomPreview]" - class CustomPreview(TypedDict): header: "str" """The JSON-stringified result of formatter.header(object, config) call. @@ -87,7 +81,6 @@ class CustomPreview(TypedDict): The result value is json ML array.""" - class ObjectPreview(TypedDict): """Object containing abbreviated remote object value.""" @@ -105,7 +98,6 @@ class ObjectPreview(TypedDict): """List of the entries. Specified for `map` and `set` subtype values only.""" - class PropertyPreview(TypedDict): name: "str" """Property name.""" @@ -119,7 +111,6 @@ class PropertyPreview(TypedDict): """Object subtype hint. Specified for `object` type values only.""" - class EntryPreview(TypedDict): key: "NotRequired[ObjectPreview]" """Preview of the key. Specified for map-like collection entries.""" @@ -127,7 +118,6 @@ class EntryPreview(TypedDict): """Preview of the value.""" - class PropertyDescriptor(TypedDict): """Object property descriptor.""" @@ -157,7 +147,6 @@ class PropertyDescriptor(TypedDict): """Property symbol object, if the property is of the `symbol` type.""" - class InternalPropertyDescriptor(TypedDict): """Object internal property descriptor. This property isn't normally visible in JavaScript code.""" @@ -167,7 +156,6 @@ class InternalPropertyDescriptor(TypedDict): """The value associated with the property.""" - class PrivatePropertyDescriptor(TypedDict): """Object private field descriptor.""" @@ -183,10 +171,9 @@ class PrivatePropertyDescriptor(TypedDict): or `undefined` if there is no setter (accessor descriptors only).""" - class CallArgument(TypedDict, total=False): """Represents function call argument. Either remote object id `objectId`, primitive `value`, -unserializable primitive value or neither of (for undefined) them should be specified.""" + unserializable primitive value or neither of (for undefined) them should be specified.""" value: "Any" """Primitive value or serializable javascript object.""" @@ -196,12 +183,10 @@ class CallArgument(TypedDict, total=False): """Remote object handle.""" - ExecutionContextId = int """Id of an execution context.""" - class ExecutionContextDescription(TypedDict): """Description of an isolated world.""" @@ -220,10 +205,9 @@ class ExecutionContextDescription(TypedDict): """Embedder-specific auxiliary data likely matching {isDefault: boolean, type: 'default'|'isolated'|'worker', frameId: string}""" - class ExceptionDetails(TypedDict): """Detailed information about exception (or error) that was thrown during script compilation or -execution.""" + execution.""" exceptionId: "int" """Exception id.""" @@ -249,17 +233,14 @@ class ExceptionDetails(TypedDict): requests, etc.""" - Timestamp = float """Number of milliseconds since epoch.""" - TimeDelta = float """Number of milliseconds.""" - class CallFrame(TypedDict): """Stack entry for runtime errors and assertions.""" @@ -275,7 +256,6 @@ class CallFrame(TypedDict): """JavaScript script column number (0-based).""" - class StackTrace(TypedDict): """Call frames for assertions or error messages.""" @@ -290,15 +270,13 @@ class StackTrace(TypedDict): """Asynchronous JavaScript stack trace that preceded this stack, if available.""" - UniqueDebuggerId = str """Unique identifier of current debugger.""" - class StackTraceId(TypedDict): """If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This -allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages.""" + allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages.""" id: "str" debuggerId: "NotRequired[UniqueDebuggerId]" diff --git a/cdp_use/cdp/schema/commands.py b/cdp_use/cdp/schema/commands.py index 2bdf333..17fcfd0 100644 --- a/cdp_use/cdp/schema/commands.py +++ b/cdp_use/cdp/schema/commands.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: from .types import Domain + class GetDomainsReturns(TypedDict): domains: "List[Domain]" """List of supported domains.""" diff --git a/cdp_use/cdp/schema/events.py b/cdp_use/cdp/schema/events.py index fb83123..3ee1002 100644 --- a/cdp_use/cdp/schema/events.py +++ b/cdp_use/cdp/schema/events.py @@ -5,4 +5,4 @@ """CDP Schema Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/schema/library.py b/cdp_use/cdp/schema/library.py index 606596a..2f823a9 100644 --- a/cdp_use/cdp/schema/library.py +++ b/cdp_use/cdp/schema/library.py @@ -12,10 +12,11 @@ from ...client import CDPClient from .commands import GetDomainsReturns + class SchemaClient: """Client for Schema domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getDomains( @@ -24,10 +25,11 @@ async def getDomains( session_id: Optional[str] = None, ) -> "GetDomainsReturns": """Returns supported domains.""" - return cast("GetDomainsReturns", await self._client.send_raw( - method="Schema.getDomains", - params=params, - session_id=session_id, - )) - - + return cast( + "GetDomainsReturns", + await self._client.send_raw( + method="Schema.getDomains", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/schema/registration.py b/cdp_use/cdp/schema/registration.py index ebfae8e..87a7027 100644 --- a/cdp_use/cdp/schema/registration.py +++ b/cdp_use/cdp/schema/registration.py @@ -5,4 +5,4 @@ """CDP Schema Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/schema/types.py b/cdp_use/cdp/schema/types.py index 0d0afc2..9fae211 100644 --- a/cdp_use/cdp/schema/types.py +++ b/cdp_use/cdp/schema/types.py @@ -6,6 +6,7 @@ from typing_extensions import TypedDict + class Domain(TypedDict): """Description of the protocol domain.""" diff --git a/cdp_use/cdp/security/commands.py b/cdp_use/cdp/security/commands.py index 15a3af5..22229d6 100644 --- a/cdp_use/cdp/security/commands.py +++ b/cdp_use/cdp/security/commands.py @@ -11,14 +11,12 @@ if TYPE_CHECKING: from .types import CertificateErrorAction + class SetIgnoreCertificateErrorsParameters(TypedDict): ignore: "bool" """If true, all certificate errors will be ignored.""" - - - class HandleCertificateErrorParameters(TypedDict): eventId: "int" """The ID of the event.""" @@ -26,11 +24,6 @@ class HandleCertificateErrorParameters(TypedDict): """The action to take on the certificate error.""" - - - class SetOverrideCertificateErrorsParameters(TypedDict): override: "bool" """If true, certificate errors will be overridden.""" - - diff --git a/cdp_use/cdp/security/events.py b/cdp_use/cdp/security/events.py index 79813bc..48aab93 100644 --- a/cdp_use/cdp/security/events.py +++ b/cdp_use/cdp/security/events.py @@ -19,6 +19,8 @@ handled with the `handleCertificateError` command. Note: this event does not fire if the certificate error has been allowed internally. Only one client per target should override certificate errors at the same time.""" + + class CertificateErrorEvent(TypedDict): eventId: "int" """The ID of the event.""" @@ -28,15 +30,17 @@ class CertificateErrorEvent(TypedDict): """The url that was requested.""" - """The security state of the page changed.""" + + class VisibleSecurityStateChangedEvent(TypedDict): visibleSecurityState: "VisibleSecurityState" """Security state information about the page.""" - """The security state of the page changed. No longer being sent.""" + + class SecurityStateChangedEvent(TypedDict): securityState: "SecurityState" """Security state.""" diff --git a/cdp_use/cdp/security/library.py b/cdp_use/cdp/security/library.py index 3cc9da2..43c1deb 100644 --- a/cdp_use/cdp/security/library.py +++ b/cdp_use/cdp/security/library.py @@ -14,10 +14,11 @@ from .commands import SetIgnoreCertificateErrorsParameters from .commands import SetOverrideCertificateErrorsParameters + class SecurityClient: """Client for Security domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def disable( @@ -26,11 +27,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables tracking security state changes.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Security.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Security.disable", + params=params, + session_id=session_id, + ), + ) async def enable( self, @@ -38,11 +42,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables tracking security state changes.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Security.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Security.enable", + params=params, + session_id=session_id, + ), + ) async def setIgnoreCertificateErrors( self, @@ -50,11 +57,14 @@ async def setIgnoreCertificateErrors( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable/disable whether all certificate errors should be ignored.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Security.setIgnoreCertificateErrors", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Security.setIgnoreCertificateErrors", + params=params, + session_id=session_id, + ), + ) async def handleCertificateError( self, @@ -62,11 +72,14 @@ async def handleCertificateError( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Handles a certificate error that fired a certificateError event.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Security.handleCertificateError", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Security.handleCertificateError", + params=params, + session_id=session_id, + ), + ) async def setOverrideCertificateErrors( self, @@ -74,11 +87,12 @@ async def setOverrideCertificateErrors( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable/disable overriding certificate errors. If enabled, all certificate error events need to -be handled by the DevTools client and should be answered with `handleCertificateError` commands.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Security.setOverrideCertificateErrors", - params=params, - session_id=session_id, - )) - - + be handled by the DevTools client and should be answered with `handleCertificateError` commands.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Security.setOverrideCertificateErrors", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/security/registration.py b/cdp_use/cdp/security/registration.py index ace98a6..f0538b6 100644 --- a/cdp_use/cdp/security/registration.py +++ b/cdp_use/cdp/security/registration.py @@ -10,42 +10,47 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import CertificateErrorEvent, SecurityStateChangedEvent, VisibleSecurityStateChangedEvent + from .events import ( + CertificateErrorEvent, + SecurityStateChangedEvent, + VisibleSecurityStateChangedEvent, + ) + class SecurityRegistration: """Event registration interface for Security domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Security" def certificateError( self, - callback: Callable[['CertificateErrorEvent', Optional[str]], None], + callback: Callable[["CertificateErrorEvent", Optional[str]], None], ) -> None: """ - Register a callback for certificateError events. - - There is a certificate error. If overriding certificate errors is enabled, then it should be -handled with the `handleCertificateError` command. Note: this event does not fire if the -certificate error has been allowed internally. Only one client per target should override -certificate errors at the same time. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for certificateError events. + + There is a certificate error. If overriding certificate errors is enabled, then it should be + handled with the `handleCertificateError` command. Note: this event does not fire if the + certificate error has been allowed internally. Only one client per target should override + certificate errors at the same time. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Security.certificateError", callback) def visibleSecurityStateChanged( self, - callback: Callable[['VisibleSecurityStateChangedEvent', Optional[str]], None], + callback: Callable[["VisibleSecurityStateChangedEvent", Optional[str]], None], ) -> None: """ Register a callback for visibleSecurityStateChanged events. - + The security state of the page changed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -54,16 +59,15 @@ def visibleSecurityStateChanged( def securityStateChanged( self, - callback: Callable[['SecurityStateChangedEvent', Optional[str]], None], + callback: Callable[["SecurityStateChangedEvent", Optional[str]], None], ) -> None: """ Register a callback for securityStateChanged events. - + The security state of the page changed. No longer being sent. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Security.securityStateChanged", callback) - diff --git a/cdp_use/cdp/security/types.py b/cdp_use/cdp/security/types.py index 7059ef0..30f579a 100644 --- a/cdp_use/cdp/security/types.py +++ b/cdp_use/cdp/security/types.py @@ -17,18 +17,17 @@ """An internal certificate ID value.""" - MixedContentType = Literal["blockable", "optionally-blockable", "none"] """A description of mixed content (HTTP resources on HTTPS pages), as defined by https://www.w3.org/TR/mixed-content/#categories""" - -SecurityState = Literal["unknown", "neutral", "insecure", "secure", "info", "insecure-broken"] +SecurityState = Literal[ + "unknown", "neutral", "insecure", "secure", "info", "insecure-broken" +] """The security level of a page or resource.""" - class CertificateSecurityState(TypedDict): """Details about the security state of the page certificate.""" @@ -70,11 +69,9 @@ class CertificateSecurityState(TypedDict): """True if the connection is using an obsolete SSL signature.""" - SafetyTipStatus = Literal["badReputation", "lookalike"] - class SafetyTipInfo(TypedDict): safetyTipStatus: "SafetyTipStatus" """Describes whether the page triggers any safety tips or reputation warnings. Default is unknown.""" @@ -82,7 +79,6 @@ class SafetyTipInfo(TypedDict): """The URL the safety tip suggested (\"Did you mean?\"). Only filled in for lookalike matches.""" - class VisibleSecurityState(TypedDict): """Security state information about the page.""" @@ -96,7 +92,6 @@ class VisibleSecurityState(TypedDict): """Array of security state issues ids.""" - class SecurityStateExplanation(TypedDict): """An explanation of an factor contributing to the security state.""" @@ -116,7 +111,6 @@ class SecurityStateExplanation(TypedDict): """Recommendations to fix any issues.""" - class InsecureContentStatus(TypedDict): """Information about insecure content on the page.""" @@ -136,7 +130,6 @@ class InsecureContentStatus(TypedDict): """Always set to unknown.""" - CertificateErrorAction = Literal["continue", "cancel"] """The action to take when a certificate error occurs. continue will continue processing the request and cancel will cancel the request.""" diff --git a/cdp_use/cdp/serviceworker/commands.py b/cdp_use/cdp/serviceworker/commands.py index 8fb1bcd..796f235 100644 --- a/cdp_use/cdp/serviceworker/commands.py +++ b/cdp_use/cdp/serviceworker/commands.py @@ -11,15 +11,13 @@ if TYPE_CHECKING: from .types import RegistrationID + class DeliverPushMessageParameters(TypedDict): origin: "str" registrationId: "RegistrationID" data: "str" - - - class DispatchSyncEventParameters(TypedDict): origin: "str" registrationId: "RegistrationID" @@ -27,54 +25,31 @@ class DispatchSyncEventParameters(TypedDict): lastChance: "bool" - - - class DispatchPeriodicSyncEventParameters(TypedDict): origin: "str" registrationId: "RegistrationID" tag: "str" - - - class SetForceUpdateOnPageLoadParameters(TypedDict): forceUpdateOnPageLoad: "bool" - - - class SkipWaitingParameters(TypedDict): scopeURL: "str" - - - class StartWorkerParameters(TypedDict): scopeURL: "str" - - - class StopWorkerParameters(TypedDict): versionId: "str" - - - class UnregisterParameters(TypedDict): scopeURL: "str" - - - class UpdateRegistrationParameters(TypedDict): scopeURL: "str" - - diff --git a/cdp_use/cdp/serviceworker/events.py b/cdp_use/cdp/serviceworker/events.py index b6e2d2d..4358ddd 100644 --- a/cdp_use/cdp/serviceworker/events.py +++ b/cdp_use/cdp/serviceworker/events.py @@ -14,15 +14,14 @@ from .types import ServiceWorkerRegistration from .types import ServiceWorkerVersion + class WorkerErrorReportedEvent(TypedDict): errorMessage: "ServiceWorkerErrorMessage" - class WorkerRegistrationUpdatedEvent(TypedDict): registrations: "List[ServiceWorkerRegistration]" - class WorkerVersionUpdatedEvent(TypedDict): versions: "List[ServiceWorkerVersion]" diff --git a/cdp_use/cdp/serviceworker/library.py b/cdp_use/cdp/serviceworker/library.py index ed73ff9..177caba 100644 --- a/cdp_use/cdp/serviceworker/library.py +++ b/cdp_use/cdp/serviceworker/library.py @@ -20,10 +20,11 @@ from .commands import UnregisterParameters from .commands import UpdateRegistrationParameters + class ServiceWorkerClient: """Client for ServiceWorker domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def deliverPushMessage( @@ -31,131 +32,165 @@ async def deliverPushMessage( params: "DeliverPushMessageParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.deliverPushMessage", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.deliverPushMessage", + params=params, + session_id=session_id, + ), + ) async def disable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.disable", + params=params, + session_id=session_id, + ), + ) async def dispatchSyncEvent( self, params: "DispatchSyncEventParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.dispatchSyncEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.dispatchSyncEvent", + params=params, + session_id=session_id, + ), + ) async def dispatchPeriodicSyncEvent( self, params: "DispatchPeriodicSyncEventParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.dispatchPeriodicSyncEvent", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.dispatchPeriodicSyncEvent", + params=params, + session_id=session_id, + ), + ) async def enable( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.enable", + params=params, + session_id=session_id, + ), + ) async def setForceUpdateOnPageLoad( self, params: "SetForceUpdateOnPageLoadParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.setForceUpdateOnPageLoad", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.setForceUpdateOnPageLoad", + params=params, + session_id=session_id, + ), + ) async def skipWaiting( self, params: "SkipWaitingParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.skipWaiting", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.skipWaiting", + params=params, + session_id=session_id, + ), + ) async def startWorker( self, params: "StartWorkerParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.startWorker", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.startWorker", + params=params, + session_id=session_id, + ), + ) async def stopAllWorkers( self, params: None = None, session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.stopAllWorkers", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.stopAllWorkers", + params=params, + session_id=session_id, + ), + ) async def stopWorker( self, params: "StopWorkerParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.stopWorker", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.stopWorker", + params=params, + session_id=session_id, + ), + ) async def unregister( self, params: "UnregisterParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.unregister", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.unregister", + params=params, + session_id=session_id, + ), + ) async def updateRegistration( self, params: "UpdateRegistrationParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="ServiceWorker.updateRegistration", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="ServiceWorker.updateRegistration", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/serviceworker/registration.py b/cdp_use/cdp/serviceworker/registration.py index e8c0779..f375bce 100644 --- a/cdp_use/cdp/serviceworker/registration.py +++ b/cdp_use/cdp/serviceworker/registration.py @@ -10,22 +10,27 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import WorkerErrorReportedEvent, WorkerRegistrationUpdatedEvent, WorkerVersionUpdatedEvent + from .events import ( + WorkerErrorReportedEvent, + WorkerRegistrationUpdatedEvent, + WorkerVersionUpdatedEvent, + ) + class ServiceWorkerRegistration: """Event registration interface for ServiceWorker domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "ServiceWorker" def workerErrorReported( self, - callback: Callable[['WorkerErrorReportedEvent', Optional[str]], None], + callback: Callable[["WorkerErrorReportedEvent", Optional[str]], None], ) -> None: """ Register a callback for workerErrorReported events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,11 +39,11 @@ def workerErrorReported( def workerRegistrationUpdated( self, - callback: Callable[['WorkerRegistrationUpdatedEvent', Optional[str]], None], + callback: Callable[["WorkerRegistrationUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for workerRegistrationUpdated events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -47,14 +52,13 @@ def workerRegistrationUpdated( def workerVersionUpdated( self, - callback: Callable[['WorkerVersionUpdatedEvent', Optional[str]], None], + callback: Callable[["WorkerVersionUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for workerVersionUpdated events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("ServiceWorker.workerVersionUpdated", callback) - diff --git a/cdp_use/cdp/serviceworker/types.py b/cdp_use/cdp/serviceworker/types.py index e071356..b78513e 100644 --- a/cdp_use/cdp/serviceworker/types.py +++ b/cdp_use/cdp/serviceworker/types.py @@ -16,7 +16,6 @@ RegistrationID = str - class ServiceWorkerRegistration(TypedDict): """ServiceWorker registration.""" @@ -25,13 +24,14 @@ class ServiceWorkerRegistration(TypedDict): isDeleted: "bool" - -ServiceWorkerVersionRunningStatus = Literal["stopped", "starting", "running", "stopping"] - +ServiceWorkerVersionRunningStatus = Literal[ + "stopped", "starting", "running", "stopping" +] -ServiceWorkerVersionStatus = Literal["new", "installing", "installed", "activating", "activated", "redundant"] - +ServiceWorkerVersionStatus = Literal[ + "new", "installing", "installed", "activating", "activated", "redundant" +] class ServiceWorkerVersion(TypedDict): @@ -52,7 +52,6 @@ class ServiceWorkerVersion(TypedDict): routerRules: "NotRequired[str]" - class ServiceWorkerErrorMessage(TypedDict): """ServiceWorker error message.""" diff --git a/cdp_use/cdp/storage/commands.py b/cdp_use/cdp/storage/commands.py index eac6e1f..04124cd 100644 --- a/cdp_use/cdp/storage/commands.py +++ b/cdp_use/cdp/storage/commands.py @@ -22,6 +22,7 @@ from .types import TrustTokens from .types import UsageForType + class GetStorageKeyForFrameParameters(TypedDict): frameId: "FrameId" @@ -30,6 +31,13 @@ class GetStorageKeyForFrameReturns(TypedDict): storageKey: "SerializedStorageKey" +class GetStorageKeyParameters(TypedDict, total=False): + frameId: "FrameId" + + +class GetStorageKeyReturns(TypedDict): + storageKey: "SerializedStorageKey" + class ClearDataForOriginParameters(TypedDict): origin: "str" @@ -38,9 +46,6 @@ class ClearDataForOriginParameters(TypedDict): """Comma separated list of StorageType to clear.""" - - - class ClearDataForStorageKeyParameters(TypedDict): storageKey: "str" """Storage key.""" @@ -48,9 +53,6 @@ class ClearDataForStorageKeyParameters(TypedDict): """Comma separated list of StorageType to clear.""" - - - class GetCookiesParameters(TypedDict, total=False): browserContextId: "BrowserContextID" """Browser context to use when called on the browser endpoint.""" @@ -61,7 +63,6 @@ class GetCookiesReturns(TypedDict): """Array of cookie objects.""" - class SetCookiesParameters(TypedDict): cookies: "List[CookieParam]" """Cookies to be set.""" @@ -69,17 +70,11 @@ class SetCookiesParameters(TypedDict): """Browser context to use when called on the browser endpoint.""" - - - class ClearCookiesParameters(TypedDict, total=False): browserContextId: "BrowserContextID" """Browser context to use when called on the browser endpoint.""" - - - class GetUsageAndQuotaParameters(TypedDict): origin: "str" """Security origin.""" @@ -96,7 +91,6 @@ class GetUsageAndQuotaReturns(TypedDict): """Storage usage per type (bytes).""" - class OverrideQuotaForOriginParameters(TypedDict): origin: "str" """Security origin.""" @@ -110,78 +104,50 @@ class OverrideQuotaForOriginParameters(TypedDict): disabled (called without a quotaSize).""" - - - class TrackCacheStorageForOriginParameters(TypedDict): origin: "str" """Security origin.""" - - - class TrackCacheStorageForStorageKeyParameters(TypedDict): storageKey: "str" """Storage key.""" - - - class TrackIndexedDBForOriginParameters(TypedDict): origin: "str" """Security origin.""" - - - class TrackIndexedDBForStorageKeyParameters(TypedDict): storageKey: "str" """Storage key.""" - - - class UntrackCacheStorageForOriginParameters(TypedDict): origin: "str" """Security origin.""" - - - class UntrackCacheStorageForStorageKeyParameters(TypedDict): storageKey: "str" """Storage key.""" - - - class UntrackIndexedDBForOriginParameters(TypedDict): origin: "str" """Security origin.""" - - - class UntrackIndexedDBForStorageKeyParameters(TypedDict): storageKey: "str" """Storage key.""" - - - class GetTrustTokensReturns(TypedDict): tokens: "List[TrustTokens]" - class ClearTrustTokensParameters(TypedDict): issuerOrigin: "str" @@ -191,7 +157,6 @@ class ClearTrustTokensReturns(TypedDict): """True if any tokens were deleted, false otherwise.""" - class GetInterestGroupDetailsParameters(TypedDict): ownerOrigin: "str" name: "str" @@ -205,21 +170,14 @@ class GetInterestGroupDetailsReturns(TypedDict): also adds joiningOrigin.""" - class SetInterestGroupTrackingParameters(TypedDict): enable: "bool" - - - class SetInterestGroupAuctionTrackingParameters(TypedDict): enable: "bool" - - - class GetSharedStorageMetadataParameters(TypedDict): ownerOrigin: "str" @@ -228,7 +186,6 @@ class GetSharedStorageMetadataReturns(TypedDict): metadata: "SharedStorageMetadata" - class GetSharedStorageEntriesParameters(TypedDict): ownerOrigin: "str" @@ -237,7 +194,6 @@ class GetSharedStorageEntriesReturns(TypedDict): entries: "List[SharedStorageEntry]" - class SetSharedStorageEntryParameters(TypedDict): ownerOrigin: "str" key: "str" @@ -247,84 +203,54 @@ class SetSharedStorageEntryParameters(TypedDict): `key` doesn't already exist.""" - - - class DeleteSharedStorageEntryParameters(TypedDict): ownerOrigin: "str" key: "str" - - - class ClearSharedStorageEntriesParameters(TypedDict): ownerOrigin: "str" - - - class ResetSharedStorageBudgetParameters(TypedDict): ownerOrigin: "str" - - - class SetSharedStorageTrackingParameters(TypedDict): enable: "bool" - - - class SetStorageBucketTrackingParameters(TypedDict): storageKey: "str" enable: "bool" - - - class DeleteStorageBucketParameters(TypedDict): bucket: "StorageBucket" - - - class RunBounceTrackingMitigationsReturns(TypedDict): deletedSites: "List[str]" - class SetAttributionReportingLocalTestingModeParameters(TypedDict): enabled: "bool" """If enabled, noise is suppressed and reports are sent immediately.""" - - - class SetAttributionReportingTrackingParameters(TypedDict): enable: "bool" - - - class SendPendingAttributionReportsReturns(TypedDict): numSent: "int" """The number of reports that were sent.""" - class GetRelatedWebsiteSetsReturns(TypedDict): sets: "List[RelatedWebsiteSet]" - class GetAffectedUrlsForThirdPartyCookieMetadataParameters(TypedDict): firstPartyUrl: "str" """The URL of the page currently being visited.""" @@ -338,10 +264,7 @@ class GetAffectedUrlsForThirdPartyCookieMetadataReturns(TypedDict): party URL, only the first-party URL is returned in the array.""" - class SetProtectedAudienceKAnonymityParameters(TypedDict): owner: "str" name: "str" hashes: "List[str]" - - diff --git a/cdp_use/cdp/storage/events.py b/cdp_use/cdp/storage/events.py index 52814d7..7c3b4a0 100644 --- a/cdp_use/cdp/storage/events.py +++ b/cdp_use/cdp/storage/events.py @@ -30,6 +30,8 @@ from .types import StorageBucketInfo """A cache's contents have been modified.""" + + class CacheStorageContentUpdatedEvent(TypedDict): origin: "str" """Origin to update.""" @@ -41,8 +43,9 @@ class CacheStorageContentUpdatedEvent(TypedDict): """Name of cache in origin.""" - """A cache has been added/deleted.""" + + class CacheStorageListUpdatedEvent(TypedDict): origin: "str" """Origin to update.""" @@ -52,8 +55,9 @@ class CacheStorageListUpdatedEvent(TypedDict): """Storage bucket to update.""" - """The origin's IndexedDB object store has been modified.""" + + class IndexedDBContentUpdatedEvent(TypedDict): origin: "str" """Origin to update.""" @@ -67,8 +71,9 @@ class IndexedDBContentUpdatedEvent(TypedDict): """ObjectStore to update.""" - """The origin's IndexedDB database list has been modified.""" + + class IndexedDBListUpdatedEvent(TypedDict): origin: "str" """Origin to update.""" @@ -78,9 +83,10 @@ class IndexedDBListUpdatedEvent(TypedDict): """Storage bucket to update.""" - """One of the interest groups was accessed. Note that these events are global to all targets sharing an interest group store.""" + + class InterestGroupAccessedEvent(TypedDict): accessTime: "TimeSinceEpoch" type: "InterestGroupAccessType" @@ -96,9 +102,10 @@ class InterestGroupAccessedEvent(TypedDict): """For non-global events --- links to interestGroupAuctionEvent""" - """An auction involving interest groups is taking place. These events are target-specific.""" + + class InterestGroupAuctionEventOccurredEvent(TypedDict): eventTime: "TimeSinceEpoch" type: "InterestGroupAuctionEventType" @@ -109,11 +116,12 @@ class InterestGroupAuctionEventOccurredEvent(TypedDict): """Set for started and configResolved""" - """Specifies which auctions a particular network fetch may be related to, and in what role. Note that it is not ordered with respect to Network.requestWillBeSent (but will happen before loadingFinished loadingFailed).""" + + class InterestGroupAuctionNetworkRequestCreatedEvent(TypedDict): type: "InterestGroupAuctionFetchType" requestId: "RequestId" @@ -123,9 +131,10 @@ class InterestGroupAuctionNetworkRequestCreatedEvent(TypedDict): them actually care about the keys being queried.""" - """Shared storage was accessed by the associated page. The following parameters are included in all events.""" + + class SharedStorageAccessedEvent(TypedDict): accessTime: "TimeSinceEpoch" """Time of the access.""" @@ -144,9 +153,10 @@ class SharedStorageAccessedEvent(TypedDict): presence/absence depends on `type`.""" - """A shared storage run or selectURL operation finished its execution. The following parameters are included in all events.""" + + class SharedStorageWorkletOperationExecutionFinishedEvent(TypedDict): finishedTime: "TimeSinceEpoch" """Time that the operation finished.""" @@ -166,30 +176,25 @@ class SharedStorageWorkletOperationExecutionFinishedEvent(TypedDict): """Serialization of the origin owning the Shared Storage data.""" - class StorageBucketCreatedOrUpdatedEvent(TypedDict): bucketInfo: "StorageBucketInfo" - class StorageBucketDeletedEvent(TypedDict): bucketId: "str" - class AttributionReportingSourceRegisteredEvent(TypedDict): registration: "AttributionReportingSourceRegistration" result: "AttributionReportingSourceRegistrationResult" - class AttributionReportingTriggerRegisteredEvent(TypedDict): registration: "AttributionReportingTriggerRegistration" eventLevel: "AttributionReportingEventLevelResult" aggregatable: "AttributionReportingAggregatableResult" - class AttributionReportingReportSentEvent(TypedDict): url: "str" body: "Dict[str, Any]" @@ -200,7 +205,6 @@ class AttributionReportingReportSentEvent(TypedDict): httpStatusCode: "NotRequired[int]" - class AttributionReportingVerboseDebugReportSentEvent(TypedDict): url: "str" body: "NotRequired[List[Dict[str, Any]]]" diff --git a/cdp_use/cdp/storage/library.py b/cdp_use/cdp/storage/library.py index 168dd79..82a7f2c 100644 --- a/cdp_use/cdp/storage/library.py +++ b/cdp_use/cdp/storage/library.py @@ -31,6 +31,8 @@ from .commands import GetSharedStorageMetadataReturns from .commands import GetStorageKeyForFrameParameters from .commands import GetStorageKeyForFrameReturns + from .commands import GetStorageKeyParameters + from .commands import GetStorageKeyReturns from .commands import GetTrustTokensReturns from .commands import GetUsageAndQuotaParameters from .commands import GetUsageAndQuotaReturns @@ -56,10 +58,11 @@ from .commands import UntrackIndexedDBForOriginParameters from .commands import UntrackIndexedDBForStorageKeyParameters + class StorageClient: """Client for Storage domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getStorageKeyForFrame( @@ -67,12 +70,32 @@ async def getStorageKeyForFrame( params: "GetStorageKeyForFrameParameters", session_id: Optional[str] = None, ) -> "GetStorageKeyForFrameReturns": - """Returns a storage key given a frame id.""" - return cast("GetStorageKeyForFrameReturns", await self._client.send_raw( - method="Storage.getStorageKeyForFrame", - params=params, - session_id=session_id, - )) + """Returns a storage key given a frame id. + Deprecated. Please use Storage.getStorageKey instead.""" + return cast( + "GetStorageKeyForFrameReturns", + await self._client.send_raw( + method="Storage.getStorageKeyForFrame", + params=params, + session_id=session_id, + ), + ) + + async def getStorageKey( + self, + params: Optional["GetStorageKeyParameters"] = None, + session_id: Optional[str] = None, + ) -> "GetStorageKeyReturns": + """Returns storage key for the given frame. If no frame ID is provided, + the storage key of the target executing this command is returned.""" + return cast( + "GetStorageKeyReturns", + await self._client.send_raw( + method="Storage.getStorageKey", + params=params, + session_id=session_id, + ), + ) async def clearDataForOrigin( self, @@ -80,11 +103,14 @@ async def clearDataForOrigin( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears storage for origin.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.clearDataForOrigin", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.clearDataForOrigin", + params=params, + session_id=session_id, + ), + ) async def clearDataForStorageKey( self, @@ -92,11 +118,14 @@ async def clearDataForStorageKey( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears storage for storage key.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.clearDataForStorageKey", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.clearDataForStorageKey", + params=params, + session_id=session_id, + ), + ) async def getCookies( self, @@ -104,11 +133,14 @@ async def getCookies( session_id: Optional[str] = None, ) -> "GetCookiesReturns": """Returns all browser cookies.""" - return cast("GetCookiesReturns", await self._client.send_raw( - method="Storage.getCookies", - params=params, - session_id=session_id, - )) + return cast( + "GetCookiesReturns", + await self._client.send_raw( + method="Storage.getCookies", + params=params, + session_id=session_id, + ), + ) async def setCookies( self, @@ -116,11 +148,14 @@ async def setCookies( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets given cookies.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setCookies", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setCookies", + params=params, + session_id=session_id, + ), + ) async def clearCookies( self, @@ -128,11 +163,14 @@ async def clearCookies( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears cookies.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.clearCookies", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.clearCookies", + params=params, + session_id=session_id, + ), + ) async def getUsageAndQuota( self, @@ -140,11 +178,14 @@ async def getUsageAndQuota( session_id: Optional[str] = None, ) -> "GetUsageAndQuotaReturns": """Returns usage and quota in bytes.""" - return cast("GetUsageAndQuotaReturns", await self._client.send_raw( - method="Storage.getUsageAndQuota", - params=params, - session_id=session_id, - )) + return cast( + "GetUsageAndQuotaReturns", + await self._client.send_raw( + method="Storage.getUsageAndQuota", + params=params, + session_id=session_id, + ), + ) async def overrideQuotaForOrigin( self, @@ -152,11 +193,14 @@ async def overrideQuotaForOrigin( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Override quota for the specified origin""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.overrideQuotaForOrigin", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.overrideQuotaForOrigin", + params=params, + session_id=session_id, + ), + ) async def trackCacheStorageForOrigin( self, @@ -164,11 +208,14 @@ async def trackCacheStorageForOrigin( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Registers origin to be notified when an update occurs to its cache storage list.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.trackCacheStorageForOrigin", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.trackCacheStorageForOrigin", + params=params, + session_id=session_id, + ), + ) async def trackCacheStorageForStorageKey( self, @@ -176,11 +223,14 @@ async def trackCacheStorageForStorageKey( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Registers storage key to be notified when an update occurs to its cache storage list.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.trackCacheStorageForStorageKey", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.trackCacheStorageForStorageKey", + params=params, + session_id=session_id, + ), + ) async def trackIndexedDBForOrigin( self, @@ -188,11 +238,14 @@ async def trackIndexedDBForOrigin( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Registers origin to be notified when an update occurs to its IndexedDB.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.trackIndexedDBForOrigin", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.trackIndexedDBForOrigin", + params=params, + session_id=session_id, + ), + ) async def trackIndexedDBForStorageKey( self, @@ -200,11 +253,14 @@ async def trackIndexedDBForStorageKey( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Registers storage key to be notified when an update occurs to its IndexedDB.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.trackIndexedDBForStorageKey", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.trackIndexedDBForStorageKey", + params=params, + session_id=session_id, + ), + ) async def untrackCacheStorageForOrigin( self, @@ -212,11 +268,14 @@ async def untrackCacheStorageForOrigin( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Unregisters origin from receiving notifications for cache storage.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.untrackCacheStorageForOrigin", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.untrackCacheStorageForOrigin", + params=params, + session_id=session_id, + ), + ) async def untrackCacheStorageForStorageKey( self, @@ -224,11 +283,14 @@ async def untrackCacheStorageForStorageKey( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Unregisters storage key from receiving notifications for cache storage.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.untrackCacheStorageForStorageKey", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.untrackCacheStorageForStorageKey", + params=params, + session_id=session_id, + ), + ) async def untrackIndexedDBForOrigin( self, @@ -236,11 +298,14 @@ async def untrackIndexedDBForOrigin( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Unregisters origin from receiving notifications for IndexedDB.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.untrackIndexedDBForOrigin", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.untrackIndexedDBForOrigin", + params=params, + session_id=session_id, + ), + ) async def untrackIndexedDBForStorageKey( self, @@ -248,11 +313,14 @@ async def untrackIndexedDBForStorageKey( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Unregisters storage key from receiving notifications for IndexedDB.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.untrackIndexedDBForStorageKey", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.untrackIndexedDBForStorageKey", + params=params, + session_id=session_id, + ), + ) async def getTrustTokens( self, @@ -260,12 +328,15 @@ async def getTrustTokens( session_id: Optional[str] = None, ) -> "GetTrustTokensReturns": """Returns the number of stored Trust Tokens per issuer for the -current browsing context.""" - return cast("GetTrustTokensReturns", await self._client.send_raw( - method="Storage.getTrustTokens", - params=params, - session_id=session_id, - )) + current browsing context.""" + return cast( + "GetTrustTokensReturns", + await self._client.send_raw( + method="Storage.getTrustTokens", + params=params, + session_id=session_id, + ), + ) async def clearTrustTokens( self, @@ -273,12 +344,15 @@ async def clearTrustTokens( session_id: Optional[str] = None, ) -> "ClearTrustTokensReturns": """Removes all Trust Tokens issued by the provided issuerOrigin. -Leaves other stored data, including the issuer's Redemption Records, intact.""" - return cast("ClearTrustTokensReturns", await self._client.send_raw( - method="Storage.clearTrustTokens", - params=params, - session_id=session_id, - )) + Leaves other stored data, including the issuer's Redemption Records, intact.""" + return cast( + "ClearTrustTokensReturns", + await self._client.send_raw( + method="Storage.clearTrustTokens", + params=params, + session_id=session_id, + ), + ) async def getInterestGroupDetails( self, @@ -286,11 +360,14 @@ async def getInterestGroupDetails( session_id: Optional[str] = None, ) -> "GetInterestGroupDetailsReturns": """Gets details for a named interest group.""" - return cast("GetInterestGroupDetailsReturns", await self._client.send_raw( - method="Storage.getInterestGroupDetails", - params=params, - session_id=session_id, - )) + return cast( + "GetInterestGroupDetailsReturns", + await self._client.send_raw( + method="Storage.getInterestGroupDetails", + params=params, + session_id=session_id, + ), + ) async def setInterestGroupTracking( self, @@ -298,11 +375,14 @@ async def setInterestGroupTracking( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables/Disables issuing of interestGroupAccessed events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setInterestGroupTracking", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setInterestGroupTracking", + params=params, + session_id=session_id, + ), + ) async def setInterestGroupAuctionTracking( self, @@ -310,12 +390,15 @@ async def setInterestGroupAuctionTracking( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables/Disables issuing of interestGroupAuctionEventOccurred and -interestGroupAuctionNetworkRequestCreated.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setInterestGroupAuctionTracking", - params=params, - session_id=session_id, - )) + interestGroupAuctionNetworkRequestCreated.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setInterestGroupAuctionTracking", + params=params, + session_id=session_id, + ), + ) async def getSharedStorageMetadata( self, @@ -323,11 +406,14 @@ async def getSharedStorageMetadata( session_id: Optional[str] = None, ) -> "GetSharedStorageMetadataReturns": """Gets metadata for an origin's shared storage.""" - return cast("GetSharedStorageMetadataReturns", await self._client.send_raw( - method="Storage.getSharedStorageMetadata", - params=params, - session_id=session_id, - )) + return cast( + "GetSharedStorageMetadataReturns", + await self._client.send_raw( + method="Storage.getSharedStorageMetadata", + params=params, + session_id=session_id, + ), + ) async def getSharedStorageEntries( self, @@ -335,11 +421,14 @@ async def getSharedStorageEntries( session_id: Optional[str] = None, ) -> "GetSharedStorageEntriesReturns": """Gets the entries in an given origin's shared storage.""" - return cast("GetSharedStorageEntriesReturns", await self._client.send_raw( - method="Storage.getSharedStorageEntries", - params=params, - session_id=session_id, - )) + return cast( + "GetSharedStorageEntriesReturns", + await self._client.send_raw( + method="Storage.getSharedStorageEntries", + params=params, + session_id=session_id, + ), + ) async def setSharedStorageEntry( self, @@ -347,11 +436,14 @@ async def setSharedStorageEntry( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets entry with `key` and `value` for a given origin's shared storage.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setSharedStorageEntry", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setSharedStorageEntry", + params=params, + session_id=session_id, + ), + ) async def deleteSharedStorageEntry( self, @@ -359,11 +451,14 @@ async def deleteSharedStorageEntry( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes entry for `key` (if it exists) for a given origin's shared storage.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.deleteSharedStorageEntry", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.deleteSharedStorageEntry", + params=params, + session_id=session_id, + ), + ) async def clearSharedStorageEntries( self, @@ -371,11 +466,14 @@ async def clearSharedStorageEntries( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears all entries for a given origin's shared storage.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.clearSharedStorageEntries", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.clearSharedStorageEntries", + params=params, + session_id=session_id, + ), + ) async def resetSharedStorageBudget( self, @@ -383,11 +481,14 @@ async def resetSharedStorageBudget( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Resets the budget for `ownerOrigin` by clearing all budget withdrawals.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.resetSharedStorageBudget", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.resetSharedStorageBudget", + params=params, + session_id=session_id, + ), + ) async def setSharedStorageTracking( self, @@ -395,11 +496,14 @@ async def setSharedStorageTracking( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables/disables issuing of sharedStorageAccessed events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setSharedStorageTracking", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setSharedStorageTracking", + params=params, + session_id=session_id, + ), + ) async def setStorageBucketTracking( self, @@ -407,11 +511,14 @@ async def setStorageBucketTracking( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Set tracking for a storage key's buckets.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setStorageBucketTracking", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setStorageBucketTracking", + params=params, + session_id=session_id, + ), + ) async def deleteStorageBucket( self, @@ -419,11 +526,14 @@ async def deleteStorageBucket( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes the Storage Bucket with the given storage key and bucket name.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.deleteStorageBucket", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.deleteStorageBucket", + params=params, + session_id=session_id, + ), + ) async def runBounceTrackingMitigations( self, @@ -431,11 +541,14 @@ async def runBounceTrackingMitigations( session_id: Optional[str] = None, ) -> "RunBounceTrackingMitigationsReturns": """Deletes state for sites identified as potential bounce trackers, immediately.""" - return cast("RunBounceTrackingMitigationsReturns", await self._client.send_raw( - method="Storage.runBounceTrackingMitigations", - params=params, - session_id=session_id, - )) + return cast( + "RunBounceTrackingMitigationsReturns", + await self._client.send_raw( + method="Storage.runBounceTrackingMitigations", + params=params, + session_id=session_id, + ), + ) async def setAttributionReportingLocalTestingMode( self, @@ -443,11 +556,14 @@ async def setAttributionReportingLocalTestingMode( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """https://wicg.github.io/attribution-reporting-api/""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setAttributionReportingLocalTestingMode", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setAttributionReportingLocalTestingMode", + params=params, + session_id=session_id, + ), + ) async def setAttributionReportingTracking( self, @@ -455,11 +571,14 @@ async def setAttributionReportingTracking( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables/disables issuing of Attribution Reporting events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setAttributionReportingTracking", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setAttributionReportingTracking", + params=params, + session_id=session_id, + ), + ) async def sendPendingAttributionReports( self, @@ -467,12 +586,15 @@ async def sendPendingAttributionReports( session_id: Optional[str] = None, ) -> "SendPendingAttributionReportsReturns": """Sends all pending Attribution Reports immediately, regardless of their -scheduled report time.""" - return cast("SendPendingAttributionReportsReturns", await self._client.send_raw( - method="Storage.sendPendingAttributionReports", - params=params, - session_id=session_id, - )) + scheduled report time.""" + return cast( + "SendPendingAttributionReportsReturns", + await self._client.send_raw( + method="Storage.sendPendingAttributionReports", + params=params, + session_id=session_id, + ), + ) async def getRelatedWebsiteSets( self, @@ -480,12 +602,15 @@ async def getRelatedWebsiteSets( session_id: Optional[str] = None, ) -> "GetRelatedWebsiteSetsReturns": """Returns the effective Related Website Sets in use by this profile for the browser -session. The effective Related Website Sets will not change during a browser session.""" - return cast("GetRelatedWebsiteSetsReturns", await self._client.send_raw( - method="Storage.getRelatedWebsiteSets", - params=params, - session_id=session_id, - )) + session. The effective Related Website Sets will not change during a browser session.""" + return cast( + "GetRelatedWebsiteSetsReturns", + await self._client.send_raw( + method="Storage.getRelatedWebsiteSets", + params=params, + session_id=session_id, + ), + ) async def getAffectedUrlsForThirdPartyCookieMetadata( self, @@ -493,23 +618,27 @@ async def getAffectedUrlsForThirdPartyCookieMetadata( session_id: Optional[str] = None, ) -> "GetAffectedUrlsForThirdPartyCookieMetadataReturns": """Returns the list of URLs from a page and its embedded resources that match -existing grace period URL pattern rules. -https://developers.google.com/privacy-sandbox/cookies/temporary-exceptions/grace-period""" - return cast("GetAffectedUrlsForThirdPartyCookieMetadataReturns", await self._client.send_raw( - method="Storage.getAffectedUrlsForThirdPartyCookieMetadata", - params=params, - session_id=session_id, - )) + existing grace period URL pattern rules. + https://developers.google.com/privacy-sandbox/cookies/temporary-exceptions/grace-period""" + return cast( + "GetAffectedUrlsForThirdPartyCookieMetadataReturns", + await self._client.send_raw( + method="Storage.getAffectedUrlsForThirdPartyCookieMetadata", + params=params, + session_id=session_id, + ), + ) async def setProtectedAudienceKAnonymity( self, params: "SetProtectedAudienceKAnonymityParameters", session_id: Optional[str] = None, ) -> "Dict[str, Any]": - return cast("Dict[str, Any]", await self._client.send_raw( - method="Storage.setProtectedAudienceKAnonymity", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Storage.setProtectedAudienceKAnonymity", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/storage/registration.py b/cdp_use/cdp/storage/registration.py index 8b5507e..24fad2c 100644 --- a/cdp_use/cdp/storage/registration.py +++ b/cdp_use/cdp/storage/registration.py @@ -11,39 +11,40 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - AttributionReportingReportSentEvent, - AttributionReportingSourceRegisteredEvent, - AttributionReportingTriggerRegisteredEvent, - AttributionReportingVerboseDebugReportSentEvent, - CacheStorageContentUpdatedEvent, - CacheStorageListUpdatedEvent, - IndexedDBContentUpdatedEvent, - IndexedDBListUpdatedEvent, - InterestGroupAccessedEvent, - InterestGroupAuctionEventOccurredEvent, - InterestGroupAuctionNetworkRequestCreatedEvent, - SharedStorageAccessedEvent, - SharedStorageWorkletOperationExecutionFinishedEvent, - StorageBucketCreatedOrUpdatedEvent, - StorageBucketDeletedEvent -) + AttributionReportingReportSentEvent, + AttributionReportingSourceRegisteredEvent, + AttributionReportingTriggerRegisteredEvent, + AttributionReportingVerboseDebugReportSentEvent, + CacheStorageContentUpdatedEvent, + CacheStorageListUpdatedEvent, + IndexedDBContentUpdatedEvent, + IndexedDBListUpdatedEvent, + InterestGroupAccessedEvent, + InterestGroupAuctionEventOccurredEvent, + InterestGroupAuctionNetworkRequestCreatedEvent, + SharedStorageAccessedEvent, + SharedStorageWorkletOperationExecutionFinishedEvent, + StorageBucketCreatedOrUpdatedEvent, + StorageBucketDeletedEvent, + ) + class StorageRegistration: """Event registration interface for Storage domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Storage" def cacheStorageContentUpdated( self, - callback: Callable[['CacheStorageContentUpdatedEvent', Optional[str]], None], + callback: Callable[["CacheStorageContentUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for cacheStorageContentUpdated events. - + A cache's contents have been modified. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -52,13 +53,13 @@ def cacheStorageContentUpdated( def cacheStorageListUpdated( self, - callback: Callable[['CacheStorageListUpdatedEvent', Optional[str]], None], + callback: Callable[["CacheStorageListUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for cacheStorageListUpdated events. - + A cache has been added/deleted. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -67,13 +68,13 @@ def cacheStorageListUpdated( def indexedDBContentUpdated( self, - callback: Callable[['IndexedDBContentUpdatedEvent', Optional[str]], None], + callback: Callable[["IndexedDBContentUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for indexedDBContentUpdated events. - + The origin's IndexedDB object store has been modified. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -82,13 +83,13 @@ def indexedDBContentUpdated( def indexedDBListUpdated( self, - callback: Callable[['IndexedDBListUpdatedEvent', Optional[str]], None], + callback: Callable[["IndexedDBListUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for indexedDBListUpdated events. - + The origin's IndexedDB database list has been modified. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -97,93 +98,103 @@ def indexedDBListUpdated( def interestGroupAccessed( self, - callback: Callable[['InterestGroupAccessedEvent', Optional[str]], None], + callback: Callable[["InterestGroupAccessedEvent", Optional[str]], None], ) -> None: """ - Register a callback for interestGroupAccessed events. - - One of the interest groups was accessed. Note that these events are global -to all targets sharing an interest group store. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for interestGroupAccessed events. + + One of the interest groups was accessed. Note that these events are global + to all targets sharing an interest group store. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Storage.interestGroupAccessed", callback) def interestGroupAuctionEventOccurred( self, - callback: Callable[['InterestGroupAuctionEventOccurredEvent', Optional[str]], None], + callback: Callable[ + ["InterestGroupAuctionEventOccurredEvent", Optional[str]], None + ], ) -> None: """ - Register a callback for interestGroupAuctionEventOccurred events. - - An auction involving interest groups is taking place. These events are -target-specific. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for interestGroupAuctionEventOccurred events. + + An auction involving interest groups is taking place. These events are + target-specific. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Storage.interestGroupAuctionEventOccurred", callback) def interestGroupAuctionNetworkRequestCreated( self, - callback: Callable[['InterestGroupAuctionNetworkRequestCreatedEvent', Optional[str]], None], + callback: Callable[ + ["InterestGroupAuctionNetworkRequestCreatedEvent", Optional[str]], None + ], ) -> None: """ - Register a callback for interestGroupAuctionNetworkRequestCreated events. - - Specifies which auctions a particular network fetch may be related to, and -in what role. Note that it is not ordered with respect to -Network.requestWillBeSent (but will happen before loadingFinished -loadingFailed). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for interestGroupAuctionNetworkRequestCreated events. + + Specifies which auctions a particular network fetch may be related to, and + in what role. Note that it is not ordered with respect to + Network.requestWillBeSent (but will happen before loadingFinished + loadingFailed). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ - self._registry.register("Storage.interestGroupAuctionNetworkRequestCreated", callback) + self._registry.register( + "Storage.interestGroupAuctionNetworkRequestCreated", callback + ) def sharedStorageAccessed( self, - callback: Callable[['SharedStorageAccessedEvent', Optional[str]], None], + callback: Callable[["SharedStorageAccessedEvent", Optional[str]], None], ) -> None: """ - Register a callback for sharedStorageAccessed events. - - Shared storage was accessed by the associated page. -The following parameters are included in all events. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for sharedStorageAccessed events. + + Shared storage was accessed by the associated page. + The following parameters are included in all events. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Storage.sharedStorageAccessed", callback) def sharedStorageWorkletOperationExecutionFinished( self, - callback: Callable[['SharedStorageWorkletOperationExecutionFinishedEvent', Optional[str]], None], + callback: Callable[ + ["SharedStorageWorkletOperationExecutionFinishedEvent", Optional[str]], None + ], ) -> None: """ - Register a callback for sharedStorageWorkletOperationExecutionFinished events. - - A shared storage run or selectURL operation finished its execution. -The following parameters are included in all events. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for sharedStorageWorkletOperationExecutionFinished events. + + A shared storage run or selectURL operation finished its execution. + The following parameters are included in all events. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ - self._registry.register("Storage.sharedStorageWorkletOperationExecutionFinished", callback) + self._registry.register( + "Storage.sharedStorageWorkletOperationExecutionFinished", callback + ) def storageBucketCreatedOrUpdated( self, - callback: Callable[['StorageBucketCreatedOrUpdatedEvent', Optional[str]], None], + callback: Callable[["StorageBucketCreatedOrUpdatedEvent", Optional[str]], None], ) -> None: """ Register a callback for storageBucketCreatedOrUpdated events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -192,11 +203,11 @@ def storageBucketCreatedOrUpdated( def storageBucketDeleted( self, - callback: Callable[['StorageBucketDeletedEvent', Optional[str]], None], + callback: Callable[["StorageBucketDeletedEvent", Optional[str]], None], ) -> None: """ Register a callback for storageBucketDeleted events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -205,37 +216,47 @@ def storageBucketDeleted( def attributionReportingSourceRegistered( self, - callback: Callable[['AttributionReportingSourceRegisteredEvent', Optional[str]], None], + callback: Callable[ + ["AttributionReportingSourceRegisteredEvent", Optional[str]], None + ], ) -> None: """ Register a callback for attributionReportingSourceRegistered events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ - self._registry.register("Storage.attributionReportingSourceRegistered", callback) + self._registry.register( + "Storage.attributionReportingSourceRegistered", callback + ) def attributionReportingTriggerRegistered( self, - callback: Callable[['AttributionReportingTriggerRegisteredEvent', Optional[str]], None], + callback: Callable[ + ["AttributionReportingTriggerRegisteredEvent", Optional[str]], None + ], ) -> None: """ Register a callback for attributionReportingTriggerRegistered events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ - self._registry.register("Storage.attributionReportingTriggerRegistered", callback) + self._registry.register( + "Storage.attributionReportingTriggerRegistered", callback + ) def attributionReportingReportSent( self, - callback: Callable[['AttributionReportingReportSentEvent', Optional[str]], None], + callback: Callable[ + ["AttributionReportingReportSentEvent", Optional[str]], None + ], ) -> None: """ Register a callback for attributionReportingReportSent events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -244,14 +265,17 @@ def attributionReportingReportSent( def attributionReportingVerboseDebugReportSent( self, - callback: Callable[['AttributionReportingVerboseDebugReportSentEvent', Optional[str]], None], + callback: Callable[ + ["AttributionReportingVerboseDebugReportSentEvent", Optional[str]], None + ], ) -> None: """ Register a callback for attributionReportingVerboseDebugReportSent events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ - self._registry.register("Storage.attributionReportingVerboseDebugReportSent", callback) - + self._registry.register( + "Storage.attributionReportingVerboseDebugReportSent", callback + ) diff --git a/cdp_use/cdp/storage/types.py b/cdp_use/cdp/storage/types.py index 9ec89f8..e06f879 100644 --- a/cdp_use/cdp/storage/types.py +++ b/cdp_use/cdp/storage/types.py @@ -17,12 +17,24 @@ SerializedStorageKey = str - -StorageType = Literal["cookies", "file_systems", "indexeddb", "local_storage", "shader_cache", "websql", "service_workers", "cache_storage", "interest_groups", "shared_storage", "storage_buckets", "all", "other"] +StorageType = Literal[ + "cookies", + "file_systems", + "indexeddb", + "local_storage", + "shader_cache", + "websql", + "service_workers", + "cache_storage", + "interest_groups", + "shared_storage", + "storage_buckets", + "all", + "other", +] """Enum of possible storage types.""" - class UsageForType(TypedDict): """Usage for a storage type.""" @@ -32,46 +44,70 @@ class UsageForType(TypedDict): """Storage usage (bytes).""" - class TrustTokens(TypedDict): """Pair of issuer origin and number of available (signed, but not used) Trust -Tokens from that issuer.""" + Tokens from that issuer.""" issuerOrigin: "str" count: "float" - InterestGroupAuctionId = str """Protected audience interest group auction identifier.""" - -InterestGroupAccessType = Literal["join", "leave", "update", "loaded", "bid", "win", "additionalBid", "additionalBidWin", "topLevelBid", "topLevelAdditionalBid", "clear"] +InterestGroupAccessType = Literal[ + "join", + "leave", + "update", + "loaded", + "bid", + "win", + "additionalBid", + "additionalBidWin", + "topLevelBid", + "topLevelAdditionalBid", + "clear", +] """Enum of interest group access types.""" - InterestGroupAuctionEventType = Literal["started", "configResolved"] """Enum of auction events.""" - -InterestGroupAuctionFetchType = Literal["bidderJs", "bidderWasm", "sellerJs", "bidderTrustedSignals", "sellerTrustedSignals"] +InterestGroupAuctionFetchType = Literal[ + "bidderJs", "bidderWasm", "sellerJs", "bidderTrustedSignals", "sellerTrustedSignals" +] """Enum of network fetches auctions can do.""" - -SharedStorageAccessScope = Literal["window", "sharedStorageWorklet", "protectedAudienceWorklet", "header"] +SharedStorageAccessScope = Literal[ + "window", "sharedStorageWorklet", "protectedAudienceWorklet", "header" +] """Enum of shared storage access scopes.""" - -SharedStorageAccessMethod = Literal["addModule", "createWorklet", "selectURL", "run", "batchUpdate", "set", "append", "delete", "clear", "get", "keys", "values", "entries", "length", "remainingBudget"] +SharedStorageAccessMethod = Literal[ + "addModule", + "createWorklet", + "selectURL", + "run", + "batchUpdate", + "set", + "append", + "delete", + "clear", + "get", + "keys", + "values", + "entries", + "length", + "remainingBudget", +] """Enum of shared storage access methods.""" - class SharedStorageEntry(TypedDict): """Struct for a single key-value pair in an origin's shared storage.""" @@ -79,7 +115,6 @@ class SharedStorageEntry(TypedDict): value: "str" - class SharedStorageMetadata(TypedDict): """Details for an origin's shared storage.""" @@ -94,10 +129,9 @@ class SharedStorageMetadata(TypedDict): storage.""" - class SharedStoragePrivateAggregationConfig(TypedDict): """Represents a dictionary object passed in as privateAggregationConfig to -run or selectURL.""" + run or selectURL.""" aggregationCoordinatorOrigin: "NotRequired[str]" """The chosen aggregation service deployment.""" @@ -109,7 +143,6 @@ class SharedStoragePrivateAggregationConfig(TypedDict): """The limit on the number of contributions in the final report.""" - class SharedStorageReportingMetadata(TypedDict): """Pair of reporting metadata details for a candidate URL for `selectURL()`.""" @@ -117,7 +150,6 @@ class SharedStorageReportingMetadata(TypedDict): reportingUrl: "str" - class SharedStorageUrlWithMetadata(TypedDict): """Bundles a candidate URL with its reporting metadata.""" @@ -127,10 +159,9 @@ class SharedStorageUrlWithMetadata(TypedDict): """Any associated reporting metadata.""" - class SharedStorageAccessParams(TypedDict, total=False): """Bundles the parameters for shared storage access events whose -presence/absence can vary according to SharedStorageAccessType.""" + presence/absence can vary according to SharedStorageAccessType.""" scriptSourceUrl: "str" """Spec of the module script URL. @@ -198,18 +229,15 @@ class SharedStorageAccessParams(TypedDict, total=False): Present only for SharedStorageAccessMethod: batchUpdate.""" - StorageBucketsDurability = Literal["relaxed", "strict"] - class StorageBucket(TypedDict): storageKey: "SerializedStorageKey" name: "NotRequired[str]" """If not specified, it is the default bucket of the storageKey.""" - class StorageBucketInfo(TypedDict): bucket: "StorageBucket" id: "str" @@ -220,48 +248,39 @@ class StorageBucketInfo(TypedDict): durability: "StorageBucketsDurability" - AttributionReportingSourceType = Literal["navigation", "event"] - UnsignedInt64AsBase10 = str - UnsignedInt128AsBase16 = str - SignedInt64AsBase10 = str - class AttributionReportingFilterDataEntry(TypedDict): key: "str" values: "List[str]" - class AttributionReportingFilterConfig(TypedDict): filterValues: "List[AttributionReportingFilterDataEntry]" lookbackWindow: "NotRequired[int]" """duration in seconds""" - class AttributionReportingFilterPair(TypedDict): filters: "List[AttributionReportingFilterConfig]" notFilters: "List[AttributionReportingFilterConfig]" - class AttributionReportingAggregationKeysEntry(TypedDict): key: "str" value: "UnsignedInt128AsBase16" - class AttributionReportingEventReportWindows(TypedDict): start: "int" """duration in seconds""" @@ -269,11 +288,9 @@ class AttributionReportingEventReportWindows(TypedDict): """duration in seconds""" - AttributionReportingTriggerDataMatching = Literal["exact", "modulus"] - class AttributionReportingAggregatableDebugReportingData(TypedDict): keyPiece: "UnsignedInt128AsBase16" value: "float" @@ -282,7 +299,6 @@ class AttributionReportingAggregatableDebugReportingData(TypedDict): types: "List[str]" - class AttributionReportingAggregatableDebugReportingConfig(TypedDict): budget: "NotRequired[float]" """number instead of integer because not all uint32 can be represented by @@ -292,7 +308,6 @@ class AttributionReportingAggregatableDebugReportingConfig(TypedDict): aggregationCoordinatorOrigin: "NotRequired[str]" - class AttributionScopesData(TypedDict): values: "List[str]" limit: "float" @@ -301,13 +316,11 @@ class AttributionScopesData(TypedDict): maxEventStates: "float" - class AttributionReportingNamedBudgetDef(TypedDict): name: "str" budget: "int" - class AttributionReportingSourceRegistration(TypedDict): time: "TimeSinceEpoch" expiry: "int" @@ -329,7 +342,9 @@ class AttributionReportingSourceRegistration(TypedDict): debugKey: "NotRequired[UnsignedInt64AsBase10]" triggerDataMatching: "AttributionReportingTriggerDataMatching" destinationLimitPriority: "SignedInt64AsBase10" - aggregatableDebugReportingConfig: "AttributionReportingAggregatableDebugReportingConfig" + aggregatableDebugReportingConfig: ( + "AttributionReportingAggregatableDebugReportingConfig" + ) scopesData: "NotRequired[AttributionScopesData]" maxEventLevelReports: "int" namedBudgets: "List[AttributionReportingNamedBudgetDef]" @@ -337,15 +352,29 @@ class AttributionReportingSourceRegistration(TypedDict): eventLevelEpsilon: "float" - -AttributionReportingSourceRegistrationResult = Literal["success", "internalError", "insufficientSourceCapacity", "insufficientUniqueDestinationCapacity", "excessiveReportingOrigins", "prohibitedByBrowserPolicy", "successNoised", "destinationReportingLimitReached", "destinationGlobalLimitReached", "destinationBothLimitsReached", "reportingOriginsPerSiteLimitReached", "exceedsMaxChannelCapacity", "exceedsMaxScopesChannelCapacity", "exceedsMaxTriggerStateCardinality", "exceedsMaxEventStatesLimit", "destinationPerDayReportingLimitReached"] - +AttributionReportingSourceRegistrationResult = Literal[ + "success", + "internalError", + "insufficientSourceCapacity", + "insufficientUniqueDestinationCapacity", + "excessiveReportingOrigins", + "prohibitedByBrowserPolicy", + "successNoised", + "destinationReportingLimitReached", + "destinationGlobalLimitReached", + "destinationBothLimitsReached", + "reportingOriginsPerSiteLimitReached", + "exceedsMaxChannelCapacity", + "exceedsMaxScopesChannelCapacity", + "exceedsMaxTriggerStateCardinality", + "exceedsMaxEventStatesLimit", + "destinationPerDayReportingLimitReached", +] AttributionReportingSourceRegistrationTimeConfig = Literal["include", "exclude"] - class AttributionReportingAggregatableValueDictEntry(TypedDict): key: "str" value: "float" @@ -354,13 +383,11 @@ class AttributionReportingAggregatableValueDictEntry(TypedDict): filteringId: "UnsignedInt64AsBase10" - class AttributionReportingAggregatableValueEntry(TypedDict): values: "List[AttributionReportingAggregatableValueDictEntry]" filters: "AttributionReportingFilterPair" - class AttributionReportingEventTriggerData(TypedDict): data: "UnsignedInt64AsBase10" priority: "SignedInt64AsBase10" @@ -368,26 +395,22 @@ class AttributionReportingEventTriggerData(TypedDict): filters: "AttributionReportingFilterPair" - class AttributionReportingAggregatableTriggerData(TypedDict): keyPiece: "UnsignedInt128AsBase16" sourceKeys: "List[str]" filters: "AttributionReportingFilterPair" - class AttributionReportingAggregatableDedupKey(TypedDict): dedupKey: "NotRequired[UnsignedInt64AsBase10]" filters: "AttributionReportingFilterPair" - class AttributionReportingNamedBudgetCandidate(TypedDict): name: "NotRequired[str]" filters: "AttributionReportingFilterPair" - class AttributionReportingTriggerRegistration(TypedDict): filters: "AttributionReportingFilterPair" debugKey: "NotRequired[UnsignedInt64AsBase10]" @@ -400,22 +423,58 @@ class AttributionReportingTriggerRegistration(TypedDict): aggregationCoordinatorOrigin: "NotRequired[str]" sourceRegistrationTimeConfig: "AttributionReportingSourceRegistrationTimeConfig" triggerContextId: "NotRequired[str]" - aggregatableDebugReportingConfig: "AttributionReportingAggregatableDebugReportingConfig" + aggregatableDebugReportingConfig: ( + "AttributionReportingAggregatableDebugReportingConfig" + ) scopes: "List[str]" namedBudgets: "List[AttributionReportingNamedBudgetCandidate]" - -AttributionReportingEventLevelResult = Literal["success", "successDroppedLowerPriority", "internalError", "noCapacityForAttributionDestination", "noMatchingSources", "deduplicated", "excessiveAttributions", "priorityTooLow", "neverAttributedSource", "excessiveReportingOrigins", "noMatchingSourceFilterData", "prohibitedByBrowserPolicy", "noMatchingConfigurations", "excessiveReports", "falselyAttributedSource", "reportWindowPassed", "notRegistered", "reportWindowNotStarted", "noMatchingTriggerData"] - - - -AttributionReportingAggregatableResult = Literal["success", "internalError", "noCapacityForAttributionDestination", "noMatchingSources", "excessiveAttributions", "excessiveReportingOrigins", "noHistograms", "insufficientBudget", "insufficientNamedBudget", "noMatchingSourceFilterData", "notRegistered", "prohibitedByBrowserPolicy", "deduplicated", "reportWindowPassed", "excessiveReports"] - - - -AttributionReportingReportResult = Literal["sent", "prohibited", "failedToAssemble", "expired"] - +AttributionReportingEventLevelResult = Literal[ + "success", + "successDroppedLowerPriority", + "internalError", + "noCapacityForAttributionDestination", + "noMatchingSources", + "deduplicated", + "excessiveAttributions", + "priorityTooLow", + "neverAttributedSource", + "excessiveReportingOrigins", + "noMatchingSourceFilterData", + "prohibitedByBrowserPolicy", + "noMatchingConfigurations", + "excessiveReports", + "falselyAttributedSource", + "reportWindowPassed", + "notRegistered", + "reportWindowNotStarted", + "noMatchingTriggerData", +] + + +AttributionReportingAggregatableResult = Literal[ + "success", + "internalError", + "noCapacityForAttributionDestination", + "noMatchingSources", + "excessiveAttributions", + "excessiveReportingOrigins", + "noHistograms", + "insufficientBudget", + "insufficientNamedBudget", + "noMatchingSourceFilterData", + "notRegistered", + "prohibitedByBrowserPolicy", + "deduplicated", + "reportWindowPassed", + "excessiveReports", +] + + +AttributionReportingReportResult = Literal[ + "sent", "prohibited", "failedToAssemble", "expired" +] class RelatedWebsiteSet(TypedDict): diff --git a/cdp_use/cdp/systeminfo/commands.py b/cdp_use/cdp/systeminfo/commands.py index cb05670..cfedb38 100644 --- a/cdp_use/cdp/systeminfo/commands.py +++ b/cdp_use/cdp/systeminfo/commands.py @@ -13,6 +13,7 @@ from .types import GPUInfo from .types import ProcessInfo + class GetInfoReturns(TypedDict): gpu: "GPUInfo" """Information about the GPUs on the system.""" @@ -27,7 +28,6 @@ class GetInfoReturns(TypedDict): supported.""" - class GetFeatureStateParameters(TypedDict): featureState: "str" @@ -36,7 +36,6 @@ class GetFeatureStateReturns(TypedDict): featureEnabled: "bool" - class GetProcessInfoReturns(TypedDict): processInfo: "List[ProcessInfo]" """An array of process info blocks.""" diff --git a/cdp_use/cdp/systeminfo/events.py b/cdp_use/cdp/systeminfo/events.py index 3f1e8a4..8f5c801 100644 --- a/cdp_use/cdp/systeminfo/events.py +++ b/cdp_use/cdp/systeminfo/events.py @@ -5,4 +5,4 @@ """CDP SystemInfo Domain Events""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/systeminfo/library.py b/cdp_use/cdp/systeminfo/library.py index 65fcf20..a3a2de9 100644 --- a/cdp_use/cdp/systeminfo/library.py +++ b/cdp_use/cdp/systeminfo/library.py @@ -15,10 +15,11 @@ from .commands import GetInfoReturns from .commands import GetProcessInfoReturns + class SystemInfoClient: """Client for SystemInfo domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def getInfo( @@ -27,11 +28,14 @@ async def getInfo( session_id: Optional[str] = None, ) -> "GetInfoReturns": """Returns information about the system.""" - return cast("GetInfoReturns", await self._client.send_raw( - method="SystemInfo.getInfo", - params=params, - session_id=session_id, - )) + return cast( + "GetInfoReturns", + await self._client.send_raw( + method="SystemInfo.getInfo", + params=params, + session_id=session_id, + ), + ) async def getFeatureState( self, @@ -39,11 +43,14 @@ async def getFeatureState( session_id: Optional[str] = None, ) -> "GetFeatureStateReturns": """Returns information about the feature state.""" - return cast("GetFeatureStateReturns", await self._client.send_raw( - method="SystemInfo.getFeatureState", - params=params, - session_id=session_id, - )) + return cast( + "GetFeatureStateReturns", + await self._client.send_raw( + method="SystemInfo.getFeatureState", + params=params, + session_id=session_id, + ), + ) async def getProcessInfo( self, @@ -51,10 +58,11 @@ async def getProcessInfo( session_id: Optional[str] = None, ) -> "GetProcessInfoReturns": """Returns information about all running processes.""" - return cast("GetProcessInfoReturns", await self._client.send_raw( - method="SystemInfo.getProcessInfo", - params=params, - session_id=session_id, - )) - - + return cast( + "GetProcessInfoReturns", + await self._client.send_raw( + method="SystemInfo.getProcessInfo", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/systeminfo/registration.py b/cdp_use/cdp/systeminfo/registration.py index 7c42503..f9fda75 100644 --- a/cdp_use/cdp/systeminfo/registration.py +++ b/cdp_use/cdp/systeminfo/registration.py @@ -5,4 +5,4 @@ """CDP SystemInfo Domain Event Registration""" -# No events defined for this domain \ No newline at end of file +# No events defined for this domain diff --git a/cdp_use/cdp/systeminfo/types.py b/cdp_use/cdp/systeminfo/types.py index 2569fd8..71a2913 100644 --- a/cdp_use/cdp/systeminfo/types.py +++ b/cdp_use/cdp/systeminfo/types.py @@ -8,6 +8,7 @@ from typing_extensions import Literal from typing_extensions import NotRequired, TypedDict + class GPUDevice(TypedDict): """Describes a single graphics processor (GPU).""" @@ -29,7 +30,6 @@ class GPUDevice(TypedDict): """String description of the GPU driver version.""" - class Size(TypedDict): """Describes the width and height dimensions of an entity.""" @@ -39,10 +39,9 @@ class Size(TypedDict): """Height in pixels.""" - class VideoDecodeAcceleratorCapability(TypedDict): """Describes a supported video decoding profile with its associated minimum and -maximum resolutions.""" + maximum resolutions.""" profile: "str" """Video codec profile that is supported, e.g. VP9 Profile 2.""" @@ -52,10 +51,9 @@ class VideoDecodeAcceleratorCapability(TypedDict): """Minimum video dimensions in pixels supported for this |profile|.""" - class VideoEncodeAcceleratorCapability(TypedDict): """Describes a supported video encoding profile with its associated maximum -resolution and maximum framerate.""" + resolution and maximum framerate.""" profile: "str" """Video codec profile that is supported, e.g H264 Main.""" @@ -68,32 +66,14 @@ class VideoEncodeAcceleratorCapability(TypedDict): maxFramerateDenominator: "int" - SubsamplingFormat = Literal["yuv420", "yuv422", "yuv444"] """YUV subsampling type of the pixels of a given image.""" - ImageType = Literal["jpeg", "webp", "unknown"] """Image format of a given image.""" - -class ImageDecodeAcceleratorCapability(TypedDict): - """Describes a supported image decoding profile with its associated minimum and -maximum resolutions and subsampling.""" - - imageType: "ImageType" - """Image coded, e.g. Jpeg.""" - maxDimensions: "Size" - """Maximum supported dimensions of the image in pixels.""" - minDimensions: "Size" - """Minimum supported dimensions of the image in pixels.""" - subsamplings: "List[SubsamplingFormat]" - """Optional array of supported subsampling formats, e.g. 4:2:0, if known.""" - - - class GPUInfo(TypedDict): """Provides information about the GPU(s) on the system.""" @@ -109,9 +89,6 @@ class GPUInfo(TypedDict): """Supported accelerated video decoding capabilities.""" videoEncoding: "List[VideoEncodeAcceleratorCapability]" """Supported accelerated video encoding capabilities.""" - imageDecoding: "List[ImageDecodeAcceleratorCapability]" - """Supported accelerated image decoding capabilities.""" - class ProcessInfo(TypedDict): diff --git a/cdp_use/cdp/target/commands.py b/cdp_use/cdp/target/commands.py index 4ab7437..f20bc83 100644 --- a/cdp_use/cdp/target/commands.py +++ b/cdp_use/cdp/target/commands.py @@ -18,13 +18,11 @@ from .types import TargetInfo from .types import WindowState + class ActivateTargetParameters(TypedDict): targetId: "TargetID" - - - class AttachToTargetParameters(TypedDict): targetId: "TargetID" flatten: "NotRequired[bool]" @@ -38,13 +36,11 @@ class AttachToTargetReturns(TypedDict): """Id assigned to the session.""" - class AttachToBrowserTargetReturns(TypedDict): sessionId: "SessionID" """Id assigned to the session.""" - class CloseTargetParameters(TypedDict): targetId: "TargetID" @@ -54,7 +50,6 @@ class CloseTargetReturns(TypedDict): """Always set to true. If an error occurs, the response indicates protocol error.""" - class ExposeDevToolsProtocolParameters(TypedDict): targetId: "TargetID" bindingName: "NotRequired[str]" @@ -63,9 +58,6 @@ class ExposeDevToolsProtocolParameters(TypedDict): """If true, inherits the current root session's permissions (default: false).""" - - - class CreateBrowserContextParameters(TypedDict, total=False): disposeOnDetach: "bool" """If specified, disposes this context when debugging session disconnects.""" @@ -83,13 +75,11 @@ class CreateBrowserContextReturns(TypedDict): """The id of the context created.""" - class GetBrowserContextsReturns(TypedDict): browserContextIds: "List[BrowserContextID]" """An array of browser context ids.""" - class CreateTargetParameters(TypedDict): url: "str" """The initial URL the page will be navigated to. An empty string indicates about:blank.""" @@ -127,7 +117,6 @@ class CreateTargetReturns(TypedDict): """The id of the page opened.""" - class DetachFromTargetParameters(TypedDict, total=False): sessionId: "SessionID" """Session to detach.""" @@ -135,16 +124,10 @@ class DetachFromTargetParameters(TypedDict, total=False): """Deprecated.""" - - - class DisposeBrowserContextParameters(TypedDict): browserContextId: "BrowserContextID" - - - class GetTargetInfoParameters(TypedDict, total=False): targetId: "TargetID" @@ -153,7 +136,6 @@ class GetTargetInfoReturns(TypedDict): targetInfo: "TargetInfo" - class GetTargetsParameters(TypedDict, total=False): filter: "TargetFilter" """Only targets matching filter will be reported. If filter is not specified @@ -166,7 +148,6 @@ class GetTargetsReturns(TypedDict): """The list of targets.""" - class SendMessageToTargetParameters(TypedDict): message: "str" sessionId: "NotRequired[SessionID]" @@ -175,9 +156,6 @@ class SendMessageToTargetParameters(TypedDict): """Deprecated.""" - - - class SetAutoAttachParameters(TypedDict): autoAttach: "bool" """Whether to auto-attach to related targets.""" @@ -192,9 +170,6 @@ class SetAutoAttachParameters(TypedDict): """Only targets matching filter will be attached.""" - - - class AutoAttachRelatedParameters(TypedDict): targetId: "TargetID" waitForDebuggerOnStart: "bool" @@ -204,9 +179,6 @@ class AutoAttachRelatedParameters(TypedDict): """Only targets matching filter will be attached.""" - - - class SetDiscoverTargetsParameters(TypedDict): discover: "bool" """Whether to discover available targets.""" @@ -215,20 +187,18 @@ class SetDiscoverTargetsParameters(TypedDict): `filter` must be omitted or empty.""" - - - class SetRemoteLocationsParameters(TypedDict): locations: "List[RemoteLocation]" """List of remote locations.""" - - - class OpenDevToolsParameters(TypedDict): targetId: "TargetID" """This can be the page or tab target ID.""" + panelId: "NotRequired[str]" + """The id of the panel we want DevTools to open initially. Currently +supported panels are elements, console, network, sources, resources +and performance.""" class OpenDevToolsReturns(TypedDict): diff --git a/cdp_use/cdp/target/events.py b/cdp_use/cdp/target/events.py index 2e9a2f6..2fd913e 100644 --- a/cdp_use/cdp/target/events.py +++ b/cdp_use/cdp/target/events.py @@ -14,6 +14,8 @@ from .types import TargetInfo """Issued when attached to target because of auto-attach or `attachToTarget` command.""" + + class AttachedToTargetEvent(TypedDict): sessionId: "SessionID" """Identifier assigned to the session used to send/receive messages.""" @@ -21,9 +23,10 @@ class AttachedToTargetEvent(TypedDict): waitingForDebugger: "bool" - """Issued when detached from target for any reason (including `detachFromTarget` command). Can be issued multiple times per target if multiple sessions have been attached to it.""" + + class DetachedFromTargetEvent(TypedDict): sessionId: "SessionID" """Detached session identifier.""" @@ -31,9 +34,10 @@ class DetachedFromTargetEvent(TypedDict): """Deprecated.""" - """Notifies about a new protocol message received from the session (as reported in `attachedToTarget` event).""" + + class ReceivedMessageFromTargetEvent(TypedDict): sessionId: "SessionID" """Identifier of a session which sends a message.""" @@ -42,20 +46,23 @@ class ReceivedMessageFromTargetEvent(TypedDict): """Deprecated.""" - """Issued when a possible inspection target is created.""" + + class TargetCreatedEvent(TypedDict): targetInfo: "TargetInfo" - """Issued when a target is destroyed.""" + + class TargetDestroyedEvent(TypedDict): targetId: "TargetID" - """Issued when a target has crashed.""" + + class TargetCrashedEvent(TypedDict): targetId: "TargetID" status: "str" @@ -64,8 +71,9 @@ class TargetCrashedEvent(TypedDict): """Termination error code.""" - """Issued when some information about a target has changed. This only happens between `targetCreated` and `targetDestroyed`.""" + + class TargetInfoChangedEvent(TypedDict): targetInfo: "TargetInfo" diff --git a/cdp_use/cdp/target/library.py b/cdp_use/cdp/target/library.py index 32fbaf7..7f83ea5 100644 --- a/cdp_use/cdp/target/library.py +++ b/cdp_use/cdp/target/library.py @@ -36,10 +36,11 @@ from .commands import SetDiscoverTargetsParameters from .commands import SetRemoteLocationsParameters + class TargetClient: """Client for Target domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def activateTarget( @@ -48,11 +49,14 @@ async def activateTarget( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Activates (focuses) the target.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.activateTarget", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.activateTarget", + params=params, + session_id=session_id, + ), + ) async def attachToTarget( self, @@ -60,11 +64,14 @@ async def attachToTarget( session_id: Optional[str] = None, ) -> "AttachToTargetReturns": """Attaches to the target with given id.""" - return cast("AttachToTargetReturns", await self._client.send_raw( - method="Target.attachToTarget", - params=params, - session_id=session_id, - )) + return cast( + "AttachToTargetReturns", + await self._client.send_raw( + method="Target.attachToTarget", + params=params, + session_id=session_id, + ), + ) async def attachToBrowserTarget( self, @@ -72,11 +79,14 @@ async def attachToBrowserTarget( session_id: Optional[str] = None, ) -> "AttachToBrowserTargetReturns": """Attaches to the browser target, only uses flat sessionId mode.""" - return cast("AttachToBrowserTargetReturns", await self._client.send_raw( - method="Target.attachToBrowserTarget", - params=params, - session_id=session_id, - )) + return cast( + "AttachToBrowserTargetReturns", + await self._client.send_raw( + method="Target.attachToBrowserTarget", + params=params, + session_id=session_id, + ), + ) async def closeTarget( self, @@ -84,11 +94,14 @@ async def closeTarget( session_id: Optional[str] = None, ) -> "CloseTargetReturns": """Closes the target. If the target is a page that gets closed too.""" - return cast("CloseTargetReturns", await self._client.send_raw( - method="Target.closeTarget", - params=params, - session_id=session_id, - )) + return cast( + "CloseTargetReturns", + await self._client.send_raw( + method="Target.closeTarget", + params=params, + session_id=session_id, + ), + ) async def exposeDevToolsProtocol( self, @@ -96,18 +109,21 @@ async def exposeDevToolsProtocol( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Inject object to the target's main frame that provides a communication -channel with browser target. + channel with browser target. -Injected object will be available as `window[bindingName]`. + Injected object will be available as `window[bindingName]`. -The object has the following API: -- `binding.send(json)` - a method to send messages over the remote debugging protocol -- `binding.onmessage = json => handleMessage(json)` - a callback that will be called for the protocol notifications and command responses.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.exposeDevToolsProtocol", - params=params, - session_id=session_id, - )) + The object has the following API: + - `binding.send(json)` - a method to send messages over the remote debugging protocol + - `binding.onmessage = json => handleMessage(json)` - a callback that will be called for the protocol notifications and command responses.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.exposeDevToolsProtocol", + params=params, + session_id=session_id, + ), + ) async def createBrowserContext( self, @@ -115,12 +131,15 @@ async def createBrowserContext( session_id: Optional[str] = None, ) -> "CreateBrowserContextReturns": """Creates a new empty BrowserContext. Similar to an incognito profile but you can have more than -one.""" - return cast("CreateBrowserContextReturns", await self._client.send_raw( - method="Target.createBrowserContext", - params=params, - session_id=session_id, - )) + one.""" + return cast( + "CreateBrowserContextReturns", + await self._client.send_raw( + method="Target.createBrowserContext", + params=params, + session_id=session_id, + ), + ) async def getBrowserContexts( self, @@ -128,11 +147,14 @@ async def getBrowserContexts( session_id: Optional[str] = None, ) -> "GetBrowserContextsReturns": """Returns all browser contexts created with `Target.createBrowserContext` method.""" - return cast("GetBrowserContextsReturns", await self._client.send_raw( - method="Target.getBrowserContexts", - params=params, - session_id=session_id, - )) + return cast( + "GetBrowserContextsReturns", + await self._client.send_raw( + method="Target.getBrowserContexts", + params=params, + session_id=session_id, + ), + ) async def createTarget( self, @@ -140,11 +162,14 @@ async def createTarget( session_id: Optional[str] = None, ) -> "CreateTargetReturns": """Creates a new page.""" - return cast("CreateTargetReturns", await self._client.send_raw( - method="Target.createTarget", - params=params, - session_id=session_id, - )) + return cast( + "CreateTargetReturns", + await self._client.send_raw( + method="Target.createTarget", + params=params, + session_id=session_id, + ), + ) async def detachFromTarget( self, @@ -152,11 +177,14 @@ async def detachFromTarget( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Detaches session with given id.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.detachFromTarget", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.detachFromTarget", + params=params, + session_id=session_id, + ), + ) async def disposeBrowserContext( self, @@ -164,12 +192,15 @@ async def disposeBrowserContext( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Deletes a BrowserContext. All the belonging pages will be closed without calling their -beforeunload hooks.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.disposeBrowserContext", - params=params, - session_id=session_id, - )) + beforeunload hooks.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.disposeBrowserContext", + params=params, + session_id=session_id, + ), + ) async def getTargetInfo( self, @@ -177,11 +208,14 @@ async def getTargetInfo( session_id: Optional[str] = None, ) -> "GetTargetInfoReturns": """Returns information about a target.""" - return cast("GetTargetInfoReturns", await self._client.send_raw( - method="Target.getTargetInfo", - params=params, - session_id=session_id, - )) + return cast( + "GetTargetInfoReturns", + await self._client.send_raw( + method="Target.getTargetInfo", + params=params, + session_id=session_id, + ), + ) async def getTargets( self, @@ -189,11 +223,14 @@ async def getTargets( session_id: Optional[str] = None, ) -> "GetTargetsReturns": """Retrieves a list of available targets.""" - return cast("GetTargetsReturns", await self._client.send_raw( - method="Target.getTargets", - params=params, - session_id=session_id, - )) + return cast( + "GetTargetsReturns", + await self._client.send_raw( + method="Target.getTargets", + params=params, + session_id=session_id, + ), + ) async def sendMessageToTarget( self, @@ -201,13 +238,16 @@ async def sendMessageToTarget( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sends protocol message over session with given id. -Consider using flat mode instead; see commands attachToTarget, setAutoAttach, -and crbug.com/991325.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.sendMessageToTarget", - params=params, - session_id=session_id, - )) + Consider using flat mode instead; see commands attachToTarget, setAutoAttach, + and crbug.com/991325.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.sendMessageToTarget", + params=params, + session_id=session_id, + ), + ) async def setAutoAttach( self, @@ -215,18 +255,21 @@ async def setAutoAttach( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Controls whether to automatically attach to new targets which are considered -to be directly related to this one (for example, iframes or workers). -When turned on, attaches to all existing related targets as well. When turned off, -automatically detaches from all currently attached targets. -This also clears all targets added by `autoAttachRelated` from the list of targets to watch -for creation of related targets. -You might want to call this recursively for auto-attached targets to attach -to all available targets.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.setAutoAttach", - params=params, - session_id=session_id, - )) + to be directly related to this one (for example, iframes or workers). + When turned on, attaches to all existing related targets as well. When turned off, + automatically detaches from all currently attached targets. + This also clears all targets added by `autoAttachRelated` from the list of targets to watch + for creation of related targets. + You might want to call this recursively for auto-attached targets to attach + to all available targets.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.setAutoAttach", + params=params, + session_id=session_id, + ), + ) async def autoAttachRelated( self, @@ -234,15 +277,18 @@ async def autoAttachRelated( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Adds the specified target to the list of targets that will be monitored for any related target -creation (such as child frames, child workers and new versions of service worker) and reported -through `attachedToTarget`. The specified target is also auto-attached. -This cancels the effect of any previous `setAutoAttach` and is also cancelled by subsequent -`setAutoAttach`. Only available at the Browser target.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.autoAttachRelated", - params=params, - session_id=session_id, - )) + creation (such as child frames, child workers and new versions of service worker) and reported + through `attachedToTarget`. The specified target is also auto-attached. + This cancels the effect of any previous `setAutoAttach` and is also cancelled by subsequent + `setAutoAttach`. Only available at the Browser target.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.autoAttachRelated", + params=params, + session_id=session_id, + ), + ) async def setDiscoverTargets( self, @@ -250,12 +296,15 @@ async def setDiscoverTargets( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Controls whether to discover available targets and notify via -`targetCreated/targetInfoChanged/targetDestroyed` events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.setDiscoverTargets", - params=params, - session_id=session_id, - )) + `targetCreated/targetInfoChanged/targetDestroyed` events.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.setDiscoverTargets", + params=params, + session_id=session_id, + ), + ) async def setRemoteLocations( self, @@ -263,12 +312,15 @@ async def setRemoteLocations( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables target discovery for the specified locations, when `setDiscoverTargets` was set to -`true`.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Target.setRemoteLocations", - params=params, - session_id=session_id, - )) + `true`.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Target.setRemoteLocations", + params=params, + session_id=session_id, + ), + ) async def openDevTools( self, @@ -276,10 +328,11 @@ async def openDevTools( session_id: Optional[str] = None, ) -> "OpenDevToolsReturns": """Opens a DevTools window for the target.""" - return cast("OpenDevToolsReturns", await self._client.send_raw( - method="Target.openDevTools", - params=params, - session_id=session_id, - )) - - + return cast( + "OpenDevToolsReturns", + await self._client.send_raw( + method="Target.openDevTools", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/target/registration.py b/cdp_use/cdp/target/registration.py index 7da8f14..4f56268 100644 --- a/cdp_use/cdp/target/registration.py +++ b/cdp_use/cdp/target/registration.py @@ -11,31 +11,32 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - AttachedToTargetEvent, - DetachedFromTargetEvent, - ReceivedMessageFromTargetEvent, - TargetCrashedEvent, - TargetCreatedEvent, - TargetDestroyedEvent, - TargetInfoChangedEvent -) + AttachedToTargetEvent, + DetachedFromTargetEvent, + ReceivedMessageFromTargetEvent, + TargetCrashedEvent, + TargetCreatedEvent, + TargetDestroyedEvent, + TargetInfoChangedEvent, + ) + class TargetRegistration: """Event registration interface for Target domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Target" def attachedToTarget( self, - callback: Callable[['AttachedToTargetEvent', Optional[str]], None], + callback: Callable[["AttachedToTargetEvent", Optional[str]], None], ) -> None: """ Register a callback for attachedToTarget events. - + Issued when attached to target because of auto-attach or `attachToTarget` command. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -44,45 +45,45 @@ def attachedToTarget( def detachedFromTarget( self, - callback: Callable[['DetachedFromTargetEvent', Optional[str]], None], + callback: Callable[["DetachedFromTargetEvent", Optional[str]], None], ) -> None: """ - Register a callback for detachedFromTarget events. - - Issued when detached from target for any reason (including `detachFromTarget` command). Can be -issued multiple times per target if multiple sessions have been attached to it. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for detachedFromTarget events. + + Issued when detached from target for any reason (including `detachFromTarget` command). Can be + issued multiple times per target if multiple sessions have been attached to it. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Target.detachedFromTarget", callback) def receivedMessageFromTarget( self, - callback: Callable[['ReceivedMessageFromTargetEvent', Optional[str]], None], + callback: Callable[["ReceivedMessageFromTargetEvent", Optional[str]], None], ) -> None: """ - Register a callback for receivedMessageFromTarget events. - - Notifies about a new protocol message received from the session (as reported in -`attachedToTarget` event). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for receivedMessageFromTarget events. + + Notifies about a new protocol message received from the session (as reported in + `attachedToTarget` event). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Target.receivedMessageFromTarget", callback) def targetCreated( self, - callback: Callable[['TargetCreatedEvent', Optional[str]], None], + callback: Callable[["TargetCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for targetCreated events. - + Issued when a possible inspection target is created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -91,13 +92,13 @@ def targetCreated( def targetDestroyed( self, - callback: Callable[['TargetDestroyedEvent', Optional[str]], None], + callback: Callable[["TargetDestroyedEvent", Optional[str]], None], ) -> None: """ Register a callback for targetDestroyed events. - + Issued when a target is destroyed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -106,13 +107,13 @@ def targetDestroyed( def targetCrashed( self, - callback: Callable[['TargetCrashedEvent', Optional[str]], None], + callback: Callable[["TargetCrashedEvent", Optional[str]], None], ) -> None: """ Register a callback for targetCrashed events. - + Issued when a target has crashed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -121,17 +122,16 @@ def targetCrashed( def targetInfoChanged( self, - callback: Callable[['TargetInfoChangedEvent', Optional[str]], None], + callback: Callable[["TargetInfoChangedEvent", Optional[str]], None], ) -> None: """ - Register a callback for targetInfoChanged events. - - Issued when some information about a target has changed. This only happens between -`targetCreated` and `targetDestroyed`. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for targetInfoChanged events. + + Issued when some information about a target has changed. This only happens between + `targetCreated` and `targetDestroyed`. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Target.targetInfoChanged", callback) - diff --git a/cdp_use/cdp/target/types.py b/cdp_use/cdp/target/types.py index 54fb5dd..a92fd5a 100644 --- a/cdp_use/cdp/target/types.py +++ b/cdp_use/cdp/target/types.py @@ -17,12 +17,10 @@ TargetID = str - SessionID = str """Unique identifier of attached debugging session.""" - class TargetInfo(TypedDict): targetId: "TargetID" type: "str" @@ -45,7 +43,6 @@ class TargetInfo(TypedDict): the type of \"page\", this may be set to \"prerender\".""" - class FilterEntry(TypedDict, total=False): """A filter used by target query/discovery/auto-attach operations.""" @@ -55,7 +52,6 @@ class FilterEntry(TypedDict, total=False): """If not present, matches any type.""" - TargetFilter = List[FilterEntry] """The entries in TargetFilter are matched sequentially against targets and the first entry that matches determines if the target is included or not, @@ -65,12 +61,10 @@ class FilterEntry(TypedDict, total=False): (i.e. include everything but `browser` and `tab`).""" - class RemoteLocation(TypedDict): host: "str" port: "int" - WindowState = Literal["normal", "minimized", "maximized", "fullscreen"] """The state of the target window.""" diff --git a/cdp_use/cdp/tethering/commands.py b/cdp_use/cdp/tethering/commands.py index e96c2dd..42e94c7 100644 --- a/cdp_use/cdp/tethering/commands.py +++ b/cdp_use/cdp/tethering/commands.py @@ -6,16 +6,12 @@ from typing_extensions import TypedDict + class BindParameters(TypedDict): port: "int" """Port number to bind.""" - - - class UnbindParameters(TypedDict): port: "int" """Port number to unbind.""" - - diff --git a/cdp_use/cdp/tethering/events.py b/cdp_use/cdp/tethering/events.py index a2c8f24..3a1d2c7 100644 --- a/cdp_use/cdp/tethering/events.py +++ b/cdp_use/cdp/tethering/events.py @@ -7,6 +7,8 @@ from typing_extensions import TypedDict """Informs that port was successfully bound and got a specified connection id.""" + + class AcceptedEvent(TypedDict): port: "int" """Port number that was successfully bound.""" diff --git a/cdp_use/cdp/tethering/library.py b/cdp_use/cdp/tethering/library.py index 72ded2c..87c8a79 100644 --- a/cdp_use/cdp/tethering/library.py +++ b/cdp_use/cdp/tethering/library.py @@ -13,10 +13,11 @@ from .commands import BindParameters from .commands import UnbindParameters + class TetheringClient: """Client for Tethering domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def bind( @@ -25,11 +26,14 @@ async def bind( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Request browser port binding.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Tethering.bind", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Tethering.bind", + params=params, + session_id=session_id, + ), + ) async def unbind( self, @@ -37,10 +41,11 @@ async def unbind( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Request browser port unbinding.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Tethering.unbind", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Tethering.unbind", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/tethering/registration.py b/cdp_use/cdp/tethering/registration.py index a4d8bcc..41c0dfd 100644 --- a/cdp_use/cdp/tethering/registration.py +++ b/cdp_use/cdp/tethering/registration.py @@ -12,25 +12,25 @@ from ..registry import EventRegistry from .events import AcceptedEvent + class TetheringRegistration: """Event registration interface for Tethering domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Tethering" def accepted( self, - callback: Callable[['AcceptedEvent', Optional[str]], None], + callback: Callable[["AcceptedEvent", Optional[str]], None], ) -> None: """ Register a callback for accepted events. - + Informs that port was successfully bound and got a specified connection id. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("Tethering.accepted", callback) - diff --git a/cdp_use/cdp/tethering/types.py b/cdp_use/cdp/tethering/types.py index 22a4638..84bcb5d 100644 --- a/cdp_use/cdp/tethering/types.py +++ b/cdp_use/cdp/tethering/types.py @@ -5,4 +5,4 @@ """CDP Tethering Domain Types""" -# No types defined for this domain \ No newline at end of file +# No types defined for this domain diff --git a/cdp_use/cdp/tracing/commands.py b/cdp_use/cdp/tracing/commands.py index 2186d22..ac88059 100644 --- a/cdp_use/cdp/tracing/commands.py +++ b/cdp_use/cdp/tracing/commands.py @@ -16,20 +16,17 @@ from .types import TraceConfig from .types import TracingBackend + class GetCategoriesReturns(TypedDict): categories: "List[str]" """A list of supported tracing categories.""" - class RecordClockSyncMarkerParameters(TypedDict): syncId: "str" """The ID of this clock sync marker""" - - - class RequestMemoryDumpParameters(TypedDict, total=False): deterministic: "bool" """Enables more deterministic results by forcing garbage collection""" @@ -44,7 +41,6 @@ class RequestMemoryDumpReturns(TypedDict): """True iff the global memory dump succeeded.""" - class StartParameters(TypedDict, total=False): categories: "str" """Category/tag filter""" @@ -68,5 +64,3 @@ class StartParameters(TypedDict, total=False): are ignored. (Encoded as a base64 string when passed over JSON)""" tracingBackend: "TracingBackend" """Backend type (defaults to `auto`)""" - - diff --git a/cdp_use/cdp/tracing/events.py b/cdp_use/cdp/tracing/events.py index 349a92c..76e0bed 100644 --- a/cdp_use/cdp/tracing/events.py +++ b/cdp_use/cdp/tracing/events.py @@ -14,6 +14,7 @@ from .types import StreamCompression from .types import StreamFormat + class BufferUsageEvent(TypedDict, total=False): percentFull: "float" """A number in range [0..1] that indicates the used size of event buffer as a fraction of its @@ -25,16 +26,18 @@ class BufferUsageEvent(TypedDict, total=False): total size.""" - """Contains a bucket of collected trace events. When tracing is stopped collected events will be sent as a sequence of dataCollected events followed by tracingComplete event.""" + + class DataCollectedEvent(TypedDict): value: "List[Dict[str, Any]]" - """Signals that tracing is stopped and there is no trace buffers pending flush, all data were delivered via dataCollected events.""" + + class TracingCompleteEvent(TypedDict): dataLossOccurred: "bool" """Indicates whether some trace data is known to have been lost, e.g. because the trace ring diff --git a/cdp_use/cdp/tracing/library.py b/cdp_use/cdp/tracing/library.py index 1a3d4c3..2dcf196 100644 --- a/cdp_use/cdp/tracing/library.py +++ b/cdp_use/cdp/tracing/library.py @@ -16,10 +16,11 @@ from .commands import RequestMemoryDumpReturns from .commands import StartParameters + class TracingClient: """Client for Tracing domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def end( @@ -28,11 +29,14 @@ async def end( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Stop trace events collection.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Tracing.end", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Tracing.end", + params=params, + session_id=session_id, + ), + ) async def getCategories( self, @@ -40,11 +44,14 @@ async def getCategories( session_id: Optional[str] = None, ) -> "GetCategoriesReturns": """Gets supported tracing categories.""" - return cast("GetCategoriesReturns", await self._client.send_raw( - method="Tracing.getCategories", - params=params, - session_id=session_id, - )) + return cast( + "GetCategoriesReturns", + await self._client.send_raw( + method="Tracing.getCategories", + params=params, + session_id=session_id, + ), + ) async def recordClockSyncMarker( self, @@ -52,11 +59,14 @@ async def recordClockSyncMarker( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Record a clock sync marker in the trace.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Tracing.recordClockSyncMarker", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Tracing.recordClockSyncMarker", + params=params, + session_id=session_id, + ), + ) async def requestMemoryDump( self, @@ -64,11 +74,14 @@ async def requestMemoryDump( session_id: Optional[str] = None, ) -> "RequestMemoryDumpReturns": """Request a global memory dump.""" - return cast("RequestMemoryDumpReturns", await self._client.send_raw( - method="Tracing.requestMemoryDump", - params=params, - session_id=session_id, - )) + return cast( + "RequestMemoryDumpReturns", + await self._client.send_raw( + method="Tracing.requestMemoryDump", + params=params, + session_id=session_id, + ), + ) async def start( self, @@ -76,10 +89,11 @@ async def start( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Start trace events collection.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="Tracing.start", - params=params, - session_id=session_id, - )) - - + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="Tracing.start", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/tracing/registration.py b/cdp_use/cdp/tracing/registration.py index 9dda31b..8fed51a 100644 --- a/cdp_use/cdp/tracing/registration.py +++ b/cdp_use/cdp/tracing/registration.py @@ -12,20 +12,21 @@ from ..registry import EventRegistry from .events import BufferUsageEvent, DataCollectedEvent, TracingCompleteEvent + class TracingRegistration: """Event registration interface for Tracing domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "Tracing" def bufferUsage( self, - callback: Callable[['BufferUsageEvent', Optional[str]], None], + callback: Callable[["BufferUsageEvent", Optional[str]], None], ) -> None: """ Register a callback for bufferUsage events. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -34,33 +35,32 @@ def bufferUsage( def dataCollected( self, - callback: Callable[['DataCollectedEvent', Optional[str]], None], + callback: Callable[["DataCollectedEvent", Optional[str]], None], ) -> None: """ - Register a callback for dataCollected events. - - Contains a bucket of collected trace events. When tracing is stopped collected events will be -sent as a sequence of dataCollected events followed by tracingComplete event. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for dataCollected events. + + Contains a bucket of collected trace events. When tracing is stopped collected events will be + sent as a sequence of dataCollected events followed by tracingComplete event. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Tracing.dataCollected", callback) def tracingComplete( self, - callback: Callable[['TracingCompleteEvent', Optional[str]], None], + callback: Callable[["TracingCompleteEvent", Optional[str]], None], ) -> None: """ - Register a callback for tracingComplete events. - - Signals that tracing is stopped and there is no trace buffers pending flush, all data were -delivered via dataCollected events. - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for tracingComplete events. + + Signals that tracing is stopped and there is no trace buffers pending flush, all data were + delivered via dataCollected events. + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("Tracing.tracingComplete", callback) - diff --git a/cdp_use/cdp/tracing/types.py b/cdp_use/cdp/tracing/types.py index 7f2fa3b..7ddf3e2 100644 --- a/cdp_use/cdp/tracing/types.py +++ b/cdp_use/cdp/tracing/types.py @@ -8,11 +8,11 @@ from typing_extensions import Literal from typing_extensions import TypedDict + class MemoryDumpConfig(TypedDict): """Configuration for memory dump. Used only when \"memory-infra\" category is enabled.""" - class TraceConfig(TypedDict, total=False): recordMode: "str" """Controls how the trace buffer stores data. The default is `recordUntilFull`.""" @@ -35,25 +35,21 @@ class TraceConfig(TypedDict, total=False): """Configuration for memory dump triggers. Used only when \"memory-infra\" category is enabled.""" - StreamFormat = Literal["json", "proto"] """Data format of a trace. Can be either the legacy JSON format or the protocol buffer format. Note that the JSON format will be deprecated soon.""" - StreamCompression = Literal["none", "gzip"] """Compression type to use for traces returned via streams.""" - MemoryDumpLevelOfDetail = Literal["background", "light", "detailed"] """Details exposed when memory request explicitly declared. Keep consistent with memory_dump_request_args.h and memory_instrumentation.mojom""" - TracingBackend = Literal["auto", "chrome", "system"] """Backend type to use for tracing. `chrome` uses the Chrome-integrated tracing service and is supported on all platforms. `system` is only diff --git a/cdp_use/cdp/webaudio/commands.py b/cdp_use/cdp/webaudio/commands.py index d4f60ef..114c0bf 100644 --- a/cdp_use/cdp/webaudio/commands.py +++ b/cdp_use/cdp/webaudio/commands.py @@ -12,6 +12,7 @@ from .types import ContextRealtimeData from .types import GraphObjectId + class GetRealtimeDataParameters(TypedDict): contextId: "GraphObjectId" diff --git a/cdp_use/cdp/webaudio/events.py b/cdp_use/cdp/webaudio/events.py index dc0e5d0..d86e811 100644 --- a/cdp_use/cdp/webaudio/events.py +++ b/cdp_use/cdp/webaudio/events.py @@ -16,64 +16,75 @@ from .types import GraphObjectId """Notifies that a new BaseAudioContext has been created.""" + + class ContextCreatedEvent(TypedDict): context: "BaseAudioContext" - """Notifies that an existing BaseAudioContext will be destroyed.""" + + class ContextWillBeDestroyedEvent(TypedDict): contextId: "GraphObjectId" - """Notifies that existing BaseAudioContext has changed some properties (id stays the same)..""" + + class ContextChangedEvent(TypedDict): context: "BaseAudioContext" - """Notifies that the construction of an AudioListener has finished.""" + + class AudioListenerCreatedEvent(TypedDict): listener: "AudioListener" - """Notifies that a new AudioListener has been created.""" + + class AudioListenerWillBeDestroyedEvent(TypedDict): contextId: "GraphObjectId" listenerId: "GraphObjectId" - """Notifies that a new AudioNode has been created.""" + + class AudioNodeCreatedEvent(TypedDict): node: "AudioNode" - """Notifies that an existing AudioNode has been destroyed.""" + + class AudioNodeWillBeDestroyedEvent(TypedDict): contextId: "GraphObjectId" nodeId: "GraphObjectId" - """Notifies that a new AudioParam has been created.""" + + class AudioParamCreatedEvent(TypedDict): param: "AudioParam" - """Notifies that an existing AudioParam has been destroyed.""" + + class AudioParamWillBeDestroyedEvent(TypedDict): contextId: "GraphObjectId" nodeId: "GraphObjectId" paramId: "GraphObjectId" - """Notifies that two AudioNodes are connected.""" + + class NodesConnectedEvent(TypedDict): contextId: "GraphObjectId" sourceId: "GraphObjectId" @@ -82,8 +93,9 @@ class NodesConnectedEvent(TypedDict): destinationInputIndex: "NotRequired[float]" - """Notifies that AudioNodes are disconnected. The destination can be null, and it means all the outgoing connections from the source are disconnected.""" + + class NodesDisconnectedEvent(TypedDict): contextId: "GraphObjectId" sourceId: "GraphObjectId" @@ -92,8 +104,9 @@ class NodesDisconnectedEvent(TypedDict): destinationInputIndex: "NotRequired[float]" - """Notifies that an AudioNode is connected to an AudioParam.""" + + class NodeParamConnectedEvent(TypedDict): contextId: "GraphObjectId" sourceId: "GraphObjectId" @@ -101,8 +114,9 @@ class NodeParamConnectedEvent(TypedDict): sourceOutputIndex: "NotRequired[float]" - """Notifies that an AudioNode is disconnected to an AudioParam.""" + + class NodeParamDisconnectedEvent(TypedDict): contextId: "GraphObjectId" sourceId: "GraphObjectId" diff --git a/cdp_use/cdp/webaudio/library.py b/cdp_use/cdp/webaudio/library.py index 57fea1c..c51a5ca 100644 --- a/cdp_use/cdp/webaudio/library.py +++ b/cdp_use/cdp/webaudio/library.py @@ -13,10 +13,11 @@ from .commands import GetRealtimeDataParameters from .commands import GetRealtimeDataReturns + class WebAudioClient: """Client for WebAudio domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -25,11 +26,14 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enables the WebAudio domain and starts sending context lifetime events.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAudio.enable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAudio.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -37,11 +41,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disables the WebAudio domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAudio.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAudio.disable", + params=params, + session_id=session_id, + ), + ) async def getRealtimeData( self, @@ -49,10 +56,11 @@ async def getRealtimeData( session_id: Optional[str] = None, ) -> "GetRealtimeDataReturns": """Fetch the realtime data from the registered contexts.""" - return cast("GetRealtimeDataReturns", await self._client.send_raw( - method="WebAudio.getRealtimeData", - params=params, - session_id=session_id, - )) - - + return cast( + "GetRealtimeDataReturns", + await self._client.send_raw( + method="WebAudio.getRealtimeData", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/webaudio/registration.py b/cdp_use/cdp/webaudio/registration.py index edc498f..717ebd9 100644 --- a/cdp_use/cdp/webaudio/registration.py +++ b/cdp_use/cdp/webaudio/registration.py @@ -11,37 +11,38 @@ if TYPE_CHECKING: from ..registry import EventRegistry from .events import ( - AudioListenerCreatedEvent, - AudioListenerWillBeDestroyedEvent, - AudioNodeCreatedEvent, - AudioNodeWillBeDestroyedEvent, - AudioParamCreatedEvent, - AudioParamWillBeDestroyedEvent, - ContextChangedEvent, - ContextCreatedEvent, - ContextWillBeDestroyedEvent, - NodeParamConnectedEvent, - NodeParamDisconnectedEvent, - NodesConnectedEvent, - NodesDisconnectedEvent -) + AudioListenerCreatedEvent, + AudioListenerWillBeDestroyedEvent, + AudioNodeCreatedEvent, + AudioNodeWillBeDestroyedEvent, + AudioParamCreatedEvent, + AudioParamWillBeDestroyedEvent, + ContextChangedEvent, + ContextCreatedEvent, + ContextWillBeDestroyedEvent, + NodeParamConnectedEvent, + NodeParamDisconnectedEvent, + NodesConnectedEvent, + NodesDisconnectedEvent, + ) + class WebAudioRegistration: """Event registration interface for WebAudio domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "WebAudio" def contextCreated( self, - callback: Callable[['ContextCreatedEvent', Optional[str]], None], + callback: Callable[["ContextCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for contextCreated events. - + Notifies that a new BaseAudioContext has been created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -50,13 +51,13 @@ def contextCreated( def contextWillBeDestroyed( self, - callback: Callable[['ContextWillBeDestroyedEvent', Optional[str]], None], + callback: Callable[["ContextWillBeDestroyedEvent", Optional[str]], None], ) -> None: """ Register a callback for contextWillBeDestroyed events. - + Notifies that an existing BaseAudioContext will be destroyed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -65,13 +66,13 @@ def contextWillBeDestroyed( def contextChanged( self, - callback: Callable[['ContextChangedEvent', Optional[str]], None], + callback: Callable[["ContextChangedEvent", Optional[str]], None], ) -> None: """ Register a callback for contextChanged events. - + Notifies that existing BaseAudioContext has changed some properties (id stays the same).. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -80,13 +81,13 @@ def contextChanged( def audioListenerCreated( self, - callback: Callable[['AudioListenerCreatedEvent', Optional[str]], None], + callback: Callable[["AudioListenerCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for audioListenerCreated events. - + Notifies that the construction of an AudioListener has finished. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -95,13 +96,13 @@ def audioListenerCreated( def audioListenerWillBeDestroyed( self, - callback: Callable[['AudioListenerWillBeDestroyedEvent', Optional[str]], None], + callback: Callable[["AudioListenerWillBeDestroyedEvent", Optional[str]], None], ) -> None: """ Register a callback for audioListenerWillBeDestroyed events. - + Notifies that a new AudioListener has been created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -110,13 +111,13 @@ def audioListenerWillBeDestroyed( def audioNodeCreated( self, - callback: Callable[['AudioNodeCreatedEvent', Optional[str]], None], + callback: Callable[["AudioNodeCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for audioNodeCreated events. - + Notifies that a new AudioNode has been created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -125,13 +126,13 @@ def audioNodeCreated( def audioNodeWillBeDestroyed( self, - callback: Callable[['AudioNodeWillBeDestroyedEvent', Optional[str]], None], + callback: Callable[["AudioNodeWillBeDestroyedEvent", Optional[str]], None], ) -> None: """ Register a callback for audioNodeWillBeDestroyed events. - + Notifies that an existing AudioNode has been destroyed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -140,13 +141,13 @@ def audioNodeWillBeDestroyed( def audioParamCreated( self, - callback: Callable[['AudioParamCreatedEvent', Optional[str]], None], + callback: Callable[["AudioParamCreatedEvent", Optional[str]], None], ) -> None: """ Register a callback for audioParamCreated events. - + Notifies that a new AudioParam has been created. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -155,13 +156,13 @@ def audioParamCreated( def audioParamWillBeDestroyed( self, - callback: Callable[['AudioParamWillBeDestroyedEvent', Optional[str]], None], + callback: Callable[["AudioParamWillBeDestroyedEvent", Optional[str]], None], ) -> None: """ Register a callback for audioParamWillBeDestroyed events. - + Notifies that an existing AudioParam has been destroyed. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -170,13 +171,13 @@ def audioParamWillBeDestroyed( def nodesConnected( self, - callback: Callable[['NodesConnectedEvent', Optional[str]], None], + callback: Callable[["NodesConnectedEvent", Optional[str]], None], ) -> None: """ Register a callback for nodesConnected events. - + Notifies that two AudioNodes are connected. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -185,13 +186,13 @@ def nodesConnected( def nodesDisconnected( self, - callback: Callable[['NodesDisconnectedEvent', Optional[str]], None], + callback: Callable[["NodesDisconnectedEvent", Optional[str]], None], ) -> None: """ Register a callback for nodesDisconnected events. - + Notifies that AudioNodes are disconnected. The destination can be null, and it means all the outgoing connections from the source are disconnected. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -200,13 +201,13 @@ def nodesDisconnected( def nodeParamConnected( self, - callback: Callable[['NodeParamConnectedEvent', Optional[str]], None], + callback: Callable[["NodeParamConnectedEvent", Optional[str]], None], ) -> None: """ Register a callback for nodeParamConnected events. - + Notifies that an AudioNode is connected to an AudioParam. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -215,16 +216,15 @@ def nodeParamConnected( def nodeParamDisconnected( self, - callback: Callable[['NodeParamDisconnectedEvent', Optional[str]], None], + callback: Callable[["NodeParamDisconnectedEvent", Optional[str]], None], ) -> None: """ Register a callback for nodeParamDisconnected events. - + Notifies that an AudioNode is disconnected to an AudioParam. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("WebAudio.nodeParamDisconnected", callback) - diff --git a/cdp_use/cdp/webaudio/types.py b/cdp_use/cdp/webaudio/types.py index 54bcb81..ad0158e 100644 --- a/cdp_use/cdp/webaudio/types.py +++ b/cdp_use/cdp/webaudio/types.py @@ -11,42 +11,34 @@ """An unique ID for a graph object (AudioContext, AudioNode, AudioParam) in Web Audio API""" - ContextType = Literal["realtime", "offline"] """Enum of BaseAudioContext types""" - ContextState = Literal["suspended", "running", "closed", "interrupted"] """Enum of AudioContextState from the spec""" - NodeType = str """Enum of AudioNode types""" - ChannelCountMode = Literal["clamped-max", "explicit", "max"] """Enum of AudioNode::ChannelCountMode from the spec""" - ChannelInterpretation = Literal["discrete", "speakers"] """Enum of AudioNode::ChannelInterpretation from the spec""" - ParamType = str """Enum of AudioParam types""" - AutomationRate = Literal["a-rate", "k-rate"] """Enum of AudioParam::AutomationRate from the spec""" - class ContextRealtimeData(TypedDict): """Fields in AudioContext that change in real-time.""" @@ -62,7 +54,6 @@ class ContextRealtimeData(TypedDict): """A running variance of callback interval.""" - class BaseAudioContext(TypedDict): """Protocol object for BaseAudioContext""" @@ -78,7 +69,6 @@ class BaseAudioContext(TypedDict): """Context sample rate.""" - class AudioListener(TypedDict): """Protocol object for AudioListener""" @@ -86,7 +76,6 @@ class AudioListener(TypedDict): contextId: "GraphObjectId" - class AudioNode(TypedDict): """Protocol object for AudioNode""" @@ -100,7 +89,6 @@ class AudioNode(TypedDict): channelInterpretation: "ChannelInterpretation" - class AudioParam(TypedDict): """Protocol object for AudioParam""" diff --git a/cdp_use/cdp/webauthn/commands.py b/cdp_use/cdp/webauthn/commands.py index 9a46f2a..75f955b 100644 --- a/cdp_use/cdp/webauthn/commands.py +++ b/cdp_use/cdp/webauthn/commands.py @@ -14,6 +14,7 @@ from .types import Credential from .types import VirtualAuthenticatorOptions + class EnableParameters(TypedDict, total=False): enableUI: "bool" """Whether to enable the WebAuthn user interface. Enabling the UI is @@ -23,9 +24,6 @@ class EnableParameters(TypedDict, total=False): Defaults to false.""" - - - class AddVirtualAuthenticatorParameters(TypedDict): options: "VirtualAuthenticatorOptions" @@ -34,7 +32,6 @@ class AddVirtualAuthenticatorReturns(TypedDict): authenticatorId: "AuthenticatorId" - class SetResponseOverrideBitsParameters(TypedDict): authenticatorId: "AuthenticatorId" isBogusSignature: "NotRequired[bool]" @@ -48,24 +45,15 @@ class SetResponseOverrideBitsParameters(TypedDict): be zero. Defaults to false.""" - - - class RemoveVirtualAuthenticatorParameters(TypedDict): authenticatorId: "AuthenticatorId" - - - class AddCredentialParameters(TypedDict): authenticatorId: "AuthenticatorId" credential: "Credential" - - - class GetCredentialParameters(TypedDict): authenticatorId: "AuthenticatorId" credentialId: "str" @@ -75,7 +63,6 @@ class GetCredentialReturns(TypedDict): credential: "Credential" - class GetCredentialsParameters(TypedDict): authenticatorId: "AuthenticatorId" @@ -84,42 +71,27 @@ class GetCredentialsReturns(TypedDict): credentials: "List[Credential]" - class RemoveCredentialParameters(TypedDict): authenticatorId: "AuthenticatorId" credentialId: "str" - - - class ClearCredentialsParameters(TypedDict): authenticatorId: "AuthenticatorId" - - - class SetUserVerifiedParameters(TypedDict): authenticatorId: "AuthenticatorId" isUserVerified: "bool" - - - class SetAutomaticPresenceSimulationParameters(TypedDict): authenticatorId: "AuthenticatorId" enabled: "bool" - - - class SetCredentialPropertiesParameters(TypedDict): authenticatorId: "AuthenticatorId" credentialId: "str" backupEligibility: "NotRequired[bool]" backupState: "NotRequired[bool]" - - diff --git a/cdp_use/cdp/webauthn/events.py b/cdp_use/cdp/webauthn/events.py index f1e366f..9b996dd 100644 --- a/cdp_use/cdp/webauthn/events.py +++ b/cdp_use/cdp/webauthn/events.py @@ -13,29 +13,34 @@ from .types import Credential """Triggered when a credential is added to an authenticator.""" + + class CredentialAddedEvent(TypedDict): authenticatorId: "AuthenticatorId" credential: "Credential" - """Triggered when a credential is deleted, e.g. through PublicKeyCredential.signalUnknownCredential().""" + + class CredentialDeletedEvent(TypedDict): authenticatorId: "AuthenticatorId" credentialId: "str" - """Triggered when a credential is updated, e.g. through PublicKeyCredential.signalCurrentUserDetails().""" + + class CredentialUpdatedEvent(TypedDict): authenticatorId: "AuthenticatorId" credential: "Credential" - """Triggered when a credential is used in a webauthn assertion.""" + + class CredentialAssertedEvent(TypedDict): authenticatorId: "AuthenticatorId" credential: "Credential" diff --git a/cdp_use/cdp/webauthn/library.py b/cdp_use/cdp/webauthn/library.py index b1328f9..494cbbe 100644 --- a/cdp_use/cdp/webauthn/library.py +++ b/cdp_use/cdp/webauthn/library.py @@ -26,10 +26,11 @@ from .commands import SetResponseOverrideBitsParameters from .commands import SetUserVerifiedParameters + class WebAuthnClient: """Client for WebAuthn domain commands.""" - def __init__(self, client: 'CDPClient'): + def __init__(self, client: "CDPClient"): self._client = client async def enable( @@ -38,12 +39,15 @@ async def enable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Enable the WebAuthn domain and start intercepting credential storage and -retrieval with a virtual authenticator.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.enable", - params=params, - session_id=session_id, - )) + retrieval with a virtual authenticator.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.enable", + params=params, + session_id=session_id, + ), + ) async def disable( self, @@ -51,11 +55,14 @@ async def disable( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Disable the WebAuthn domain.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.disable", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.disable", + params=params, + session_id=session_id, + ), + ) async def addVirtualAuthenticator( self, @@ -63,11 +70,14 @@ async def addVirtualAuthenticator( session_id: Optional[str] = None, ) -> "AddVirtualAuthenticatorReturns": """Creates and adds a virtual authenticator.""" - return cast("AddVirtualAuthenticatorReturns", await self._client.send_raw( - method="WebAuthn.addVirtualAuthenticator", - params=params, - session_id=session_id, - )) + return cast( + "AddVirtualAuthenticatorReturns", + await self._client.send_raw( + method="WebAuthn.addVirtualAuthenticator", + params=params, + session_id=session_id, + ), + ) async def setResponseOverrideBits( self, @@ -75,11 +85,14 @@ async def setResponseOverrideBits( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Resets parameters isBogusSignature, isBadUV, isBadUP to false if they are not present.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.setResponseOverrideBits", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.setResponseOverrideBits", + params=params, + session_id=session_id, + ), + ) async def removeVirtualAuthenticator( self, @@ -87,11 +100,14 @@ async def removeVirtualAuthenticator( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes the given authenticator.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.removeVirtualAuthenticator", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.removeVirtualAuthenticator", + params=params, + session_id=session_id, + ), + ) async def addCredential( self, @@ -99,11 +115,14 @@ async def addCredential( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Adds the credential to the specified authenticator.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.addCredential", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.addCredential", + params=params, + session_id=session_id, + ), + ) async def getCredential( self, @@ -111,12 +130,15 @@ async def getCredential( session_id: Optional[str] = None, ) -> "GetCredentialReturns": """Returns a single credential stored in the given virtual authenticator that -matches the credential ID.""" - return cast("GetCredentialReturns", await self._client.send_raw( - method="WebAuthn.getCredential", - params=params, - session_id=session_id, - )) + matches the credential ID.""" + return cast( + "GetCredentialReturns", + await self._client.send_raw( + method="WebAuthn.getCredential", + params=params, + session_id=session_id, + ), + ) async def getCredentials( self, @@ -124,11 +146,14 @@ async def getCredentials( session_id: Optional[str] = None, ) -> "GetCredentialsReturns": """Returns all the credentials stored in the given virtual authenticator.""" - return cast("GetCredentialsReturns", await self._client.send_raw( - method="WebAuthn.getCredentials", - params=params, - session_id=session_id, - )) + return cast( + "GetCredentialsReturns", + await self._client.send_raw( + method="WebAuthn.getCredentials", + params=params, + session_id=session_id, + ), + ) async def removeCredential( self, @@ -136,11 +161,14 @@ async def removeCredential( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Removes a credential from the authenticator.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.removeCredential", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.removeCredential", + params=params, + session_id=session_id, + ), + ) async def clearCredentials( self, @@ -148,11 +176,14 @@ async def clearCredentials( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Clears all the credentials from the specified device.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.clearCredentials", - params=params, - session_id=session_id, - )) + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.clearCredentials", + params=params, + session_id=session_id, + ), + ) async def setUserVerified( self, @@ -160,12 +191,15 @@ async def setUserVerified( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets whether User Verification succeeds or fails for an authenticator. -The default is true.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.setUserVerified", - params=params, - session_id=session_id, - )) + The default is true.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.setUserVerified", + params=params, + session_id=session_id, + ), + ) async def setAutomaticPresenceSimulation( self, @@ -173,12 +207,15 @@ async def setAutomaticPresenceSimulation( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Sets whether tests of user presence will succeed immediately (if true) or fail to resolve (if false) for an authenticator. -The default is true.""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.setAutomaticPresenceSimulation", - params=params, - session_id=session_id, - )) + The default is true.""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.setAutomaticPresenceSimulation", + params=params, + session_id=session_id, + ), + ) async def setCredentialProperties( self, @@ -186,11 +223,12 @@ async def setCredentialProperties( session_id: Optional[str] = None, ) -> "Dict[str, Any]": """Allows setting credential properties. -https://w3c.github.io/webauthn/#sctn-automation-set-credential-properties""" - return cast("Dict[str, Any]", await self._client.send_raw( - method="WebAuthn.setCredentialProperties", - params=params, - session_id=session_id, - )) - - + https://w3c.github.io/webauthn/#sctn-automation-set-credential-properties""" + return cast( + "Dict[str, Any]", + await self._client.send_raw( + method="WebAuthn.setCredentialProperties", + params=params, + session_id=session_id, + ), + ) diff --git a/cdp_use/cdp/webauthn/registration.py b/cdp_use/cdp/webauthn/registration.py index 22c0d7a..c71c775 100644 --- a/cdp_use/cdp/webauthn/registration.py +++ b/cdp_use/cdp/webauthn/registration.py @@ -10,24 +10,30 @@ if TYPE_CHECKING: from ..registry import EventRegistry - from .events import CredentialAddedEvent, CredentialAssertedEvent, CredentialDeletedEvent, CredentialUpdatedEvent + from .events import ( + CredentialAddedEvent, + CredentialAssertedEvent, + CredentialDeletedEvent, + CredentialUpdatedEvent, + ) + class WebAuthnRegistration: """Event registration interface for WebAuthn domain.""" - def __init__(self, registry: 'EventRegistry'): + def __init__(self, registry: "EventRegistry"): self._registry = registry self._domain = "WebAuthn" def credentialAdded( self, - callback: Callable[['CredentialAddedEvent', Optional[str]], None], + callback: Callable[["CredentialAddedEvent", Optional[str]], None], ) -> None: """ Register a callback for credentialAdded events. - + Triggered when a credential is added to an authenticator. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. @@ -36,48 +42,47 @@ def credentialAdded( def credentialDeleted( self, - callback: Callable[['CredentialDeletedEvent', Optional[str]], None], + callback: Callable[["CredentialDeletedEvent", Optional[str]], None], ) -> None: """ - Register a callback for credentialDeleted events. - - Triggered when a credential is deleted, e.g. through -PublicKeyCredential.signalUnknownCredential(). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for credentialDeleted events. + + Triggered when a credential is deleted, e.g. through + PublicKeyCredential.signalUnknownCredential(). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("WebAuthn.credentialDeleted", callback) def credentialUpdated( self, - callback: Callable[['CredentialUpdatedEvent', Optional[str]], None], + callback: Callable[["CredentialUpdatedEvent", Optional[str]], None], ) -> None: """ - Register a callback for credentialUpdated events. - - Triggered when a credential is updated, e.g. through -PublicKeyCredential.signalCurrentUserDetails(). - - Args: - callback: Function to call when event occurs. - Receives (event_data, session_id) as parameters. + Register a callback for credentialUpdated events. + + Triggered when a credential is updated, e.g. through + PublicKeyCredential.signalCurrentUserDetails(). + + Args: + callback: Function to call when event occurs. + Receives (event_data, session_id) as parameters. """ self._registry.register("WebAuthn.credentialUpdated", callback) def credentialAsserted( self, - callback: Callable[['CredentialAssertedEvent', Optional[str]], None], + callback: Callable[["CredentialAssertedEvent", Optional[str]], None], ) -> None: """ Register a callback for credentialAsserted events. - + Triggered when a credential is used in a webauthn assertion. - + Args: callback: Function to call when event occurs. Receives (event_data, session_id) as parameters. """ self._registry.register("WebAuthn.credentialAsserted", callback) - diff --git a/cdp_use/cdp/webauthn/types.py b/cdp_use/cdp/webauthn/types.py index 941665b..d2cdfc0 100644 --- a/cdp_use/cdp/webauthn/types.py +++ b/cdp_use/cdp/webauthn/types.py @@ -10,19 +10,15 @@ AuthenticatorId = str - AuthenticatorProtocol = Literal["u2f", "ctap2"] - Ctap2Version = Literal["ctap2_0", "ctap2_1"] - AuthenticatorTransport = Literal["usb", "nfc", "ble", "cable", "internal"] - class VirtualAuthenticatorOptions(TypedDict): protocol: "AuthenticatorProtocol" ctap2Version: "NotRequired[Ctap2Version]" @@ -64,7 +60,6 @@ class VirtualAuthenticatorOptions(TypedDict): https://w3c.github.io/webauthn/#sctn-credential-backup""" - class Credential(TypedDict): credentialId: "str" isResidentCredential: "bool" diff --git a/cdp_use/custom_protocols/browseruse.json b/cdp_use/custom_protocols/browseruse.json index 4c17209..727016f 100644 --- a/cdp_use/custom_protocols/browseruse.json +++ b/cdp_use/custom_protocols/browseruse.json @@ -48,9 +48,16 @@ }, { "name": "eventTimeout", "type": "number", "optional": true } ] + }, + { + "name": "activeTargetChanged", + "description": "Fired when a target is activated via Target.activateTarget.", + "parameters": [ + { "name": "targetId", "$ref": "Target.TargetID" }, + { "name": "eventTimeout", "type": "number", "optional": true } + ] } ] } ] } - diff --git a/cdp_use/generator/generator.py b/cdp_use/generator/generator.py index 0477b22..997c24e 100644 --- a/cdp_use/generator/generator.py +++ b/cdp_use/generator/generator.py @@ -188,7 +188,11 @@ def generate_event_registry(self, domains: List[Dict[str, Any]]) -> None: def generate_main_registration_library(self, domains: List[Dict[str, Any]]) -> None: """Generate the main registration library file.""" - content = self.registration_library_generator.generate_main_registration_library(domains) + content = ( + self.registration_library_generator.generate_main_registration_library( + domains + ) + ) self.write_file(self.output_dir / "registration_library.py", content) def generate_domain_init(self, domain: Dict[str, Any]) -> str: diff --git a/cdp_use/generator/registration_generator.py b/cdp_use/generator/registration_generator.py index f3b05f9..0ffb78f 100644 --- a/cdp_use/generator/registration_generator.py +++ b/cdp_use/generator/registration_generator.py @@ -4,7 +4,6 @@ Generates type-safe event registration interfaces for CDP domains. """ -import re from typing import Any, Dict, List @@ -126,23 +125,23 @@ def generate_event_registration_method( description = event.get("description", "") if description: escaped_desc = description.replace("\\", "\\\\").replace('"', '\\"') - content += f' """\n' + content += ' """\n' content += f" Register a callback for {event_name} events.\n" - content += f" \n" + content += " \n" content += f" {escaped_desc}\n" - content += f" \n" - content += f" Args:\n" - content += f" callback: Function to call when event occurs.\n" - content += f" Receives (event_data, session_id) as parameters.\n" - content += f' """\n' + content += " \n" + content += " Args:\n" + content += " callback: Function to call when event occurs.\n" + content += " Receives (event_data, session_id) as parameters.\n" + content += ' """\n' else: - content += f' """\n' + content += ' """\n' content += f" Register a callback for {event_name} events.\n" - content += f" \n" - content += f" Args:\n" - content += f" callback: Function to call when event occurs.\n" - content += f" Receives (event_data, session_id) as parameters.\n" - content += f' """\n' + content += " \n" + content += " Args:\n" + content += " callback: Function to call when event occurs.\n" + content += " Receives (event_data, session_id) as parameters.\n" + content += ' """\n' content += f' self._registry.register("{cdp_method_name}", callback)\n' diff --git a/cdp_use/generator/registration_library_generator.py b/cdp_use/generator/registration_library_generator.py index a0b1dfa..d0fe32e 100644 --- a/cdp_use/generator/registration_library_generator.py +++ b/cdp_use/generator/registration_library_generator.py @@ -23,7 +23,7 @@ def generate_main_registration_library(self, domains: List[Dict[str, Any]]) -> s domain_name = domain["domain"] domain_lower = domain_name.lower() registration_class_name = f"{domain_name}Registration" - + # Only include domains that have events events = domain.get("events", []) if events: @@ -74,11 +74,11 @@ def build_main_registration_library_file(self) -> str: registration_class_name = domain_info["class_name"] content += f"\n # {domain_name} domain registration\n" + content += f" from .{domain_lower}.registration import {registration_class_name}\n" content += ( - f" from .{domain_lower}.registration import {registration_class_name}\n" + f" self.{domain_name} = {registration_class_name}(registry)\n" ) - content += f" self.{domain_name} = {registration_class_name}(registry)\n" content += "\n" - return content \ No newline at end of file + return content diff --git a/pyproject.toml b/pyproject.toml index e5aece2..b7df35e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,25 +4,26 @@ version = "1.4.0" description = "Type safe generator/client library for CDP" readme = "README.md" requires-python = ">=3.11" -dependencies = [ - "httpx>=0.28.1", - "websockets>=15.0.1", -] +dependencies = ["httpx>=0.28.1", "websockets>=15.0.1"] [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [dependency-groups] -dev = [ - "build>=1.2.2.post1", - "ruff>=0.12.2", -] +dev = ["build>=1.2.2.post1", "ruff>=0.12.2"] [tool.hatch.build] -include = [ - "cdp_use/**/*.py" -] -exclude = [ - "cdp_use/generator/*.py" -] +include = ["cdp_use/**/*.py"] +exclude = ["cdp_use/generator/*.py"] + +[tool.ruff] +exclude = [".git", "__pycache__", "dist", "build"] + +[tool.ruff.lint] +# Ignore wildcard imports (F403) and redefinition (F811) in generated code +ignore = [] + +[tool.ruff.lint.per-file-ignores] +# Generated CDP code uses wildcard imports by design +"cdp_use/cdp/**/*.py" = ["F403", "F811"] From 1d1898c678b51199edf55f661be4643057b1f38e Mon Sep 17 00:00:00 2001 From: reformedot Date: Wed, 26 Nov 2025 11:25:00 -0800 Subject: [PATCH 3/5] feat: add format-json task and update JSON protocol files for consistency --- README.md | 1 + Taskfile.yml | 8 +++++ cdp_use/custom_protocols/browseruse.json | 38 +++++++++++++++++++----- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8e202d3..34bf7e1 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,7 @@ task generate # Regenerate CDP types from protocol definitions task build # Build the distribution package task lint # Run ruff linter task format # Format code with ruff +task format-json # Format JSON protocol files task example # Run the simple example task clean # Clean generated files and build artifacts ``` diff --git a/Taskfile.yml b/Taskfile.yml index 2697557..42905cf 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -26,6 +26,14 @@ tasks: cmds: - uv run ruff format cdp_use/ + format-json: + desc: "Format JSON protocol files" + cmds: + - | + for file in cdp_use/custom_protocols/*.json; do + python3 -m json.tool "$file" "$file.tmp" && mv "$file.tmp" "$file" + done + example: desc: "Run the simple example" cmds: diff --git a/cdp_use/custom_protocols/browseruse.json b/cdp_use/custom_protocols/browseruse.json index 727016f..d0c42e8 100644 --- a/cdp_use/custom_protocols/browseruse.json +++ b/cdp_use/custom_protocols/browseruse.json @@ -10,7 +10,10 @@ "name": "captchaSolverStarted", "description": "Captcha solving started.", "parameters": [ - { "name": "targetId", "$ref": "Target.TargetID" }, + { + "name": "targetId", + "$ref": "Target.TargetID" + }, { "name": "vendor", "type": "string" @@ -24,14 +27,21 @@ "type": "integer", "description": "Unix millis" }, - { "name": "eventTimeout", "type": "number", "optional": true } + { + "name": "eventTimeout", + "type": "number", + "optional": true + } ] }, { "name": "captchaSolverFinished", "description": "Captcha solving finished.", "parameters": [ - { "name": "targetId", "$ref": "Target.TargetID" }, + { + "name": "targetId", + "$ref": "Target.TargetID" + }, { "name": "vendor", "type": "string" @@ -40,21 +50,35 @@ "name": "url", "type": "string" }, - { "name": "durationMs", "type": "integer" }, + { + "name": "durationMs", + "type": "integer" + }, { "name": "finishedAt", "type": "integer", "description": "Unix millis" }, - { "name": "eventTimeout", "type": "number", "optional": true } + { + "name": "eventTimeout", + "type": "number", + "optional": true + } ] }, { "name": "activeTargetChanged", "description": "Fired when a target is activated via Target.activateTarget.", "parameters": [ - { "name": "targetId", "$ref": "Target.TargetID" }, - { "name": "eventTimeout", "type": "number", "optional": true } + { + "name": "targetId", + "$ref": "Target.TargetID" + }, + { + "name": "eventTimeout", + "type": "number", + "optional": true + } ] } ] From b3ee5c0af1b82013fa7d82bd912fd359e1fa1d74 Mon Sep 17 00:00:00 2001 From: reformedot Date: Wed, 26 Nov 2025 11:41:13 -0800 Subject: [PATCH 4/5] fix: add file existence check in JSON formatting task to prevent errors --- Taskfile.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/Taskfile.yml b/Taskfile.yml index 42905cf..dd4ead9 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -31,6 +31,7 @@ tasks: cmds: - | for file in cdp_use/custom_protocols/*.json; do + [ -f "$file" ] || continue python3 -m json.tool "$file" "$file.tmp" && mv "$file.tmp" "$file" done From f99397fa29964bcc5f47df0ba897758e41c8dbc1 Mon Sep 17 00:00:00 2001 From: reformedot Date: Wed, 26 Nov 2025 12:13:07 -0800 Subject: [PATCH 5/5] docs: add version pinning instructions to README for CDP specification --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 34bf7e1..443b87f 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,20 @@ This will: 3. Create domain-specific client classes 4. Format the code +### Version Pinning + +By default, the generator downloads the latest CDP specification from the master branch. To pin a specific version, edit `cdp_use/generator/constants.py`: + +```python +# Pin to a specific commit +CDP_VERSION = "4b0c3f2e8c5d6a7b9e1f2a3c4d5e6f7a8b9c0d1e" + +# Or use master for latest +CDP_VERSION = "refs/heads/master" +``` + +To find specific commits, visit: https://github.com/ChromeDevTools/devtools-protocol/commits/master + ### Available Tasks ```bash