Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / navigable_3.lucb

#==============================================================================================
#
#   navigable_3 - HTML::Navigable: navigation params from policy containers, opener policies,
#   non-fetch schemes, srcdoc resources, and the navigation params fetch
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/Navigable.cpp lines 889-1283
#       (determine_navigation_params_policy_container, obtain_an_opener_policy,
#       attempt_to_create_a_non_fetch_scheme_document,
#       create_navigation_params_from_a_srcdoc_resource, perform_navigation_params_fetch). The
#       fetch itself, its controller and requests are Fetch's (phase 2 closure stubs).
#
#       Copyright (c) 2022-2024, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2023-2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Policy containers and opener policies ===================================================

## Ported from Navigable.cpp:891 Web::HTML::determine_navigation_params_policy_container.
# https://html.spec.whatwg.org/multipage/browsers.html#determining-navigation-params-policy-container
func html_determine_navigation_params_policy_container(response_url: web_url.Url, heap: gc.Heap*, history_policy_container: HtmlPolicyContainer*?, initiator_policy_container: HtmlPolicyContainer*?, parent_policy_container: HtmlPolicyContainer*?, response_policy_container: HtmlPolicyContainer*?) -> HtmlPolicyContainer*:
    # 1. If historyPolicyContainer is not null, then:
    if let history = history_policy_container:
        # FIXME: 1. Assert: responseURL requires storing the policy container in history.

        # 2. Return a clone of historyPolicyContainer.
        return html_policy_container_clone(history, heap)

    # 2. If responseURL is about:srcdoc, then:
    if web_url.url_eq(&response_url, web_url.about_srcdoc()):
        # 1. Assert: parentPolicyContainer is not null.
        # 2. Return a clone of parentPolicyContainer.
        return html_policy_container_clone(parent_policy_container else trap("VERIFY: parent_policy_container"), heap)

    # 3. If responseURL is local and initiatorPolicyContainer is not null, then return a clone of initiatorPolicyContainer.
    if fetch_is_local_url(response_url):
        if let initiator = initiator_policy_container:
            return html_policy_container_clone(initiator, heap)

    # 4. If responsePolicyContainer is not null, then return responsePolicyContainer.
    # FIXME: File a spec issue to say "a clone of" here for consistency
    if let response_container = response_policy_container:
        return html_policy_container_clone(response_container, heap)

    # 5. Return a new policy container.
    return heap_allocate_html_policy_container(heap)

## Ported from Navigable.cpp:929 Web::HTML::obtain_an_opener_policy.
# https://html.spec.whatwg.org/multipage/browsers.html#obtain-coop
func html_obtain_an_opener_policy(arg0: FetchResponse*, reserved_client: HtmlEnvironment*?) -> HtmlOpenerPolicy:
    # 1. Let policy be a new opener policy.
    let policy = HtmlOpenerPolicy()

    # AD-HOC: We don't yet setup environments in all cases
    let reserved_environment = reserved_client else return policy

    # 2. If reservedEnvironment is a non-secure context, then return policy.
    if html_is_non_secure_context(reserved_environment):
        return policy

    # FIXME: We don't yet have the technology to extract structured data from Fetch headers
    # FIXME: 3. Let parsedItem be the result of getting a structured field value given `Cross-Origin-Opener-Policy` and "item" from response's header list.
    # FIXME: 4. If parsedItem is not null, then:
    #     FIXME: nested steps...
    # FIXME: 5. Set parsedItem to the result of getting a structured field value given `Cross-Origin-Opener-Policy-Report-Only` and "item" from response's header list.
    # FIXME: 6. If parsedItem is not null, then:
    #     FIXME: nested steps...

    # 7. Return policy.
    return policy

