#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/TypeCasts.h>
#include <AK/Variant.h>
#include <AK/Vector.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/DataView.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/PropertyDescriptor.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Bindings/XMLHttpRequest.h>
#include <LibWeb/Bindings/XMLHttpRequestEventTarget.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOMURL/URLSearchParams.h>
#include <LibWeb/FileAPI/Blob.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/OverloadResolution.h>
#include <LibWeb/WebIDL/OverloadTypes.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>
#include <LibWeb/XHR/FormData.h>
#include <LibWeb/XHR/XMLHttpRequest.h>
#include <LibWeb/XHR/XMLHttpRequestUpload.h>

namespace Web::Bindings {

void XMLHttpRequestConstructor::initialize(JS::Realm& realm, JS::NativeFunction& object)
{
    auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;

    object.set_prototype(&ensure_web_constructor<XMLHttpRequestEventTargetPrototype>(realm, "XMLHttpRequestEventTarget"_fly_string));
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "XMLHttpRequest"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<XMLHttpRequestPrototype>(realm, "XMLHttpRequest"_fly_string), 0);

    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("UNSENT"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(0)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("OPENED"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(1)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("HEADERS_RECEIVED"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(2)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("LOADING"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(3)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("DONE"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(4)), JS::Attribute::Enumerable);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> XMLHttpRequestConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "XMLHttpRequestConstructor::construct");
    auto& vm = constructor.vm();
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // To internally create a new object implementing the interface XMLHttpRequest:

    // 3.2. Let prototype be ? Get(newTarget, "prototype").
    auto prototype = TRY(new_target.get(vm.names.prototype));

    // 3.3. If Type(prototype) is not Object, then:
    if (!prototype.is_object()) {
        // 1. Let targetRealm be ? GetFunctionRealm(newTarget).
        auto* target_realm = TRY(JS::get_function_realm(vm, new_target));

        // 2. Set prototype to the interface prototype object for interface in targetRealm.
        VERIFY(target_realm);
        prototype = &Bindings::ensure_web_prototype<XMLHttpRequestPrototype>(*target_realm, "XMLHttpRequest"_fly_string);
    }

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return XHR::XMLHttpRequest::construct_impl(realm); }));

    // 7. Set instance.[[Prototype]] to prototype.
    VERIFY(prototype.is_object());
    impl->set_prototype(&prototype.as_object());

    // FIXME: Steps 8...11. of the "internally create a new object implementing the interface XMLHttpRequest" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within XHR::XMLHttpRequest::construct_impl().

    return *impl;
}

