Truly independent web browser
LibWeb: Transmit the request body in HTTP-network fetch
Shannon Bootha10cff93af4c
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 58a6c02185f..88c3130f7f8 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -2503,6 +2503,65 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(network_request->set_body_delivery_paused(true);fetch_params.controller()->set_pending_request(network_request);+ // To transmit request’s body body, run these steps:+ // 1. If body is null and fetchParams’s process request end-of-body is non-null, then queue a fetch task given+ // fetchParams’s process request end-of-body and fetchParams’s task destination.+ if (request->body().has<Empty>()) {+ if (fetch_params.algorithms()->process_request_end_of_body()) {+ Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), GC::create_function(GC::Heap::the(), [&fetch_params]() {+ fetch_params.algorithms()->process_request_end_of_body()();+ }));+ }+ }+ // 2. Otherwise, if body is non-null:+ else if (auto const* body = request->body().get_pointer<GC::Ref<Infrastructure::Body>>()) {+ // 1. Let processBodyChunk given bytes be these steps:+ auto process_body_chunk = GC::create_function(GC::Heap::the(), [&fetch_params](ByteBuffer bytes) {+ // 1. If fetchParams is canceled, then abort these steps.+ if (fetch_params.is_canceled())+ return;++ // 2. Run this step in parallel: transmit bytes.+ // NB: The whole body was handed to RequestServer above, from body's source.++ // 3. If fetchParams’s process request body chunk length is non-null, then run fetchParams’s process+ // request body chunk length given bytes’s length.+ if (fetch_params.algorithms()->process_request_body_chunk_length())+ fetch_params.algorithms()->process_request_body_chunk_length()(bytes.size());+ });++ // 2. Let processEndOfBody be these steps:+ auto process_end_of_body = GC::create_function(GC::Heap::the(), [&fetch_params]() {+ // 1. If fetchParams is canceled, then abort these steps.+ if (fetch_params.is_canceled())+ return;++ // 2. If fetchParams’s process request end-of-body is non-null, then run fetchParams’s process request+ // end-of-body.+ if (fetch_params.algorithms()->process_request_end_of_body())+ fetch_params.algorithms()->process_request_end_of_body()();+ });++ // 3. Let processBodyError given e be these steps:+ auto process_body_error = GC::create_function(GC::Heap::the(), [&realm, &fetch_params](JS::Value error) {+ // 1. If fetchParams is canceled, then abort these steps.+ if (fetch_params.is_canceled())+ return;++ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.+ auto const* exception = error.is_object() ? Bindings::dom_exception_from_object(error.as_object()) : nullptr;+ if (exception && exception->name() == "AbortError"_utf16_fly_string)+ fetch_params.controller()->abort(realm, {});+ // 3. Otherwise, terminate fetchParams’s controller.+ else+ fetch_params.controller()->terminate();+ });++ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and+ // fetchParams’s task destination.+ (void)(*body)->incrementally_read(realm, process_body_chunk, process_end_of_body, process_body_error, fetch_params.task_destination());+ }+return pending_response;}diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 468529809e9..d08af4a4537 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -495,6 +495,15 @@ Text/input/Streams/init-from-fetch.htmlText/input/Wasm/WebAssembly-instantiate-streaming.htmlText/input/XHR/XMLHttpRequest-network-error-message.htmlText/input/XHR/XMLHttpRequest-override-mimetype-blob.html+Text/input/wpt-import/xhr/abort-during-upload.any.html+Text/input/wpt-import/xhr/abort-upload-event-abort.any.html+Text/input/wpt-import/xhr/abort-upload-event-loadend.any.html+Text/input/wpt-import/xhr/cors-upload.any.html+Text/input/wpt-import/xhr/event-loadstart-upload.any.html+Text/input/wpt-import/xhr/send-redirect-post-upload.htm+Text/input/wpt-import/xhr/send-response-upload-event-loadend.htm+Text/input/wpt-import/xhr/send-response-upload-event-loadstart.htm+Text/input/wpt-import/xhr/send-response-upload-event-progress.htmText/input/XML/error-page.htmlText/input/XML/error-page-namespace-error.htmlText/input/base/a-element-target.htmldiff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-during-upload.any.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-during-upload.any.txtnew file mode 100644index 00000000000..0050f431820--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-during-upload.any.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: abort() while sending data\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-upload-event-abort.any.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-upload-event-abort.any.txtnew file mode 100644index 00000000000..0672bbac253--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-upload-event-abort.any.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: The abort() method: Fire a progress event named abort on the XMLHttpRequestUpload object\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-upload-event-loadend.any.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-upload-event-loadend.any.txtnew file mode 100644index 00000000000..715356ac6b4--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/abort-upload-event-loadend.any.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: The abort() method: Fire a progress event named loadend on the XMLHttpRequestUpload object\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/cors-upload.any.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/cors-upload.any.txtnew file mode 100644index 00000000000..d1daa9e395f--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/cors-upload.any.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass Cross-Origin POST FormData body but no preflight+Pass Cross-Origin POST with preflight and FormData body\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/event-loadstart-upload.any.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/event-loadstart-upload.any.txtnew file mode 100644index 00000000000..e19d4cd636b--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/event-loadstart-upload.any.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: The send() method: Fire a progress event named loadstart on upload object (synchronous flag is unset)\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/send-redirect-post-upload.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-redirect-post-upload.txtnew file mode 100644index 00000000000..6ff8279fbf4--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-redirect-post-upload.txt@@ -0,0 +1,10 @@+Harness status: OK++Found 5 tests++5 Fail+Fail XMLHttpRequest: The send() method: POSTing to URL that redirects (301)+Fail XMLHttpRequest: The send() method: POSTing to URL that redirects (302)+Fail XMLHttpRequest: The send() method: POSTing to URL that redirects (303)+Fail XMLHttpRequest: The send() method: POSTing to URL that redirects (307 (string))+Fail XMLHttpRequest: The send() method: POSTing to URL that redirects (307 (blob))\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-loadend.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-loadend.txtnew file mode 100644index 00000000000..27018672181--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-loadend.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: The send() method: Fire a progress event named loadend on the XMLHttpRequestUpload (synchronous flag is unset)\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-loadstart.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-loadstart.txtnew file mode 100644index 00000000000..658c87137f4--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-loadstart.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: The send() method: Fire a progress event named loadstart on the XMLHttpRequestUpload (synchronous flag is unset)\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-progress.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-progress.txtnew file mode 100644index 00000000000..0eea54593f7--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/send-response-upload-event-progress.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass XMLHttpRequest: The send() method: Fire a progress event named progress on the XMLHttpRequestUpload (synchronous flag is unset)\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/abort-during-upload.any.html b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-during-upload.any.htmlnew file mode 100644index 00000000000..bfe276bf180--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-during-upload.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>+<title>XMLHttpRequest: abort() while sending data</title>+<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>+<script src="resources/xmlhttprequest-event-order.js"></script>+<div id=log></div>+<script src="../xhr/abort-during-upload.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/abort-during-upload.any.js b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-during-upload.any.jsnew file mode 100644index 00000000000..fe4963da673--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-during-upload.any.js@@ -0,0 +1,17 @@+// META: title=XMLHttpRequest: abort() while sending data+// META: script=resources/xmlhttprequest-event-order.js++ var test = async_test()+ test.step(function() {+ var client = new XMLHttpRequest()+ prepare_xhr_for_event_order_test(client);+ client.open("POST", "resources/delay.py?ms=1000")+ client.addEventListener("loadend", function(e) {+ test.step(function() {+ assert_xhr_event_order_matches([1, "loadstart(0,0,false)", "upload.loadstart(0,9999,true)", 4, "upload.abort(0,0,false)", "upload.loadend(0,0,false)", "abort(0,0,false)", "loadend(0,0,false)"]);+ test.done()+ })+ });+ client.send((new Array(10000)).join('a'))+ client.abort()+ })diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-abort.any.html b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-abort.any.htmlnew file mode 100644index 00000000000..28998bbe7f5--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-abort.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/abort-upload-event-abort.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-abort.any.js b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-abort.any.jsnew file mode 100644index 00000000000..3c85a5554bd--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-abort.any.js@@ -0,0 +1,31 @@+ var test = async_test("XMLHttpRequest: The abort() method: Fire a progress event named abort on the XMLHttpRequestUpload object");++ test.step(function()+ {+ var xhr = new XMLHttpRequest();++ xhr.onloadstart = function()+ {+ test.step(function()+ {+ if (xhr.readyState == 1)+ {+ xhr.abort();+ }+ });+ };++ xhr.upload.onabort = function(e)+ {+ test.step(function()+ {+ assert_true(e instanceof ProgressEvent);+ assert_equals(e.type, "abort");+ assert_equals(e.target, xhr.upload);+ test.done();+ });+ };++ xhr.open("POST", "./resources/content.py", true);+ xhr.send("Test Message");+ });diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-loadend.any.html b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-loadend.any.htmlnew file mode 100644index 00000000000..b07cbfd8100--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-loadend.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/abort-upload-event-loadend.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-loadend.any.js b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-loadend.any.jsnew file mode 100644index 00000000000..91c5dc5c72e--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/abort-upload-event-loadend.any.js@@ -0,0 +1,31 @@+ var test = async_test("XMLHttpRequest: The abort() method: Fire a progress event named loadend on the XMLHttpRequestUpload object");++ test.step(function()+ {+ var xhr = new XMLHttpRequest();++ xhr.onloadstart = function()+ {+ test.step(function ()+ {+ if (xhr.readyState == 1)+ {+ xhr.abort();+ }+ });+ };++ xhr.upload.onloadend = function(e)+ {+ test.step(function()+ {+ assert_true(e instanceof ProgressEvent);+ assert_equals(e.type, "loadend");+ assert_equals(e.target, xhr.upload);+ test.done();+ });+ };++ xhr.open("POST", "./resources/content.py", true);+ xhr.send("Test Message");+ });diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/cors-upload.any.html b/Tests/LibWeb/Text/input/wpt-import/xhr/cors-upload.any.htmlnew file mode 100644index 00000000000..ed7d882d9b0--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/cors-upload.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>+<title>Cross-Origin POST with preflight and FormData body should send body</title>+<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>+<script src="../common/get-host-info.sub.js"></script>+<div id=log></div>+<script src="../xhr/cors-upload.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/cors-upload.any.js b/Tests/LibWeb/Text/input/wpt-import/xhr/cors-upload.any.jsnew file mode 100644index 00000000000..3beb0637ccf--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/cors-upload.any.js@@ -0,0 +1,59 @@+// META: title=Cross-Origin POST with preflight and FormData body should send body+// META: script=/common/get-host-info.sub.js+"use strict";++function testCorsFormDataUpload(description, path, method, form, headers, withCredentials) {+ const test = async_test(description);+ const client = new XMLHttpRequest();+ const url = corsURL(path);++ client.open(method, url, true);+ client.withCredentials = withCredentials;+ for (const key of Object.keys(headers)) {+ client.setRequestHeader(key, headers[key]);+ }++ client.send(form);++ client.onload = () => {+ test.step(() => {+ assert_equals(client.status, 200);+ assert_regexp_match(client.responseText, /Content-Disposition: form-data/);++ for (const key of form.keys()) {+ assert_regexp_match(client.responseText, new RegExp(key));+ assert_regexp_match(client.responseText, new RegExp(form.get(key)));+ }+ });+ test.done();+ };+}++function corsURL(path) {+ const url = new URL(path, location.href);+ url.hostname = get_host_info().REMOTE_HOST;+ return url.href;+}++const form = new FormData();+form.append("key", "value");++testCorsFormDataUpload(+ "Cross-Origin POST FormData body but no preflight",+ "resources/echo-content-cors.py",+ "POST",+ form,+ {},+ false+);++testCorsFormDataUpload(+ "Cross-Origin POST with preflight and FormData body",+ "resources/echo-content-cors.py",+ "POST",+ form,+ {+ Authorization: "Bearer access-token"+ },+ true+);diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/event-loadstart-upload.any.html b/Tests/LibWeb/Text/input/wpt-import/xhr/event-loadstart-upload.any.htmlnew file mode 100644index 00000000000..64b5618a6ba--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/event-loadstart-upload.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>+<title>XMLHttpRequest: The send() method: Fire a progress event named loadstart on upload object (synchronous flag is unset)</title>+<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/event-loadstart-upload.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/event-loadstart-upload.any.js b/Tests/LibWeb/Text/input/wpt-import/xhr/event-loadstart-upload.any.jsnew file mode 100644index 00000000000..3918adb66a9--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/event-loadstart-upload.any.js@@ -0,0 +1,19 @@+// META: title=XMLHttpRequest: The send() method: Fire a progress event named loadstart on upload object (synchronous flag is unset)++var test = async_test();+test.step(function () {+ var client = new XMLHttpRequest();+ client.upload.onloadstart = test.step_func(function (e) {+ assert_true(e instanceof ProgressEvent);+ assert_equals(e.total, 7, 'upload.onloadstart: event.total');+ assert_equals(e.loaded, 0, 'upload.onloadstart: event.loaded');+ assert_equals(e.type, "loadstart");+ test.done();+ });+ client.onreadystatechange = test.step_func(function () {+ if (client.readyState === 4)+ assert_unreached("onloadstart not called.");+ });+ client.open("POST", "resources/trickle.py?ms=5&count=8");+ client.send('foo=bar');+});diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/echo-content-cors.py b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/echo-content-cors.pynew file mode 100644index 00000000000..4ffb3e72a55--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/echo-content-cors.py@@ -0,0 +1,23 @@+def main(request, response):+ headers = [(b"X-Request-Method", request.method),+ (b"X-Request-Content-Length", request.headers.get(b"Content-Length", b"NO")),+ (b"X-Request-Content-Type", request.headers.get(b"Content-Type", b"NO")),+ (b"Access-Control-Allow-Credentials", b"true"),+ # Avoid any kind of content sniffing on the response.+ (b"Content-Type", b"text/plain")]++ origin = request.GET.first(b"origin", request.headers.get(b"origin"))+ if origin != None:+ headers.append((b"Access-Control-Allow-Origin", origin))++ request_headers = request.GET.first(b"origin", request.headers.get(b"access-control-request-headers"))+ if request_headers != None:+ headers.append((b"Access-Control-Allow-Headers", request_headers))++ request_method = request.GET.first(b"origin", request.headers.get(b"access-control-request-method"))+ if request_method != None:+ headers.append((b"Access-Control-Allow-Methods", b"OPTIONS, " + request_method))++ content = request.body++ return headers, contentdiff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/redirect.py b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/redirect.pynew file mode 100644index 00000000000..e2786b45031--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/redirect.py@@ -0,0 +1,21 @@+import time+from urllib.parse import parse_qs++from wptserve.utils import isomorphic_encode++def main(request, response):+ code = int(request.GET.first(b"code", 302))+ location = request.GET.first(b"location", isomorphic_encode(request.url_parts.path + u"?followed"))+ if location:+ location = parse_qs(u"location=" + location.decode(u"UTF-8"))[u"location"][0]+ if location.startswith(u"redirect.py"):+ location += u"&code=" + str(code)++ if b"delay" in request.GET:+ delay = float(request.GET.first(b"delay"))+ time.sleep(delay / 1E3)++ if b"followed" in request.GET:+ return [(b"Content:Type", b"text/plain")], b"MAGIC HAPPENED"+ else:+ return (code, b"WEBSRT MARKETING"), [(b"Location", location)], b"TEST"diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/trickle.py b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/trickle.pynew file mode 100644index 00000000000..eab5310387e--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/trickle.py@@ -0,0 +1,15 @@+import time++def main(request, response):+ chunk = b"TEST_TRICKLE\n"+ delay = float(request.GET.first(b"ms", 500)) / 1E3+ count = int(request.GET.first(b"count", 50))+ if b"specifylength" in request.GET:+ response.headers.set(b"Content-Length", count * len(chunk))+ time.sleep(delay)+ response.headers.set(b"Content-type", b"text/plain")+ response.write_status_headers()+ time.sleep(delay)+ for i in range(count):+ response.writer.write_content(chunk)+ time.sleep(delay)diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/resources/xmlhttprequest-event-order.js b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/xmlhttprequest-event-order.jsnew file mode 100644index 00000000000..b6bb6cdf3c3--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/resources/xmlhttprequest-event-order.js@@ -0,0 +1,83 @@+(function(global) {+ var recorded_xhr_events = [];++ function record_xhr_event(e) {+ var prefix = e.target instanceof XMLHttpRequestUpload ? "upload." : "";+ recorded_xhr_events.push((prefix || "") + e.type + "(" + e.loaded + "," + e.total + "," + e.lengthComputable + ")");+ }++ global.prepare_xhr_for_event_order_test = function(xhr) {+ xhr.addEventListener("readystatechange", function(e) {+ recorded_xhr_events.push(xhr.readyState);+ });+ var events = ["loadstart", "progress", "abort", "timeout", "error", "load", "loadend"];+ for(var i=0; i<events.length; ++i) {+ xhr.addEventListener(events[i], record_xhr_event);+ }+ if ("upload" in xhr) {+ for(var i=0; i<events.length; ++i) {+ xhr.upload.addEventListener(events[i], record_xhr_event);+ }+ }+ }++ function getNextEvent(arr) {+ var event = { str: arr.shift() };++ // we can only handle strings, numbers (readystates) and undefined+ if (event.str === undefined) {+ return event;+ }++ if (typeof event.str !== "string") {+ if (Number.isInteger(event.str)) {+ event.state = event.str;+ event.str = "readystatechange(" + event.str + ")";+ } else {+ throw "Test error: unexpected event type " + event.str;+ }+ }++ // parse out the general type, loaded and total values+ var type = event.type = event.str.split("(")[0].split(".").pop();+ var loadedAndTotal = event.str.match(/.*\((\d+),(\d+),(true|false)\)/);+ if (loadedAndTotal) {+ event.loaded = parseInt(loadedAndTotal[1]);+ event.total = parseInt(loadedAndTotal[2]);+ event.lengthComputable = loadedAndTotal[3] == "true";+ }++ return event;+ }++ global.assert_xhr_event_order_matches = function(expected) {+ var recorded = recorded_xhr_events;+ var lastRecordedLoaded = -1;+ while(expected.length && recorded.length) {+ var currentExpected = getNextEvent(expected),+ currentRecorded = getNextEvent(recorded);++ // skip to the last progress event if we've hit one (note the next+ // event after a progress event should be a LOADING readystatechange,+ // if there are multiple progress events in a row).+ while (recorded.length && currentRecorded.type == "progress" &&+ parseInt(recorded) === 3) {+ assert_greater_than(currentRecorded.loaded, lastRecordedLoaded,+ "progress event 'loaded' values must only increase");+ lastRecordedLoaded = currentRecorded.loaded;+ }+ if (currentRecorded.type == "loadend") {+ recordedProgressCount = 0;+ lastRecordedLoaded = -1;+ }++ assert_equals(currentRecorded.str, currentExpected.str);+ }+ if (recorded.length) {+ throw "\nUnexpected extra events: " + recorded.join(", ");+ }+ if (expected.length) {+ throw "\nExpected more events: " + expected.join(", ");+ }+ }+}(this));diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/send-redirect-post-upload.htm b/Tests/LibWeb/Text/input/wpt-import/xhr/send-redirect-post-upload.htmnew file mode 100644index 00000000000..ff82315d39a--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/send-redirect-post-upload.htm@@ -0,0 +1,140 @@+<!DOCTYPE html>+<html>+<head>+ <link rel="help" href="https://xhr.spec.whatwg.org/#handler-xhr-onprogress" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#event-xhr-progress" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#the-send()-method" data-tested-assertations="following::dt[@id='dom-xmlhttprequest-send-bodyinit']/following::dd[1]/p[2] following::ol[1]/li[9]//li[1] following::ol[1]/li[9]//li[2]" />+ <link rel="help" href="https://fetch.spec.whatwg.org/#http-fetch" data-tested-assertations="following::ol[1]/li[6]/dl/dd[1]//dd[3]" />+ <link rel="help" href="https://fetch.spec.whatwg.org/#concept-http-redirect-fetch" data-tested-assertations="following::li[16]" />+ <script src="../resources/testharness.js"></script>+ <script src="../resources/testharnessreport.js"></script>+ <title>XMLHttpRequest: The send() method: POSTing to URL that redirects</title>+</head>++<body>+ <div id="log"></div>++ <script type="text/javascript">+ function testRedirectPost(params) {+ var test = async_test(document.title + " (" + params.name + ")");+ var actual = [];+ // We check upload.onprogress with a boolean because it *might* fire more than once+ var progressFiredReadyState1 = false;++ var expectedHeaders, expectedEvents;++ // 307 redirects should resend the POST data, and events and headers will be a little different..+ if(params.expectResendPost) {+ expectedHeaders = {+ "X-Request-Content-Length": "12000",+ "X-Request-Content-Type": "text/plain;charset=UTF-8",+ "X-Request-Method": "POST",+ "X-Request-Query": "NO",+ "Content-Length": "12000"+ }+ expectedEvents = [+ "xhr onreadystatechange 1",+ "xhr loadstart 1",+ "upload loadstart 1",+ "upload loadend 1",+ "xhr onreadystatechange 2",+ "xhr onreadystatechange 3",+ "xhr onreadystatechange 4",+ "xhr load 4",+ "xhr loadend 4"+ ];+ } else {+ // setting the right expectations for POST resent as GET without request body+ expectedHeaders = {+ "X-Request-Content-Length": "NO",+ "X-Request-Content-Type": "NO",+ "X-Request-Method": "GET",+ "X-Request-Query": "NO"+ }+ expectedEvents = [+ "xhr onreadystatechange 1",+ "xhr loadstart 1",+ "upload loadstart 1",+ "upload loadend 1",+ "xhr onreadystatechange 2",+ /* we expect no onreadystatechange readyState=3 event because there is no loading content */+ "xhr onreadystatechange 4",+ "xhr load 4",+ "xhr loadend 4"+ ];+ }+ // Override expectations if provided.+ if(params.expectedContentType)+ expectedHeaders["X-Request-Content-Type"] = params.expectedContentType;++ test.step(function()+ {+ var xhr = new XMLHttpRequest();++ xhr.upload.onloadstart = test.step_func(function(e) {+ actual.push("upload loadstart " + xhr.readyState);+ });+ xhr.upload.onprogress = test.step_func(function(e) {+ // events every 50ms, one final when uploading is done+ if(xhr.readyState >= xhr.HEADERS_RECEIVED) {+ assert_equals(xhr.status, 200, "JS never gets to see the 30x status code");+ }+ progressFiredReadyState1 = xhr.readyState === xhr.OPENED;+ });+ xhr.upload.onloadend = test.step_func(function() {+ actual.push("upload loadend " + xhr.readyState);+ });+ xhr.onloadstart = test.step_func(function() {+ actual.push("xhr loadstart " + xhr.readyState);+ });+ xhr.onreadystatechange = test.step_func(function() {+ if(xhr.readyState >= xhr.HEADERS_RECEIVED) {+ assert_equals(xhr.status, 200, "JS never gets to see the 30x status code");+ }++ // The UA may fire multiple "readystatechange" events while in+ // the "loading" state.+ // https://xhr.spec.whatwg.org/#the-send()-method+ if (xhr.readyState === 3 && actual[actual.length - 1] === "xhr onreadystatechange 3") {+ return;+ }++ actual.push("xhr onreadystatechange " + xhr.readyState);+ });+ xhr.onload = test.step_func(function(e)+ {+ actual.push("xhr load " + xhr.readyState);+ });+ xhr.onloadend = test.step_func(function(e)+ {+ actual.push("xhr loadend " + xhr.readyState);++ assert_true(progressFiredReadyState1, "One progress event should fire on xhr.upload when readyState is 1");++ // Headers will tell us if data was sent when expected+ for(var header in expectedHeaders) {+ assert_equals(xhr.getResponseHeader(header), expectedHeaders[header], header);+ }++ assert_array_equals(actual, expectedEvents, "events firing in expected order and states");+ if (params.expectedBody)+ assert_equals(xhr.response, params.expectedBody, 'request body was resent');+ test.done();+ });++ xhr.open("POST", "./resources/redirect.py?location=content.py&code=" + params.code, true);+ xhr.send(params.body);+ });+ }++ const stringBody = "Test Message".repeat(1000);+ const blobBody = new Blob(new Array(1000).fill("Test Message"));++ testRedirectPost({name: "301", code: 301, expectResendPost: false, body: stringBody});+ testRedirectPost({name: "302", code: 302, expectResendPost: false, body: stringBody});+ testRedirectPost({name: "303", code: 303, expectResendPost: false, body: stringBody});+ testRedirectPost({name: "307 (string)", code: 307, expectResendPost: true, body: stringBody, expectedBody: stringBody });+ testRedirectPost({name: "307 (blob)", code: 307, expectResendPost: true, body: blobBody, expectedBody: stringBody, expectedContentType: "NO" });+ </script>+</body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-loadend.htm b/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-loadend.htmnew file mode 100644index 00000000000..657b4ac1765--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-loadend.htm@@ -0,0 +1,40 @@+<!DOCTYPE html>+<html>+<head>+ <link rel="help" href="https://xhr.spec.whatwg.org/#handler-xhr-onloadend" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#event-xhr-loadend" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#the-send()-method" data-tested-assertations="following::a[contains(@href,'#make-upload-progress-notifications')]/.. following::ol[1]/li[8]" />+ <link rel="help" href="https://xhr.spec.whatwg.org/#make-upload-progress-notifications" data-tested-assertations="following::ul[1]/li[2]/ol[1]/li[4]" />++ <script src="../resources/testharness.js"></script>+ <script src="../resources/testharnessreport.js"></script>+ <title>XMLHttpRequest: The send() method: Fire a progress event named loadend on the XMLHttpRequestUpload (synchronous flag is unset)</title>+</head>++<body>+ <div id="log"></div>++ <script type="text/javascript">+ var test = async_test();++ test.step(function()+ {+ var xhr = new XMLHttpRequest();++ xhr.upload.onloadend = function(e)+ {+ test.step(function()+ {+ assert_true(e instanceof ProgressEvent);+ assert_equals(e.type, "loadend");+ assert_equals(e.target, xhr.upload);+ test.done();+ });+ };++ xhr.open("POST", "./resources/content.py", true);+ xhr.send("Test Message");+ });+ </script>+</body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-loadstart.htm b/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-loadstart.htmnew file mode 100644index 00000000000..961d37fd602--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-loadstart.htm@@ -0,0 +1,39 @@+<!DOCTYPE html>+<html>+<head>+ <link rel="help" href="https://xhr.spec.whatwg.org/#handler-xhr-onloadstart" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#event-xhr-loadstart" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#the-send()-method" data-tested-assertations="following::ol[1]/li[8] following-sibling::ol/li[9]/ol/li[3]" />++ <script src="../resources/testharness.js"></script>+ <script src="../resources/testharnessreport.js"></script>+ <title>XMLHttpRequest: The send() method: Fire a progress event named loadstart on the XMLHttpRequestUpload (synchronous flag is unset)</title>+</head>++<body>+ <div id="log"></div>++ <script type="text/javascript">+ var test = async_test();++ test.step(function()+ {+ var xhr = new XMLHttpRequest();++ xhr.upload.onloadstart = function(e)+ {+ test.step(function()+ {+ assert_true(e instanceof ProgressEvent);+ assert_equals(e.type, "loadstart");+ assert_equals(e.target, xhr.upload);+ test.done();+ });+ };++ xhr.open("POST", "./resources/content.py", true);+ xhr.send("Test Message");+ });+ </script>+</body>+</html>diff --git a/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-progress.htm b/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-progress.htmnew file mode 100644index 00000000000..11f2784efd4--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/xhr/send-response-upload-event-progress.htm@@ -0,0 +1,39 @@+<!DOCTYPE html>+<html>+<head>+ <link rel="help" href="https://xhr.spec.whatwg.org/#handler-xhr-onprogress" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#event-xhr-progress" data-tested-assertations="../.." />+ <link rel="help" href="https://xhr.spec.whatwg.org/#the-send()-method" data-tested-assertations="following::a[contains(@href,'#make-upload-progress-notifications')]/.. following::ol[1]/li[8]" />+ <link rel="help" href="https://xhr.spec.whatwg.org/#make-upload-progress-notifications" data-tested-assertations="following::ul[1]/li[2]/ol[1]/li[2]" />+ <script src="../resources/testharness.js"></script>+ <script src="../resources/testharnessreport.js"></script>+ <title>XMLHttpRequest: The send() method: Fire a progress event named progress on the XMLHttpRequestUpload (synchronous flag is unset)</title>+</head>++<body>+ <div id="log"></div>++ <script type="text/javascript">+ var test = async_test();++ test.step(function()+ {+ var xhr = new XMLHttpRequest();++ xhr.upload.onprogress = function(e)+ {+ test.step(function()+ {+ assert_true(e instanceof ProgressEvent);+ assert_equals(e.type, "progress");+ assert_equals(e.target, xhr.upload);+ test.done();+ });+ };++ xhr.open("POST", "./resources/content.py", true);+ xhr.send("Test Message");+ });+ </script>+</body>+</html>