## Ported from Navigable.cpp:958 Web::HTML::attempt_to_create_a_non_fetch_scheme_document.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-create-a-non-fetch-scheme-document
func html_attempt_to_create_a_non_fetch_scheme_document(params: HtmlNonFetchSchemeNavigationParams*) -> DomDocument*?:
    # 1. Let url be navigationParams's URL.
    let url = params.url

    # 2. Let navigable be navigationParams's navigable.
    _ = params.navigable

    # 3. FIXME: If url is to be handled using a mechanism that does not affect navigable, e.g., because url's scheme is
    #    handled externally, then:
    #    1. FIXME: Hand-off to external software given url, navigable, navigationParams's target snapshot sandboxing flags,
    #       navigationParams's source snapshot has transient activation, and navigationParams's initiator origin.
    #    2. Return null.
    #    (C++: `if (false) { ... return {}; }`.)

    # 4. FIXME: Handle url by displaying some sort of inline content, e.g., an error message because the specified scheme is
    #    not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for
    #    the given scheme. Return the result of displaying the inline content given navigable, navigationParams's id,
    #    navigationParams's navigation timing type, and navigationParams's user involvement.

    let serialized = web_url.url_serialize(&url)
    ak.dbgln(f"FIXME: Don't know how to navigate to {ak.string_view_text(ak.string_bytes_as_string_view(&serialized))}")
    return none

# mark: Navigation params from a srcdoc resource ================================================

## `history_policy_container_variant.visit(...)`: a policy container from a serialized one, or null for "client".
func html_history_policy_container_from_variant(heap: gc.Heap*, history_policy_container_variant: HtmlSerializedPolicyContainerOrHtmlDocumentStateClient) -> HtmlPolicyContainer*?:
    match history_policy_container_variant:
        .html_serialized_policy_container(serialized):
            return html_create_a_policy_container_from_serialized_policy_container(heap, serialized)
        .html_document_state_client(_):
            return none

## `vm.heap().allocate<NavigationParams>(...)` of a navigation: heap_allocate_html_navigation_params.
## Ported from Navigable.cpp:986 Web::HTML::create_navigation_params_from_a_srcdoc_resource.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-from-a-srcdoc-resource
func html_create_navigation_params_from_a_srcdoc_resource(document_resource: EmptyOrStringOrHtmlPostResource, origin: web_url.Origin?, history_policy_container_variant: HtmlSerializedPolicyContainerOrHtmlDocumentStateClient, about_base_url: web_url.Url?, navigable: HtmlNavigable*?, target_snapshot_params: HtmlTargetSnapshotParams, user_involvement: HtmlUserNavigationInvolvement, navigation_id: ak.String?) -> HtmlNavigationParams*:
    let the_navigable = navigable else trap("no navigable")
    let vm = js_cell_vm(the_navigable.js_cell())
    let window = html_navigable_active_window(the_navigable) else trap("VERIFY: navigable->active_window()")
    let realm = bind_platform_object_realm(window.bind_platform_object())
    let heap = realm_heap(realm)

    # 1. Let documentResource be entry's document state's resource.
    var srcdoc = ak.string_new()
    match document_resource:
        .string(resource):
            srcdoc = resource
        _:
            trap("VERIFY: document_resource.has<String>()")

    # 2. Let response be a new response with
    #    URL: about:srcdoc
    #    header list: (`Content-Type`, `text/html`)
    #    body: the UTF-8 encoding of documentResource, as a body
    let response = fetch_infrastructure_response_create(vm)
    ak.vector_append_t(fetch_response_url_list(response), web_url.about_srcdoc())
    http_header_list_append(fetch_response_header_list(response), http_header_create(ak.sv("Content-Type"), ak.sv("text/html")))
    let srcdoc_view = ak.string_bytes_as_string_view(&srcdoc)
    fetch_response_set_body(response, fetch_byte_sequence_as_body(realm, ak.string_view_bytes(&srcdoc_view)))

    # 3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, and entry's document state's origin.
    let response_url = fetch_response_url(response)
    let response_origin = html_determine_the_origin_of_optional_url(response_url, target_snapshot_params.sandboxing_flags, origin)

    # 4. Let coop be a new opener policy.
    let coop = HtmlOpenerPolicy()

    # 5. Let coopEnforcementResult be a new opener policy enforcement result with
    #    url: response's URL
    #    origin: responseOrigin
    #    opener policy: coop
    let coop_enforcement_result = HtmlOpenerPolicyEnforcementResult(url = response_url else trap("the response has no URL"), origin = response_origin, opener_policy = coop)

    # 6. Let policyContainer be the result of determining navigation params policy container given response's URL,
    #    entry's document state's history policy container, null, navigable's container document's policy container, and null.
    let history_policy_container = html_history_policy_container_from_variant(heap, history_policy_container_variant)
    var policy_container: HtmlPolicyContainer*? = none
    if html_navigable_container(the_navigable) != none:
        # NOTE: Specification assumes that only navigables corresponding to iframes can be navigated to about:srcdoc.
        #       We also use srcdoc to implement load_html() for top level navigables so we need to null check container
        #       because it might be null.
        let container_document = html_navigable_container_document(the_navigable) else trap("no container document")
        policy_container = html_determine_navigation_params_policy_container(response_url else trap("the response has no URL"), heap, history_policy_container, none, dom_document_policy_container(container_document), none)
    else:
        policy_container = heap_allocate_html_policy_container(heap)

    # 7. Return a new navigation params, with
    #    id: navigationId
    #    navigable: navigable
    #    request: null
    #    response: response
    #    fetch controller: null
    #    commit early hints: null
    #    COOP enforcement result: coopEnforcementResult
    #    reserved environment: null
    #    origin: responseOrigin
    #    policy container: policyContainer
    #    final sandboxing flag set: targetSnapshotParams's sandboxing flags
    #    opener policy: coop
    #    FIXME: navigation timing type: navTimingType
    #    about base URL: entry's document state's about base URL
    #    user involvement: userInvolvement
    return heap_allocate_html_navigation_params(vm_heap(vm), navigation_id, navigable, none, response, none, none, coop_enforcement_result, none, response_origin, policy_container, target_snapshot_params.sandboxing_flags, coop, about_base_url, user_involvement)

