summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--AK/Debug.h.in4
-rw-r--r--Meta/CMake/all_the_debug_macros.cmake1
-rw-r--r--Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp5
-rw-r--r--Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h3
-rw-r--r--Userland/Libraries/LibWeb/CMakeLists.txt3
-rw-r--r--Userland/Libraries/LibWeb/Forward.h4
-rw-r--r--Userland/Libraries/LibWeb/HTML/MessageChannel.cpp2
-rw-r--r--Userland/Libraries/LibWeb/HTML/MessagePort.cpp2
-rw-r--r--Userland/Libraries/LibWeb/HTML/MessagePort.h2
-rw-r--r--Userland/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h50
-rw-r--r--Userland/Libraries/LibWeb/HTML/Worker.cpp347
-rw-r--r--Userland/Libraries/LibWeb/HTML/Worker.h108
-rw-r--r--Userland/Libraries/LibWeb/HTML/Worker.idl16
-rw-r--r--Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp83
-rw-r--r--Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.h32
15 files changed, 659 insertions, 3 deletions
diff --git a/AK/Debug.h.in b/AK/Debug.h.in
index bc57678f95..1f429de173 100644
--- a/AK/Debug.h.in
+++ b/AK/Debug.h.in
@@ -470,6 +470,10 @@
#cmakedefine01 WEBSERVER_DEBUG
#endif
+#ifndef WEB_WORKER_DEBUG
+#cmakedefine01 WEB_WORKER_DEBUG
+#endif
+
#ifndef WINDOWMANAGER_DEBUG
#cmakedefine01 WINDOWMANAGER_DEBUG
#endif
diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmake
index 517b1c00b3..f6e6641f60 100644
--- a/Meta/CMake/all_the_debug_macros.cmake
+++ b/Meta/CMake/all_the_debug_macros.cmake
@@ -204,6 +204,7 @@ set(WASM_BINPARSER_DEBUG ON)
set(WASM_TRACE_DEBUG ON)
set(WASM_VALIDATOR_DEBUG ON)
set(WEBSERVER_DEBUG ON)
+set(WEB_WORKER_DEBUG ON)
set(WINDOWMANAGER_DEBUG ON)
set(WSMESSAGELOOP_DEBUG ON)
set(WSSCREEN_DEBUG ON)
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp
index df17512353..0a63aca6b5 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp
@@ -2613,8 +2613,13 @@ void generate_prototype_implementation(IDL::Interface const& interface)
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/LocationObject.h>
#include <LibWeb/Bindings/WindowObject.h>
+#include <LibWeb/Bindings/WorkerLocationWrapper.h>
+#include <LibWeb/Bindings/WorkerNavigatorWrapper.h>
+#include <LibWeb/Bindings/WorkerWrapper.h>
+#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/IDLEventListener.h>
+#include <LibWeb/DOM/Range.h>
#include <LibWeb/DOM/Window.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/Origin.h>
diff --git a/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h b/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h
index 8e1d3e880d..d7bd9c1f76 100644
--- a/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h
+++ b/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h
@@ -303,6 +303,8 @@
#include <LibWeb/Bindings/URLSearchParamsPrototype.h>
#include <LibWeb/Bindings/WebSocketConstructor.h>
#include <LibWeb/Bindings/WebSocketPrototype.h>
+#include <LibWeb/Bindings/WorkerConstructor.h>
+#include <LibWeb/Bindings/WorkerPrototype.h>
#include <LibWeb/Bindings/XMLHttpRequestConstructor.h>
#include <LibWeb/Bindings/XMLHttpRequestEventTargetConstructor.h>
#include <LibWeb/Bindings/XMLHttpRequestEventTargetPrototype.h>
@@ -467,6 +469,7 @@
ADD_WINDOW_OBJECT_INTERFACE(URLSearchParams) \
ADD_WINDOW_OBJECT_INTERFACE(URL) \
ADD_WINDOW_OBJECT_INTERFACE(WebSocket) \
+ ADD_WINDOW_OBJECT_INTERFACE(Worker) \
ADD_WINDOW_OBJECT_INTERFACE(XMLHttpRequest) \
ADD_WINDOW_OBJECT_INTERFACE(XMLHttpRequestEventTarget) \
ADD_WINDOW_OBJECT_CONSTRUCTOR_AND_PROTOTYPE(Image, ImageConstructor, HTMLImageElementPrototype)
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt
index 26b51ec814..fc74355c7b 100644
--- a/Userland/Libraries/LibWeb/CMakeLists.txt
+++ b/Userland/Libraries/LibWeb/CMakeLists.txt
@@ -206,6 +206,8 @@ set(SOURCES
HTML/TagNames.cpp
HTML/TextMetrics.cpp
HTML/WebSocket.cpp
+ HTML/Worker.cpp
+ HTML/WorkerDebugConsoleClient.cpp
HTML/WorkerGlobalScope.cpp
HTML/WorkerLocation.cpp
HighResolutionTime/Performance.cpp
@@ -518,6 +520,7 @@ libweb_js_wrapper(HTML/Storage)
libweb_js_wrapper(HTML/SubmitEvent)
libweb_js_wrapper(HTML/TextMetrics)
libweb_js_wrapper(HTML/WebSocket)
+libweb_js_wrapper(HTML/Worker)
libweb_js_wrapper(HTML/WorkerGlobalScope)
libweb_js_wrapper(HTML/WorkerLocation)
libweb_js_wrapper(HTML/WorkerNavigator)
diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h
index 43c2902631..8bbd0754fe 100644
--- a/Userland/Libraries/LibWeb/Forward.h
+++ b/Userland/Libraries/LibWeb/Forward.h
@@ -215,11 +215,14 @@ class MessageEvent;
class MessagePort;
class PageTransitionEvent;
class PromiseRejectionEvent;
+class WorkerDebugConsoleClient;
class Storage;
class SubmitEvent;
class TextMetrics;
class WebSocket;
class WindowEnvironmentSettingsObject;
+class Worker;
+class WorkerEnvironmentSettingsObject;
class WorkerGlobalScope;
class WorkerLocation;
class WorkerNavigator;
@@ -488,6 +491,7 @@ class URLSearchParamsWrapper;
class URLWrapper;
class WebSocketWrapper;
class WindowObject;
+class WorkerWrapper;
class WorkerGlobalScopeWrapper;
class WorkerLocationWrapper;
class WorkerNavigatorWrapper;
diff --git a/Userland/Libraries/LibWeb/HTML/MessageChannel.cpp b/Userland/Libraries/LibWeb/HTML/MessageChannel.cpp
index bd47c9da86..1714d5905c 100644
--- a/Userland/Libraries/LibWeb/HTML/MessageChannel.cpp
+++ b/Userland/Libraries/LibWeb/HTML/MessageChannel.cpp
@@ -19,7 +19,7 @@ MessageChannel::MessageChannel()
m_port2 = MessagePort::create();
// 3. Entangle this's port 1 and this's port 2.
- m_port1->entangle_with({}, *m_port2);
+ m_port1->entangle_with(*m_port2);
}
MessageChannel::~MessageChannel()
diff --git a/Userland/Libraries/LibWeb/HTML/MessagePort.cpp b/Userland/Libraries/LibWeb/HTML/MessagePort.cpp
index b467d84020..39b55e3d2a 100644
--- a/Userland/Libraries/LibWeb/HTML/MessagePort.cpp
+++ b/Userland/Libraries/LibWeb/HTML/MessagePort.cpp
@@ -30,7 +30,7 @@ void MessagePort::disentangle()
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
-void MessagePort::entangle_with(Badge<MessageChannel>, MessagePort& remote_port)
+void MessagePort::entangle_with(MessagePort& remote_port)
{
if (m_remote_port == &remote_port)
return;
diff --git a/Userland/Libraries/LibWeb/HTML/MessagePort.h b/Userland/Libraries/LibWeb/HTML/MessagePort.h
index 926781f0f1..fc8031582b 100644
--- a/Userland/Libraries/LibWeb/HTML/MessagePort.h
+++ b/Userland/Libraries/LibWeb/HTML/MessagePort.h
@@ -43,7 +43,7 @@ public:
virtual JS::Object* create_wrapper(JS::GlobalObject&) override;
// https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
- void entangle_with(Badge<MessageChannel>, MessagePort&);
+ void entangle_with(MessagePort&);
// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage
void post_message(JS::Value);
diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h b/Userland/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h
new file mode 100644
index 0000000000..f31c69bbf0
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/URL.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::HTML {
+
+// FIXME: This is a bit ugly, this implementation is basically a 1:1 copy of what is in ESO
+// just modified to use DOM::Document instead of DOM::Window since workers have no window
+class WorkerEnvironmentSettingsObject final
+ : public EnvironmentSettingsObject
+ , public Weakable<WorkerEnvironmentSettingsObject> {
+public:
+ WorkerEnvironmentSettingsObject(DOM::Document& document, JS::ExecutionContext& execution_context)
+ : EnvironmentSettingsObject(execution_context)
+ , m_document(document)
+ {
+ }
+
+ static WeakPtr<WorkerEnvironmentSettingsObject> setup(DOM::Document& document, JS::ExecutionContext& execution_context /* FIXME: null or an environment reservedEnvironment, a URL topLevelCreationURL, and an origin topLevelOrigin */)
+ {
+ auto* realm = execution_context.realm;
+ VERIFY(realm);
+ auto settings_object = adopt_own(*new WorkerEnvironmentSettingsObject(document, execution_context));
+ settings_object->target_browsing_context = nullptr;
+ realm->set_host_defined(move(settings_object));
+
+ return static_cast<WorkerEnvironmentSettingsObject*>(realm->host_defined());
+ }
+
+ virtual ~WorkerEnvironmentSettingsObject() override = default;
+
+ RefPtr<DOM::Document> responsible_document() override { return m_document; }
+ String api_url_character_encoding() override { return m_document->encoding_or_default(); }
+ AK::URL api_base_url() override { return m_document->url(); }
+ Origin origin() override { return m_document->origin(); }
+ CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability() override { TODO(); }
+
+private:
+ NonnullRefPtr<DOM::Document> m_document;
+};
+
+}
diff --git a/Userland/Libraries/LibWeb/HTML/Worker.cpp b/Userland/Libraries/LibWeb/HTML/Worker.cpp
new file mode 100644
index 0000000000..0cd10ff0f7
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/Worker.cpp
@@ -0,0 +1,347 @@
+/*
+ * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/String.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/Bindings/MainThreadVM.h>
+#include <LibWeb/Bindings/WorkerWrapper.h>
+#include <LibWeb/DOM/ExceptionOr.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Worker.h>
+#include <LibWeb/HTML/WorkerDebugConsoleClient.h>
+
+namespace Web::HTML {
+
+// https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-worker-interface
+Worker::Worker(FlyString const& script_url, WorkerOptions const options, DOM::Document& document)
+ : m_script_url(script_url)
+ , m_options(options)
+ , m_document(&document)
+ , m_custom_data()
+ , m_worker_vm(JS::VM::create(adopt_own(m_custom_data)))
+ , m_interpreter(JS::Interpreter::create<JS::GlobalObject>(m_worker_vm))
+ , m_interpreter_scope(*m_interpreter)
+ , m_execution_context(m_worker_vm->heap())
+ , m_implicit_port(MessagePort::create())
+{
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#dom-worker
+DOM::ExceptionOr<NonnullRefPtr<Worker>> Worker::create(FlyString const& script_url, WorkerOptions const options, DOM::Document& document)
+{
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Creating worker with script_url = {}", script_url);
+
+ // Returns a new Worker object. scriptURL will be fetched and executed in the background,
+ // creating a new global environment for which worker represents the communication channel.
+ // options can be used to define the name of that global environment via the name option,
+ // primarily for debugging purposes. It can also ensure this new global environment supports
+ // JavaScript modules (specify type: "module"), and if that is specified, can also be used
+ // to specify how scriptURL is fetched through the credentials option.
+
+ // FIXME: 1. The user agent may throw a "SecurityError" DOMException if the request violates
+ // a policy decision (e.g. if the user agent is configured to not allow the page to start dedicated workers).
+ // Technically not a fixme if our policy is not to throw errors :^)
+
+ // 2. Let outside settings be the current settings object.
+ auto& outside_settings = document.relevant_settings_object();
+
+ // 3. Parse the scriptURL argument relative to outside settings.
+ auto url = document.parse_url(script_url);
+
+ // 4. If this fails, throw a "SyntaxError" DOMException.
+ if (!url.is_valid()) {
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Invalid URL loaded '{}'.", script_url);
+ return DOM::SyntaxError::create("url is not valid");
+ }
+
+ // 5. Let worker URL be the resulting URL record.
+
+ // 6. Let worker be a new Worker object.
+ auto worker = adopt_ref(*new Worker(script_url, options, document));
+
+ // 7. Let outside port be a new MessagePort in outside settings's Realm.
+ auto outside_port = MessagePort::create();
+
+ // 8. Associate the outside port with worker
+ worker->m_outside_port = outside_port;
+
+ // 9. Run this step in parallel:
+ // 1. Run a worker given worker, worker URL, outside settings, outside port, and options.
+ worker->run_a_worker(url, outside_settings, outside_port, options);
+
+ // 10. Return worker
+ return worker;
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#run-a-worker
+void Worker::run_a_worker(AK::URL& url, EnvironmentSettingsObject& outside_settings, MessagePort& outside_port, WorkerOptions const options)
+{
+ // 1. Let is shared be true if worker is a SharedWorker object, and false otherwise.
+ // FIXME: SharedWorker support
+ auto is_shared = false;
+ auto is_top_level = false;
+
+ // 2. Let owner be the relevant owner to add given outside settings.
+ // FIXME: Support WorkerGlobalScope options
+ if (!is<HTML::WindowEnvironmentSettingsObject>(outside_settings))
+ TODO();
+
+ // 3. Let parent worker global scope be null.
+ // 4. If owner is a WorkerGlobalScope object (i.e., we are creating a nested dedicated worker),
+ // then set parent worker global scope to owner.
+ // FIXME: Support for nested workers.
+
+ // 5. Let unsafeWorkerCreationTime be the unsafe shared current time.
+
+ // 6. Let agent be the result of obtaining a dedicated/shared worker agent given outside settings
+ // and is shared. Run the rest of these steps in that agent.
+ // NOTE: This is effectively the worker's vm
+
+ // 7. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
+ // FIXME: Perform the full steps for 'create a new JavaScript realm'
+ // https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm
+ m_worker_realm = JS::Realm::create(m_worker_vm);
+
+ // 7a. For the global object, if is shared is true, create a new SharedWorkerGlobalScope object.
+ // 7b. Otherwise, create a new DedicatedWorkerGlobalScope object.
+ // FIXME: Proper support for both SharedWorkerGlobalScope and DedicatedWorkerGlobalScope
+ if (is_shared)
+ TODO();
+
+ // FIXME: Make and use subclasses of WorkerGlobalScope, however this requries JS::GlobalObject to
+ // play nicely with the IDL interpreter, to make spec-compliant extensions, which it currently does not.
+ m_worker_scope = m_worker_vm->heap().allocate_without_global_object<JS::GlobalObject>();
+ m_worker_scope->initialize_global_object();
+
+ m_console = adopt_ref(*new WorkerDebugConsoleClient(m_worker_scope->console()));
+ m_worker_scope->console().set_client(*m_console);
+
+ // FIXME: This should be done with IDL
+ u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
+ m_worker_scope->define_native_function(
+ "postMessage", [this](auto& vm, auto&) {
+ // This is the implementation of the function that the spawned worked calls
+
+ // https://html.spec.whatwg.org/multipage/workers.html#dom-dedicatedworkerglobalscope-postmessage
+ // The postMessage(message, transfer) and postMessage(message, options) methods on DedicatedWorkerGlobalScope
+ // objects act as if, when invoked, it immediately invoked the respective postMessage(message, transfer) and
+ // postMessage(message, options) on the port, with the same arguments, and returned the same return value
+
+ auto message = vm.argument(0);
+ // FIXME: `transfer` not support by post_message yet
+
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Inner post_message");
+
+ // FIXME: This is a bit of a hack, in reality, we should m_outside_port->post_message and the onmessage event
+ // should bubble up to the Worker itself from there.
+
+ auto& event_loop = get_vm_event_loop(m_document->realm().vm());
+
+ event_loop.task_queue().add(HTML::Task::create(HTML::Task::Source::PostedMessage, nullptr, [this, message]() mutable {
+ MessageEventInit event_init {};
+ event_init.data = message;
+ event_init.origin = "<origin>";
+ dispatch_event(MessageEvent::create(HTML::EventNames::message, event_init));
+ }));
+
+ return JS::js_undefined();
+ },
+ 2, attr);
+
+ // FIXME: This is because I don't know all the libraries well enough to properly setup the environment to spec
+ // let alone making it a parallel implementation.
+ m_execution_context.current_node = nullptr;
+ m_execution_context.this_value = m_worker_scope;
+ m_execution_context.function_name = "(global execution context)"sv;
+ m_execution_context.lexical_environment = &m_worker_realm->global_environment();
+ m_execution_context.variable_environment = &m_worker_realm->global_environment();
+ m_execution_context.realm = m_worker_realm;
+
+ m_worker_vm->push_execution_context(m_execution_context, *m_worker_scope);
+ m_worker_realm->set_global_object(*m_worker_scope, m_worker_scope);
+
+ // 8. Let worker global scope be the global object of realm execution context's Realm component.
+ // NOTE: This is the DedicatedWorkerGlobalScope or SharedWorkerGlobalScope object created in the previous step.
+
+ // 9. Set up a worker environment settings object with realm execution context,
+ // outside settings, and unsafeWorkerCreationTime, and let inside settings be the result.
+ m_inner_settings = WorkerEnvironmentSettingsObject::setup(*m_document, m_execution_context);
+
+ // 10. Set worker global scope's name to the value of options's name member.
+ // FIXME: name propery requires the SharedWorkerGlobalScope or DedicatedWorkerGlobalScope child class to be used
+
+ // 11. Append owner to worker global scope's owner set.
+ // FIXME: support for 'owner' set on WorkerGlobalScope
+
+ // 12. If is shared is true, then:
+ if (is_shared) {
+ // FIXME: Shared worker support
+ // 1. Set worker global scope's constructor origin to outside settings's origin.
+ // 2. Set worker global scope's constructor url to url.
+ // 3. Set worker global scope's type to the value of options's type member.
+ // 4. Set worker global scope's credentials to the value of options's credentials member.
+ }
+
+ // 13. Let destination be "sharedworker" if is shared is true, and "worker" otherwise.
+
+ // 14. Obtain script by switching on the value of options's type member:
+ // classic: Fetch a classic worker script given url, outside settings, destination, and inside settings.
+ // module: Fetch a module worker script graph given url, outside settings, destination, the value of the
+ // credentials member of options, and inside settings.
+ if (options.type != "classic") {
+ dbgln_if(WEB_WORKER_DEBUG, "Unsupported script type {} for LibWeb/Worker", options.type);
+ TODO();
+ }
+
+ ResourceLoader::the().load(
+ url,
+ [this, is_shared, is_top_level, url, &outside_port](auto data, auto&, auto) {
+ // In both cases, to perform the fetch given request, perform the following steps if the is top-level flag is set:
+ if (is_top_level) {
+ // 1. Set request's reserved client to inside settings.
+
+ // 2. Fetch request, and asynchronously wait to run the remaining steps
+ // as part of fetch's process response for the response response.
+ // Implied
+
+ // 3. Set worker global scope's url to response's url.
+
+ // 4. Initialize worker global scope's policy container given worker global scope, response, and inside settings.
+ // FIXME: implement policy container
+
+ // 5. If the Run CSP initialization for a global object algorithm returns "Blocked" when executed upon worker
+ // global scope, set response to a network error. [CSP]
+ // FIXME: CSP support
+
+ // 6. If worker global scope's embedder policy's value is compatible with cross-origin isolation and is shared is true,
+ // then set agent's agent cluster's cross-origin isolation mode to "logical" or "concrete".
+ // The one chosen is implementation-defined.
+ // FIXME: CORS policy support
+
+ // 7. If the result of checking a global object's embedder policy with worker global scope, outside settings,
+ // and response is false, then set response to a network error.
+ // FIXME: Embed policy support
+
+ // 8. Set worker global scope's cross-origin isolated capability to true if agent's agent cluster's cross-origin
+ // isolation mode is "concrete".
+ // FIXME: CORS policy support
+
+ if (!is_shared) {
+ // 9. If is shared is false and owner's cross-origin isolated capability is false, then set worker
+ // global scope's cross-origin isolated capability to false.
+ // 10. If is shared is false and response's url's scheme is "data", then set worker global scope's
+ // cross-origin isolated capability to false.
+ }
+ }
+
+ if (data.is_null()) {
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Failed to load {}", url);
+ return;
+ }
+
+ // Asynchronously complete the perform the fetch steps with response.
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Script ready!");
+ auto script = ClassicScript::create(url.to_string(), data, *m_inner_settings, AK::URL());
+
+ // NOTE: Steps 15-31 below pick up after step 14 in the main context, steps 1-10 above
+ // are only for validation when used in a top-level case (ie: from a Window)
+
+ // 15. Associate worker with worker global scope.
+ // FIXME: Global scope association
+
+ // 16. Let inside port be a new MessagePort object in inside settings's Realm.
+ auto inside_port = MessagePort::create();
+
+ // 17. Associate inside port with worker global scope.
+ // FIXME: Global scope association
+
+ // 18. Entangle outside port and inside port.
+ outside_port.entangle_with(*inside_port);
+
+ // 19. Create a new WorkerLocation object and associate it with worker global scope.
+
+ // 20. Closing orphan workers: Start monitoring the worker such that no sooner than it
+ // stops being a protected worker, and no later than it stops being a permissible worker,
+ // worker global scope's closing flag is set to true.
+ // FIXME: Worker monitoring and cleanup
+
+ // 21. Suspending workers: Start monitoring the worker, such that whenever worker global scope's
+ // closing flag is false and the worker is a suspendable worker, the user agent suspends
+ // execution of script in that worker until such time as either the closing flag switches to
+ // true or the worker stops being a suspendable worker
+ // FIXME: Worker suspending
+
+ // 22. Set inside settings's execution ready flag.
+ // FIXME: Implement worker settings object
+
+ // 23. If script is a classic script, then run the classic script script.
+ // Otherwise, it is a module script; run the module script script.
+ auto result = script->run();
+
+ // 24. Enable outside port's port message queue.
+ outside_port.start();
+
+ // 25. If is shared is false, enable the port message queue of the worker's implicit port.
+ if (!is_shared)
+ m_implicit_port->start();
+
+ // 26. If is shared is true, then queue a global task on DOM manipulation task source given worker
+ // global scope to fire an event named connect at worker global scope, using MessageEvent,
+ // with the data attribute initialized to the empty string, the ports attribute initialized
+ // to a new frozen array containing inside port, and the source attribute initialized to inside port.
+ // FIXME: Shared worker support
+
+ // 27. Enable the client message queue of the ServiceWorkerContainer object whose associated service
+ // worker client is worker global scope's relevant settings object.
+ // FIXME: Understand....and support worker global settings
+
+ // 28. Event loop: Run the responsible event loop specified by inside settings until it is destroyed.
+ },
+ [](auto&, auto) {
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: HONK! Failed to load script.");
+ });
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#dom-worker-terminate
+DOM::ExceptionOr<void> Worker::terminate()
+{
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Terminate");
+
+ return {};
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
+void Worker::post_message(JS::Value message, JS::Value)
+{
+ dbgln_if(WEB_WORKER_DEBUG, "WebWorker: Post Message: {}", message.to_string_without_side_effects());
+
+ // 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
+ auto& target_port = m_outside_port;
+
+ // 2. Let options be ยซ[ "transfer" โ†’ transfer ]ยป.
+ // 3. Run the message port post message steps providing this, targetPort, message and options.
+ target_port->post_message(message);
+}
+
+JS::Object* Worker::create_wrapper(JS::GlobalObject& global_object)
+{
+ return wrap(global_object, *this);
+}
+
+#undef __ENUMERATE
+#define __ENUMERATE(attribute_name, event_name) \
+ void Worker::set_##attribute_name(Optional<Bindings::CallbackType> value) \
+ { \
+ set_event_handler_attribute(event_name, move(value)); \
+ } \
+ Bindings::CallbackType* Worker::attribute_name() \
+ { \
+ return event_handler_attribute(event_name); \
+ }
+ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
+#undef __ENUMERATE
+
+} // namespace Web::HTML
diff --git a/Userland/Libraries/LibWeb/HTML/Worker.h b/Userland/Libraries/LibWeb/HTML/Worker.h
new file mode 100644
index 0000000000..cf3ec36196
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/Worker.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/RefCounted.h>
+#include <AK/URLParser.h>
+#include <LibJS/Interpreter.h>
+#include <LibWeb/Bindings/MainThreadVM.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/HTML/MessageEvent.h>
+#include <LibWeb/HTML/MessagePort.h>
+#include <LibWeb/HTML/Scripting/ClassicScript.h>
+#include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
+#include <LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h>
+#include <LibWeb/HTML/WorkerDebugConsoleClient.h>
+#include <LibWeb/Loader/ResourceLoader.h>
+
+#define ENUMERATE_WORKER_EVENT_HANDLERS(E) \
+ E(onmessage, HTML::EventNames::message) \
+ E(onmessageerror, HTML::EventNames::messageerror)
+
+namespace Web::HTML {
+
+struct WorkerOptions {
+ String type { "classic" };
+ String credentials { "same-origin" };
+ String name { "" };
+};
+
+// https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-worker-interface
+class Worker
+ : public RefCounted<Worker>
+ , public Weakable<Worker>
+ , public DOM::EventTarget
+ , public Bindings::Wrappable {
+public:
+ using WrapperType = Bindings::WorkerWrapper;
+
+ using RefCounted::ref;
+ using RefCounted::unref;
+
+ static DOM::ExceptionOr<NonnullRefPtr<Worker>> create(FlyString const& script_url, WorkerOptions const options, DOM::Document& document);
+ static DOM::ExceptionOr<NonnullRefPtr<Worker>> create_with_global_object(Bindings::WindowObject& window, FlyString const& script_url, WorkerOptions const options)
+ {
+ return Worker::create(script_url, options, window.impl().associated_document());
+ }
+
+ DOM::ExceptionOr<void> terminate();
+
+ void post_message(JS::Value message, JS::Value transfer);
+
+ virtual ~Worker() = default;
+
+ // ^EventTarget
+ virtual void ref_event_target() override { ref(); }
+ virtual void unref_event_target() override { unref(); }
+ virtual JS::Object* create_wrapper(JS::GlobalObject&) override;
+
+ MessagePort* implicit_message_port() { return m_implicit_port; }
+ RefPtr<MessagePort> outside_message_port() { return m_outside_port; }
+
+#undef __ENUMERATE
+#define __ENUMERATE(attribute_name, event_name) \
+ void set_##attribute_name(Optional<Bindings::CallbackType>); \
+ Bindings::CallbackType* attribute_name();
+ ENUMERATE_WORKER_EVENT_HANDLERS(__ENUMERATE)
+#undef __ENUMERATE
+
+protected:
+ Worker(FlyString const&, const WorkerOptions, DOM::Document&);
+
+private:
+ static HTML::EventLoop& get_vm_event_loop(JS::VM& target_vm)
+ {
+ return static_cast<Bindings::WebEngineCustomData*>(target_vm.custom_data())->event_loop;
+ }
+
+ FlyString m_script_url;
+ WorkerOptions m_options;
+ WeakPtr<DOM::Document> m_document;
+ Bindings::WebEngineCustomData m_custom_data;
+
+ NonnullRefPtr<JS::VM> m_worker_vm;
+ NonnullOwnPtr<JS::Interpreter> m_interpreter;
+ WeakPtr<WorkerEnvironmentSettingsObject> m_inner_settings;
+ JS::VM::InterpreterExecutionScope m_interpreter_scope;
+ JS::ExecutionContext m_execution_context;
+ WeakPtr<JS::Realm> m_worker_realm;
+ RefPtr<WorkerDebugConsoleClient> m_console;
+ JS::GlobalObject* m_worker_scope;
+
+ NonnullRefPtr<MessagePort> m_implicit_port;
+ RefPtr<MessagePort> m_outside_port;
+
+ void run_a_worker(AK::URL& url, EnvironmentSettingsObject& outside_settings, MessagePort& outside_port, WorkerOptions const options);
+};
+
+} // namespace Web::HTML
+
+namespace Web::Bindings {
+
+WorkerWrapper* wrap(JS::GlobalObject&, HTML::Worker&);
+
+}
diff --git a/Userland/Libraries/LibWeb/HTML/Worker.idl b/Userland/Libraries/LibWeb/HTML/Worker.idl
new file mode 100644
index 0000000000..73687379a1
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/Worker.idl
@@ -0,0 +1,16 @@
+[Exposed=(Window)]
+interface Worker : EventTarget {
+ constructor(DOMString scriptURL, optional WorkerOptions options = {});
+
+ undefined terminate();
+ undefined postMessage(any message, optional any transfer);
+
+ attribute EventHandler onmessage;
+ attribute EventHandler onmessageerror;
+};
+
+dictionary WorkerOptions {
+ USVString type = "classic";
+ USVString credentials = "same-origin";
+ DOMString name = "";
+};
diff --git a/Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp b/Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp
new file mode 100644
index 0000000000..86f4c5f143
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibJS/Runtime/Completion.h>
+#include <LibWeb/HTML/WorkerDebugConsoleClient.h>
+
+namespace Web::HTML {
+
+WorkerDebugConsoleClient::WorkerDebugConsoleClient(JS::Console& console)
+ : ConsoleClient(console)
+{
+}
+
+void WorkerDebugConsoleClient::clear()
+{
+ dbgln("\033[3J\033[H\033[2J");
+ m_group_stack_depth = 0;
+ fflush(stdout);
+}
+
+void WorkerDebugConsoleClient::end_group()
+{
+ if (m_group_stack_depth > 0)
+ m_group_stack_depth--;
+}
+
+// 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
+JS::ThrowCompletionOr<JS::Value> WorkerDebugConsoleClient::printer(JS::Console::LogLevel log_level, PrinterArguments arguments)
+{
+ String indent = String::repeated(" ", m_group_stack_depth);
+
+ if (log_level == JS::Console::LogLevel::Trace) {
+ auto trace = arguments.get<JS::Console::Trace>();
+ StringBuilder builder;
+ if (!trace.label.is_empty())
+ builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
+
+ for (auto& function_name : trace.stack)
+ builder.appendff("{}-> {}\n", indent, function_name);
+
+ dbgln("{}", builder.string_view());
+ return JS::js_undefined();
+ }
+
+ if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
+ auto group = arguments.get<JS::Console::Group>();
+ dbgln("{}\033[36;1m{}\033[0m", indent, group.label);
+ m_group_stack_depth++;
+ return JS::js_undefined();
+ }
+
+ auto output = String::join(" ", arguments.get<Vector<JS::Value>>());
+ m_console.output_debug_message(log_level, output);
+
+ switch (log_level) {
+ case JS::Console::LogLevel::Debug:
+ dbgln("{}\033[36;1m{}\033[0m", indent, output);
+ break;
+ case JS::Console::LogLevel::Error:
+ case JS::Console::LogLevel::Assert:
+ dbgln("{}\033[31;1m{}\033[0m", indent, output);
+ break;
+ case JS::Console::LogLevel::Info:
+ dbgln("{}(i) {}", indent, output);
+ break;
+ case JS::Console::LogLevel::Log:
+ dbgln("{}{}", indent, output);
+ break;
+ case JS::Console::LogLevel::Warn:
+ case JS::Console::LogLevel::CountReset:
+ dbgln("{}\033[33;1m{}\033[0m", indent, output);
+ break;
+ default:
+ dbgln("{}{}", indent, output);
+ break;
+ }
+ return JS::js_undefined();
+}
+
+} // namespace Web::HTML
diff --git a/Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.h b/Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.h
new file mode 100644
index 0000000000..569ce5d4af
--- /dev/null
+++ b/Userland/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2022, Ben Abraham <ben.d.abraham@gmail.com>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/RefCounted.h>
+#include <AK/Weakable.h>
+#include <LibJS/Console.h>
+
+namespace Web::HTML {
+
+// NOTE: Temporary class to handle console messages from inside Workers
+
+class WorkerDebugConsoleClient final
+ : public JS::ConsoleClient
+ , public RefCounted<WorkerDebugConsoleClient>
+ , public Weakable<WorkerDebugConsoleClient> {
+public:
+ WorkerDebugConsoleClient(JS::Console& console);
+
+ virtual void clear() override;
+ virtual void end_group() override;
+ virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override;
+
+private:
+ int m_group_stack_depth { 0 };
+};
+
+} // namespace Web::HTML