Truly independent web browser
LibWeb: Return non-object JSON values from XMLHttpRequest.response
Shannon Booth46956d840c07
diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cppindex c1351be9b22..017289564ad 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp@@ -238,14 +238,14 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response(JS::Realm& realm)auto wrapper = Bindings::wrap(wrapper_world, realm, GC::Ref { *this });m_cached_response_objects.remove_all_matching([](auto const& entry) { return !entry.wrapper; });- auto cached_response_object = [&]() -> GC::Ptr<JS::Object> {+ auto cached_response_object = [&]() -> Optional<JS::Value> {auto cached = m_cached_response_objects.find_if([&](auto const& entry) { return entry.wrapper.ptr() == wrapper; });if (cached.is_end())- return nullptr;+ return {};return cached->object;};- auto cache_response_object = [&](GC::Ref<JS::Object> object) {+ auto cache_response_object = [&](JS::Value object) {m_cached_response_objects.append({ wrapper, object });};@@ -275,8 +275,8 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response(JS::Realm& realm)// 5. If this’s response type is "arraybuffer",if (m_response_type == XMLHttpRequest::ResponseType::Arraybuffer) {- if (auto cached_object = cached_response_object())- return cached_object;+ if (auto cached_object = cached_response_object(); cached_object.has_value())+ return *cached_object;// then set this’s response object to a new ArrayBuffer object representing this’s received bytes. If this throws// an exception, then set this’s response object to failure and return null.@@ -310,8 +310,8 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response(JS::Realm& realm)if (!m_response->body())return JS::js_null();- if (auto cached_object = cached_response_object())- return cached_object;+ if (auto cached_object = cached_response_object(); cached_object.has_value())+ return *cached_object;// 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an// exception, then return null.@@ -321,13 +321,10 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response(JS::Realm& realm)// 4. Set this’s response object to jsonObject.auto json_object = json_object_result.release_value();- if (json_object.is_object()) {- cache_response_object(GC::Ref<JS::Object> { json_object.as_object() });- return json_object;- }+ cache_response_object(json_object);// 9. Return this’s response object.- return JS::js_null();+ return json_object;}// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetypediff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.h b/Libraries/LibWeb/XHR/XMLHttpRequest.hindex 3c4811cd60d..e9ca8562b1b 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.h+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.h@@ -226,7 +226,7 @@ private:Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, Failure, Empty> m_response_object;struct CachedResponseObject {GC::Weak<JS::HostObject> wrapper;- GC::Ptr<JS::Object> object;+ JS::Value object;};Vector<CachedResponseObject> m_cached_response_objects;diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 0ea59657ec6..e9517099595 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -71,6 +71,8 @@ Text/input/wpt-import/video-rvfc/Text/input/wpt-import/fetch/api/basic/text-utf8.any.htmlText/input/wpt-import/fetch/api/abort/general.any.htmlText/input/wpt-import/xhr/send-entity-body-document-bogus.htm+Text/input/wpt-import/xhr/json.any.html+Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.htmlCrash/HTML/media-element-load-with-pending-source-buffer-append.htmlText/input/HTML/HTMLMediaElement-bodyless-response.htmlText/input/HTML/HTMLMediaElement-failed-range-response-after-metadata.htmldiff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/json.any.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/json.any.txtnew file mode 100644index 00000000000..cb4c8a9ef27--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/json.any.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 6 tests++6 Pass+Pass Ensure the correct JSON parser is used+Pass Ensure UTF-16 results in an error+Pass Ensure the response charset (windows-1252) is ignored+Pass Ensure the overrideMimeType() charset (windows-1252) is ignored+Pass Ensure the response charset (utf-16le) is ignored+Pass Ensure the overrideMimeType() charset (utf-16le) is ignored\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/overridemimetype-chunked-response.window.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/overridemimetype-chunked-response.window.txtnew file mode 100644index 00000000000..7cac10af36f--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/overridemimetype-chunked-response.window.txt@@ -0,0 +1,9 @@+Harness status: OK++Found 4 tests++4 Pass+Pass overrideMimeType() charset is used for every chunk of a chunked response+Pass overrideMimeType() charset overrides the response charset for every chunk of a chunked response+Pass Response charset is used for every chunk of a chunked response when overrideMimeType() has no charset+Pass Response charset is used for every chunk of a chunked response\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-response-is-json-number.html b/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-response-is-json-number.htmlindex 810500f9cb8..031d512efcd 100644--- a/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-response-is-json-number.html+++ b/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-response-is-json-number.html@@ -6,7 +6,7 @@xhr.responseType = "json";xhr.onreadystatechange = async function() {if (xhr.readyState === 4 && xhr.status === 200) {- if (xhr.response === null)+ if (xhr.response === 5)println("PASS");elseprintln("FAIL");diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/json.any.html b/Tests/LibWeb/Text/input/wpt-import/xhr/json.any.htmlnew file mode 100644index 00000000000..2161d4918ec--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/json.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>++<div id=log></div>+<script src="../xhr/json.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/json.any.js b/Tests/LibWeb/Text/input/wpt-import/xhr/json.any.jsnew file mode 100644index 00000000000..d7827ae02f9--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/json.any.js@@ -0,0 +1,50 @@+// See also /fetch/api/response/json.any.js++async_test(t => {+ const xhr = new XMLHttpRequest();+ xhr.responseType = "json";+ xhr.open("GET", `data:,\uFEFF{ "b": 1, "a": 2, "b": 3 }`);+ xhr.send();+ xhr.onload = t.step_func_done(() => {+ assert_array_equals(Object.keys(xhr.response), ["b", "a"]);+ assert_equals(xhr.response.a, 2);+ assert_equals(xhr.response.b, 3);+ });+}, "Ensure the correct JSON parser is used");++async_test(t => {+ const client = new XMLHttpRequest();+ client.responseType = 'json';+ client.open("GET", "resources/utf16-bom.json");+ client.send();+ client.onload = t.step_func_done(() => {+ assert_equals(client.response, null);+ });+}, "Ensure UTF-16 results in an error");++// A JSON response is always decoded as UTF-8, whatever charset the response or+// overrideMimeType() declares. The response body is "é" encoded as UTF-8.+for (const charset of ["windows-1252", "utf-16le"]) {+ async_test(t => {+ const client = new XMLHttpRequest();+ client.responseType = "json";+ const body = new Uint8Array([0x22, 0xC3, 0xA9, 0x22]);+ client.open("GET", URL.createObjectURL(new Blob([body], { type: `application/json;charset=${charset}` })));+ client.send();+ client.onload = t.step_func_done(() => {+ assert_equals(client.response, "\u00e9");+ });+ }, `Ensure the response charset (${charset}) is ignored`);++ async_test(t => {+ const client = new XMLHttpRequest();+ client.responseType = "json";+ const body = new Uint8Array([0x22, 0xC3, 0xA9, 0x22]);+ client.open("GET", URL.createObjectURL(new Blob([body], { type: "application/json" })));+ client.overrideMimeType(`application/json;charset=${charset}`);+ client.send();+ client.onload = t.step_func_done(() => {+ assert_equals(client.response, "\u00e9");+ });+ }, `Ensure the overrideMimeType() charset (${charset}) is ignored`);+}diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.html b/Tests/LibWeb/Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.htmlnew file mode 100644index 00000000000..fec589df93f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.html@@ -0,0 +1,8 @@+<!doctype html>+<meta charset=utf-8>++<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>++<div id=log></div>+<script src="../xhr/overridemimetype-chunked-response.window.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.js b/Tests/LibWeb/Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.jsnew file mode 100644index 00000000000..716aef880fc--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/overridemimetype-chunked-response.window.js@@ -0,0 +1,53 @@+// The response is delivered one byte-sequence at a time, with multi-byte+// characters split across chunk boundaries, so the final encoding has to be+// resolved once and then kept for the whole body.+function chunkedURL(type, chunks) {+ return "resources/content-in-chunks.py?type=" + encodeURIComponent(type) ++ chunks.map(chunk => "&chunk=" + chunk).join("");+}++// "テスト" (83 65 83 58 83 67) in Shift_JIS, with the second and third+// characters' bytes split across chunk boundaries.+const shiftJISChunks = ["8365", "83", "5883", "67"];++async_test(t => {+ const client = new XMLHttpRequest();+ client.onload = t.step_func_done(() => {+ assert_equals(client.responseText, "テスト");+ });+ client.open("GET", chunkedURL("text/plain", shiftJISChunks));+ client.overrideMimeType("text/plain;charset=Shift_JIS");+ client.send();+}, "overrideMimeType() charset is used for every chunk of a chunked response");++async_test(t => {+ const client = new XMLHttpRequest();+ client.onload = t.step_func_done(() => {+ assert_equals(client.responseText, "テスト");+ });+ client.open("GET", chunkedURL("text/plain;charset=UTF-8", shiftJISChunks));+ client.overrideMimeType("text/plain;charset=Shift_JIS");+ client.send();+}, "overrideMimeType() charset overrides the response charset for every chunk of a chunked response");++async_test(t => {+ const client = new XMLHttpRequest();+ client.onload = t.step_func_done(() => {+ // The override has no charset of its own, so the response charset has to+ // survive for the whole body.+ assert_equals(client.responseText, "テスト");+ });+ client.open("GET", chunkedURL("text/plain;charset=Shift_JIS", shiftJISChunks));+ client.overrideMimeType("text/xml");+ client.send();+}, "Response charset is used for every chunk of a chunked response when overrideMimeType() has no charset");++async_test(t => {+ const client = new XMLHttpRequest();+ client.onload = t.step_func_done(() => {+ assert_equals(client.responseText, "aéb");+ });+ // "é" in UTF-8, split across a chunk boundary.+ client.open("GET", chunkedURL("text/plain;charset=UTF-8", ["61C3", "A962"]));+ client.send();+}, "Response charset is used for every chunk of a chunked response");diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/content-in-chunks.py b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/content-in-chunks.pynew file mode 100644index 00000000000..57a8e580514--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/content-in-chunks.py@@ -0,0 +1,21 @@+import time+++def main(request, response):+ """Streams each hex-encoded `chunk` parameter as its own chunk of a chunked+ response, pausing `ms` milliseconds in between so that consumers observe one+ network callback per chunk. `type` sets the Content-Type header."""+ content_type = request.GET.first(b"type", b"text/plain")+ delay = float(request.GET.first(b"ms", b"100")) / 1E3+ chunks = [bytes.fromhex(chunk.decode(u"ascii")) for chunk in request.GET.get_list(b"chunk")]++ response.headers.set(b"Content-Type", content_type)+ response.headers.set(b"Transfer-Encoding", b"chunked")+ response.write_status_headers()++ for chunk in chunks:+ time.sleep(delay)+ response.writer.write(b"%x\r\n" % len(chunk))+ response.writer.write(chunk)+ response.writer.write(b"\r\n")+ response.writer.write(b"0\r\n\r\n")diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/utf16-bom.json b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/utf16-bom.jsonnew file mode 100644index 00000000000..5fd0a585a30Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/utf16-bom.json differ