## determine_the_origin given an Optional<URL> (C++ passes `response->url()`, an
## Optional<URL::URL>, as its Optional<URL::URL const&>).
func html_determine_the_origin_of_optional_url(url: web_url.Url?, sandbox_flags: HtmlSandboxingFlagSet, source_origin: web_url.Origin?) -> web_url.Origin:
    if let value = url:
        return html_determine_the_origin(&value, sandbox_flags, source_origin)
    return html_determine_the_origin(none, sandbox_flags, source_origin)

# mark: The navigation params fetch =============================================================

## The captures of perform_navigation_params_fetch's processResponse.
struct HtmlPerformNavigationParamsFetchProcessResponse:
    var state_holder: HtmlNavigationParamsFetchStateHolder*

## perform_navigation_params_fetch's processResponse: the fetched response.
func html_perform_navigation_params_fetch_process_response(context: void*?, fetch_response: FetchResponse*):
    let captures = (HtmlPerformNavigationParamsFetchProcessResponse*)(context else trap("no captures"))
    let state_holder = captures.state_holder

    # 1. Set response to fetchedResponse.
    state_holder.response = fetch_response
    let continuation_steps = state_holder.continuation_steps else trap("VERIFY: state_holder->continuation_steps")
    ak.function1_call(&continuation_steps.function, HtmlNavigationParamsFetchStateHolderContinuationReason.got_response)

## The captures of perform_navigation_params_fetch's ongoing-navigation observer callback.
struct HtmlPerformNavigationParamsFetchOngoingNavigationChanged:
    var state_holder: HtmlNavigationParamsFetchStateHolder*

## perform_navigation_params_fetch's observer callback: the ongoing navigation changed.
func html_perform_navigation_params_fetch_ongoing_navigation_changed(context: void*?):
    let captures = (HtmlPerformNavigationParamsFetchOngoingNavigationChanged*)(context else trap("no captures"))
    let continuation_steps = captures.state_holder.continuation_steps else trap("VERIFY: state_holder->continuation_steps")
    ak.function1_call(&continuation_steps.function, HtmlNavigationParamsFetchStateHolderContinuationReason.ongoing_navigation_changed)

## The captures of perform_navigation_params_fetch's continuation steps.
struct HtmlPerformNavigationParamsFetchContinuation:
    var realm: Realm*
    var state_holder: HtmlNavigationParamsFetchStateHolder*
    var ongoing_navigation_changed_observer: HtmlNavigationObserver*?
    var top_level_completion_steps: gc.Function1[HtmlInternalNavigationResult*, unit]*
    var fetch_completion_steps: gc.Function0[unit]*

## The static next_id of perform_navigation_params_fetch.
var html_perform_navigation_params_fetch_next_id: i32 = 1

