Truly independent web browser
LibWeb: Report exceptions thrown in a worklet
Shannon Booth59919eb27282
diff --git a/Libraries/LibWeb/DOM/ElementFactory.cpp b/Libraries/LibWeb/DOM/ElementFactory.cppindex 0f078aeb5af..0932bbbe2cb 100644--- a/Libraries/LibWeb/DOM/ElementFactory.cpp+++ b/Libraries/LibWeb/DOM/ElementFactory.cpp@@ -87,7 +87,7 @@#include <LibWeb/HTML/HTMLUnknownElement.h>#include <LibWeb/HTML/HTMLVideoElement.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>#include <LibWeb/MathML/MathMLAnchorElement.h>#include <LibWeb/MathML/MathMLElement.h>#include <LibWeb/MathML/MathMLMiElement.h>@@ -700,8 +700,7 @@ WebIDL::ExceptionOr<GC::Ref<Element>> create_element(Document& document, Utf16Flif (upgrade_result.is_throw_completion()) {// 1. Report exception for definition’s constructor’s corresponding JavaScript object’s associated// realm’s global object.- auto& window_or_worker = HTML::relevant_window_or_worker_global_scope(definition->constructor().callback);- window_or_worker.report_an_exception(upgrade_result.error_value());+ HTML::report_an_exception(HTML::relevant_global_object(definition->constructor().callback), upgrade_result.error_value());// 2. Set result’s custom element state to "failed".result->set_custom_element_state(CustomElementState::Failed);@@ -730,8 +729,7 @@ WebIDL::ExceptionOr<GC::Ref<Element>> create_element(Document& document, Utf16Flif (constructed_element.is_throw_completion()) {// 1. Report exception for definition’s constructor’s corresponding JavaScript object’s associated// realm’s global object.- auto& window_or_worker = HTML::relevant_window_or_worker_global_scope(definition->constructor().callback);- window_or_worker.report_an_exception(constructed_element.error_value());+ HTML::report_an_exception(HTML::relevant_global_object(definition->constructor().callback), constructed_element.error_value());// 2. Set result to the result of creating an element internal given document, HTMLUnknownElement,// localName, the HTML namespace, prefix, "failed", null, and registry.diff --git a/Libraries/LibWeb/DOM/EventTarget.cpp b/Libraries/LibWeb/DOM/EventTarget.cppindex feb6f5787cc..c22b08932e2 100644--- a/Libraries/LibWeb/DOM/EventTarget.cpp+++ b/Libraries/LibWeb/DOM/EventTarget.cpp@@ -49,6 +49,7 @@#include <LibWeb/HTML/LocalTraversableNavigable.h>#include <LibWeb/HTML/Navigable.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>@@ -165,11 +166,7 @@ DOM::EventTarget* current_target_global(WebIDL::CallbackType& callback, DOM::Evevoid report_exception_for_callback(WebIDL::CallbackType& callback, JS::Value exception){auto& realm = callback.callback->shape().realm();- auto& global = realm.global_object();-- auto* window_or_worker = HTML::window_or_worker_global_scope_from_global_object(global);- VERIFY(window_or_worker);- window_or_worker->report_an_exception(exception);+ HTML::report_an_exception(realm.global_object(), exception);}JS::Completion invoke_event_listener(WebIDL::CallbackType& callback, DOM::Event& event)diff --git a/Libraries/LibWeb/HTML/CustomElements/CustomElementAlgorithms.cpp b/Libraries/LibWeb/HTML/CustomElements/CustomElementAlgorithms.cppindex 551c421e1a8..9852b1e2f22 100644--- a/Libraries/LibWeb/HTML/CustomElements/CustomElementAlgorithms.cpp+++ b/Libraries/LibWeb/HTML/CustomElements/CustomElementAlgorithms.cpp@@ -27,8 +27,8 @@#include <LibWeb/HTML/HTMLElement.h>#include <LibWeb/HTML/HTMLFormElement.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/Namespace.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/DOMException.h>@@ -319,11 +319,7 @@ void report_custom_element_upgrade_exception(HTML::CustomElementDefinition& cust{auto& callback = custom_element_definition.constructor();auto& realm = callback.callback->shape().realm();- auto& global = realm.global_object();-- auto* window_or_worker = HTML::window_or_worker_global_scope_from_global_object(global);- VERIFY(window_or_worker);- window_or_worker->report_an_exception(exception);+ HTML::report_an_exception(realm.global_object(), exception);}}diff --git a/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp b/Libraries/LibWeb/HTML/Scripting/ClassicScript.cppindex d895ff388b4..c71e3ccace5 100644--- a/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp+++ b/Libraries/LibWeb/HTML/Scripting/ClassicScript.cpp@@ -241,9 +241,7 @@ JS::Completion ClassicScript::run(RethrowErrors rethrow_errors, GC::Ptr<JS::EnviVERIFY(rethrow_errors == RethrowErrors::No);// 1. Report an exception given by evaluationStatus.[[Value]] for script's settings object's global object.- auto* window_or_worker = window_or_worker_global_scope_from_global_object(settings.global_object());- VERIFY(window_or_worker);- window_or_worker->report_an_exception(evaluation_status.value());+ report_an_exception(settings.global_object(), evaluation_status.value());// 2. Clean up after running script with settings.clean_up_after_running_script(settings);diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cppindex 4a5a624746f..221aa8fce2f 100644--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp@@ -10,7 +10,16 @@#include <LibJS/Runtime/ConsoleObject.h>#include <LibJS/Runtime/VM.h>#include <LibJS/Runtime/Value.h>+#include <LibWeb/HTML/DedicatedWorkerGlobalScope.h>+#include <LibWeb/HTML/ErrorEvent.h>+#include <LibWeb/HTML/ErrorInformation.h>+#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/HTML/Scripting/ClassicScript.h>+#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/ExceptionReporter.h>+#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>+#include <LibWeb/HighResolutionTime/TimeOrigin.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/WebIDL/DOMException.h>namespace Web::HTML {@@ -57,6 +66,89 @@ void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromiconsole.report_exception("Error"_utf16, utf16_message, *error, error_in_promise == ErrorInPromise::Yes);}+// https://html.spec.whatwg.org/multipage/webappapis.html#report-an-exception+void report_an_exception(JS::Object& global, JS::Value exception, OmitError omit_error)+{+ auto& realm = relevant_realm(global);+ auto& vm = realm.vm();++ // 1. Let notHandled be true.+ bool not_handled = true;++ // 2. Let errorInfo be the result of extracting error information from exception.+ auto error_info = extract_error_information(vm, exception);++ // 3. Let script be a script found in an implementation-defined way, or null. This should usually be the+ // running script (most notably during run a classic script).+ auto script_or_module = vm.get_active_script_or_module();++ // 4. If script is a classic script and script's muted errors is true, then set errorInfo[error] to null,+ // errorInfo[message] to "Script error.", errorInfo[filename] to the empty string, errorInfo[lineno] to+ // 0, and errorInfo[colno] to 0.+ script_or_module.visit(+ [&](GC::Ref<JS::Script> const& js_script) {+ if (as<ClassicScript>(script_from_host_defined(js_script->host_defined()))->muted_errors() == ClassicScript::MutedErrors::Yes) {+ error_info.error = JS::js_null();+ error_info.message = "Script error."_utf16;+ error_info.filename = Utf16String {};+ error_info.lineno = 0;+ error_info.colno = 0;+ }+ },+ [](auto const&) { });++ // 5. If omitError is true, then set errorInfo[error] to null.+ if (omit_error == OmitError::Yes)+ error_info.error = JS::js_null();++ // 6. If global is not in error reporting mode, then:+ // NB: WorkletGlobalScope's IDL interface does not inherit from EventTarget, so nothing can observe its in error+ // reporting mode and only Window and WorkerGlobalScope keep one.+ auto* window_or_worker = window_or_worker_global_scope_from_global_object(global);+ if (window_or_worker && !window_or_worker->is_in_error_reporting_mode()) {+ // 1. Set global's in error reporting mode to true.+ window_or_worker->set_in_error_reporting_mode(true);++ // 2. If global implements EventTarget, then set notHandled to the result of firing an event named+ // error at global, using ErrorEvent, with the cancelable attribute initialized to true, and+ // additional attributes initialized according to errorInfo.+ ErrorEventInit event_init = {};+ event_init.cancelable = true;+ event_init.message = error_info.message;+ event_init.filename = error_info.filename;+ event_init.lineno = error_info.lineno;+ event_init.colno = error_info.colno;+ event_init.error = error_info.error;++ not_handled = window_or_worker->this_impl().dispatch_event(ErrorEvent::create(EventNames::error, event_init, HighResolutionTime::current_high_resolution_time(global)));++ // 3. Set global's in error reporting mode to false.+ window_or_worker->set_in_error_reporting_mode(false);+ }++ // 7. If notHandled is true, then:+ if (not_handled) {+ // 1. Set errorInfo[error] to null.+ error_info.error = JS::js_null();++ // 2. If global implements DedicatedWorkerGlobalScope, queue a global task on the DOM manipulation+ // task source with the global's associated Worker's relevant global object to run these steps:+ if (auto* dedicated_worker_global_scope = Bindings::impl_from<DedicatedWorkerGlobalScope>(&global)) {+ if (auto* page = dedicated_worker_global_scope->page()) {+ page->client().page_did_report_worker_exception(+ error_info.message,+ error_info.filename,+ error_info.lineno,+ error_info.colno);+ }+ }+ // 3. Otherwise, the user agent may report exception to a developer console.+ else {+ report_exception_to_console(exception, realm, ErrorInPromise::No);+ }+ }+}+// https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exceptionvoid report_exception(JS::Completion const& throw_completion, JS::Realm& realm){diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.hindex eeaeb685389..78608526ed4 100644--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h@@ -16,8 +16,14 @@ enum class ErrorInPromise {Yes,};+enum class OmitError {+ No,+ Yes,+};+void report_exception_to_console(JS::Value, JS::Realm&, ErrorInPromise);WEB_API void report_exception(JS::Completion const&, JS::Realm&);+void report_an_exception(JS::Object& global, JS::Value exception, OmitError = OmitError::No);template<typename T>inline void report_exception(JS::ThrowCompletionOr<T> const& result, JS::Realm& realm)diff --git a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cppindex 7ef9a2e1bdb..631b9c88d83 100644--- a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp+++ b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp@@ -9,10 +9,10 @@#include <LibJS/ScriptCompilation.h>#include <LibWeb/CSS/StyleSheetState.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>#include <LibWeb/HTML/Scripting/Fetching.h>#include <LibWeb/HTML/Scripting/ModuleScript.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/WebAssembly/WebAssemblyModule.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOr.h>@@ -351,9 +351,7 @@ GC::Ptr<WebIDL::Promise> ModuleScript::run(PreventErrorReporting prevent_error_rif (prevent_error_reporting == PreventErrorReporting::No) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::upon_rejection(*evaluation_promise, GC::create_function(GC::Heap::the(), [&realm](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- auto* window_or_worker = window_or_worker_global_scope_from_global_object(realm.global_object());- VERIFY(window_or_worker);- window_or_worker->report_an_exception(reason);+ report_an_exception(realm.global_object(), reason);return JS::js_undefined();}));}diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex ad9e4841fde..924d577b77f 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -36,9 +36,6 @@#include <LibWeb/Fetch/FetchMethod.h>#include <LibWeb/HTML/BroadcastChannel.h>#include <LibWeb/HTML/CanvasRenderingContext2D.h>-#include <LibWeb/HTML/DedicatedWorkerGlobalScope.h>-#include <LibWeb/HTML/ErrorEvent.h>-#include <LibWeb/HTML/ErrorInformation.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/EventSource.h>#include <LibWeb/HTML/HTMLImageElement.h>@@ -1607,88 +1604,7 @@ GC::Ref<IndexedDB::IDBFactory> WindowOrWorkerGlobalScopeMixin::indexed_db()void WindowOrWorkerGlobalScopeMixin::report_error(JS::Value e){// The reportError(e) method steps are to report an exception e for this.- report_an_exception(e);-}--// https://html.spec.whatwg.org/multipage/webappapis.html#report-an-exception-void WindowOrWorkerGlobalScopeMixin::report_an_exception(JS::Value exception, OmitError omit_error)-{- auto& target = static_cast<DOM::EventTarget&>(this_impl());- auto& realm = relevant_realm(*this);- auto& vm = realm.vm();-- // 1. Let notHandled be true.- bool not_handled = true;-- // 2. Let errorInfo be the result of extracting error information from exception.- auto error_info = extract_error_information(vm, exception);-- // 3. Let script be a script found in an implementation-defined way, or null. This should usually be the- // running script (most notably during run a classic script).- auto script_or_module = vm.get_active_script_or_module();-- // 4. If script is a classic script and script's muted errors is true, then set errorInfo[error] to null,- // errorInfo[message] to "Script error.", errorInfo[filename] to the empty string, errorInfo[lineno] to- // 0, and errorInfo[colno] to 0.- script_or_module.visit(- [&](GC::Ref<JS::Script> const& js_script) {- if (as<ClassicScript>(script_from_host_defined(js_script->host_defined()))->muted_errors() == ClassicScript::MutedErrors::Yes) {- error_info.error = JS::js_null();- error_info.message = "Script error."_utf16;- error_info.filename = Utf16String {};- error_info.lineno = 0;- error_info.colno = 0;- }- },- [](auto const&) { });-- // 5. If omitError is true, then set errorInfo[error] to null.- if (omit_error == OmitError::Yes)- error_info.error = JS::js_null();-- // 6. If global is not in error reporting mode, then:- if (!m_error_reporting_mode) {- // 1. Set global's in error reporting mode to true.- m_error_reporting_mode = true;-- // 2. If global implements EventTarget, then set notHandled to the result of firing an event named- // error at global, using ErrorEvent, with the cancelable attribute initialized to true, and- // additional attributes initialized according to errorInfo.- ErrorEventInit event_init = {};- event_init.cancelable = true;- event_init.message = error_info.message;- event_init.filename = error_info.filename;- event_init.lineno = error_info.lineno;- event_init.colno = error_info.colno;- event_init.error = error_info.error;-- not_handled = target.dispatch_event(ErrorEvent::create(EventNames::error, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object())));-- // 3. Set global's in error reporting mode to false.- m_error_reporting_mode = false;- }-- // 7. If notHandled is true, then:- if (not_handled) {- // 1. Set errorInfo[error] to null.- error_info.error = JS::js_null();-- // 2. If global implements DedicatedWorkerGlobalScope, queue a global task on the DOM manipulation- // task source with the global's associated Worker's relevant global object to run these steps:- if (auto* dedicated_worker_global_scope = as_if<DedicatedWorkerGlobalScope>(target)) {- if (auto* page = dedicated_worker_global_scope->page()) {- page->client().page_did_report_worker_exception(- error_info.message,- error_info.filename,- error_info.lineno,- error_info.colno);- }- }- // 3. Otherwise, the user agent may report exception to a developer console.- else {- report_exception_to_console(exception, realm, ErrorInPromise::No);- }- }+ report_an_exception(relevant_global_object(*this), e);}// https://w3c.github.io/webcrypto/#dom-windoworworkerglobalscope-cryptodiff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.hindex 04b81a71bba..79b4839285a 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h@@ -119,11 +119,8 @@ public:void report_error(JS::Value e);- enum class OmitError {- Yes,- No,- };- void report_an_exception(JS::Value exception, OmitError = OmitError::No);+ bool is_in_error_reporting_mode() const { return m_in_error_reporting_mode; }+ void set_in_error_reporting_mode(bool value) { m_in_error_reporting_mode = value; }void push_onto_outstanding_rejected_promises_weak_set(GC::Ptr<JS::Promise>);bool remove_from_outstanding_rejected_promises_weak_set(GC::Ptr<JS::Promise>);@@ -219,7 +216,7 @@ private:GC::Ptr<TrustedTypes::TrustedTypePolicyFactory> m_trusted_type_policy_factory;- bool m_error_reporting_mode { false };+ bool m_in_error_reporting_mode { false };WebSockets::WebSocket::List m_registered_web_sockets;diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cppindex 995a59b05d3..27f1a8c20f3 100644--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp@@ -39,7 +39,7 @@ static void report_worker_exception(WindowOrWorkerGlobalScopeMixin& window_or_wo{auto& realm = relevant_realm(window_or_worker);auto wrapped_error = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { error });- window_or_worker.report_an_exception(wrapped_error, WindowOrWorkerGlobalScopeMixin::OmitError::Yes);+ report_an_exception(relevant_global_object(window_or_worker), wrapped_error, OmitError::Yes);}GC::Ref<WorkerAgentParent> WorkerAgentParent::create(URL::URL url, WorkerOptions const& options,diff --git a/Libraries/LibWeb/WebIDL/AbstractOperations.cpp b/Libraries/LibWeb/WebIDL/AbstractOperations.cppindex 657f5d6a962..b773f20050e 100644--- a/Libraries/LibWeb/WebIDL/AbstractOperations.cpp+++ b/Libraries/LibWeb/WebIDL/AbstractOperations.cpp@@ -21,7 +21,7 @@#include <LibWeb/Export.h>#include <LibWeb/HTML/CrossOrigin/AbstractOperations.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/Buffers.h>#include <LibWeb/WebIDL/CallbackType.h>@@ -387,9 +387,7 @@ JS::Completion invoke_callback(CallbackType& callback, Optional<JS::Value> this_// FIXME: 1. Assert: callable’s return type is undefined or any.// 2. Report an exception completion.[[Value]] for relevant realm’s global object.- auto* window_or_worker = HTML::window_or_worker_global_scope_from_global_object(relevant_realm.global_object());- VERIFY(window_or_worker);- window_or_worker->report_an_exception(completion.release_value());+ HTML::report_an_exception(relevant_realm.global_object(), completion.release_value());// 3. Return the unique undefined IDL value.return JS::js_undefined();diff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-throw-onmessage.https.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-throw-onmessage.https.txtnew file mode 100644index 00000000000..8a1cf034313--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-throw-onmessage.https.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass Throwing in an onmessage handler in the AudioWorkletGlobalScope shouldn't stop AudioWorkletProcessor\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/js/helpers.js b/Tests/LibWeb/Text/input/wpt-import/webaudio/js/helpers.jsnew file mode 100644index 00000000000..413c72051b8--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/js/helpers.js@@ -0,0 +1,250 @@+/*+ Returns an array (typed or not), of the passed array with removed trailing and ending+ zero-valued elements+ */+function trimEmptyElements(array) {+ var start = 0;+ var end = array.length;++ while (start < array.length) {+ if (array[start] !== 0) {+ break;+ }+ start++;+ }++ while (end > 0) {+ end--;+ if (array[end] !== 0) {+ break;+ }+ }+ return array.subarray(start, end);+}+++function fuzzyCompare(a, b) {+ return Math.abs(a - b) < 9e-3;+}++function compareChannels(buf1, buf2,+ /*optional*/ length,+ /*optional*/ sourceOffset,+ /*optional*/ destOffset,+ /*optional*/ skipLengthCheck) {+ if (!skipLengthCheck) {+ assert_equals(buf1.length, buf2.length, "Channels must have the same length");+ }+ sourceOffset = sourceOffset || 0;+ destOffset = destOffset || 0;+ if (length == undefined) {+ length = buf1.length - sourceOffset;+ }+ var difference = 0;+ var maxDifference = 0;+ var firstBadIndex = -1;+ for (var i = 0; i < length; ++i) {+ if (!fuzzyCompare(buf1[i + sourceOffset], buf2[i + destOffset])) {+ difference++;+ maxDifference = Math.max(maxDifference, Math.abs(buf1[i + sourceOffset] - buf2[i + destOffset]));+ if (firstBadIndex == -1) {+ firstBadIndex = i;+ }+ }+ };++ assert_equals(difference, 0, "maxDifference: " + maxDifference ++ ", first bad index: " + firstBadIndex + " with test-data offset " ++ sourceOffset + " and expected-data offset " + destOffset ++ "; corresponding values " + buf1[firstBadIndex + sourceOffset] + " and " ++ buf2[firstBadIndex + destOffset] + " --- differences");+}++function compareBuffers(got, expected) {+ if (got.numberOfChannels != expected.numberOfChannels) {+ assert_equals(got.numberOfChannels, expected.numberOfChannels,+ "Correct number of buffer channels");+ return;+ }+ if (got.length != expected.length) {+ assert_equals(got.length, expected.length,+ "Correct buffer length");+ return;+ }+ if (got.sampleRate != expected.sampleRate) {+ assert_equals(got.sampleRate, expected.sampleRate,+ "Correct sample rate");+ return;+ }++ for (var i = 0; i < got.numberOfChannels; ++i) {+ compareChannels(got.getChannelData(i), expected.getChannelData(i),+ got.length, 0, 0, true);+ }+}++/**+ * This function assumes that the test is a "single page test" [0], and defines a+ * single gTest variable with the following properties and methods:+ *+ * + numberOfChannels: optional property which specifies the number of channels+ * in the output. The default value is 2.+ * + createGraph: mandatory method which takes a context object and does+ * everything needed in order to set up the Web Audio graph.+ * This function returns the node to be inspected.+ * + createGraphAsync: async version of createGraph. This function takes+ * a callback which should be called with an argument+ * set to the node to be inspected when the callee is+ * ready to proceed with the test. Either this function+ * or createGraph must be provided.+ * + createExpectedBuffers: optional method which takes a context object and+ * returns either one expected buffer or an array of+ * them, designating what is expected to be observed+ * in the output. If omitted, the output is expected+ * to be silence. All buffers must have the same+ * length, which must be a bufferSize supported by+ * ScriptProcessorNode. This function is guaranteed+ * to be called before createGraph.+ * + length: property equal to the total number of frames which we are waiting+ * to see in the output, mandatory if createExpectedBuffers is not+ * provided, in which case it must be a bufferSize supported by+ * ScriptProcessorNode (256, 512, 1024, 2048, 4096, 8192, or 16384).+ * If createExpectedBuffers is provided then this must be equal to+ * the number of expected buffers * the expected buffer length.+ *+ * + skipOfflineContextTests: optional. when true, skips running tests on an offline+ * context by circumventing testOnOfflineContext.+ *+ * [0]: https://web-platform-tests.org/writing-tests/testharness-api.html#single-page-tests+ */+function runTest(name)+{+ function runTestFunction () {+ if (!gTest.numberOfChannels) {+ gTest.numberOfChannels = 2; // default+ }++ var testLength;++ function runTestOnContext(context, callback, testOutput) {+ if (!gTest.createExpectedBuffers) {+ // Assume that the output is silence+ var expectedBuffers = getEmptyBuffer(context, gTest.length);+ } else {+ var expectedBuffers = gTest.createExpectedBuffers(context);+ }+ if (!(expectedBuffers instanceof Array)) {+ expectedBuffers = [expectedBuffers];+ }+ var expectedFrames = 0;+ for (var i = 0; i < expectedBuffers.length; ++i) {+ assert_equals(expectedBuffers[i].numberOfChannels, gTest.numberOfChannels,+ "Correct number of channels for expected buffer " + i);+ expectedFrames += expectedBuffers[i].length;+ }+ if (gTest.length && gTest.createExpectedBuffers) {+ assert_equals(expectedFrames,+ gTest.length, "Correct number of expected frames");+ }++ if (gTest.createGraphAsync) {+ gTest.createGraphAsync(context, function(nodeToInspect) {+ testOutput(nodeToInspect, expectedBuffers, callback);+ });+ } else {+ testOutput(gTest.createGraph(context), expectedBuffers, callback);+ }+ }++ function testOnNormalContext(callback) {+ function testOutput(nodeToInspect, expectedBuffers, callback) {+ testLength = 0;+ var sp = context.createScriptProcessor(expectedBuffers[0].length, gTest.numberOfChannels, 1);+ nodeToInspect.connect(sp).connect(context.destination);+ sp.onaudioprocess = function(e) {+ var expectedBuffer = expectedBuffers.shift();+ testLength += expectedBuffer.length;+ compareBuffers(e.inputBuffer, expectedBuffer);+ if (expectedBuffers.length == 0) {+ sp.onaudioprocess = null;+ callback();+ }+ };+ }+ var context = new AudioContext();+ runTestOnContext(context, callback, testOutput);+ }++ function testOnOfflineContext(callback, sampleRate) {+ function testOutput(nodeToInspect, expectedBuffers, callback) {+ nodeToInspect.connect(context.destination);+ context.oncomplete = function(e) {+ var samplesSeen = 0;+ while (expectedBuffers.length) {+ var expectedBuffer = expectedBuffers.shift();+ assert_equals(e.renderedBuffer.numberOfChannels, expectedBuffer.numberOfChannels,+ "Correct number of input buffer channels");+ for (var i = 0; i < e.renderedBuffer.numberOfChannels; ++i) {+ compareChannels(e.renderedBuffer.getChannelData(i),+ expectedBuffer.getChannelData(i),+ expectedBuffer.length,+ samplesSeen,+ undefined,+ true);+ }+ samplesSeen += expectedBuffer.length;+ }+ callback();+ };+ context.startRendering();+ }++ var context = new OfflineAudioContext(gTest.numberOfChannels, testLength, sampleRate);+ runTestOnContext(context, callback, testOutput);+ }++ testOnNormalContext(function() {+ if (!gTest.skipOfflineContextTests) {+ testOnOfflineContext(function() {+ testOnOfflineContext(done, 44100);+ }, 48000);+ } else {+ done();+ }+ });+ };++ runTestFunction();+}++// Simpler than audit.js, but still logs the message. Requires+// `setup("explicit_done": true)` if testing code that runs after the "load"+// event.+function equals(a, b, msg) {+ test(function() {+ assert_equals(a, b);+ }, msg);+}+function is_true(a, msg) {+ test(function() {+ assert_true(a);+ }, msg);+}++// This allows writing AudioWorkletProcessor code in the same file as the rest+// of the test, for quick one off AudioWorkletProcessor testing.+function URLFromScriptsElements(ids)+{+ var scriptTexts = [];+ for (let id of ids) {++ const e = document.querySelector("script#"+id)+ if (!e) {+ throw id+" is not the id of a <script> tag";+ }+ scriptTexts.push(e.innerText);+ }+ const blob = new Blob(scriptTexts, {type: "application/javascript"});++ return URL.createObjectURL(blob);+}diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-throw-onmessage.https.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-throw-onmessage.https.htmlnew file mode 100644index 00000000000..250ce17825c--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-throw-onmessage.https.html@@ -0,0 +1,62 @@+<!DOCTYPE html>+<html>+ <head>+ <meta charset="utf-8" />+ <title>+ Test the behaviour of AudioWorkletProcessor when an `onmessage` handler+ throws.+ </title>+ <script src="../../../resources/testharness.js"></script>+ <script src="../../../resources/testharnessreport.js"></script>+ <script src="../../../webaudio/js/helpers.js"></script>+ </head>++ <body>+ <script id="processor" type="worklet">+ registerProcessor("test-throw", class param extends AudioWorkletProcessor {+ constructor() {+ super()+ this.i = 0;+ this.port.onmessage = function(arg) {+ throw "asdasd";+ }+ }+ process(input, output, parameters) {+ this.i++;+ this.port.postMessage(this.i);+ return true;+ }+ });+ </script>+ <script>+ var latestIndexReceived = 0;+ var node = null;+ var ac = null;+ promise_setup(function() {+ ac = new AudioContext();+ var url = URLFromScriptsElements(["processor"]);+ return ac.audioWorklet.addModule(url).then(function() {+ node = new AudioWorkletNode(ac, "test-throw");+ node.port.onmessage = function(e) {+ latestIndexReceived = parseInt(e.data);+ };+ });+ });+ promise_test(async t => {+ var currentIndex = latestIndexReceived;+ await t.step_wait(() => {+ return latestIndexReceived > currentIndex;+ }, "Process is still being called");++ node.port.postMessage("asdasd"); // This throws on the processor side.+ node.onprocessorerror = function() {+ assert_true(false, "onprocessorerror must not be called.");+ };+ currentIndex = latestIndexReceived;+ await t.step_wait(() => {+ return latestIndexReceived > currentIndex + 2;+ }, "Process is still being called");+ }, `Throwing in an onmessage handler in the AudioWorkletGlobalScope shouldn't stop AudioWorkletProcessor`);+ </script>+ </body>+</html>