Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Response.clone (#125) #178

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 87 additions & 19 deletions builtins/web/fetch/request-response.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1236,28 +1236,20 @@ bool Request::clone(JSContext *cx, unsigned argc, JS::Value *vp) {
}
init_slots(new_request);

RootedValue cloned_headers_val(cx, JS::NullValue());
RootedObject headers(cx, RequestOrResponse::maybe_headers(self));
if (headers) {
RootedValue headers_val(cx, ObjectValue(*headers));
JSObject *cloned_headers = Headers::create(cx, headers_val, Headers::guard(headers));
if (!cloned_headers) {
return false;
}
cloned_headers_val.set(ObjectValue(*cloned_headers));
} else if (RequestOrResponse::maybe_handle(self)) {
auto handle = RequestOrResponse::headers_handle_clone(cx, self);
JSObject *cloned_headers =
Headers::create(cx, handle.release(),
RequestOrResponse::is_incoming(self) ? Headers::HeadersGuard::Immutable
: Headers::HeadersGuard::Request);
if (!cloned_headers) {
return false;
}
cloned_headers_val.set(ObjectValue(*cloned_headers));
auto handle = RequestOrResponse::headers_handle_clone(cx, self);

auto headers_guard = RequestOrResponse::is_incoming(self) ? Headers::HeadersGuard::Immutable
: Headers::HeadersGuard::Response;
JSObject *cloned_headers = Headers::create(cx, handle.release(), headers_guard);

if (!cloned_headers) {
return false;
}

RootedValue cloned_headers_val(cx, ObjectValue(*cloned_headers));

SetReservedSlot(new_request, static_cast<uint32_t>(Slots::Headers), cloned_headers_val);

Value url_val = GetReservedSlot(self, static_cast<uint32_t>(Slots::URL));
SetReservedSlot(new_request, static_cast<uint32_t>(Slots::URL), url_val);
Value method_val = JS::StringValue(method(self));
Expand Down Expand Up @@ -2291,6 +2283,81 @@ bool Response::redirect(JSContext *cx, unsigned argc, Value *vp) {
// return true;
// }

/// https://fetch.spec.whatwg.org/#dom-response-clone
bool Response::clone(JSContext *cx, unsigned argc, JS::Value *vp) {
// If this is unusable, then throw a TypeError.
METHOD_HEADER(0);

// To clone a response response, run these steps:
// 1. If response is a filtered response, then return a new identical filtered response whose internal response is a clone of response’s internal response.
RootedObject new_response(cx, create(cx));
if (!new_response) {
return false;
}

init_slots(new_response);

// 2. Let newResponse be a copy of response, except for its body.
auto handle = RequestOrResponse::headers_handle_clone(cx, self);

auto headers_guard = RequestOrResponse::is_incoming(self) ? Headers::HeadersGuard::Immutable
: Headers::HeadersGuard::Response;
JSObject *cloned_headers = Headers::create(cx, handle.release(), headers_guard);

if (!cloned_headers) {
return false;
}

RootedValue cloned_headers_val(cx, ObjectValue(*cloned_headers));

SetReservedSlot(new_response, static_cast<uint32_t>(Slots::Headers), cloned_headers_val);

Value status_val = GetReservedSlot(self, static_cast<uint32_t>(Slots::Status));
Value status_message_val = GetReservedSlot(self, static_cast<uint32_t>(Slots::StatusMessage));
Value url_val = GetReservedSlot(self, static_cast<uint32_t>(Slots::URL));

SetReservedSlot(new_response, static_cast<uint32_t>(Slots::Status), status_val);
SetReservedSlot(new_response, static_cast<uint32_t>(Slots::StatusMessage), status_message_val);
SetReservedSlot(new_response, static_cast<uint32_t>(Slots::URL), url_val);

// 3. If response’s body is non-null, then set newResponse’s body to the result of cloning response’s body.
RootedObject new_body(cx);
auto has_body = RequestOrResponse::has_body(self);
if (!has_body) {
args.rval().setObject(*new_response);
return true;
}

// Here we get the current response's body stream and call ReadableStream.prototype.tee to
// get two streams for the same content.
// One of these is then used to replace the current response's body, the other is used as
// the body of the clone.
JS::RootedObject body_stream(cx, RequestOrResponse::body_stream(self));
if (!body_stream) {
body_stream = RequestOrResponse::create_body_stream(cx, self);
if (!body_stream) {
return false;
}
}

if (RequestOrResponse::body_unusable(cx, body_stream)) {
return api::throw_error(cx, FetchErrors::BodyStreamUnusable);
}

RootedObject self_body(cx);
if (!ReadableStreamTee(cx, body_stream, &self_body, &new_body)) {
return false;
}

SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyStream), ObjectValue(*self_body));
SetReservedSlot(new_response, static_cast<uint32_t>(Slots::BodyStream), ObjectValue(*new_body));
SetReservedSlot(new_response, static_cast<uint32_t>(Slots::HasBody), JS::BooleanValue(true));

// 4. Return newResponse.
args.rval().setObject(*new_response);
return true;
}

const JSFunctionSpec Response::static_methods[] = {
JS_FN("redirect", redirect, 1, JSPROP_ENUMERATE),
// JS_FN("json", json, 1, JSPROP_ENUMERATE),
Expand All @@ -2306,6 +2373,7 @@ const JSFunctionSpec Response::methods[] = {
JSPROP_ENUMERATE),
JS_FN("json", bodyAll<RequestOrResponse::BodyReadResult::JSON>, 0, JSPROP_ENUMERATE),
JS_FN("text", bodyAll<RequestOrResponse::BodyReadResult::Text>, 0, JSPROP_ENUMERATE),
JS_FN("clone", clone, 0, JSPROP_ENUMERATE),
JS_FS_END,
};

Expand Down
3 changes: 3 additions & 0 deletions builtins/web/fetch/request-response.h
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ class Response final : public BuiltinImpl<Response> {
static bool redirect(JSContext *cx, unsigned argc, JS::Value *vp);
static bool json(JSContext *cx, unsigned argc, JS::Value *vp);

static bool clone(JSContext *cx, unsigned argc, JS::Value *vp);

public:
static constexpr const char *class_name = "Response";

Expand All @@ -189,6 +191,7 @@ class Response final : public BuiltinImpl<Response> {
HasBody = static_cast<int>(RequestOrResponse::Slots::HasBody),
BodyUsed = static_cast<int>(RequestOrResponse::Slots::BodyUsed),
Headers = static_cast<int>(RequestOrResponse::Slots::Headers),
URL = static_cast<int>(RequestOrResponse::Slots::URL),
Status = static_cast<int>(RequestOrResponse::Slots::Count),
StatusMessage,
Redirected,
Expand Down
59 changes: 59 additions & 0 deletions tests/integration/fetch/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,22 @@ export const handler = serveTest(async (t) => {
body: 'te',
method: 'post'
});

request.headers.set("foo", "bar")
const newRequest = request.clone();

strictEqual(newRequest instanceof Request, true, 'newRequest instanceof Request');
strictEqual(newRequest.method, request.method, 'newRequest.method');
strictEqual(newRequest.url, request.url, 'newRequest.url');
deepStrictEqual([...newRequest.headers], [...request.headers], 'newRequest.headers');
strictEqual(request.bodyUsed, false, 'request.bodyUsed');
strictEqual(newRequest.bodyUsed, false, 'newRequest.bodyUsed');
strictEqual(newRequest.body instanceof ReadableStream, true, 'newRequest.body instanceof ReadableStream');

strictEqual(newRequest.headers.get("foo"), "bar", 'newRequest.status pre-modification');
request.headers.set("foo", "bao")
strictEqual(newRequest.headers.get("foo"), "bar", 'newRequest.status post-modification');
strictEqual(request.headers.get("foo"), "bao", 'request.status post-modification');
}

{
Expand All @@ -53,4 +61,55 @@ export const handler = serveTest(async (t) => {
await request.text();
throws(() => request.clone());
});

t.test('response-clone-bad-calls', () => {
throws(() => new Response.prototype.clone(), TypeError);
throws(() => new Response.prototype.clone.call(undefined), TypeError);
});

await t.test('response-clone-valid', async () => {
{
const response = new Response('test body', {
headers: {
hello: 'world'
},
status: 200,
statusText: 'Success'
});
response.headers.set("foo", "bar")
const newResponse = response.clone();

strictEqual(newResponse instanceof Response, true, 'newResponse instanceof Request');
strictEqual(response.bodyUsed, false, 'response.bodyUsed');
strictEqual(newResponse.bodyUsed, false, 'newResponse.bodyUsed');
deepStrictEqual([...newResponse.headers], [...response.headers], 'newResponse.headers');
strictEqual(newResponse.status, 200, 'newResponse.status');
strictEqual(newResponse.statusText, 'Success', 'newResponse.statusText');
strictEqual(newResponse.body instanceof ReadableStream, true, 'newResponse.body instanceof ReadableStream');

strictEqual(newResponse.headers.get("foo"), "bar", 'newResponse.status pre-modification');
response.headers.set("foo", "bao")
strictEqual(newResponse.headers.get("foo"), "bar", 'newResponse.status post-modification');
strictEqual(response.headers.get("foo"), "bao", 'response.status post-modification');
}

{
const response = new Response(null, {
status: 404,
statusText: "Not found",
});
const newResponse = response.clone();
strictEqual(newResponse.bodyUsed, false, 'newResponse.bodyUsed');
strictEqual(newResponse.body, null, 'newResponse.body');
}
});

await t.test('response-clone-invalid', async () => {
const response = new Response('test body', {
status: 200,
statusText: "Success"
});
await response.text();
throws(() => response.clone());
});
});
Loading