void XMLHttpRequestPrototype::initialize(JS::Realm& realm, JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;

    object.set_prototype(GC::Ref { ensure_web_prototype<XMLHttpRequestEventTargetPrototype>(realm, "XMLHttpRequestEventTarget"_fly_string) });

    auto onreadystatechange_id = "onreadystatechange"_utf16_fly_string;
    auto native_onreadystatechange_getter = JS::NativeFunction::create(realm, onreadystatechange_getter, 0, onreadystatechange_id, &realm, "get"sv);
    auto native_onreadystatechange_setter = JS::NativeFunction::create(realm, onreadystatechange_setter, 1, onreadystatechange_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto onreadystatechange_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(onreadystatechange_id, native_onreadystatechange_getter, native_onreadystatechange_setter, onreadystatechange_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto ready_state_id = "readyState"_utf16_fly_string;
    auto native_ready_state_getter = JS::NativeFunction::create(realm, ready_state_getter, 0, ready_state_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_ready_state_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto ready_state_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(ready_state_id, native_ready_state_getter, native_ready_state_setter, ready_state_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto timeout_id = "timeout"_utf16_fly_string;
    auto native_timeout_getter = JS::NativeFunction::create(realm, timeout_getter, 0, timeout_id, &realm, "get"sv);
    auto native_timeout_setter = JS::NativeFunction::create(realm, timeout_setter, 1, timeout_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto timeout_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(timeout_id, native_timeout_getter, native_timeout_setter, timeout_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto with_credentials_id = "withCredentials"_utf16_fly_string;
    auto native_with_credentials_getter = JS::NativeFunction::create(realm, with_credentials_getter, 0, with_credentials_id, &realm, "get"sv);
    auto native_with_credentials_setter = JS::NativeFunction::create(realm, with_credentials_setter, 1, with_credentials_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto with_credentials_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(with_credentials_id, native_with_credentials_getter, native_with_credentials_setter, with_credentials_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto upload_id = "upload"_utf16_fly_string;
    auto native_upload_getter = JS::NativeFunction::create(realm, upload_getter, 0, upload_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_upload_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto upload_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(upload_id, native_upload_getter, native_upload_setter, upload_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto response_url_id = "responseURL"_utf16_fly_string;
    auto native_response_url_getter = JS::NativeFunction::create(realm, response_url_getter, 0, response_url_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_response_url_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto response_url_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(response_url_id, native_response_url_getter, native_response_url_setter, response_url_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto status_id = "status"_utf16_fly_string;
    auto native_status_getter = JS::NativeFunction::create(realm, status_getter, 0, status_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_status_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto status_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(status_id, native_status_getter, native_status_setter, status_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto status_text_id = "statusText"_utf16_fly_string;
    auto native_status_text_getter = JS::NativeFunction::create(realm, status_text_getter, 0, status_text_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_status_text_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto status_text_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(status_text_id, native_status_text_getter, native_status_text_setter, status_text_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto response_type_id = "responseType"_utf16_fly_string;
    auto native_response_type_getter = JS::NativeFunction::create(realm, response_type_getter, 0, response_type_id, &realm, "get"sv);
    auto native_response_type_setter = JS::NativeFunction::create(realm, response_type_setter, 1, response_type_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto response_type_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(response_type_id, native_response_type_getter, native_response_type_setter, response_type_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto response_id = "response"_utf16_fly_string;
    auto native_response_getter = JS::NativeFunction::create(realm, response_getter, 0, response_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_response_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto response_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(response_id, native_response_getter, native_response_setter, response_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto response_text_id = "responseText"_utf16_fly_string;
    auto native_response_text_getter = JS::NativeFunction::create(realm, response_text_getter, 0, response_text_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_response_text_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto response_text_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(response_text_id, native_response_text_getter, native_response_text_setter, response_text_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    if (is<HTML::Window>(realm.global_object())) {
        auto response_xml_id = "responseXML"_utf16_fly_string;
        auto native_response_xml_getter = JS::NativeFunction::create(realm, response_xml_getter, 0, response_xml_id, &realm, "get"sv);
        GC::Ptr<JS::NativeFunction> native_response_xml_setter;
    
        // 4. Let configurable be false if attr is unforgeable and true otherwise.
        auto response_xml_attributes = default_attributes;
    
        // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.
    
        // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
        object.define_direct_accessor(response_xml_id, native_response_xml_getter, native_response_xml_setter, response_xml_attributes);
    
        // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
        }
    object.define_native_function(realm, "open"_utf16_fly_string, open, 2, default_attributes);

    object.define_native_function(realm, "setRequestHeader"_utf16_fly_string, set_request_header, 2, default_attributes);

    object.define_native_function(realm, "send"_utf16_fly_string, send, 0, default_attributes);

    object.define_native_function(realm, "abort"_utf16_fly_string, abort, 0, default_attributes);

    object.define_native_function(realm, "getResponseHeader"_utf16_fly_string, get_response_header, 1, default_attributes);

    object.define_native_function(realm, "getAllResponseHeaders"_utf16_fly_string, get_all_response_headers, 0, default_attributes);

    object.define_native_function(realm, "overrideMimeType"_utf16_fly_string, override_mime_type, 1, default_attributes);


    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("UNSENT"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(0)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("OPENED"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(1)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("HEADERS_RECEIVED"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(2)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("LOADING"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(3)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("DONE"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(4)), JS::Attribute::Enumerable);
    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "XMLHttpRequest"_utf16), JS::Attribute::Configurable);
}

void XMLHttpRequestPrototype::define_unforgeable_attributes(JS::Realm& realm, [[maybe_unused]] JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
}

[[maybe_unused]] static JS::ThrowCompletionOr<XHR::XMLHttpRequest*> impl_from(JS::VM& vm, JS::Value js_value)
{

    if (auto impl = js_value.as_if<XHR::XMLHttpRequest>())
        return impl.ptr();
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "XMLHttpRequest");
}

[[maybe_unused]] static JS::ThrowCompletionOr<XHR::XMLHttpRequest*> impl_from(JS::VM& vm)
{
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &vm.current_realm()->global_object();
    return impl_from(vm, this_value);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::onreadystatechange_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::onreadystatechange_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->onreadystatechange(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(R->callback);
    }();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::ready_state_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::ready_state_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->ready_state(); }));

    return JS::Value(static_cast<WebIDL::UnsignedShort>(R));
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::timeout_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::timeout_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->timeout(); }));

    return JS::Value(static_cast<WebIDL::UnsignedLong>(R));
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::with_credentials_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::with_credentials_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->with_credentials(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::upload_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::upload_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->upload(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::response_url_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::response_url_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->response_url(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::status_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::status_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->status(); }));

    return JS::Value(static_cast<WebIDL::UnsignedShort>(R));
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::status_text_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::status_text_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->status_text(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::response_type_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::response_type_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->response_type(); }));

    return JS::PrimitiveString::create(vm, idl_enum_to_string(R));
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::response_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::response_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->response(); }));

    return R;
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::response_text_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::response_text_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->response_text(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::response_xml_getter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::response_xml_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->response_xml(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::onreadystatechange_setter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::onreadystatechange_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;
        if (V.is_object()) {

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {

        return vm.heap().allocate<WebIDL::CallbackType>(V.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        }
        return value;
    }(); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_onreadystatechange(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::timeout_setter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::timeout_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, V, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_timeout(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::with_credentials_setter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::with_credentials_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return V.to_boolean(); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_with_credentials(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::response_type_setter)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::response_type_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> attribute's type is an enumeration
        // 1. Let S be ? ToString(V).
        auto maybe_idl_value = throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_xml_http_request_response_type(vm, V); });

        // 2. If S is not one of the enumeration's values, then return undefined.
        if (maybe_idl_value.is_error())
            return JS::js_undefined();

        // 3. Otherwise, idlValue is the enumeration value equal to S.
        auto idl_value = maybe_idl_value.release_value();

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_response_type(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::open)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::open");

    Optional<int> chosen_overload_callable_id;
    Optional<WebIDL::EffectiveOverloadSet> effective_overload_set;

    switch (min(5, vm.argument_count())) {
    case 2:
        chosen_overload_callable_id = 0;
        break;
    case 3:
        chosen_overload_callable_id = 1;
        break;
    case 4:
        chosen_overload_callable_id = 1;
        break;
    case 5:
        chosen_overload_callable_id = 1;
        break;
    }

    Vector<StringView> dictionary_types {
    };

    if (!chosen_overload_callable_id.has_value()) {
        if (!effective_overload_set.has_value())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::OverloadResolutionFailed);
        chosen_overload_callable_id = TRY(WebIDL::resolve_overload(vm, effective_overload_set.value(), dictionary_types)).callable_id;
    }


    switch (chosen_overload_callable_id.value()) {
    case 0:
        return open0(vm);
    case 1:
        return open1(vm);
    default:
        VERIFY_NOT_REACHED();
    }
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::open0)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::open0");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "open", "2");

    auto arg0 = vm.argument(0);
    auto method = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    auto arg1 = vm.argument(1);
    auto url = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->open(method, url); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::open1)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::open1");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 3)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "open", "3");

    auto arg0 = vm.argument(0);
    auto method = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_byte_string(vm, arg0));
    }(); }));

    auto arg1 = vm.argument(1);
    auto url = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg1));
    }(); }));

    auto arg2 = vm.argument(2);
    auto async = TRY(throw_dom_exception_if_needed(vm, [&] { return arg2.to_boolean(); }));

    auto arg3 = vm.argument(3);
    Optional<String> username = OptionalNone {};
    if (!arg3.is_undefined())
        username = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<String>> {
        Optional<String> value;

        if (!arg3.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg3));
    }());
        }
        return value;
    }(); }));

    auto arg4 = vm.argument(4);
    Optional<String> password = OptionalNone {};
    if (!arg4.is_undefined())
        password = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<String>> {
        Optional<String> value;

        if (!arg4.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg4));
    }());
        }
        return value;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->open(method, url, async, username, password); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::set_request_header)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::set_request_header");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "setRequestHeader", "2");

    auto arg0 = vm.argument(0);
    auto name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_byte_string(vm, arg0));
    }(); }));

    auto arg1 = vm.argument(1);
    auto value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_byte_string(vm, arg1));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_request_header(name, value); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::send)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::send");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String, Empty> body = Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String, Empty> { Empty {} };
    if (!arg0.is_undefined())
        body = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String, Empty>> {
        Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String, Empty> value;

        if (!arg0.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String>> {

        if (arg0.is_object()) {
            [[maybe_unused]] auto& object = arg0.as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Document>(object))
                    return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { GC::Ref { *result } };

                if (auto* result = as_if<FileAPI::Blob>(object))
                    return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { GC::Ref { *result } };

                if (auto* result = as_if<XHR::FormData>(object))
                    return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { GC::Ref { *result } };

                if (auto* result = as_if<DOMURL::URLSearchParams>(object))
                    return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { GC::Ref { *result } };
            }

            if (auto* array_buffer = as_if<JS::ArrayBuffer>(object)) {
                if (!array_buffer->is_shared_array_buffer()) {
                    // 1. If types includes ArrayBuffer, then return the result of converting V to ArrayBuffer.
                    auto array_buffer_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::ArrayBuffer>> {
        // A JavaScript value V is converted to an IDL ArrayBuffer value by running the following algorithm:
        // 1. If V is not an Object, or V does not have an [[ArrayBufferData]] internal slot, then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::ArrayBuffer>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "ArrayBuffer");

        // 2. If IsSharedArrayBuffer(V) is true, then throw a TypeError.
        if (builtin_buffer->is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V) is false, then throw a TypeError.
        if (!builtin_buffer->is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length ArrayBuffer");

        // 4. Return the IDL ArrayBuffer value that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                    return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { array_buffer_union_type };
                }
            }

            if (as_if<JS::DataView>(object)) {
                // 1. If types includes DataView, then return the result of converting V to DataView.
                auto data_view_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::DataView>> {
        // A JavaScript value V is converted to an IDL DataView value by running the following algorithm:
        // 1. If V is not an Object, or V does not have a [[DataView]] internal slot, then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::DataView>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "DataView");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length DataView");

        // 4. Return the IDL DataView value that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { data_view_union_type };
            }

            if (as_if<JS::Int8Array>(object)) {
                auto int8_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Int8Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Int8Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Int8Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Int8Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { int8_array_union_type };
            }

            if (as_if<JS::Int16Array>(object)) {
                auto int16_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Int16Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Int16Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Int16Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Int16Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { int16_array_union_type };
            }

            if (as_if<JS::Int32Array>(object)) {
                auto int32_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Int32Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Int32Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Int32Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Int32Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { int32_array_union_type };
            }

            if (as_if<JS::Uint8Array>(object)) {
                auto uint8_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Uint8Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Uint8Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Uint8Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { uint8_array_union_type };
            }

            if (as_if<JS::Uint16Array>(object)) {
                auto uint16_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Uint16Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Uint16Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint16Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Uint16Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { uint16_array_union_type };
            }

            if (as_if<JS::Uint32Array>(object)) {
                auto uint32_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Uint32Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Uint32Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint32Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Uint32Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { uint32_array_union_type };
            }

            if (as_if<JS::Uint8ClampedArray>(object)) {
                auto uint8_clamped_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Uint8ClampedArray>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Uint8ClampedArray>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8ClampedArray");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Uint8ClampedArray");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { uint8_clamped_array_union_type };
            }

            if (as_if<JS::BigInt64Array>(object)) {
                auto big_int64_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::BigInt64Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::BigInt64Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BigInt64Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length BigInt64Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { big_int64_array_union_type };
            }

            if (as_if<JS::BigUint64Array>(object)) {
                auto big_uint64_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::BigUint64Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::BigUint64Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BigUint64Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length BigUint64Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { big_uint64_array_union_type };
            }

            if (as_if<JS::Float16Array>(object)) {
                auto float16_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Float16Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Float16Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Float16Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Float16Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { float16_array_union_type };
            }

            if (as_if<JS::Float32Array>(object)) {
                auto float32_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Float32Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Float32Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Float32Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Float32Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { float32_array_union_type };
            }

            if (as_if<JS::Float64Array>(object)) {
                auto float64_array_union_type = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Float64Array>> {
        // A JavaScript value V is converted to an IDL typed array value by running the following algorithm:
        // 1. Let T be the IDL type V is being converted to.
        // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
        //    then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::Float64Array>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Float64Array");

        auto& viewed_array_buffer = *builtin_buffer->viewed_array_buffer();

        // 2. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
        //    IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
        if (viewed_array_buffer.is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
        if (!viewed_array_buffer.is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length Float64Array");

        // 5. Return the IDL value of type T that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }());
                return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { float64_array_union_type };
            }
        }

        auto body_string = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg0));
    }());
        return Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, GC::Ref<JS::Int8Array>, GC::Ref<JS::Int16Array>, GC::Ref<JS::Int32Array>, GC::Ref<JS::Uint8Array>, GC::Ref<JS::Uint16Array>, GC::Ref<JS::Uint32Array>, GC::Ref<JS::Uint8ClampedArray>, GC::Ref<JS::BigInt64Array>, GC::Ref<JS::BigUint64Array>, GC::Ref<JS::Float16Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float64Array>, GC::Ref<JS::DataView>, GC::Ref<JS::ArrayBuffer>, GC::Ref<XHR::FormData>, GC::Ref<DOMURL::URLSearchParams>, String> { body_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }());
        }
        return value;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->send(body); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::abort)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::abort");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->abort(); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::get_response_header)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::get_response_header");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "getResponseHeader");

    auto arg0 = vm.argument(0);
    auto name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_byte_string(vm, arg0));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_response_header(name); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R.has_value())
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(WebIDL::primitive_string_from_string(vm, R.value()));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::get_all_response_headers)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::get_all_response_headers");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_all_response_headers(); }));
    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(XMLHttpRequestPrototype::override_mime_type)
{
    WebIDL::log_trace(vm, "XMLHttpRequestPrototype::override_mime_type");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] XHR::XMLHttpRequest* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "overrideMimeType");

    auto arg0 = vm.argument(0);
    auto mime = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->override_mime_type(mime); }));
    return JS::js_undefined();
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<XMLHttpRequestResponseType> convert_to_idl_value_for_xml_http_request_response_type(JS::VM& vm, JS::Value value)
{
    // 1. Let S be the result of calling ? ToString(V).
    auto value_as_string = TRY(value.to_utf16_string(vm));

    // 2. If S is not one of E’s enumeration values, then throw a TypeError.
    // 3. Return the enumeration value of type E that is equal to S.
    if (value_as_string == ""sv)
        return XMLHttpRequestResponseType::Empty;
    if (value_as_string == "arraybuffer"sv)
        return XMLHttpRequestResponseType::Arraybuffer;
    if (value_as_string == "blob"sv)
        return XMLHttpRequestResponseType::Blob;
    if (value_as_string == "document"sv)
        return XMLHttpRequestResponseType::Document;
    if (value_as_string == "json"sv)
        return XMLHttpRequestResponseType::Json;
    if (value_as_string == "text"sv)
        return XMLHttpRequestResponseType::Text;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "XMLHttpRequestResponseType");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(XMLHttpRequestResponseType value)
{
    // The result of converting an IDL enumeration type value to a JavaScript value is the String value that represents the same sequence of code units as the enumeration value.
    switch (value) {
    case XMLHttpRequestResponseType::Empty:
        return ""_utf16;
    case XMLHttpRequestResponseType::Arraybuffer:
        return "arraybuffer"_utf16;
    case XMLHttpRequestResponseType::Blob:
        return "blob"_utf16;
    case XMLHttpRequestResponseType::Document:
        return "document"_utf16;
    case XMLHttpRequestResponseType::Json:
        return "json"_utf16;
    case XMLHttpRequestResponseType::Text:
        return "text"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