## Ported from Navigable.cpp:1076 Web::HTML::perform_navigation_params_fetch.
func html_perform_navigation_params_fetch(realm: Realm*, state_holder: HtmlNavigationParamsFetchStateHolder*, top_level_completion_steps: gc.Function1[HtmlInternalNavigationResult*, unit]*, fetch_completion_steps: gc.Function0[unit]*):
    # 21. While true:
    # NOTE: To make this async, a loop is performed by calling "perform_navigation_params_fetch" again from within "perform_navigation_params_fetch",
    #       performs breaks by calling the passed in fetch completion steps and then returning and performs returns by
    #       calling the top level completion steps and then returning.
    let navigable = state_holder.navigable else trap("the fetch has no navigable")

    # 1. If request's reserved client is not null and currentURL's origin is not the same as request's reserved client's creation URL's origin, then:
    if let reserved_client = fetch_request_reserved_client(state_holder.request):
        let current_origin = web_url.url_origin(&state_holder.current_url)
        if not web_url.origin_is_same_origin(&current_origin, web_url.url_origin(&reserved_client.creation_url)):
            # 1. Run the environment discarding steps for request's reserved client.
            html_environment_discard_environment(reserved_client)

            # 2. Set request's reserved client to null.
            fetch_request_set_reserved_client(state_holder.request, none)

            # 3. Set commitEarlyHints to null.
            state_holder.commit_early_hints = none

    # 2. If request's reserved client is null, then:
    if fetch_request_reserved_client(state_holder.request) == none:
        # 1. Let topLevelCreationURL be currentURL.
        var top_level_creation_url: web_url.Url? = state_holder.current_url

        # 2. Let topLevelOrigin be null.
        var top_level_origin: web_url.Origin? = none

        # 3. If navigable is not a top-level traversable, then:
        if not html_navigable_is_top_level_traversable(navigable):
            # 1. Let parentEnvironment be navigable's parent's active document's relevant settings object.
            let parent = html_navigable_parent(navigable) else trap("no parent")
            let parent_environment = dom_document_relevant_settings_object(html_navigable_active_document(parent) else trap("no active document"))

            # 2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.
            top_level_creation_url = parent_environment.environment.top_level_creation_url

            # 3. Set topLevelOrigin to parentEnvironment's top-level origin.
            top_level_origin = parent_environment.environment.top_level_origin

        # 4. Set request's reserved client to a new environment whose id is a unique opaque string,
        #    target browsing context is navigable's active browsing context,
        #    creation URL is currentURL,
        #    top-level creation URL is topLevelCreationURL,
        #    and top-level origin is topLevelOrigin.
        # FIXME: Make this a proper unique opaque string.
        var id_builder = ak.string_builder_new()
        ak.string_builder_append(&id_builder, "create-by-fetching-")
        let id_number = ak.string_number_i64(html_perform_navigation_params_fetch_next_id)
        ak.string_builder_append_string_view(&id_builder, ak.string_bytes_as_string_view(&id_number))
        html_perform_navigation_params_fetch_next_id += 1
        let id_string = ak.string_builder_to_string_without_validation(&id_builder)
        fetch_request_set_reserved_client(state_holder.request, realm_create_html_environment(realm, id_string, state_holder.current_url, top_level_creation_url, top_level_origin, html_navigable_active_browsing_context(navigable)))

    # 3. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then set response to a network error and break. [CSP]
    if content_security_policy_should_navigation_request_of_type_be_blocked_by_content_security_policy(state_holder.request, state_holder.csp_navigation_type) == ContentSecurityPolicyResult.blocked:
        state_holder.response = fetch_response_network_error(realm_vm(realm), ak.string_from_str("Blocked by Content Security Policy"))
        ak.function0_call(&fetch_completion_steps.function)
        return

    # 4. Set response to null.
    state_holder.response = none

    # 5. If fetchController is null, then set fetchController to the result of fetching request,
    #    with processEarlyHintsResponse set to processEarlyHintsResponse as defined below, processResponse
    #    set to processResponse as defined below, and useParallelQueue set to true.
    if state_holder.fetch_controller == none:
        # FIXME: Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:

        # Let processResponse be the following algorithm given a response fetchedResponse:
        let process_response = new HtmlPerformNavigationParamsFetchProcessResponse(state_holder = state_holder) else trap("out of memory")

        # (useParallelQueue: Fetch::Fetching::UseParallelQueue::Yes.)
        state_holder.fetch_controller = fetch_fetching_fetch_use_parallel_queue(realm, state_holder.request, fetch_algorithms_create_with_process_response(realm_vm(realm), ak.Function1[FetchResponse*, unit](call = html_perform_navigation_params_fetch_process_response, context = process_response)))
    # 6. Otherwise, process the next manual redirect for fetchController.
    else:
        fetch_controller_process_next_manual_redirect(state_holder.fetch_controller else trap("unreachable: checked above"))

    # 7. Wait until either response is non-null, or navigable's ongoing navigation changes to no longer equal navigationId.
    var ongoing_navigation_changed_observer: HtmlNavigationObserver*? = none
    if state_holder.navigation_id != none:
        let observer = realm_create_html_navigation_observer(realm, realm, navigable)
        ongoing_navigation_changed_observer = observer
        let observer_captures = new HtmlPerformNavigationParamsFetchOngoingNavigationChanged(state_holder = state_holder) else trap("out of memory")
        html_navigation_observer_set_ongoing_navigation_changed(observer, ak.Function0[unit](call = html_perform_navigation_params_fetch_ongoing_navigation_changed, context = observer_captures))

    let captures = new HtmlPerformNavigationParamsFetchContinuation(realm = realm, state_holder = state_holder, ongoing_navigation_changed_observer = ongoing_navigation_changed_observer, top_level_completion_steps = top_level_completion_steps, fetch_completion_steps = fetch_completion_steps) else trap("out of memory")
    state_holder.continuation_steps = gc.create_function1(realm_heap(realm), ak.Function1[HtmlNavigationParamsFetchStateHolderContinuationReason, unit](call = html_perform_navigation_params_fetch_continue, context = captures))

