Source code for nodriver.cdp.network

# DO NOT EDIT THIS FILE!
#
# This file is generated from the CDP specification. If you need to make
# changes, edit the generator and regenerate all of the modules.
#
# CDP domain: Network

from __future__ import annotations
import enum
import typing
from dataclasses import dataclass
from .util import event_class, T_JSON_DICT

from . import debugger
from . import emulation
from . import io
from . import page
from . import runtime
from . import security
from deprecated.sphinx import deprecated  # type: ignore


[docs] class ResourceType(enum.Enum): """ Resource type as it was perceived by the rendering engine. """ DOCUMENT = "Document" STYLESHEET = "Stylesheet" IMAGE = "Image" MEDIA = "Media" FONT = "Font" SCRIPT = "Script" TEXT_TRACK = "TextTrack" XHR = "XHR" FETCH = "Fetch" PREFETCH = "Prefetch" EVENT_SOURCE = "EventSource" WEB_SOCKET = "WebSocket" MANIFEST = "Manifest" SIGNED_EXCHANGE = "SignedExchange" PING = "Ping" CSP_VIOLATION_REPORT = "CSPViolationReport" PREFLIGHT = "Preflight" OTHER = "Other" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ResourceType: return cls(json)
[docs] class LoaderId(str): """ Unique loader identifier. """ def to_json(self) -> str: return self @classmethod def from_json(cls, json: str) -> LoaderId: return cls(json) def __repr__(self): return "LoaderId({})".format(super().__repr__())
[docs] class RequestId(str): """ Unique request identifier. """ def to_json(self) -> str: return self @classmethod def from_json(cls, json: str) -> RequestId: return cls(json) def __repr__(self): return "RequestId({})".format(super().__repr__())
[docs] class InterceptionId(str): """ Unique intercepted request identifier. """ def to_json(self) -> str: return self @classmethod def from_json(cls, json: str) -> InterceptionId: return cls(json) def __repr__(self): return "InterceptionId({})".format(super().__repr__())
[docs] class ErrorReason(enum.Enum): """ Network level fetch failure reason. """ FAILED = "Failed" ABORTED = "Aborted" TIMED_OUT = "TimedOut" ACCESS_DENIED = "AccessDenied" CONNECTION_CLOSED = "ConnectionClosed" CONNECTION_RESET = "ConnectionReset" CONNECTION_REFUSED = "ConnectionRefused" CONNECTION_ABORTED = "ConnectionAborted" CONNECTION_FAILED = "ConnectionFailed" NAME_NOT_RESOLVED = "NameNotResolved" INTERNET_DISCONNECTED = "InternetDisconnected" ADDRESS_UNREACHABLE = "AddressUnreachable" BLOCKED_BY_CLIENT = "BlockedByClient" BLOCKED_BY_RESPONSE = "BlockedByResponse" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ErrorReason: return cls(json)
[docs] class TimeSinceEpoch(float): """ UTC time in seconds, counted from January 1, 1970. """ def to_json(self) -> float: return self @classmethod def from_json(cls, json: float) -> TimeSinceEpoch: return cls(json) def __repr__(self): return "TimeSinceEpoch({})".format(super().__repr__())
[docs] class MonotonicTime(float): """ Monotonically increasing time in seconds since an arbitrary point in the past. """ def to_json(self) -> float: return self @classmethod def from_json(cls, json: float) -> MonotonicTime: return cls(json) def __repr__(self): return "MonotonicTime({})".format(super().__repr__())
[docs] class Headers(dict): """ Request / response headers as keys / values of JSON object. """ def to_json(self) -> dict: return self @classmethod def from_json(cls, json: dict) -> Headers: return cls(json) def __repr__(self): return "Headers({})".format(super().__repr__())
[docs] class ConnectionType(enum.Enum): """ The underlying connection technology that the browser is supposedly using. """ NONE = "none" CELLULAR2G = "cellular2g" CELLULAR3G = "cellular3g" CELLULAR4G = "cellular4g" BLUETOOTH = "bluetooth" ETHERNET = "ethernet" WIFI = "wifi" WIMAX = "wimax" OTHER = "other" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ConnectionType: return cls(json)
[docs] class CookieSameSite(enum.Enum): """ Represents the cookie's 'SameSite' status: https://tools.ietf.org/html/draft-west-first-party-cookies """ STRICT = "Strict" LAX = "Lax" NONE = "None" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CookieSameSite: return cls(json)
[docs] class CookiePriority(enum.Enum): """ Represents the cookie's 'Priority' status: https://tools.ietf.org/html/draft-west-cookie-priority-00 """ LOW = "Low" MEDIUM = "Medium" HIGH = "High" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CookiePriority: return cls(json)
[docs] class CookieSourceScheme(enum.Enum): """ 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. """ UNSET = "Unset" NON_SECURE = "NonSecure" SECURE = "Secure" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CookieSourceScheme: return cls(json)
[docs] @dataclass class ResourceTiming: """ Timing information for the request. """ #: Timing's requestTime is a baseline in seconds, while the other numbers are ticks in #: milliseconds relatively to this requestTime. request_time: float #: Started resolving proxy. proxy_start: float #: Finished resolving proxy. proxy_end: float #: Started DNS address resolve. dns_start: float #: Finished DNS address resolve. dns_end: float #: Started connecting to the remote host. connect_start: float #: Connected to the remote host. connect_end: float #: Started SSL handshake. ssl_start: float #: Finished SSL handshake. ssl_end: float #: Started running ServiceWorker. worker_start: float #: Finished Starting ServiceWorker. worker_ready: float #: Started fetch event. worker_fetch_start: float #: Settled fetch event respondWith promise. worker_respond_with_settled: float #: Started sending request. send_start: float #: Finished sending request. send_end: float #: Time the server started pushing request. push_start: float #: Time the server finished pushing request. push_end: float #: Started receiving response headers. receive_headers_start: float #: Finished receiving response headers. receive_headers_end: float #: Started ServiceWorker static routing source evaluation. worker_router_evaluation_start: typing.Optional[float] = None #: Started cache lookup when the source was evaluated to ``cache``. worker_cache_lookup_start: typing.Optional[float] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["requestTime"] = self.request_time json["proxyStart"] = self.proxy_start json["proxyEnd"] = self.proxy_end json["dnsStart"] = self.dns_start json["dnsEnd"] = self.dns_end json["connectStart"] = self.connect_start json["connectEnd"] = self.connect_end json["sslStart"] = self.ssl_start json["sslEnd"] = self.ssl_end json["workerStart"] = self.worker_start json["workerReady"] = self.worker_ready json["workerFetchStart"] = self.worker_fetch_start json["workerRespondWithSettled"] = self.worker_respond_with_settled json["sendStart"] = self.send_start json["sendEnd"] = self.send_end json["pushStart"] = self.push_start json["pushEnd"] = self.push_end json["receiveHeadersStart"] = self.receive_headers_start json["receiveHeadersEnd"] = self.receive_headers_end if self.worker_router_evaluation_start is not None: json["workerRouterEvaluationStart"] = self.worker_router_evaluation_start if self.worker_cache_lookup_start is not None: json["workerCacheLookupStart"] = self.worker_cache_lookup_start return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ResourceTiming: return cls( request_time=float(json["requestTime"]), proxy_start=float(json["proxyStart"]), proxy_end=float(json["proxyEnd"]), dns_start=float(json["dnsStart"]), dns_end=float(json["dnsEnd"]), connect_start=float(json["connectStart"]), connect_end=float(json["connectEnd"]), ssl_start=float(json["sslStart"]), ssl_end=float(json["sslEnd"]), worker_start=float(json["workerStart"]), worker_ready=float(json["workerReady"]), worker_fetch_start=float(json["workerFetchStart"]), worker_respond_with_settled=float(json["workerRespondWithSettled"]), send_start=float(json["sendStart"]), send_end=float(json["sendEnd"]), push_start=float(json["pushStart"]), push_end=float(json["pushEnd"]), receive_headers_start=float(json["receiveHeadersStart"]), receive_headers_end=float(json["receiveHeadersEnd"]), worker_router_evaluation_start=( float(json["workerRouterEvaluationStart"]) if json.get("workerRouterEvaluationStart", None) is not None else None ), worker_cache_lookup_start=( float(json["workerCacheLookupStart"]) if json.get("workerCacheLookupStart", None) is not None else None ), )
[docs] class ResourcePriority(enum.Enum): """ Loading priority of a resource request. """ VERY_LOW = "VeryLow" LOW = "Low" MEDIUM = "Medium" HIGH = "High" VERY_HIGH = "VeryHigh" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ResourcePriority: return cls(json)
[docs] @dataclass class PostDataEntry: """ Post data entry for HTTP request """ bytes_: typing.Optional[str] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() if self.bytes_ is not None: json["bytes"] = self.bytes_ return json @classmethod def from_json(cls, json: T_JSON_DICT) -> PostDataEntry: return cls( bytes_=str(json["bytes"]) if json.get("bytes", None) is not None else None, )
[docs] @dataclass class Request: """ HTTP request data. """ #: Request URL (without fragment). url: str #: HTTP request method. method: str #: HTTP request headers. headers: Headers #: Priority of the resource request at the time request is sent. initial_priority: ResourcePriority #: The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/ referrer_policy: str #: Fragment of the requested URL starting with hash, if present. url_fragment: typing.Optional[str] = None #: HTTP POST request data. #: Use postDataEntries instead. post_data: typing.Optional[str] = None #: True when the request has POST data. Note that postData might still be omitted when this flag is true when the data is too long. has_post_data: typing.Optional[bool] = None #: Request body elements (post data broken into individual entries). post_data_entries: typing.Optional[typing.List[PostDataEntry]] = None #: The mixed content type of the request. mixed_content_type: typing.Optional[security.MixedContentType] = None #: Whether is loaded via link preload. is_link_preload: typing.Optional[bool] = None #: Set for requests when the TrustToken API is used. Contains the parameters #: passed by the developer (e.g. via "fetch") as understood by the backend. trust_token_params: typing.Optional[TrustTokenParams] = None #: True if this resource request is considered to be the 'same site' as the #: request corresponding to the main frame. is_same_site: typing.Optional[bool] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["url"] = self.url json["method"] = self.method json["headers"] = self.headers.to_json() json["initialPriority"] = self.initial_priority.to_json() json["referrerPolicy"] = self.referrer_policy if self.url_fragment is not None: json["urlFragment"] = self.url_fragment if self.post_data is not None: json["postData"] = self.post_data if self.has_post_data is not None: json["hasPostData"] = self.has_post_data if self.post_data_entries is not None: json["postDataEntries"] = [i.to_json() for i in self.post_data_entries] if self.mixed_content_type is not None: json["mixedContentType"] = self.mixed_content_type.to_json() if self.is_link_preload is not None: json["isLinkPreload"] = self.is_link_preload if self.trust_token_params is not None: json["trustTokenParams"] = self.trust_token_params.to_json() if self.is_same_site is not None: json["isSameSite"] = self.is_same_site return json @classmethod def from_json(cls, json: T_JSON_DICT) -> Request: return cls( url=str(json["url"]), method=str(json["method"]), headers=Headers.from_json(json["headers"]), initial_priority=ResourcePriority.from_json(json["initialPriority"]), referrer_policy=str(json["referrerPolicy"]), url_fragment=( str(json["urlFragment"]) if json.get("urlFragment", None) is not None else None ), post_data=( str(json["postData"]) if json.get("postData", None) is not None else None ), has_post_data=( bool(json["hasPostData"]) if json.get("hasPostData", None) is not None else None ), post_data_entries=( [PostDataEntry.from_json(i) for i in json["postDataEntries"]] if json.get("postDataEntries", None) is not None else None ), mixed_content_type=( security.MixedContentType.from_json(json["mixedContentType"]) if json.get("mixedContentType", None) is not None else None ), is_link_preload=( bool(json["isLinkPreload"]) if json.get("isLinkPreload", None) is not None else None ), trust_token_params=( TrustTokenParams.from_json(json["trustTokenParams"]) if json.get("trustTokenParams", None) is not None else None ), is_same_site=( bool(json["isSameSite"]) if json.get("isSameSite", None) is not None else None ), )
[docs] @dataclass class SignedCertificateTimestamp: """ Details of a signed certificate timestamp (SCT). """ #: Validation status. status: str #: Origin. origin: str #: Log name / description. log_description: str #: Log ID. log_id: str #: Issuance date. Unlike TimeSinceEpoch, this contains the number of #: milliseconds since January 1, 1970, UTC, not the number of seconds. timestamp: float #: Hash algorithm. hash_algorithm: str #: Signature algorithm. signature_algorithm: str #: Signature data. signature_data: str def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["status"] = self.status json["origin"] = self.origin json["logDescription"] = self.log_description json["logId"] = self.log_id json["timestamp"] = self.timestamp json["hashAlgorithm"] = self.hash_algorithm json["signatureAlgorithm"] = self.signature_algorithm json["signatureData"] = self.signature_data return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SignedCertificateTimestamp: return cls( status=str(json["status"]), origin=str(json["origin"]), log_description=str(json["logDescription"]), log_id=str(json["logId"]), timestamp=float(json["timestamp"]), hash_algorithm=str(json["hashAlgorithm"]), signature_algorithm=str(json["signatureAlgorithm"]), signature_data=str(json["signatureData"]), )
[docs] @dataclass class SecurityDetails: """ Security details about a request. """ #: Protocol name (e.g. "TLS 1.2" or "QUIC"). protocol: str #: Key Exchange used by the connection, or the empty string if not applicable. key_exchange: str #: Cipher name. cipher: str #: Certificate ID value. certificate_id: security.CertificateId #: Certificate subject name. subject_name: str #: Subject Alternative Name (SAN) DNS names and IP addresses. san_list: typing.List[str] #: Name of the issuing CA. issuer: str #: Certificate valid from date. valid_from: TimeSinceEpoch #: Certificate valid to (expiration) date valid_to: TimeSinceEpoch #: List of signed certificate timestamps (SCTs). signed_certificate_timestamp_list: typing.List[SignedCertificateTimestamp] #: Whether the request complied with Certificate Transparency policy certificate_transparency_compliance: CertificateTransparencyCompliance #: Whether the connection used Encrypted ClientHello encrypted_client_hello: bool #: (EC)DH group used by the connection, if applicable. key_exchange_group: typing.Optional[str] = None #: TLS MAC. Note that AEAD ciphers do not have separate MACs. mac: typing.Optional[str] = None #: The signature algorithm used by the server in the TLS server signature, #: represented as a TLS SignatureScheme code point. Omitted if not #: applicable or not known. server_signature_algorithm: typing.Optional[int] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["protocol"] = self.protocol json["keyExchange"] = self.key_exchange json["cipher"] = self.cipher json["certificateId"] = self.certificate_id.to_json() json["subjectName"] = self.subject_name json["sanList"] = [i for i in self.san_list] json["issuer"] = self.issuer json["validFrom"] = self.valid_from.to_json() json["validTo"] = self.valid_to.to_json() json["signedCertificateTimestampList"] = [ i.to_json() for i in self.signed_certificate_timestamp_list ] json["certificateTransparencyCompliance"] = ( self.certificate_transparency_compliance.to_json() ) json["encryptedClientHello"] = self.encrypted_client_hello if self.key_exchange_group is not None: json["keyExchangeGroup"] = self.key_exchange_group if self.mac is not None: json["mac"] = self.mac if self.server_signature_algorithm is not None: json["serverSignatureAlgorithm"] = self.server_signature_algorithm return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SecurityDetails: return cls( protocol=str(json["protocol"]), key_exchange=str(json["keyExchange"]), cipher=str(json["cipher"]), certificate_id=security.CertificateId.from_json(json["certificateId"]), subject_name=str(json["subjectName"]), san_list=[str(i) for i in json["sanList"]], issuer=str(json["issuer"]), valid_from=TimeSinceEpoch.from_json(json["validFrom"]), valid_to=TimeSinceEpoch.from_json(json["validTo"]), signed_certificate_timestamp_list=[ SignedCertificateTimestamp.from_json(i) for i in json["signedCertificateTimestampList"] ], certificate_transparency_compliance=CertificateTransparencyCompliance.from_json( json["certificateTransparencyCompliance"] ), encrypted_client_hello=bool(json["encryptedClientHello"]), key_exchange_group=( str(json["keyExchangeGroup"]) if json.get("keyExchangeGroup", None) is not None else None ), mac=str(json["mac"]) if json.get("mac", None) is not None else None, server_signature_algorithm=( int(json["serverSignatureAlgorithm"]) if json.get("serverSignatureAlgorithm", None) is not None else None ), )
[docs] class CertificateTransparencyCompliance(enum.Enum): """ Whether the request complied with Certificate Transparency policy. """ UNKNOWN = "unknown" NOT_COMPLIANT = "not-compliant" COMPLIANT = "compliant" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CertificateTransparencyCompliance: return cls(json)
[docs] class BlockedReason(enum.Enum): """ The reason why request was blocked. """ OTHER = "other" CSP = "csp" MIXED_CONTENT = "mixed-content" ORIGIN = "origin" INSPECTOR = "inspector" SUBRESOURCE_FILTER = "subresource-filter" CONTENT_TYPE = "content-type" COEP_FRAME_RESOURCE_NEEDS_COEP_HEADER = "coep-frame-resource-needs-coep-header" COOP_SANDBOXED_IFRAME_CANNOT_NAVIGATE_TO_COOP_PAGE = ( "coop-sandboxed-iframe-cannot-navigate-to-coop-page" ) CORP_NOT_SAME_ORIGIN = "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-coep" ) CORP_NOT_SAME_ORIGIN_AFTER_DEFAULTED_TO_SAME_ORIGIN_BY_DIP = ( "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-origin-after-defaulted-to-same-origin-by-coep-and-dip" ) CORP_NOT_SAME_SITE = "corp-not-same-site" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> BlockedReason: return cls(json)
[docs] class CorsError(enum.Enum): """ The reason why request was blocked. """ DISALLOWED_BY_MODE = "DisallowedByMode" INVALID_RESPONSE = "InvalidResponse" WILDCARD_ORIGIN_NOT_ALLOWED = "WildcardOriginNotAllowed" MISSING_ALLOW_ORIGIN_HEADER = "MissingAllowOriginHeader" MULTIPLE_ALLOW_ORIGIN_VALUES = "MultipleAllowOriginValues" INVALID_ALLOW_ORIGIN_VALUE = "InvalidAllowOriginValue" ALLOW_ORIGIN_MISMATCH = "AllowOriginMismatch" INVALID_ALLOW_CREDENTIALS = "InvalidAllowCredentials" CORS_DISABLED_SCHEME = "CorsDisabledScheme" PREFLIGHT_INVALID_STATUS = "PreflightInvalidStatus" PREFLIGHT_DISALLOWED_REDIRECT = "PreflightDisallowedRedirect" PREFLIGHT_WILDCARD_ORIGIN_NOT_ALLOWED = "PreflightWildcardOriginNotAllowed" PREFLIGHT_MISSING_ALLOW_ORIGIN_HEADER = "PreflightMissingAllowOriginHeader" PREFLIGHT_MULTIPLE_ALLOW_ORIGIN_VALUES = "PreflightMultipleAllowOriginValues" PREFLIGHT_INVALID_ALLOW_ORIGIN_VALUE = "PreflightInvalidAllowOriginValue" PREFLIGHT_ALLOW_ORIGIN_MISMATCH = "PreflightAllowOriginMismatch" PREFLIGHT_INVALID_ALLOW_CREDENTIALS = "PreflightInvalidAllowCredentials" PREFLIGHT_MISSING_ALLOW_EXTERNAL = "PreflightMissingAllowExternal" PREFLIGHT_INVALID_ALLOW_EXTERNAL = "PreflightInvalidAllowExternal" PREFLIGHT_MISSING_ALLOW_PRIVATE_NETWORK = "PreflightMissingAllowPrivateNetwork" PREFLIGHT_INVALID_ALLOW_PRIVATE_NETWORK = "PreflightInvalidAllowPrivateNetwork" INVALID_ALLOW_METHODS_PREFLIGHT_RESPONSE = "InvalidAllowMethodsPreflightResponse" INVALID_ALLOW_HEADERS_PREFLIGHT_RESPONSE = "InvalidAllowHeadersPreflightResponse" METHOD_DISALLOWED_BY_PREFLIGHT_RESPONSE = "MethodDisallowedByPreflightResponse" HEADER_DISALLOWED_BY_PREFLIGHT_RESPONSE = "HeaderDisallowedByPreflightResponse" REDIRECT_CONTAINS_CREDENTIALS = "RedirectContainsCredentials" INSECURE_PRIVATE_NETWORK = "InsecurePrivateNetwork" INVALID_PRIVATE_NETWORK_ACCESS = "InvalidPrivateNetworkAccess" UNEXPECTED_PRIVATE_NETWORK_ACCESS = "UnexpectedPrivateNetworkAccess" NO_CORS_REDIRECT_MODE_NOT_FOLLOW = "NoCorsRedirectModeNotFollow" PREFLIGHT_MISSING_PRIVATE_NETWORK_ACCESS_ID = ( "PreflightMissingPrivateNetworkAccessId" ) PREFLIGHT_MISSING_PRIVATE_NETWORK_ACCESS_NAME = ( "PreflightMissingPrivateNetworkAccessName" ) PRIVATE_NETWORK_ACCESS_PERMISSION_UNAVAILABLE = ( "PrivateNetworkAccessPermissionUnavailable" ) PRIVATE_NETWORK_ACCESS_PERMISSION_DENIED = "PrivateNetworkAccessPermissionDenied" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CorsError: return cls(json)
[docs] @dataclass class CorsErrorStatus: cors_error: CorsError failed_parameter: str def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["corsError"] = self.cors_error.to_json() json["failedParameter"] = self.failed_parameter return json @classmethod def from_json(cls, json: T_JSON_DICT) -> CorsErrorStatus: return cls( cors_error=CorsError.from_json(json["corsError"]), failed_parameter=str(json["failedParameter"]), )
[docs] class ServiceWorkerResponseSource(enum.Enum): """ Source of serviceworker response. """ CACHE_STORAGE = "cache-storage" HTTP_CACHE = "http-cache" FALLBACK_CODE = "fallback-code" NETWORK = "network" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ServiceWorkerResponseSource: return cls(json)
[docs] @dataclass class TrustTokenParams: """ 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. """ operation: TrustTokenOperationType #: Only set for "token-redemption" operation and determine whether #: to request a fresh SRR or use a still valid cached SRR. refresh_policy: str #: Origins of issuers from whom to request tokens or redemption #: records. issuers: typing.Optional[typing.List[str]] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["operation"] = self.operation.to_json() json["refreshPolicy"] = self.refresh_policy if self.issuers is not None: json["issuers"] = [i for i in self.issuers] return json @classmethod def from_json(cls, json: T_JSON_DICT) -> TrustTokenParams: return cls( operation=TrustTokenOperationType.from_json(json["operation"]), refresh_policy=str(json["refreshPolicy"]), issuers=( [str(i) for i in json["issuers"]] if json.get("issuers", None) is not None else None ), )
[docs] class TrustTokenOperationType(enum.Enum): ISSUANCE = "Issuance" REDEMPTION = "Redemption" SIGNING = "Signing" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> TrustTokenOperationType: return cls(json)
[docs] class AlternateProtocolUsage(enum.Enum): """ The reason why Chrome uses a specific transport protocol for HTTP semantics. """ ALTERNATIVE_JOB_WON_WITHOUT_RACE = "alternativeJobWonWithoutRace" ALTERNATIVE_JOB_WON_RACE = "alternativeJobWonRace" MAIN_JOB_WON_RACE = "mainJobWonRace" MAPPING_MISSING = "mappingMissing" BROKEN = "broken" DNS_ALPN_H3_JOB_WON_WITHOUT_RACE = "dnsAlpnH3JobWonWithoutRace" DNS_ALPN_H3_JOB_WON_RACE = "dnsAlpnH3JobWonRace" UNSPECIFIED_REASON = "unspecifiedReason" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> AlternateProtocolUsage: return cls(json)
[docs] class ServiceWorkerRouterSource(enum.Enum): """ Source of service worker router. """ NETWORK = "network" CACHE = "cache" FETCH_EVENT = "fetch-event" RACE_NETWORK_AND_FETCH_HANDLER = "race-network-and-fetch-handler" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ServiceWorkerRouterSource: return cls(json)
[docs] @dataclass class ServiceWorkerRouterInfo: #: ID of the rule matched. If there is a matched rule, this field will #: be set, otherwiser no value will be set. rule_id_matched: typing.Optional[int] = None #: The router source of the matched rule. If there is a matched rule, this #: field will be set, otherwise no value will be set. matched_source_type: typing.Optional[ServiceWorkerRouterSource] = None #: The actual router source used. actual_source_type: typing.Optional[ServiceWorkerRouterSource] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() if self.rule_id_matched is not None: json["ruleIdMatched"] = self.rule_id_matched if self.matched_source_type is not None: json["matchedSourceType"] = self.matched_source_type.to_json() if self.actual_source_type is not None: json["actualSourceType"] = self.actual_source_type.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ServiceWorkerRouterInfo: return cls( rule_id_matched=( int(json["ruleIdMatched"]) if json.get("ruleIdMatched", None) is not None else None ), matched_source_type=( ServiceWorkerRouterSource.from_json(json["matchedSourceType"]) if json.get("matchedSourceType", None) is not None else None ), actual_source_type=( ServiceWorkerRouterSource.from_json(json["actualSourceType"]) if json.get("actualSourceType", None) is not None else None ), )
[docs] @dataclass class Response: """ HTTP response data. """ #: Response URL. This URL can be different from CachedResource.url in case of redirect. url: str #: HTTP response status code. status: int #: HTTP response status text. status_text: str #: HTTP response headers. headers: Headers #: Resource mimeType as determined by the browser. mime_type: str #: Resource charset as determined by the browser (if applicable). charset: str #: Specifies whether physical connection was actually reused for this request. connection_reused: bool #: Physical connection id that was actually used for this request. connection_id: float #: Total number of bytes received for this request so far. encoded_data_length: float #: Security state of the request resource. security_state: security.SecurityState #: HTTP response headers text. This has been replaced by the headers in Network.responseReceivedExtraInfo. headers_text: typing.Optional[str] = None #: Refined HTTP request headers that were actually transmitted over the network. request_headers: typing.Optional[Headers] = None #: HTTP request headers text. This has been replaced by the headers in Network.requestWillBeSentExtraInfo. request_headers_text: typing.Optional[str] = None #: Remote IP address. remote_ip_address: typing.Optional[str] = None #: Remote port. remote_port: typing.Optional[int] = None #: Specifies that the request was served from the disk cache. from_disk_cache: typing.Optional[bool] = None #: Specifies that the request was served from the ServiceWorker. from_service_worker: typing.Optional[bool] = None #: Specifies that the request was served from the prefetch cache. from_prefetch_cache: typing.Optional[bool] = None #: Specifies that the request was served from the prefetch cache. from_early_hints: typing.Optional[bool] = None #: Information about how ServiceWorker Static Router API was used. If this #: field is set with ``matchedSourceType`` field, a matching rule is found. #: If this field is set without ``matchedSource``, no matching rule is found. #: Otherwise, the API is not used. service_worker_router_info: typing.Optional[ServiceWorkerRouterInfo] = None #: Timing information for the given request. timing: typing.Optional[ResourceTiming] = None #: Response source of response from ServiceWorker. service_worker_response_source: typing.Optional[ServiceWorkerResponseSource] = None #: The time at which the returned response was generated. response_time: typing.Optional[TimeSinceEpoch] = None #: Cache Storage Cache Name. cache_storage_cache_name: typing.Optional[str] = None #: Protocol used to fetch this request. protocol: typing.Optional[str] = None #: The reason why Chrome uses a specific transport protocol for HTTP semantics. alternate_protocol_usage: typing.Optional[AlternateProtocolUsage] = None #: Security details for the request. security_details: typing.Optional[SecurityDetails] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["url"] = self.url json["status"] = self.status json["statusText"] = self.status_text json["headers"] = self.headers.to_json() json["mimeType"] = self.mime_type json["charset"] = self.charset json["connectionReused"] = self.connection_reused json["connectionId"] = self.connection_id json["encodedDataLength"] = self.encoded_data_length json["securityState"] = self.security_state.to_json() if self.headers_text is not None: json["headersText"] = self.headers_text if self.request_headers is not None: json["requestHeaders"] = self.request_headers.to_json() if self.request_headers_text is not None: json["requestHeadersText"] = self.request_headers_text if self.remote_ip_address is not None: json["remoteIPAddress"] = self.remote_ip_address if self.remote_port is not None: json["remotePort"] = self.remote_port if self.from_disk_cache is not None: json["fromDiskCache"] = self.from_disk_cache if self.from_service_worker is not None: json["fromServiceWorker"] = self.from_service_worker if self.from_prefetch_cache is not None: json["fromPrefetchCache"] = self.from_prefetch_cache if self.from_early_hints is not None: json["fromEarlyHints"] = self.from_early_hints if self.service_worker_router_info is not None: json["serviceWorkerRouterInfo"] = self.service_worker_router_info.to_json() if self.timing is not None: json["timing"] = self.timing.to_json() if self.service_worker_response_source is not None: json["serviceWorkerResponseSource"] = ( self.service_worker_response_source.to_json() ) if self.response_time is not None: json["responseTime"] = self.response_time.to_json() if self.cache_storage_cache_name is not None: json["cacheStorageCacheName"] = self.cache_storage_cache_name if self.protocol is not None: json["protocol"] = self.protocol if self.alternate_protocol_usage is not None: json["alternateProtocolUsage"] = self.alternate_protocol_usage.to_json() if self.security_details is not None: json["securityDetails"] = self.security_details.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> Response: return cls( url=str(json["url"]), status=int(json["status"]), status_text=str(json["statusText"]), headers=Headers.from_json(json["headers"]), mime_type=str(json["mimeType"]), charset=str(json["charset"]), connection_reused=bool(json["connectionReused"]), connection_id=float(json["connectionId"]), encoded_data_length=float(json["encodedDataLength"]), security_state=security.SecurityState.from_json(json["securityState"]), headers_text=( str(json["headersText"]) if json.get("headersText", None) is not None else None ), request_headers=( Headers.from_json(json["requestHeaders"]) if json.get("requestHeaders", None) is not None else None ), request_headers_text=( str(json["requestHeadersText"]) if json.get("requestHeadersText", None) is not None else None ), remote_ip_address=( str(json["remoteIPAddress"]) if json.get("remoteIPAddress", None) is not None else None ), remote_port=( int(json["remotePort"]) if json.get("remotePort", None) is not None else None ), from_disk_cache=( bool(json["fromDiskCache"]) if json.get("fromDiskCache", None) is not None else None ), from_service_worker=( bool(json["fromServiceWorker"]) if json.get("fromServiceWorker", None) is not None else None ), from_prefetch_cache=( bool(json["fromPrefetchCache"]) if json.get("fromPrefetchCache", None) is not None else None ), from_early_hints=( bool(json["fromEarlyHints"]) if json.get("fromEarlyHints", None) is not None else None ), service_worker_router_info=( ServiceWorkerRouterInfo.from_json(json["serviceWorkerRouterInfo"]) if json.get("serviceWorkerRouterInfo", None) is not None else None ), timing=( ResourceTiming.from_json(json["timing"]) if json.get("timing", None) is not None else None ), service_worker_response_source=( ServiceWorkerResponseSource.from_json( json["serviceWorkerResponseSource"] ) if json.get("serviceWorkerResponseSource", None) is not None else None ), response_time=( TimeSinceEpoch.from_json(json["responseTime"]) if json.get("responseTime", None) is not None else None ), cache_storage_cache_name=( str(json["cacheStorageCacheName"]) if json.get("cacheStorageCacheName", None) is not None else None ), protocol=( str(json["protocol"]) if json.get("protocol", None) is not None else None ), alternate_protocol_usage=( AlternateProtocolUsage.from_json(json["alternateProtocolUsage"]) if json.get("alternateProtocolUsage", None) is not None else None ), security_details=( SecurityDetails.from_json(json["securityDetails"]) if json.get("securityDetails", None) is not None else None ), )
[docs] @dataclass class WebSocketRequest: """ WebSocket request data. """ #: HTTP request headers. headers: Headers def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["headers"] = self.headers.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketRequest: return cls( headers=Headers.from_json(json["headers"]), )
[docs] @dataclass class WebSocketResponse: """ WebSocket response data. """ #: HTTP response status code. status: int #: HTTP response status text. status_text: str #: HTTP response headers. headers: Headers #: HTTP response headers text. headers_text: typing.Optional[str] = None #: HTTP request headers. request_headers: typing.Optional[Headers] = None #: HTTP request headers text. request_headers_text: typing.Optional[str] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["status"] = self.status json["statusText"] = self.status_text json["headers"] = self.headers.to_json() if self.headers_text is not None: json["headersText"] = self.headers_text if self.request_headers is not None: json["requestHeaders"] = self.request_headers.to_json() if self.request_headers_text is not None: json["requestHeadersText"] = self.request_headers_text return json @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketResponse: return cls( status=int(json["status"]), status_text=str(json["statusText"]), headers=Headers.from_json(json["headers"]), headers_text=( str(json["headersText"]) if json.get("headersText", None) is not None else None ), request_headers=( Headers.from_json(json["requestHeaders"]) if json.get("requestHeaders", None) is not None else None ), request_headers_text=( str(json["requestHeadersText"]) if json.get("requestHeadersText", None) is not None else None ), )
[docs] @dataclass class WebSocketFrame: """ WebSocket message data. This represents an entire WebSocket message, not just a fragmented frame as the name suggests. """ #: WebSocket message opcode. opcode: float #: WebSocket message mask. mask: bool #: WebSocket message payload data. #: If the opcode is 1, this is a text message and payloadData is a UTF-8 string. #: If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data. payload_data: str def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["opcode"] = self.opcode json["mask"] = self.mask json["payloadData"] = self.payload_data return json @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketFrame: return cls( opcode=float(json["opcode"]), mask=bool(json["mask"]), payload_data=str(json["payloadData"]), )
[docs] @dataclass class CachedResource: """ Information about the cached resource. """ #: Resource URL. This is the url of the original network request. url: str #: Type of this resource. type_: ResourceType #: Cached response body size. body_size: float #: Cached response data. response: typing.Optional[Response] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["url"] = self.url json["type"] = self.type_.to_json() json["bodySize"] = self.body_size if self.response is not None: json["response"] = self.response.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> CachedResource: return cls( url=str(json["url"]), type_=ResourceType.from_json(json["type"]), body_size=float(json["bodySize"]), response=( Response.from_json(json["response"]) if json.get("response", None) is not None else None ), )
[docs] @dataclass class Initiator: """ Information about the request initiator. """ #: Type of this initiator. type_: str #: Initiator JavaScript stack trace, set for Script only. stack: typing.Optional[runtime.StackTrace] = None #: Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. url: typing.Optional[str] = None #: Initiator line number, set for Parser type or for Script type (when script is importing #: module) (0-based). line_number: typing.Optional[float] = None #: Initiator column number, set for Parser type or for Script type (when script is importing #: module) (0-based). column_number: typing.Optional[float] = None #: Set if another request triggered this request (e.g. preflight). request_id: typing.Optional[RequestId] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["type"] = self.type_ if self.stack is not None: json["stack"] = self.stack.to_json() if self.url is not None: json["url"] = self.url if self.line_number is not None: json["lineNumber"] = self.line_number if self.column_number is not None: json["columnNumber"] = self.column_number if self.request_id is not None: json["requestId"] = self.request_id.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> Initiator: return cls( type_=str(json["type"]), stack=( runtime.StackTrace.from_json(json["stack"]) if json.get("stack", None) is not None else None ), url=str(json["url"]) if json.get("url", None) is not None else None, line_number=( float(json["lineNumber"]) if json.get("lineNumber", None) is not None else None ), column_number=( float(json["columnNumber"]) if json.get("columnNumber", None) is not None else None ), request_id=( RequestId.from_json(json["requestId"]) if json.get("requestId", None) is not None else None ), )
[docs] @dataclass class CookiePartitionKey: """ 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 site of the top-level URL the browser was visiting at the start #: of the request to the endpoint that set the cookie. top_level_site: str #: Indicates if the cookie has any ancestors that are cross-site to the topLevelSite. has_cross_site_ancestor: bool def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["topLevelSite"] = self.top_level_site json["hasCrossSiteAncestor"] = self.has_cross_site_ancestor return json @classmethod def from_json(cls, json: T_JSON_DICT) -> CookiePartitionKey: return cls( top_level_site=str(json["topLevelSite"]), has_cross_site_ancestor=bool(json["hasCrossSiteAncestor"]), )
[docs] class SetCookieBlockedReason(enum.Enum): """ Types of reasons why a cookie may not be stored from a response. """ SECURE_ONLY = "SecureOnly" SAME_SITE_STRICT = "SameSiteStrict" SAME_SITE_LAX = "SameSiteLax" SAME_SITE_UNSPECIFIED_TREATED_AS_LAX = "SameSiteUnspecifiedTreatedAsLax" SAME_SITE_NONE_INSECURE = "SameSiteNoneInsecure" USER_PREFERENCES = "UserPreferences" THIRD_PARTY_PHASEOUT = "ThirdPartyPhaseout" THIRD_PARTY_BLOCKED_IN_FIRST_PARTY_SET = "ThirdPartyBlockedInFirstPartySet" SYNTAX_ERROR = "SyntaxError" SCHEME_NOT_SUPPORTED = "SchemeNotSupported" OVERWRITE_SECURE = "OverwriteSecure" INVALID_DOMAIN = "InvalidDomain" INVALID_PREFIX = "InvalidPrefix" UNKNOWN_ERROR = "UnknownError" SCHEMEFUL_SAME_SITE_STRICT = "SchemefulSameSiteStrict" SCHEMEFUL_SAME_SITE_LAX = "SchemefulSameSiteLax" SCHEMEFUL_SAME_SITE_UNSPECIFIED_TREATED_AS_LAX = ( "SchemefulSameSiteUnspecifiedTreatedAsLax" ) SAME_PARTY_FROM_CROSS_PARTY_CONTEXT = "SamePartyFromCrossPartyContext" SAME_PARTY_CONFLICTS_WITH_OTHER_ATTRIBUTES = "SamePartyConflictsWithOtherAttributes" NAME_VALUE_PAIR_EXCEEDS_MAX_SIZE = "NameValuePairExceedsMaxSize" DISALLOWED_CHARACTER = "DisallowedCharacter" NO_COOKIE_CONTENT = "NoCookieContent" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> SetCookieBlockedReason: return cls(json)
[docs] class CookieBlockedReason(enum.Enum): """ Types of reasons why a cookie may not be sent with a request. """ SECURE_ONLY = "SecureOnly" NOT_ON_PATH = "NotOnPath" DOMAIN_MISMATCH = "DomainMismatch" SAME_SITE_STRICT = "SameSiteStrict" SAME_SITE_LAX = "SameSiteLax" SAME_SITE_UNSPECIFIED_TREATED_AS_LAX = "SameSiteUnspecifiedTreatedAsLax" SAME_SITE_NONE_INSECURE = "SameSiteNoneInsecure" USER_PREFERENCES = "UserPreferences" THIRD_PARTY_PHASEOUT = "ThirdPartyPhaseout" THIRD_PARTY_BLOCKED_IN_FIRST_PARTY_SET = "ThirdPartyBlockedInFirstPartySet" UNKNOWN_ERROR = "UnknownError" SCHEMEFUL_SAME_SITE_STRICT = "SchemefulSameSiteStrict" SCHEMEFUL_SAME_SITE_LAX = "SchemefulSameSiteLax" SCHEMEFUL_SAME_SITE_UNSPECIFIED_TREATED_AS_LAX = ( "SchemefulSameSiteUnspecifiedTreatedAsLax" ) SAME_PARTY_FROM_CROSS_PARTY_CONTEXT = "SamePartyFromCrossPartyContext" NAME_VALUE_PAIR_EXCEEDS_MAX_SIZE = "NameValuePairExceedsMaxSize" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CookieBlockedReason: return cls(json)
[docs] class CookieExemptionReason(enum.Enum): """ Types of reasons why a cookie should have been blocked by 3PCD but is exempted for the request. """ NONE = "None" USER_SETTING = "UserSetting" TPCD_METADATA = "TPCDMetadata" TPCD_DEPRECATION_TRIAL = "TPCDDeprecationTrial" TPCD_HEURISTICS = "TPCDHeuristics" ENTERPRISE_POLICY = "EnterprisePolicy" STORAGE_ACCESS = "StorageAccess" TOP_LEVEL_STORAGE_ACCESS = "TopLevelStorageAccess" CORS_OPT_IN = "CorsOptIn" SCHEME = "Scheme" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CookieExemptionReason: return cls(json)
[docs] @dataclass class BlockedSetCookieWithReason: """ A cookie which was not stored from a response with the corresponding reason. """ #: The reason(s) this cookie was blocked. blocked_reasons: typing.List[SetCookieBlockedReason] #: The string representing this individual cookie as it would appear in the header. #: This is not the entire "cookie" or "set-cookie" header which could have multiple cookies. cookie_line: str #: The cookie object which represents the cookie which was not stored. It is optional because #: sometimes complete cookie information is not available, such as in the case of parsing #: errors. cookie: typing.Optional[Cookie] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["blockedReasons"] = [i.to_json() for i in self.blocked_reasons] json["cookieLine"] = self.cookie_line if self.cookie is not None: json["cookie"] = self.cookie.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> BlockedSetCookieWithReason: return cls( blocked_reasons=[ SetCookieBlockedReason.from_json(i) for i in json["blockedReasons"] ], cookie_line=str(json["cookieLine"]), cookie=( Cookie.from_json(json["cookie"]) if json.get("cookie", None) is not None else None ), )
[docs] @dataclass class ExemptedSetCookieWithReason: """ 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. """ #: The reason the cookie was exempted. exemption_reason: CookieExemptionReason #: The string representing this individual cookie as it would appear in the header. cookie_line: str #: The cookie object representing the cookie. cookie: Cookie def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["exemptionReason"] = self.exemption_reason.to_json() json["cookieLine"] = self.cookie_line json["cookie"] = self.cookie.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ExemptedSetCookieWithReason: return cls( exemption_reason=CookieExemptionReason.from_json(json["exemptionReason"]), cookie_line=str(json["cookieLine"]), cookie=Cookie.from_json(json["cookie"]), )
[docs] @dataclass class AssociatedCookie: """ 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. """ #: The cookie object representing the cookie which was not sent. cookie: Cookie #: The reason(s) the cookie was blocked. If empty means the cookie is included. blocked_reasons: typing.List[CookieBlockedReason] #: The reason the cookie should have been blocked by 3PCD but is exempted. A cookie could #: only have at most one exemption reason. exemption_reason: typing.Optional[CookieExemptionReason] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["cookie"] = self.cookie.to_json() json["blockedReasons"] = [i.to_json() for i in self.blocked_reasons] if self.exemption_reason is not None: json["exemptionReason"] = self.exemption_reason.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> AssociatedCookie: return cls( cookie=Cookie.from_json(json["cookie"]), blocked_reasons=[ CookieBlockedReason.from_json(i) for i in json["blockedReasons"] ], exemption_reason=( CookieExemptionReason.from_json(json["exemptionReason"]) if json.get("exemptionReason", None) is not None else None ), )
[docs] @dataclass class CookieParam: """ Cookie parameter object """ #: Cookie name. name: str #: Cookie value. value: str #: The request-URI to associate with the setting of the cookie. This value can affect the #: default domain, path, source port, and source scheme values of the created cookie. url: typing.Optional[str] = None #: Cookie domain. domain: typing.Optional[str] = None #: Cookie path. path: typing.Optional[str] = None #: True if cookie is secure. secure: typing.Optional[bool] = None #: True if cookie is http-only. http_only: typing.Optional[bool] = None #: Cookie SameSite type. same_site: typing.Optional[CookieSameSite] = None #: Cookie expiration date, session cookie if not set expires: typing.Optional[TimeSinceEpoch] = None #: Cookie Priority. priority: typing.Optional[CookiePriority] = None #: True if cookie is SameParty. same_party: typing.Optional[bool] = None #: Cookie source scheme type. source_scheme: typing.Optional[CookieSourceScheme] = None #: Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. #: An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. #: This is a temporary ability and it will be removed in the future. source_port: typing.Optional[int] = None #: Cookie partition key. If not set, the cookie will be set as not partitioned. partition_key: typing.Optional[CookiePartitionKey] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["name"] = self.name json["value"] = self.value if self.url is not None: json["url"] = self.url if self.domain is not None: json["domain"] = self.domain if self.path is not None: json["path"] = self.path if self.secure is not None: json["secure"] = self.secure if self.http_only is not None: json["httpOnly"] = self.http_only if self.same_site is not None: json["sameSite"] = self.same_site.to_json() if self.expires is not None: json["expires"] = self.expires.to_json() if self.priority is not None: json["priority"] = self.priority.to_json() if self.same_party is not None: json["sameParty"] = self.same_party if self.source_scheme is not None: json["sourceScheme"] = self.source_scheme.to_json() if self.source_port is not None: json["sourcePort"] = self.source_port if self.partition_key is not None: json["partitionKey"] = self.partition_key.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> CookieParam: return cls( name=str(json["name"]), value=str(json["value"]), url=str(json["url"]) if json.get("url", None) is not None else None, domain=( str(json["domain"]) if json.get("domain", None) is not None else None ), path=str(json["path"]) if json.get("path", None) is not None else None, secure=( bool(json["secure"]) if json.get("secure", None) is not None else None ), http_only=( bool(json["httpOnly"]) if json.get("httpOnly", None) is not None else None ), same_site=( CookieSameSite.from_json(json["sameSite"]) if json.get("sameSite", None) is not None else None ), expires=( TimeSinceEpoch.from_json(json["expires"]) if json.get("expires", None) is not None else None ), priority=( CookiePriority.from_json(json["priority"]) if json.get("priority", None) is not None else None ), same_party=( bool(json["sameParty"]) if json.get("sameParty", None) is not None else None ), source_scheme=( CookieSourceScheme.from_json(json["sourceScheme"]) if json.get("sourceScheme", None) is not None else None ), source_port=( int(json["sourcePort"]) if json.get("sourcePort", None) is not None else None ), partition_key=( CookiePartitionKey.from_json(json["partitionKey"]) if json.get("partitionKey", None) is not None else None ), )
[docs] @dataclass class AuthChallenge: """ Authorization challenge for HTTP status code 401 or 407. """ #: Origin of the challenger. origin: str #: The authentication scheme used, such as basic or digest scheme: str #: The realm of the challenge. May be empty. realm: str #: Source of the authentication challenge. source: typing.Optional[str] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["origin"] = self.origin json["scheme"] = self.scheme json["realm"] = self.realm if self.source is not None: json["source"] = self.source return json @classmethod def from_json(cls, json: T_JSON_DICT) -> AuthChallenge: return cls( origin=str(json["origin"]), scheme=str(json["scheme"]), realm=str(json["realm"]), source=( str(json["source"]) if json.get("source", None) is not None else None ), )
[docs] @dataclass class AuthChallengeResponse: """ Response to an AuthChallenge. """ #: The decision on what to do in response to the authorization challenge. Default means #: deferring to the default behavior of the net stack, which will likely either the Cancel #: authentication or display a popup dialog box. response: str #: The username to provide, possibly empty. Should only be set if response is #: ProvideCredentials. username: typing.Optional[str] = None #: The password to provide, possibly empty. Should only be set if response is #: ProvideCredentials. password: typing.Optional[str] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["response"] = self.response if self.username is not None: json["username"] = self.username if self.password is not None: json["password"] = self.password return json @classmethod def from_json(cls, json: T_JSON_DICT) -> AuthChallengeResponse: return cls( response=str(json["response"]), username=( str(json["username"]) if json.get("username", None) is not None else None ), password=( str(json["password"]) if json.get("password", None) is not None else None ), )
[docs] class InterceptionStage(enum.Enum): """ Stages of the interception to begin intercepting. Request will intercept before the request is sent. Response will intercept after the response is received. """ REQUEST = "Request" HEADERS_RECEIVED = "HeadersReceived" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> InterceptionStage: return cls(json)
[docs] @dataclass class RequestPattern: """ Request pattern for interception. """ #: Wildcards (``'*'`` -> zero or more, ``'?'`` -> exactly one) are allowed. Escape character is #: backslash. Omitting is equivalent to ``"*"``. url_pattern: typing.Optional[str] = None #: If set, only requests for matching resource types will be intercepted. resource_type: typing.Optional[ResourceType] = None #: Stage at which to begin intercepting requests. Default is Request. interception_stage: typing.Optional[InterceptionStage] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() if self.url_pattern is not None: json["urlPattern"] = self.url_pattern if self.resource_type is not None: json["resourceType"] = self.resource_type.to_json() if self.interception_stage is not None: json["interceptionStage"] = self.interception_stage.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> RequestPattern: return cls( url_pattern=( str(json["urlPattern"]) if json.get("urlPattern", None) is not None else None ), resource_type=( ResourceType.from_json(json["resourceType"]) if json.get("resourceType", None) is not None else None ), interception_stage=( InterceptionStage.from_json(json["interceptionStage"]) if json.get("interceptionStage", None) is not None else None ), )
[docs] @dataclass class SignedExchangeSignature: """ Information about a signed exchange signature. https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#rfc.section.3.1 """ #: Signed exchange signature label. label: str #: The hex string of signed exchange signature. signature: str #: Signed exchange signature integrity. integrity: str #: Signed exchange signature validity Url. validity_url: str #: Signed exchange signature date. date: int #: Signed exchange signature expires. expires: int #: Signed exchange signature cert Url. cert_url: typing.Optional[str] = None #: The hex string of signed exchange signature cert sha256. cert_sha256: typing.Optional[str] = None #: The encoded certificates. certificates: typing.Optional[typing.List[str]] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["label"] = self.label json["signature"] = self.signature json["integrity"] = self.integrity json["validityUrl"] = self.validity_url json["date"] = self.date json["expires"] = self.expires if self.cert_url is not None: json["certUrl"] = self.cert_url if self.cert_sha256 is not None: json["certSha256"] = self.cert_sha256 if self.certificates is not None: json["certificates"] = [i for i in self.certificates] return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SignedExchangeSignature: return cls( label=str(json["label"]), signature=str(json["signature"]), integrity=str(json["integrity"]), validity_url=str(json["validityUrl"]), date=int(json["date"]), expires=int(json["expires"]), cert_url=( str(json["certUrl"]) if json.get("certUrl", None) is not None else None ), cert_sha256=( str(json["certSha256"]) if json.get("certSha256", None) is not None else None ), certificates=( [str(i) for i in json["certificates"]] if json.get("certificates", None) is not None else None ), )
[docs] @dataclass class SignedExchangeHeader: """ Information about a signed exchange header. https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cbor-representation """ #: Signed exchange request URL. request_url: str #: Signed exchange response code. response_code: int #: Signed exchange response headers. response_headers: Headers #: Signed exchange response signature. signatures: typing.List[SignedExchangeSignature] #: Signed exchange header integrity hash in the form of ``sha256-<base64-hash-value>``. header_integrity: str def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["requestUrl"] = self.request_url json["responseCode"] = self.response_code json["responseHeaders"] = self.response_headers.to_json() json["signatures"] = [i.to_json() for i in self.signatures] json["headerIntegrity"] = self.header_integrity return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SignedExchangeHeader: return cls( request_url=str(json["requestUrl"]), response_code=int(json["responseCode"]), response_headers=Headers.from_json(json["responseHeaders"]), signatures=[ SignedExchangeSignature.from_json(i) for i in json["signatures"] ], header_integrity=str(json["headerIntegrity"]), )
[docs] class SignedExchangeErrorField(enum.Enum): """ Field type for a signed exchange related error. """ SIGNATURE_SIG = "signatureSig" SIGNATURE_INTEGRITY = "signatureIntegrity" SIGNATURE_CERT_URL = "signatureCertUrl" SIGNATURE_CERT_SHA256 = "signatureCertSha256" SIGNATURE_VALIDITY_URL = "signatureValidityUrl" SIGNATURE_TIMESTAMPS = "signatureTimestamps" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> SignedExchangeErrorField: return cls(json)
[docs] @dataclass class SignedExchangeError: """ Information about a signed exchange response. """ #: Error message. message: str #: The index of the signature which caused the error. signature_index: typing.Optional[int] = None #: The field which caused the error. error_field: typing.Optional[SignedExchangeErrorField] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["message"] = self.message if self.signature_index is not None: json["signatureIndex"] = self.signature_index if self.error_field is not None: json["errorField"] = self.error_field.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SignedExchangeError: return cls( message=str(json["message"]), signature_index=( int(json["signatureIndex"]) if json.get("signatureIndex", None) is not None else None ), error_field=( SignedExchangeErrorField.from_json(json["errorField"]) if json.get("errorField", None) is not None else None ), )
[docs] @dataclass class SignedExchangeInfo: """ Information about a signed exchange response. """ #: The outer response of signed HTTP exchange which was received from network. outer_response: Response #: Information about the signed exchange header. header: typing.Optional[SignedExchangeHeader] = None #: Security details for the signed exchange header. security_details: typing.Optional[SecurityDetails] = None #: Errors occurred while handling the signed exchange. errors: typing.Optional[typing.List[SignedExchangeError]] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["outerResponse"] = self.outer_response.to_json() if self.header is not None: json["header"] = self.header.to_json() if self.security_details is not None: json["securityDetails"] = self.security_details.to_json() if self.errors is not None: json["errors"] = [i.to_json() for i in self.errors] return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SignedExchangeInfo: return cls( outer_response=Response.from_json(json["outerResponse"]), header=( SignedExchangeHeader.from_json(json["header"]) if json.get("header", None) is not None else None ), security_details=( SecurityDetails.from_json(json["securityDetails"]) if json.get("securityDetails", None) is not None else None ), errors=( [SignedExchangeError.from_json(i) for i in json["errors"]] if json.get("errors", None) is not None else None ), )
[docs] class ContentEncoding(enum.Enum): """ List of content encodings supported by the backend. """ DEFLATE = "deflate" GZIP = "gzip" BR = "br" ZSTD = "zstd" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ContentEncoding: return cls(json)
[docs] class PrivateNetworkRequestPolicy(enum.Enum): ALLOW = "Allow" BLOCK_FROM_INSECURE_TO_MORE_PRIVATE = "BlockFromInsecureToMorePrivate" WARN_FROM_INSECURE_TO_MORE_PRIVATE = "WarnFromInsecureToMorePrivate" PREFLIGHT_BLOCK = "PreflightBlock" PREFLIGHT_WARN = "PreflightWarn" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> PrivateNetworkRequestPolicy: return cls(json)
[docs] class IPAddressSpace(enum.Enum): LOCAL = "Local" PRIVATE = "Private" PUBLIC = "Public" UNKNOWN = "Unknown" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> IPAddressSpace: return cls(json)
[docs] @dataclass class ConnectTiming: #: Timing's requestTime is a baseline in seconds, while the other numbers are ticks in #: milliseconds relatively to this requestTime. Matches ResourceTiming's requestTime for #: the same request (but not for redirected requests). request_time: float def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["requestTime"] = self.request_time return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ConnectTiming: return cls( request_time=float(json["requestTime"]), )
[docs] @dataclass class ClientSecurityState: initiator_is_secure_context: bool initiator_ip_address_space: IPAddressSpace private_network_request_policy: PrivateNetworkRequestPolicy def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["initiatorIsSecureContext"] = self.initiator_is_secure_context json["initiatorIPAddressSpace"] = self.initiator_ip_address_space.to_json() json["privateNetworkRequestPolicy"] = ( self.private_network_request_policy.to_json() ) return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ClientSecurityState: return cls( initiator_is_secure_context=bool(json["initiatorIsSecureContext"]), initiator_ip_address_space=IPAddressSpace.from_json( json["initiatorIPAddressSpace"] ), private_network_request_policy=PrivateNetworkRequestPolicy.from_json( json["privateNetworkRequestPolicy"] ), )
[docs] class CrossOriginOpenerPolicyValue(enum.Enum): SAME_ORIGIN = "SameOrigin" SAME_ORIGIN_ALLOW_POPUPS = "SameOriginAllowPopups" RESTRICT_PROPERTIES = "RestrictProperties" UNSAFE_NONE = "UnsafeNone" SAME_ORIGIN_PLUS_COEP = "SameOriginPlusCoep" RESTRICT_PROPERTIES_PLUS_COEP = "RestrictPropertiesPlusCoep" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CrossOriginOpenerPolicyValue: return cls(json)
[docs] @dataclass class CrossOriginOpenerPolicyStatus: value: CrossOriginOpenerPolicyValue report_only_value: CrossOriginOpenerPolicyValue reporting_endpoint: typing.Optional[str] = None report_only_reporting_endpoint: typing.Optional[str] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["value"] = self.value.to_json() json["reportOnlyValue"] = self.report_only_value.to_json() if self.reporting_endpoint is not None: json["reportingEndpoint"] = self.reporting_endpoint if self.report_only_reporting_endpoint is not None: json["reportOnlyReportingEndpoint"] = self.report_only_reporting_endpoint return json @classmethod def from_json(cls, json: T_JSON_DICT) -> CrossOriginOpenerPolicyStatus: return cls( value=CrossOriginOpenerPolicyValue.from_json(json["value"]), report_only_value=CrossOriginOpenerPolicyValue.from_json( json["reportOnlyValue"] ), reporting_endpoint=( str(json["reportingEndpoint"]) if json.get("reportingEndpoint", None) is not None else None ), report_only_reporting_endpoint=( str(json["reportOnlyReportingEndpoint"]) if json.get("reportOnlyReportingEndpoint", None) is not None else None ), )
[docs] class CrossOriginEmbedderPolicyValue(enum.Enum): NONE = "None" CREDENTIALLESS = "Credentialless" REQUIRE_CORP = "RequireCorp" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> CrossOriginEmbedderPolicyValue: return cls(json)
[docs] @dataclass class CrossOriginEmbedderPolicyStatus: value: CrossOriginEmbedderPolicyValue report_only_value: CrossOriginEmbedderPolicyValue reporting_endpoint: typing.Optional[str] = None report_only_reporting_endpoint: typing.Optional[str] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["value"] = self.value.to_json() json["reportOnlyValue"] = self.report_only_value.to_json() if self.reporting_endpoint is not None: json["reportingEndpoint"] = self.reporting_endpoint if self.report_only_reporting_endpoint is not None: json["reportOnlyReportingEndpoint"] = self.report_only_reporting_endpoint return json @classmethod def from_json(cls, json: T_JSON_DICT) -> CrossOriginEmbedderPolicyStatus: return cls( value=CrossOriginEmbedderPolicyValue.from_json(json["value"]), report_only_value=CrossOriginEmbedderPolicyValue.from_json( json["reportOnlyValue"] ), reporting_endpoint=( str(json["reportingEndpoint"]) if json.get("reportingEndpoint", None) is not None else None ), report_only_reporting_endpoint=( str(json["reportOnlyReportingEndpoint"]) if json.get("reportOnlyReportingEndpoint", None) is not None else None ), )
[docs] class ContentSecurityPolicySource(enum.Enum): HTTP = "HTTP" META = "Meta" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ContentSecurityPolicySource: return cls(json)
[docs] @dataclass class ContentSecurityPolicyStatus: effective_directives: str is_enforced: bool source: ContentSecurityPolicySource def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["effectiveDirectives"] = self.effective_directives json["isEnforced"] = self.is_enforced json["source"] = self.source.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ContentSecurityPolicyStatus: return cls( effective_directives=str(json["effectiveDirectives"]), is_enforced=bool(json["isEnforced"]), source=ContentSecurityPolicySource.from_json(json["source"]), )
[docs] @dataclass class SecurityIsolationStatus: coop: typing.Optional[CrossOriginOpenerPolicyStatus] = None coep: typing.Optional[CrossOriginEmbedderPolicyStatus] = None csp: typing.Optional[typing.List[ContentSecurityPolicyStatus]] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() if self.coop is not None: json["coop"] = self.coop.to_json() if self.coep is not None: json["coep"] = self.coep.to_json() if self.csp is not None: json["csp"] = [i.to_json() for i in self.csp] return json @classmethod def from_json(cls, json: T_JSON_DICT) -> SecurityIsolationStatus: return cls( coop=( CrossOriginOpenerPolicyStatus.from_json(json["coop"]) if json.get("coop", None) is not None else None ), coep=( CrossOriginEmbedderPolicyStatus.from_json(json["coep"]) if json.get("coep", None) is not None else None ), csp=( [ContentSecurityPolicyStatus.from_json(i) for i in json["csp"]] if json.get("csp", None) is not None else None ), )
[docs] class ReportStatus(enum.Enum): """ The status of a Reporting API report. """ QUEUED = "Queued" PENDING = "Pending" MARKED_FOR_REMOVAL = "MarkedForRemoval" SUCCESS = "Success" def to_json(self) -> str: return self.value @classmethod def from_json(cls, json: str) -> ReportStatus: return cls(json)
[docs] class ReportId(str): def to_json(self) -> str: return self @classmethod def from_json(cls, json: str) -> ReportId: return cls(json) def __repr__(self): return "ReportId({})".format(super().__repr__())
[docs] @dataclass class ReportingApiReport: """ An object representing a report generated by the Reporting API. """ id_: ReportId #: The URL of the document that triggered the report. initiator_url: str #: The name of the endpoint group that should be used to deliver the report. destination: str #: The type of the report (specifies the set of data that is contained in the report body). type_: str #: When the report was generated. timestamp: TimeSinceEpoch #: How many uploads deep the related request was. depth: int #: The number of delivery attempts made so far, not including an active attempt. completed_attempts: int body: dict status: ReportStatus def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["id"] = self.id_.to_json() json["initiatorUrl"] = self.initiator_url json["destination"] = self.destination json["type"] = self.type_ json["timestamp"] = self.timestamp.to_json() json["depth"] = self.depth json["completedAttempts"] = self.completed_attempts json["body"] = self.body json["status"] = self.status.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ReportingApiReport: return cls( id_=ReportId.from_json(json["id"]), initiator_url=str(json["initiatorUrl"]), destination=str(json["destination"]), type_=str(json["type"]), timestamp=TimeSinceEpoch.from_json(json["timestamp"]), depth=int(json["depth"]), completed_attempts=int(json["completedAttempts"]), body=dict(json["body"]), status=ReportStatus.from_json(json["status"]), )
[docs] @dataclass class ReportingApiEndpoint: #: The URL of the endpoint to which reports may be delivered. url: str #: Name of the endpoint group. group_name: str def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["url"] = self.url json["groupName"] = self.group_name return json @classmethod def from_json(cls, json: T_JSON_DICT) -> ReportingApiEndpoint: return cls( url=str(json["url"]), group_name=str(json["groupName"]), )
[docs] @dataclass class LoadNetworkResourcePageResult: """ An object providing the result of a network resource load. """ success: bool #: Optional values used for error reporting. net_error: typing.Optional[float] = None net_error_name: typing.Optional[str] = None http_status_code: typing.Optional[float] = None #: If successful, one of the following two fields holds the result. stream: typing.Optional[io.StreamHandle] = None #: Response headers. headers: typing.Optional[Headers] = None def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["success"] = self.success if self.net_error is not None: json["netError"] = self.net_error if self.net_error_name is not None: json["netErrorName"] = self.net_error_name if self.http_status_code is not None: json["httpStatusCode"] = self.http_status_code if self.stream is not None: json["stream"] = self.stream.to_json() if self.headers is not None: json["headers"] = self.headers.to_json() return json @classmethod def from_json(cls, json: T_JSON_DICT) -> LoadNetworkResourcePageResult: return cls( success=bool(json["success"]), net_error=( float(json["netError"]) if json.get("netError", None) is not None else None ), net_error_name=( str(json["netErrorName"]) if json.get("netErrorName", None) is not None else None ), http_status_code=( float(json["httpStatusCode"]) if json.get("httpStatusCode", None) is not None else None ), stream=( io.StreamHandle.from_json(json["stream"]) if json.get("stream", None) is not None else None ), headers=( Headers.from_json(json["headers"]) if json.get("headers", None) is not None else None ), )
[docs] @dataclass class LoadNetworkResourceOptions: """ An options object that may be extended later to better support CORS, CORB and streaming. """ disable_cache: bool include_credentials: bool def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() json["disableCache"] = self.disable_cache json["includeCredentials"] = self.include_credentials return json @classmethod def from_json(cls, json: T_JSON_DICT) -> LoadNetworkResourceOptions: return cls( disable_cache=bool(json["disableCache"]), include_credentials=bool(json["includeCredentials"]), )
[docs] def set_accepted_encodings( encodings: typing.List[ContentEncoding], ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Sets a list of content encodings that will be accepted. Empty list means no encoding is accepted. **EXPERIMENTAL** :param encodings: List of accepted content encodings. """ params: T_JSON_DICT = dict() params["encodings"] = [i.to_json() for i in encodings] cmd_dict: T_JSON_DICT = { "method": "Network.setAcceptedEncodings", "params": params, } json = yield cmd_dict
[docs] def clear_accepted_encodings_override() -> ( typing.Generator[T_JSON_DICT, T_JSON_DICT, None] ): """ Clears accepted encodings set by setAcceptedEncodings **EXPERIMENTAL** """ cmd_dict: T_JSON_DICT = { "method": "Network.clearAcceptedEncodingsOverride", } json = yield cmd_dict
[docs] @deprecated(version="1.3") def can_clear_browser_cache() -> typing.Generator[T_JSON_DICT, T_JSON_DICT, bool]: """ Tells whether clearing browser cache is supported. .. deprecated:: 1.3 :returns: True if browser cache can be cleared. """ cmd_dict: T_JSON_DICT = { "method": "Network.canClearBrowserCache", } json = yield cmd_dict return bool(json["result"])
[docs] @deprecated(version="1.3") def can_clear_browser_cookies() -> typing.Generator[T_JSON_DICT, T_JSON_DICT, bool]: """ Tells whether clearing browser cookies is supported. .. deprecated:: 1.3 :returns: True if browser cookies can be cleared. """ cmd_dict: T_JSON_DICT = { "method": "Network.canClearBrowserCookies", } json = yield cmd_dict return bool(json["result"])
[docs] @deprecated(version="1.3") def can_emulate_network_conditions() -> ( typing.Generator[T_JSON_DICT, T_JSON_DICT, bool] ): """ Tells whether emulation of network conditions is supported. .. deprecated:: 1.3 :returns: True if emulation of network conditions is supported. """ cmd_dict: T_JSON_DICT = { "method": "Network.canEmulateNetworkConditions", } json = yield cmd_dict return bool(json["result"])
[docs] def clear_browser_cache() -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Clears browser cache. """ cmd_dict: T_JSON_DICT = { "method": "Network.clearBrowserCache", } json = yield cmd_dict
[docs] def clear_browser_cookies() -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Clears browser cookies. """ cmd_dict: T_JSON_DICT = { "method": "Network.clearBrowserCookies", } json = yield cmd_dict
[docs] @deprecated(version="1.3") def continue_intercepted_request( interception_id: InterceptionId, error_reason: typing.Optional[ErrorReason] = None, raw_response: typing.Optional[str] = None, url: typing.Optional[str] = None, method: typing.Optional[str] = None, post_data: typing.Optional[str] = None, headers: typing.Optional[Headers] = None, auth_challenge_response: typing.Optional[AuthChallengeResponse] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ 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. .. deprecated:: 1.3 **EXPERIMENTAL** :param interception_id: :param error_reason: *(Optional)* If set this causes the request to fail with the given reason. Passing ```Aborted```` for requests marked with ````isNavigationRequest``` also cancels the navigation. Must not be set in response to an authChallenge. :param raw_response: *(Optional)* If set the requests completes using with the provided base64 encoded raw response, including HTTP status line and headers etc... Must not be set in response to an authChallenge. (Encoded as a base64 string when passed over JSON) :param url: *(Optional)* If set the request url will be modified in a way that's not observable by page. Must not be set in response to an authChallenge. :param method: *(Optional)* If set this allows the request method to be overridden. Must not be set in response to an authChallenge. :param post_data: *(Optional)* If set this allows postData to be set. Must not be set in response to an authChallenge. :param headers: *(Optional)* If set this allows the request headers to be changed. Must not be set in response to an authChallenge. :param auth_challenge_response: *(Optional)* Response to a requestIntercepted with an authChallenge. Must not be set otherwise. """ params: T_JSON_DICT = dict() params["interceptionId"] = interception_id.to_json() if error_reason is not None: params["errorReason"] = error_reason.to_json() if raw_response is not None: params["rawResponse"] = raw_response if url is not None: params["url"] = url if method is not None: params["method"] = method if post_data is not None: params["postData"] = post_data if headers is not None: params["headers"] = headers.to_json() if auth_challenge_response is not None: params["authChallengeResponse"] = auth_challenge_response.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.continueInterceptedRequest", "params": params, } json = yield cmd_dict
[docs] def delete_cookies( name: str, url: typing.Optional[str] = None, domain: typing.Optional[str] = None, path: typing.Optional[str] = None, partition_key: typing.Optional[CookiePartitionKey] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Deletes browser cookies with matching name and url or domain/path/partitionKey pair. :param name: Name of the cookies to remove. :param url: *(Optional)* If specified, deletes all the cookies with the given name where domain and path match provided URL. :param domain: *(Optional)* If specified, deletes only cookies with the exact domain. :param path: *(Optional)* If specified, deletes only cookies with the exact path. :param partition_key: **(EXPERIMENTAL)** *(Optional)* If specified, deletes only cookies with the the given name and partitionKey where all partition key attributes match the cookie partition key attribute. """ params: T_JSON_DICT = dict() params["name"] = name if url is not None: params["url"] = url if domain is not None: params["domain"] = domain if path is not None: params["path"] = path if partition_key is not None: params["partitionKey"] = partition_key.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.deleteCookies", "params": params, } json = yield cmd_dict
[docs] def disable() -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Disables network tracking, prevents network events from being sent to the client. """ cmd_dict: T_JSON_DICT = { "method": "Network.disable", } json = yield cmd_dict
[docs] def emulate_network_conditions( offline: bool, latency: float, download_throughput: float, upload_throughput: float, connection_type: typing.Optional[ConnectionType] = None, packet_loss: typing.Optional[float] = None, packet_queue_length: typing.Optional[int] = None, packet_reordering: typing.Optional[bool] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Activates emulation of network conditions. :param offline: True to emulate internet disconnection. :param latency: Minimum latency from request sent to response headers received (ms). :param download_throughput: Maximal aggregated download throughput (bytes/sec). -1 disables download throttling. :param upload_throughput: Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling. :param connection_type: *(Optional)* Connection type if known. :param packet_loss: **(EXPERIMENTAL)** *(Optional)* WebRTC packet loss (percent, 0-100). 0 disables packet loss emulation, 100 drops all the packets. :param packet_queue_length: **(EXPERIMENTAL)** *(Optional)* WebRTC packet queue length (packet). 0 removes any queue length limitations. :param packet_reordering: **(EXPERIMENTAL)** *(Optional)* WebRTC packetReordering feature. """ params: T_JSON_DICT = dict() params["offline"] = offline params["latency"] = latency params["downloadThroughput"] = download_throughput params["uploadThroughput"] = upload_throughput if connection_type is not None: params["connectionType"] = connection_type.to_json() if packet_loss is not None: params["packetLoss"] = packet_loss if packet_queue_length is not None: params["packetQueueLength"] = packet_queue_length if packet_reordering is not None: params["packetReordering"] = packet_reordering cmd_dict: T_JSON_DICT = { "method": "Network.emulateNetworkConditions", "params": params, } json = yield cmd_dict
[docs] def enable( max_total_buffer_size: typing.Optional[int] = None, max_resource_buffer_size: typing.Optional[int] = None, max_post_data_size: typing.Optional[int] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Enables network tracking, network events will now be delivered to the client. :param max_total_buffer_size: **(EXPERIMENTAL)** *(Optional)* Buffer size in bytes to use when preserving network payloads (XHRs, etc). :param max_resource_buffer_size: **(EXPERIMENTAL)** *(Optional)* Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). :param max_post_data_size: *(Optional)* Longest post body size (in bytes) that would be included in requestWillBeSent notification """ params: T_JSON_DICT = dict() if max_total_buffer_size is not None: params["maxTotalBufferSize"] = max_total_buffer_size if max_resource_buffer_size is not None: params["maxResourceBufferSize"] = max_resource_buffer_size if max_post_data_size is not None: params["maxPostDataSize"] = max_post_data_size cmd_dict: T_JSON_DICT = { "method": "Network.enable", "params": params, } json = yield cmd_dict
[docs] @deprecated(version="1.3") def get_all_cookies() -> ( typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.List[Cookie]] ): """ Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the ``cookies`` field. Deprecated. Use Storage.getCookies instead. .. deprecated:: 1.3 :returns: Array of cookie objects. """ cmd_dict: T_JSON_DICT = { "method": "Network.getAllCookies", } json = yield cmd_dict return [Cookie.from_json(i) for i in json["cookies"]]
[docs] def get_certificate( origin: str, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.List[str]]: """ Returns the DER-encoded certificate. **EXPERIMENTAL** :param origin: Origin to get certificate for. :returns: """ params: T_JSON_DICT = dict() params["origin"] = origin cmd_dict: T_JSON_DICT = { "method": "Network.getCertificate", "params": params, } json = yield cmd_dict return [str(i) for i in json["tableNames"]]
[docs] def get_cookies( urls: typing.Optional[typing.List[str]] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.List[Cookie]]: """ Returns all browser cookies for the current URL. Depending on the backend support, will return detailed cookie information in the ``cookies`` field. :param urls: *(Optional)* The list of URLs for which applicable cookies will be fetched. If not specified, it's assumed to be set to the list containing the URLs of the page and all of its subframes. :returns: Array of cookie objects. """ params: T_JSON_DICT = dict() if urls is not None: params["urls"] = [i for i in urls] cmd_dict: T_JSON_DICT = { "method": "Network.getCookies", "params": params, } json = yield cmd_dict return [Cookie.from_json(i) for i in json["cookies"]]
[docs] def get_response_body( request_id: RequestId, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.Tuple[str, bool]]: """ Returns content served for the given request. :param request_id: Identifier of the network request to get content for. :returns: A tuple with the following items: 0. **body** - Response body. 1. **base64Encoded** - True, if content was sent as base64. """ params: T_JSON_DICT = dict() params["requestId"] = request_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.getResponseBody", "params": params, } json = yield cmd_dict return (str(json["body"]), bool(json["base64Encoded"]))
[docs] def get_request_post_data( request_id: RequestId, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, str]: """ Returns post data sent with the request. Returns an error when no data was sent with the request. :param request_id: Identifier of the network request to get content for. :returns: Request body string, omitting files from multipart requests """ params: T_JSON_DICT = dict() params["requestId"] = request_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.getRequestPostData", "params": params, } json = yield cmd_dict return str(json["postData"])
[docs] def get_response_body_for_interception( interception_id: InterceptionId, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.Tuple[str, bool]]: """ Returns content served for the given currently intercepted request. **EXPERIMENTAL** :param interception_id: Identifier for the intercepted request to get body for. :returns: A tuple with the following items: 0. **body** - Response body. 1. **base64Encoded** - True, if content was sent as base64. """ params: T_JSON_DICT = dict() params["interceptionId"] = interception_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.getResponseBodyForInterception", "params": params, } json = yield cmd_dict return (str(json["body"]), bool(json["base64Encoded"]))
[docs] def take_response_body_for_interception_as_stream( interception_id: InterceptionId, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, io.StreamHandle]: """ 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. **EXPERIMENTAL** :param interception_id: :returns: """ params: T_JSON_DICT = dict() params["interceptionId"] = interception_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.takeResponseBodyForInterceptionAsStream", "params": params, } json = yield cmd_dict return io.StreamHandle.from_json(json["stream"])
[docs] def replay_xhr( request_id: RequestId, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ 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. **EXPERIMENTAL** :param request_id: Identifier of XHR to replay. """ params: T_JSON_DICT = dict() params["requestId"] = request_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.replayXHR", "params": params, } json = yield cmd_dict
[docs] def search_in_response_body( request_id: RequestId, query: str, case_sensitive: typing.Optional[bool] = None, is_regex: typing.Optional[bool] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.List[debugger.SearchMatch]]: """ Searches for given string in response content. **EXPERIMENTAL** :param request_id: Identifier of the network response to search. :param query: String to search for. :param case_sensitive: *(Optional)* If true, search is case sensitive. :param is_regex: *(Optional)* If true, treats string parameter as regex. :returns: List of search matches. """ params: T_JSON_DICT = dict() params["requestId"] = request_id.to_json() params["query"] = query if case_sensitive is not None: params["caseSensitive"] = case_sensitive if is_regex is not None: params["isRegex"] = is_regex cmd_dict: T_JSON_DICT = { "method": "Network.searchInResponseBody", "params": params, } json = yield cmd_dict return [debugger.SearchMatch.from_json(i) for i in json["result"]]
[docs] def set_blocked_ur_ls( urls: typing.List[str], ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Blocks URLs from loading. **EXPERIMENTAL** :param urls: URL patterns to block. Wildcards ('*') are allowed. """ params: T_JSON_DICT = dict() params["urls"] = [i for i in urls] cmd_dict: T_JSON_DICT = { "method": "Network.setBlockedURLs", "params": params, } json = yield cmd_dict
[docs] def set_bypass_service_worker( bypass: bool, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Toggles ignoring of service worker for each request. :param bypass: Bypass service worker and load from network. """ params: T_JSON_DICT = dict() params["bypass"] = bypass cmd_dict: T_JSON_DICT = { "method": "Network.setBypassServiceWorker", "params": params, } json = yield cmd_dict
[docs] def set_cache_disabled( cache_disabled: bool, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Toggles ignoring cache for each request. If ``true``, cache will not be used. :param cache_disabled: Cache disabled state. """ params: T_JSON_DICT = dict() params["cacheDisabled"] = cache_disabled cmd_dict: T_JSON_DICT = { "method": "Network.setCacheDisabled", "params": params, } json = yield cmd_dict
[docs] def set_cookies( cookies: typing.List[CookieParam], ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Sets given cookies. :param cookies: Cookies to be set. """ params: T_JSON_DICT = dict() params["cookies"] = [i.to_json() for i in cookies] cmd_dict: T_JSON_DICT = { "method": "Network.setCookies", "params": params, } json = yield cmd_dict
[docs] def set_extra_http_headers( headers: Headers, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Specifies whether to always send extra HTTP headers with the requests from this page. :param headers: Map with extra HTTP headers. """ params: T_JSON_DICT = dict() params["headers"] = headers.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.setExtraHTTPHeaders", "params": params, } json = yield cmd_dict
[docs] def set_attach_debug_stack( enabled: bool, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Specifies whether to attach a page script stack id in requests **EXPERIMENTAL** :param enabled: Whether to attach a page script stack for debugging purpose. """ params: T_JSON_DICT = dict() params["enabled"] = enabled cmd_dict: T_JSON_DICT = { "method": "Network.setAttachDebugStack", "params": params, } json = yield cmd_dict
[docs] @deprecated(version="1.3") def set_request_interception( patterns: typing.List[RequestPattern], ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Sets the requests to intercept that match the provided patterns and optionally resource types. Deprecated, please use Fetch.enable instead. .. deprecated:: 1.3 **EXPERIMENTAL** :param patterns: Requests matching any of these patterns will be forwarded and wait for the corresponding continueInterceptedRequest call. """ params: T_JSON_DICT = dict() params["patterns"] = [i.to_json() for i in patterns] cmd_dict: T_JSON_DICT = { "method": "Network.setRequestInterception", "params": params, } json = yield cmd_dict
[docs] def set_user_agent_override( user_agent: str, accept_language: typing.Optional[str] = None, platform: typing.Optional[str] = None, user_agent_metadata: typing.Optional[emulation.UserAgentMetadata] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ Allows overriding user agent with the given string. :param user_agent: User agent to use. :param accept_language: *(Optional)* Browser language to emulate. :param platform: *(Optional)* The platform navigator.platform should return. :param user_agent_metadata: **(EXPERIMENTAL)** *(Optional)* To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData """ params: T_JSON_DICT = dict() params["userAgent"] = user_agent if accept_language is not None: params["acceptLanguage"] = accept_language if platform is not None: params["platform"] = platform if user_agent_metadata is not None: params["userAgentMetadata"] = user_agent_metadata.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.setUserAgentOverride", "params": params, } json = yield cmd_dict
[docs] def stream_resource_content( request_id: RequestId, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, str]: """ Enables streaming of the response for the given requestId. If enabled, the dataReceived event contains the data that was received during streaming. **EXPERIMENTAL** :param request_id: Identifier of the request to stream. :returns: Data that has been buffered until streaming is enabled. (Encoded as a base64 string when passed over JSON) """ params: T_JSON_DICT = dict() params["requestId"] = request_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.streamResourceContent", "params": params, } json = yield cmd_dict return str(json["bufferedData"])
[docs] def get_security_isolation_status( frame_id: typing.Optional[page.FrameId] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, SecurityIsolationStatus]: """ Returns information about the COEP/COOP isolation status. **EXPERIMENTAL** :param frame_id: *(Optional)* If no frameId is provided, the status of the target is provided. :returns: """ params: T_JSON_DICT = dict() if frame_id is not None: params["frameId"] = frame_id.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.getSecurityIsolationStatus", "params": params, } json = yield cmd_dict return SecurityIsolationStatus.from_json(json["status"])
[docs] def enable_reporting_api( enable: bool, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, None]: """ 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. **EXPERIMENTAL** :param enable: Whether to enable or disable events for the Reporting API """ params: T_JSON_DICT = dict() params["enable"] = enable cmd_dict: T_JSON_DICT = { "method": "Network.enableReportingApi", "params": params, } json = yield cmd_dict
[docs] def load_network_resource( url: str, options: LoadNetworkResourceOptions, frame_id: typing.Optional[page.FrameId] = None, ) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, LoadNetworkResourcePageResult]: """ Fetches the resource and returns the content. **EXPERIMENTAL** :param frame_id: *(Optional)* Frame id to get the resource for. Mandatory for frame targets, and should be omitted for worker targets. :param url: URL of the resource to get content for. :param options: Options for the request. :returns: """ params: T_JSON_DICT = dict() if frame_id is not None: params["frameId"] = frame_id.to_json() params["url"] = url params["options"] = options.to_json() cmd_dict: T_JSON_DICT = { "method": "Network.loadNetworkResource", "params": params, } json = yield cmd_dict return LoadNetworkResourcePageResult.from_json(json["resource"])
[docs] @event_class("Network.dataReceived") @dataclass class DataReceived: """ Fired when data chunk was received over the network. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: Data chunk length. data_length: int #: Actual bytes received (might be less than dataLength for compressed encodings). encoded_data_length: int #: Data that was received. (Encoded as a base64 string when passed over JSON) data: typing.Optional[str] @classmethod def from_json(cls, json: T_JSON_DICT) -> DataReceived: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), data_length=int(json["dataLength"]), encoded_data_length=int(json["encodedDataLength"]), data=str(json["data"]) if json.get("data", None) is not None else None, )
[docs] @event_class("Network.eventSourceMessageReceived") @dataclass class EventSourceMessageReceived: """ Fired when EventSource message is received. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: Message type. event_name: str #: Message identifier. event_id: str #: Message content. data: str @classmethod def from_json(cls, json: T_JSON_DICT) -> EventSourceMessageReceived: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), event_name=str(json["eventName"]), event_id=str(json["eventId"]), data=str(json["data"]), )
[docs] @event_class("Network.loadingFailed") @dataclass class LoadingFailed: """ Fired when HTTP request has failed to load. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: Resource type. type_: ResourceType #: Error message. List of network errors: https://cs.chromium.org/chromium/src/net/base/net_error_list.h error_text: str #: True if loading was canceled. canceled: typing.Optional[bool] #: The reason why loading was blocked, if any. blocked_reason: typing.Optional[BlockedReason] #: The reason why loading was blocked by CORS, if any. cors_error_status: typing.Optional[CorsErrorStatus] @classmethod def from_json(cls, json: T_JSON_DICT) -> LoadingFailed: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), type_=ResourceType.from_json(json["type"]), error_text=str(json["errorText"]), canceled=( bool(json["canceled"]) if json.get("canceled", None) is not None else None ), blocked_reason=( BlockedReason.from_json(json["blockedReason"]) if json.get("blockedReason", None) is not None else None ), cors_error_status=( CorsErrorStatus.from_json(json["corsErrorStatus"]) if json.get("corsErrorStatus", None) is not None else None ), )
[docs] @event_class("Network.loadingFinished") @dataclass class LoadingFinished: """ Fired when HTTP request has finished loading. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: Total number of bytes received for this request. encoded_data_length: float @classmethod def from_json(cls, json: T_JSON_DICT) -> LoadingFinished: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), encoded_data_length=float(json["encodedDataLength"]), )
[docs] @deprecated(version="1.3") @event_class("Network.requestIntercepted") @dataclass class RequestIntercepted: """ **EXPERIMENTAL** Details of an intercepted HTTP request, which must be either allowed, blocked, modified or mocked. Deprecated, use Fetch.requestPaused instead. """ #: Each request the page makes will have a unique id, however if any redirects are encountered #: while processing that fetch, they will be reported with the same id as the original fetch. #: Likewise if HTTP authentication is needed then the same fetch id will be used. interception_id: InterceptionId request: Request #: The id of the frame that initiated the request. frame_id: page.FrameId #: How the requested resource will be used. resource_type: ResourceType #: Whether this is a navigation request, which can abort the navigation completely. is_navigation_request: bool #: Set if the request is a navigation that will result in a download. #: Only present after response is received from the server (i.e. HeadersReceived stage). is_download: typing.Optional[bool] #: Redirect location, only sent if a redirect was intercepted. redirect_url: typing.Optional[str] #: Details of the Authorization Challenge encountered. If this is set then #: continueInterceptedRequest must contain an authChallengeResponse. auth_challenge: typing.Optional[AuthChallenge] #: Response error if intercepted at response stage or if redirect occurred while intercepting #: request. response_error_reason: typing.Optional[ErrorReason] #: Response code if intercepted at response stage or if redirect occurred while intercepting #: request or auth retry occurred. response_status_code: typing.Optional[int] #: Response headers if intercepted at the response stage or if redirect occurred while #: intercepting request or auth retry occurred. response_headers: typing.Optional[Headers] #: If the intercepted request had a corresponding requestWillBeSent event fired for it, then #: this requestId will be the same as the requestId present in the requestWillBeSent event. request_id: typing.Optional[RequestId] @classmethod def from_json(cls, json: T_JSON_DICT) -> RequestIntercepted: return cls( interception_id=InterceptionId.from_json(json["interceptionId"]), request=Request.from_json(json["request"]), frame_id=page.FrameId.from_json(json["frameId"]), resource_type=ResourceType.from_json(json["resourceType"]), is_navigation_request=bool(json["isNavigationRequest"]), is_download=( bool(json["isDownload"]) if json.get("isDownload", None) is not None else None ), redirect_url=( str(json["redirectUrl"]) if json.get("redirectUrl", None) is not None else None ), auth_challenge=( AuthChallenge.from_json(json["authChallenge"]) if json.get("authChallenge", None) is not None else None ), response_error_reason=( ErrorReason.from_json(json["responseErrorReason"]) if json.get("responseErrorReason", None) is not None else None ), response_status_code=( int(json["responseStatusCode"]) if json.get("responseStatusCode", None) is not None else None ), response_headers=( Headers.from_json(json["responseHeaders"]) if json.get("responseHeaders", None) is not None else None ), request_id=( RequestId.from_json(json["requestId"]) if json.get("requestId", None) is not None else None ), )
[docs] @event_class("Network.requestServedFromCache") @dataclass class RequestServedFromCache: """ Fired if request ended up loading from cache. """ #: Request identifier. request_id: RequestId @classmethod def from_json(cls, json: T_JSON_DICT) -> RequestServedFromCache: return cls(request_id=RequestId.from_json(json["requestId"]))
[docs] @event_class("Network.requestWillBeSent") @dataclass class RequestWillBeSent: """ Fired when page is about to send HTTP request. """ #: Request identifier. request_id: RequestId #: Loader identifier. Empty string if the request is fetched from worker. loader_id: LoaderId #: URL of the document this request is loaded for. document_url: str #: Request data. request: Request #: Timestamp. timestamp: MonotonicTime #: Timestamp. wall_time: TimeSinceEpoch #: Request initiator. initiator: Initiator #: In the case that redirectResponse is populated, this flag indicates whether #: requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be or were emitted #: for the request which was just redirected. redirect_has_extra_info: bool #: Redirect response data. redirect_response: typing.Optional[Response] #: Type of this resource. type_: typing.Optional[ResourceType] #: Frame identifier. frame_id: typing.Optional[page.FrameId] #: Whether the request is initiated by a user gesture. Defaults to false. has_user_gesture: typing.Optional[bool] @classmethod def from_json(cls, json: T_JSON_DICT) -> RequestWillBeSent: return cls( request_id=RequestId.from_json(json["requestId"]), loader_id=LoaderId.from_json(json["loaderId"]), document_url=str(json["documentURL"]), request=Request.from_json(json["request"]), timestamp=MonotonicTime.from_json(json["timestamp"]), wall_time=TimeSinceEpoch.from_json(json["wallTime"]), initiator=Initiator.from_json(json["initiator"]), redirect_has_extra_info=bool(json["redirectHasExtraInfo"]), redirect_response=( Response.from_json(json["redirectResponse"]) if json.get("redirectResponse", None) is not None else None ), type_=( ResourceType.from_json(json["type"]) if json.get("type", None) is not None else None ), frame_id=( page.FrameId.from_json(json["frameId"]) if json.get("frameId", None) is not None else None ), has_user_gesture=( bool(json["hasUserGesture"]) if json.get("hasUserGesture", None) is not None else None ), )
[docs] @event_class("Network.resourceChangedPriority") @dataclass class ResourceChangedPriority: """ **EXPERIMENTAL** Fired when resource loading priority is changed """ #: Request identifier. request_id: RequestId #: New priority new_priority: ResourcePriority #: Timestamp. timestamp: MonotonicTime @classmethod def from_json(cls, json: T_JSON_DICT) -> ResourceChangedPriority: return cls( request_id=RequestId.from_json(json["requestId"]), new_priority=ResourcePriority.from_json(json["newPriority"]), timestamp=MonotonicTime.from_json(json["timestamp"]), )
[docs] @event_class("Network.signedExchangeReceived") @dataclass class SignedExchangeReceived: """ **EXPERIMENTAL** Fired when a signed exchange was received over the network """ #: Request identifier. request_id: RequestId #: Information about the signed exchange response. info: SignedExchangeInfo @classmethod def from_json(cls, json: T_JSON_DICT) -> SignedExchangeReceived: return cls( request_id=RequestId.from_json(json["requestId"]), info=SignedExchangeInfo.from_json(json["info"]), )
[docs] @event_class("Network.responseReceived") @dataclass class ResponseReceived: """ Fired when HTTP response is available. """ #: Request identifier. request_id: RequestId #: Loader identifier. Empty string if the request is fetched from worker. loader_id: LoaderId #: Timestamp. timestamp: MonotonicTime #: Resource type. type_: ResourceType #: Response data. response: Response #: Indicates whether requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be #: or were emitted for this request. has_extra_info: bool #: Frame identifier. frame_id: typing.Optional[page.FrameId] @classmethod def from_json(cls, json: T_JSON_DICT) -> ResponseReceived: return cls( request_id=RequestId.from_json(json["requestId"]), loader_id=LoaderId.from_json(json["loaderId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), type_=ResourceType.from_json(json["type"]), response=Response.from_json(json["response"]), has_extra_info=bool(json["hasExtraInfo"]), frame_id=( page.FrameId.from_json(json["frameId"]) if json.get("frameId", None) is not None else None ), )
[docs] @event_class("Network.webSocketClosed") @dataclass class WebSocketClosed: """ Fired when WebSocket is closed. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketClosed: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), )
[docs] @event_class("Network.webSocketCreated") @dataclass class WebSocketCreated: """ Fired upon WebSocket creation. """ #: Request identifier. request_id: RequestId #: WebSocket request URL. url: str #: Request initiator. initiator: typing.Optional[Initiator] @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketCreated: return cls( request_id=RequestId.from_json(json["requestId"]), url=str(json["url"]), initiator=( Initiator.from_json(json["initiator"]) if json.get("initiator", None) is not None else None ), )
[docs] @event_class("Network.webSocketFrameError") @dataclass class WebSocketFrameError: """ Fired when WebSocket message error occurs. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: WebSocket error message. error_message: str @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketFrameError: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), error_message=str(json["errorMessage"]), )
[docs] @event_class("Network.webSocketFrameReceived") @dataclass class WebSocketFrameReceived: """ Fired when WebSocket message is received. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: WebSocket response data. response: WebSocketFrame @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketFrameReceived: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), response=WebSocketFrame.from_json(json["response"]), )
[docs] @event_class("Network.webSocketFrameSent") @dataclass class WebSocketFrameSent: """ Fired when WebSocket message is sent. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: WebSocket response data. response: WebSocketFrame @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketFrameSent: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), response=WebSocketFrame.from_json(json["response"]), )
[docs] @event_class("Network.webSocketHandshakeResponseReceived") @dataclass class WebSocketHandshakeResponseReceived: """ Fired when WebSocket handshake response becomes available. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: WebSocket response data. response: WebSocketResponse @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketHandshakeResponseReceived: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), response=WebSocketResponse.from_json(json["response"]), )
[docs] @event_class("Network.webSocketWillSendHandshakeRequest") @dataclass class WebSocketWillSendHandshakeRequest: """ Fired when WebSocket is about to initiate handshake. """ #: Request identifier. request_id: RequestId #: Timestamp. timestamp: MonotonicTime #: UTC Timestamp. wall_time: TimeSinceEpoch #: WebSocket request data. request: WebSocketRequest @classmethod def from_json(cls, json: T_JSON_DICT) -> WebSocketWillSendHandshakeRequest: return cls( request_id=RequestId.from_json(json["requestId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), wall_time=TimeSinceEpoch.from_json(json["wallTime"]), request=WebSocketRequest.from_json(json["request"]), )
[docs] @event_class("Network.webTransportCreated") @dataclass class WebTransportCreated: """ Fired upon WebTransport creation. """ #: WebTransport identifier. transport_id: RequestId #: WebTransport request URL. url: str #: Timestamp. timestamp: MonotonicTime #: Request initiator. initiator: typing.Optional[Initiator] @classmethod def from_json(cls, json: T_JSON_DICT) -> WebTransportCreated: return cls( transport_id=RequestId.from_json(json["transportId"]), url=str(json["url"]), timestamp=MonotonicTime.from_json(json["timestamp"]), initiator=( Initiator.from_json(json["initiator"]) if json.get("initiator", None) is not None else None ), )
[docs] @event_class("Network.webTransportConnectionEstablished") @dataclass class WebTransportConnectionEstablished: """ Fired when WebTransport handshake is finished. """ #: WebTransport identifier. transport_id: RequestId #: Timestamp. timestamp: MonotonicTime @classmethod def from_json(cls, json: T_JSON_DICT) -> WebTransportConnectionEstablished: return cls( transport_id=RequestId.from_json(json["transportId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), )
[docs] @event_class("Network.webTransportClosed") @dataclass class WebTransportClosed: """ Fired when WebTransport is disposed. """ #: WebTransport identifier. transport_id: RequestId #: Timestamp. timestamp: MonotonicTime @classmethod def from_json(cls, json: T_JSON_DICT) -> WebTransportClosed: return cls( transport_id=RequestId.from_json(json["transportId"]), timestamp=MonotonicTime.from_json(json["timestamp"]), )
[docs] @event_class("Network.requestWillBeSentExtraInfo") @dataclass class RequestWillBeSentExtraInfo: """ **EXPERIMENTAL** 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. """ #: Request identifier. Used to match this information to an existing requestWillBeSent event. request_id: RequestId #: A list of cookies potentially associated to the requested URL. This includes both cookies sent with #: the request and the ones not sent; the latter are distinguished by having blockedReasons field set. associated_cookies: typing.List[AssociatedCookie] #: Raw request headers as they will be sent over the wire. headers: Headers #: Connection timing information for the request. connect_timing: ConnectTiming #: The client security state set for the request. client_security_state: typing.Optional[ClientSecurityState] #: Whether the site has partitioned cookies stored in a partition different than the current one. site_has_cookie_in_other_partition: typing.Optional[bool] @classmethod def from_json(cls, json: T_JSON_DICT) -> RequestWillBeSentExtraInfo: return cls( request_id=RequestId.from_json(json["requestId"]), associated_cookies=[ AssociatedCookie.from_json(i) for i in json["associatedCookies"] ], headers=Headers.from_json(json["headers"]), connect_timing=ConnectTiming.from_json(json["connectTiming"]), client_security_state=( ClientSecurityState.from_json(json["clientSecurityState"]) if json.get("clientSecurityState", None) is not None else None ), site_has_cookie_in_other_partition=( bool(json["siteHasCookieInOtherPartition"]) if json.get("siteHasCookieInOtherPartition", None) is not None else None ), )
[docs] @event_class("Network.responseReceivedExtraInfo") @dataclass class ResponseReceivedExtraInfo: """ **EXPERIMENTAL** 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. """ #: Request identifier. Used to match this information to another responseReceived event. request_id: RequestId #: A list of cookies which were not stored from the response along with the corresponding #: reasons for blocking. The cookies here may not be valid due to syntax errors, which #: are represented by the invalid cookie line string instead of a proper cookie. blocked_cookies: typing.List[BlockedSetCookieWithReason] #: Raw response headers as they were received over the wire. headers: Headers #: The IP address space of the resource. The address space can only be determined once the transport #: established the connection, so we can't send it in ``requestWillBeSentExtraInfo``. resource_ip_address_space: IPAddressSpace #: The status code of the response. This is useful in cases the request failed and no responseReceived #: event is triggered, which is the case for, e.g., CORS errors. This is also the correct status code #: for cached requests, where the status in responseReceived is a 200 and this will be 304. status_code: int #: Raw response header text as it was received over the wire. The raw text may not always be #: available, such as in the case of HTTP/2 or QUIC. headers_text: typing.Optional[str] #: The cookie partition key that will be used to store partitioned cookies set in this response. #: Only sent when partitioned cookies are enabled. cookie_partition_key: typing.Optional[CookiePartitionKey] #: True if partitioned cookies are enabled, but the partition key is not serializable to string. cookie_partition_key_opaque: typing.Optional[bool] #: A list of cookies which should have been blocked by 3PCD but are exempted and stored from #: the response with the corresponding reason. exempted_cookies: typing.Optional[typing.List[ExemptedSetCookieWithReason]] @classmethod def from_json(cls, json: T_JSON_DICT) -> ResponseReceivedExtraInfo: return cls( request_id=RequestId.from_json(json["requestId"]), blocked_cookies=[ BlockedSetCookieWithReason.from_json(i) for i in json["blockedCookies"] ], headers=Headers.from_json(json["headers"]), resource_ip_address_space=IPAddressSpace.from_json( json["resourceIPAddressSpace"] ), status_code=int(json["statusCode"]), headers_text=( str(json["headersText"]) if json.get("headersText", None) is not None else None ), cookie_partition_key=( CookiePartitionKey.from_json(json["cookiePartitionKey"]) if json.get("cookiePartitionKey", None) is not None else None ), cookie_partition_key_opaque=( bool(json["cookiePartitionKeyOpaque"]) if json.get("cookiePartitionKeyOpaque", None) is not None else None ), exempted_cookies=( [ ExemptedSetCookieWithReason.from_json(i) for i in json["exemptedCookies"] ] if json.get("exemptedCookies", None) is not None else None ), )
[docs] @event_class("Network.responseReceivedEarlyHints") @dataclass class ResponseReceivedEarlyHints: """ **EXPERIMENTAL** 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. """ #: Request identifier. Used to match this information to another responseReceived event. request_id: RequestId #: Raw response headers as they were received over the wire. headers: Headers @classmethod def from_json(cls, json: T_JSON_DICT) -> ResponseReceivedEarlyHints: return cls( request_id=RequestId.from_json(json["requestId"]), headers=Headers.from_json(json["headers"]), )
[docs] @event_class("Network.trustTokenOperationDone") @dataclass class TrustTokenOperationDone: """ **EXPERIMENTAL** 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. """ #: Detailed success or error status of the operation. #: 'AlreadyExists' also signifies a successful operation, as the result #: of the operation already exists und thus, the operation was abort #: preemptively (e.g. a cache hit). status: str type_: TrustTokenOperationType request_id: RequestId #: Top level origin. The context in which the operation was attempted. top_level_origin: typing.Optional[str] #: Origin of the issuer in case of a "Issuance" or "Redemption" operation. issuer_origin: typing.Optional[str] #: The number of obtained Trust Tokens on a successful "Issuance" operation. issued_token_count: typing.Optional[int] @classmethod def from_json(cls, json: T_JSON_DICT) -> TrustTokenOperationDone: return cls( status=str(json["status"]), type_=TrustTokenOperationType.from_json(json["type"]), request_id=RequestId.from_json(json["requestId"]), top_level_origin=( str(json["topLevelOrigin"]) if json.get("topLevelOrigin", None) is not None else None ), issuer_origin=( str(json["issuerOrigin"]) if json.get("issuerOrigin", None) is not None else None ), issued_token_count=( int(json["issuedTokenCount"]) if json.get("issuedTokenCount", None) is not None else None ), )
[docs] @event_class("Network.policyUpdated") @dataclass class PolicyUpdated: """ **EXPERIMENTAL** Fired once security policy has been updated. """ @classmethod def from_json(cls, json: T_JSON_DICT) -> PolicyUpdated: return cls()
[docs] @event_class("Network.subresourceWebBundleMetadataReceived") @dataclass class SubresourceWebBundleMetadataReceived: """ **EXPERIMENTAL** Fired once when parsing the .wbn file has succeeded. The event contains the information about the web bundle contents. """ #: Request identifier. Used to match this information to another event. request_id: RequestId #: A list of URLs of resources in the subresource Web Bundle. urls: typing.List[str] @classmethod def from_json(cls, json: T_JSON_DICT) -> SubresourceWebBundleMetadataReceived: return cls( request_id=RequestId.from_json(json["requestId"]), urls=[str(i) for i in json["urls"]], )
[docs] @event_class("Network.subresourceWebBundleMetadataError") @dataclass class SubresourceWebBundleMetadataError: """ **EXPERIMENTAL** Fired once when parsing the .wbn file has failed. """ #: Request identifier. Used to match this information to another event. request_id: RequestId #: Error message error_message: str @classmethod def from_json(cls, json: T_JSON_DICT) -> SubresourceWebBundleMetadataError: return cls( request_id=RequestId.from_json(json["requestId"]), error_message=str(json["errorMessage"]), )
[docs] @event_class("Network.subresourceWebBundleInnerResponseParsed") @dataclass class SubresourceWebBundleInnerResponseParsed: """ **EXPERIMENTAL** Fired when handling requests for resources within a .wbn file. Note: this will only be fired for resources that are requested by the webpage. """ #: Request identifier of the subresource request inner_request_id: RequestId #: URL of the subresource resource. inner_request_url: str #: 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. bundle_request_id: typing.Optional[RequestId] @classmethod def from_json(cls, json: T_JSON_DICT) -> SubresourceWebBundleInnerResponseParsed: return cls( inner_request_id=RequestId.from_json(json["innerRequestId"]), inner_request_url=str(json["innerRequestURL"]), bundle_request_id=( RequestId.from_json(json["bundleRequestId"]) if json.get("bundleRequestId", None) is not None else None ), )
[docs] @event_class("Network.subresourceWebBundleInnerResponseError") @dataclass class SubresourceWebBundleInnerResponseError: """ **EXPERIMENTAL** Fired when request for resources within a .wbn file failed. """ #: Request identifier of the subresource request inner_request_id: RequestId #: URL of the subresource resource. inner_request_url: str #: Error message error_message: str #: 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. bundle_request_id: typing.Optional[RequestId] @classmethod def from_json(cls, json: T_JSON_DICT) -> SubresourceWebBundleInnerResponseError: return cls( inner_request_id=RequestId.from_json(json["innerRequestId"]), inner_request_url=str(json["innerRequestURL"]), error_message=str(json["errorMessage"]), bundle_request_id=( RequestId.from_json(json["bundleRequestId"]) if json.get("bundleRequestId", None) is not None else None ), )
[docs] @event_class("Network.reportingApiReportAdded") @dataclass class ReportingApiReportAdded: """ **EXPERIMENTAL** Is sent whenever a new report is added. And after 'enableReportingApi' for all existing reports. """ report: ReportingApiReport @classmethod def from_json(cls, json: T_JSON_DICT) -> ReportingApiReportAdded: return cls(report=ReportingApiReport.from_json(json["report"]))
[docs] @event_class("Network.reportingApiReportUpdated") @dataclass class ReportingApiReportUpdated: """ **EXPERIMENTAL** """ report: ReportingApiReport @classmethod def from_json(cls, json: T_JSON_DICT) -> ReportingApiReportUpdated: return cls(report=ReportingApiReport.from_json(json["report"]))
[docs] @event_class("Network.reportingApiEndpointsChangedForOrigin") @dataclass class ReportingApiEndpointsChangedForOrigin: """ **EXPERIMENTAL** """ #: Origin of the document(s) which configured the endpoints. origin: str endpoints: typing.List[ReportingApiEndpoint] @classmethod def from_json(cls, json: T_JSON_DICT) -> ReportingApiEndpointsChangedForOrigin: return cls( origin=str(json["origin"]), endpoints=[ReportingApiEndpoint.from_json(i) for i in json["endpoints"]], )