#include "config.h"
#include "FetchEvent.h"
#include "JSDOMPromise.h"
#include "JSFetchResponse.h"
#if ENABLE(SERVICE_WORKER)
namespace WebCore {
Ref<FetchEvent> FetchEvent::createForTesting(ScriptExecutionContext& context)
{
FetchEvent::Init init;
init.request = FetchRequest::create(context, { }, FetchHeaders::create(FetchHeaders::Guard::Immutable, { }), { }, { }, { });
return FetchEvent::create("fetch", WTFMove(init), Event::IsTrusted::Yes);
}
FetchEvent::FetchEvent(const AtomicString& type, Init&& initializer, IsTrusted isTrusted)
: ExtendableEvent(type, initializer, isTrusted)
, m_request(initializer.request.releaseNonNull())
, m_clientId(WTFMove(initializer.clientId))
, m_reservedClientId(WTFMove(initializer.reservedClientId))
, m_targetClientId(WTFMove(initializer.targetClientId))
{
}
FetchEvent::~FetchEvent()
{
if (auto callback = WTFMove(m_onResponse))
callback(nullptr);
}
ExceptionOr<void> FetchEvent::respondWith(Ref<DOMPromise>&& promise)
{
if (!isBeingDispatched())
return Exception { InvalidStateError, ASCIILiteral("Event is not being dispatched") };
if (m_respondWithEntered)
return Exception { InvalidStateError, ASCIILiteral("Event respondWith flag is set") };
m_respondPromise = WTFMove(promise);
addExtendLifetimePromise(*m_respondPromise);
m_respondPromise->whenSettled([this, weakThis = createWeakPtr()] () {
if (!weakThis)
return;
promiseIsSettled();
});
stopPropagation();
stopImmediatePropagation();
m_respondWithEntered = true;
m_waitToRespond = true;
return { };
}
void FetchEvent::onResponse(CompletionHandler<void(FetchResponse*)>&& callback)
{
ASSERT(!m_onResponse);
m_onResponse = WTFMove(callback);
}
void FetchEvent::respondWithError()
{
m_respondWithError = true;
processResponse(nullptr);
}
void FetchEvent::processResponse(FetchResponse* response)
{
m_respondPromise = nullptr;
m_waitToRespond = false;
if (auto callback = WTFMove(m_onResponse))
callback(response);
}
void FetchEvent::promiseIsSettled()
{
if (m_respondPromise->status() == DOMPromise::Status::Rejected) {
respondWithError();
return;
}
ASSERT(m_respondPromise->status() == DOMPromise::Status::Fulfilled);
auto response = JSFetchResponse::toWrapped(m_respondPromise->globalObject()->globalExec()->vm(), m_respondPromise->result());
if (!response) {
respondWithError();
return;
}
if (response->isDisturbedOrLocked()) {
respondWithError();
return;
}
processResponse(response);
}
}
#endif // ENABLE(SERVICE_WORKER)