## perform_navigation_params_fetch's continuation steps (its GC::Function lambda): steps 7 (the
## rest) to 22 of the loop's body, then the next iteration.
func html_perform_navigation_params_fetch_continue(context: void*?, continuation_reason: HtmlNavigationParamsFetchStateHolderContinuationReason):
    let captures = (HtmlPerformNavigationParamsFetchContinuation*)(context else trap("no captures"))
    let realm = captures.realm
    let state_holder = captures.state_holder
    let navigable = state_holder.navigable else trap("the fetch has no navigable")

    # If the latter condition occurs, then abort fetchController, and return. Otherwise, proceed onward.
    if let navigation_id = state_holder.navigation_id:
        let observer = captures.ongoing_navigation_changed_observer else trap("VERIFY: ongoing_navigation_changed_observer")
        html_navigation_observer_set_ongoing_navigation_changed(observer, none)

        if continuation_reason == HtmlNavigationParamsFetchStateHolderContinuationReason.ongoing_navigation_changed:
            if html_ongoing_navigation_differs_from_id(html_navigable_ongoing_navigation(navigable), navigation_id):
                fetch_controller_abort(state_holder.fetch_controller else trap("no fetch controller"), realm, none)
                let result = heap_allocate_html_internal_navigation_result(realm_heap(realm))
                result.navigation_params = HtmlNavigableNavigationParamsVariant.optional_string(none)
                ak.function1_call(&captures.top_level_completion_steps.function, result)
                return

    # 8. If request's body is null, then set entry's document state's resource to null.
    if fetch_request_body_is_empty(state_holder.request):
        state_holder.resource_cleared = true
        state_holder.resource = EmptyOrStringOrHtmlPostResource.empty

    let response = state_holder.response else trap("the fetch has no response")

    # 9. Set responsePolicyContainer to the result of creating a policy container from a fetch response given response and request's reserved client.
    let response_policy_container = html_create_a_policy_container_from_a_fetch_response(realm_heap(realm), response, fetch_request_reserved_client(state_holder.request))
    state_holder.response_policy_container = response_policy_container

    # 10. Set finalSandboxFlags to the union of targetSnapshotParams's sandboxing flags and responsePolicyContainer's CSP list's CSP-derived sandboxing flags.
    state_holder.final_sandbox_flags = state_holder.target_snapshot_params.sandboxing_flags | content_security_policy_policy_list_csp_derived_sandboxing_flags(response_policy_container.csp_list)

    # 11. Set responseOrigin to the result of determining the origin given response's URL, finalSandboxFlags, and entry's document state's initiator origin.
    let response_url = fetch_response_url(response)
    state_holder.response_origin = html_determine_the_origin_of_optional_url(response_url, state_holder.final_sandbox_flags, state_holder.initiator_origin)

    # 12. If navigable is a top-level traversable, then:
    if html_navigable_is_top_level_traversable(navigable):
        # 1. Set responseCOOP to the result of obtaining an opener policy given response and request's reserved client.
        state_holder.response_coop = html_obtain_an_opener_policy(response, fetch_request_reserved_client(state_holder.request))

        # FIXME: 2. Set coopEnforcementResult to the result of enforcing the response's opener policy given navigable's active browsing context,
        #    response's URL, responseOrigin, responseCOOP, coopEnforcementResult and request's referrer.

        # FIXME: 3. If finalSandboxFlags is not empty and responseCOOP's value is not "unsafe-none", then set response to an appropriate network error and break.
        # NOTE: This results in a network error as one cannot simultaneously provide a clean slate to a response
        #       using opener policy and sandbox the result of navigating to that response.

    # 13. FIXME: If response is not a network error, navigable is a child navigable, and the result of performing a cross-origin resource policy check
    #    with navigable's container document's origin, navigable's container document's relevant settings object, request's destination, response,
    #    and true is blocked, then set response to a network error and break.
    # NOTE: Here we're running the cross-origin resource policy check against the parent navigable rather than navigable itself
    #       This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.

    # 14. Set locationURL to response's location URL given currentURL's fragment.
    state_holder.location_url_is_error = false
    state_holder.location_url = none
    let location_url = fetch_response_location_url(response, web_url.url_fragment(&state_holder.current_url)) catch:
        state_holder.location_url_is_error = true
        recover none
    state_holder.location_url = location_url

    # 15. If locationURL is failure or null, then break.
    if state_holder.location_url_is_error or state_holder.location_url == none:
        ak.function0_call(&captures.fetch_completion_steps.function)
        return
    let location = state_holder.location_url else trap("unreachable: checked above")

    # 16. Assert: locationURL is a URL.
    # 17. Set entry's classic history API state to StructuredSerializeForStorage(null).
    state_holder.redirect_classic_history_api_state = html_structured_serialize_for_storage(realm_vm(realm), js_null()) else trap("MUST: structured_serialize_for_storage")

    # 18. Let oldDocState be entry's document state.

    # 19. Set entry's document state to a new document state, with
    # history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
    # request referrer: oldDocState's request referrer
    # request referrer policy: oldDocState's request referrer policy
    # origin: oldDocState's origin
    # resource: oldDocState's resource
    # ever populated: oldDocState's ever populated
    # navigable target name: oldDocState's navigable target name
    let new_doc_state = html_document_state_create()
    html_document_state_set_history_policy_container(new_doc_state, state_holder.history_policy_container)
    html_document_state_set_request_referrer(new_doc_state, state_holder.request_referrer)
    html_document_state_set_request_referrer_policy(new_doc_state, state_holder.request_referrer_policy)
    html_document_state_set_origin(new_doc_state, state_holder.origin)
    html_document_state_set_resource(new_doc_state, state_holder.resource)
    html_document_state_set_ever_populated(new_doc_state, state_holder.ever_populated)
    html_document_state_set_navigable_target_name(new_doc_state, state_holder.navigable_target_name)
    state_holder.replacement_document_state = new_doc_state
    state_holder.initiator_origin = none
    state_holder.about_base_url = none

    # 20. If locationURL's scheme is not an HTTP(S) scheme, then:
    let location_scheme = web_url.url_scheme(&location)
    if not fetch_is_http_or_https_scheme(ak.string_bytes_as_string_view(&location_scheme)):
        # 1. Set entry's document state's resource to null.
        html_document_state_set_resource(new_doc_state, EmptyOrStringOrHtmlPostResource.empty)

        # 2. Break.
        ak.function0_call(&captures.fetch_completion_steps.function)
        return

    # 21. Set currentURL to locationURL.
    state_holder.current_url = location

    # 22. Set entry's URL to currentURL.
    state_holder.redirected_url = state_holder.current_url

    html_perform_navigation_params_fetch(realm, state_holder, captures.top_level_completion_steps, captures.fetch_completion_steps)