| 30 | |
| 31 | |
| 32 | class HarRouter: |
| 33 | def __init__( |
| 34 | self, |
| 35 | local_utils: LocalUtils, |
| 36 | har_id: str, |
| 37 | not_found_action: RouteFromHarNotFoundPolicy, |
| 38 | url_matcher: Optional[URLMatch] = None, |
| 39 | ) -> None: |
| 40 | self._local_utils: LocalUtils = local_utils |
| 41 | self._har_id: str = har_id |
| 42 | self._not_found_action: RouteFromHarNotFoundPolicy = not_found_action |
| 43 | self._options_url_match: Optional[URLMatch] = url_matcher |
| 44 | |
| 45 | @staticmethod |
| 46 | async def create( |
| 47 | local_utils: LocalUtils, |
| 48 | file: str, |
| 49 | not_found_action: RouteFromHarNotFoundPolicy, |
| 50 | url_matcher: Optional[URLMatch] = None, |
| 51 | ) -> "HarRouter": |
| 52 | har_id = await local_utils._channel.send("harOpen", None, {"file": file}) |
| 53 | return HarRouter( |
| 54 | local_utils=local_utils, |
| 55 | har_id=har_id, |
| 56 | not_found_action=not_found_action, |
| 57 | url_matcher=url_matcher, |
| 58 | ) |
| 59 | |
| 60 | async def _handle(self, route: "Route") -> None: |
| 61 | request = route.request |
| 62 | response: HarLookupResult = await self._local_utils.har_lookup( |
| 63 | harId=self._har_id, |
| 64 | url=request.url, |
| 65 | method=request.method, |
| 66 | headers=await request.headers_array(), |
| 67 | postData=request.post_data_buffer, |
| 68 | isNavigationRequest=request.is_navigation_request(), |
| 69 | ) |
| 70 | action = response["action"] |
| 71 | if action == "redirect": |
| 72 | redirect_url = response["redirectURL"] |
| 73 | assert redirect_url |
| 74 | await route._redirected_navigation_request(redirect_url) |
| 75 | return |
| 76 | |
| 77 | if action == "fulfill": |
| 78 | # If the response status is -1, the request was canceled or stalled, so we just stall it here. |
| 79 | # See https://github.com/microsoft/playwright/issues/29311. |
| 80 | # TODO: it'd be better to abort such requests, but then we likely need to respect the timing, |
| 81 | # because the request might have been stalled for a long time until the very end of the |
| 82 | # test when HAR was recorded but we'd abort it immediately. |
| 83 | if response.get("status") == -1: |
| 84 | return |
| 85 | body = response["body"] |
| 86 | assert body is not None |
| 87 | await route.fulfill( |
| 88 | status=response.get("status"), |
| 89 | headers={ |