MainThreadVM.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. * Copyright (c) 2021-2022, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
  5. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  6. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <LibGC/DeferGC.h>
  11. #include <LibJS/AST.h>
  12. #include <LibJS/Module.h>
  13. #include <LibJS/Runtime/Array.h>
  14. #include <LibJS/Runtime/Environment.h>
  15. #include <LibJS/Runtime/FinalizationRegistry.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/ModuleRequest.h>
  18. #include <LibJS/Runtime/NativeFunction.h>
  19. #include <LibJS/Runtime/ShadowRealm.h>
  20. #include <LibJS/Runtime/VM.h>
  21. #include <LibJS/SourceTextModule.h>
  22. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  23. #include <LibWeb/Bindings/Intrinsics.h>
  24. #include <LibWeb/Bindings/MainThreadVM.h>
  25. #include <LibWeb/Bindings/SyntheticHostDefined.h>
  26. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  27. #include <LibWeb/DOM/Document.h>
  28. #include <LibWeb/DOM/MutationType.h>
  29. #include <LibWeb/Editing/CommandNames.h>
  30. #include <LibWeb/HTML/AttributeNames.h>
  31. #include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
  32. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  33. #include <LibWeb/HTML/EventNames.h>
  34. #include <LibWeb/HTML/Location.h>
  35. #include <LibWeb/HTML/PromiseRejectionEvent.h>
  36. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  37. #include <LibWeb/HTML/Scripting/Environments.h>
  38. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  39. #include <LibWeb/HTML/Scripting/Fetching.h>
  40. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  41. #include <LibWeb/HTML/Scripting/Script.h>
  42. #include <LibWeb/HTML/Scripting/SyntheticRealmSettings.h>
  43. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  44. #include <LibWeb/HTML/ShadowRealmGlobalScope.h>
  45. #include <LibWeb/HTML/TagNames.h>
  46. #include <LibWeb/HTML/Window.h>
  47. #include <LibWeb/HTML/WindowProxy.h>
  48. #include <LibWeb/HTML/WorkletGlobalScope.h>
  49. #include <LibWeb/MathML/TagNames.h>
  50. #include <LibWeb/MediaSourceExtensions/EventNames.h>
  51. #include <LibWeb/Namespace.h>
  52. #include <LibWeb/NavigationTiming/EntryNames.h>
  53. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  54. #include <LibWeb/Platform/EventLoopPlugin.h>
  55. #include <LibWeb/SVG/AttributeNames.h>
  56. #include <LibWeb/SVG/TagNames.h>
  57. #include <LibWeb/ServiceWorker/ServiceWorkerGlobalScope.h>
  58. #include <LibWeb/UIEvents/EventNames.h>
  59. #include <LibWeb/UIEvents/InputTypes.h>
  60. #include <LibWeb/WebGL/EventNames.h>
  61. #include <LibWeb/WebIDL/AbstractOperations.h>
  62. #include <LibWeb/XHR/EventNames.h>
  63. #include <LibWeb/XLink/AttributeNames.h>
  64. namespace Web::Bindings {
  65. static RefPtr<JS::VM> s_main_thread_vm;
  66. // https://html.spec.whatwg.org/multipage/webappapis.html#active-script
  67. HTML::Script* active_script()
  68. {
  69. // 1. Let record be GetActiveScriptOrModule().
  70. auto record = main_thread_vm().get_active_script_or_module();
  71. // 2. If record is null, return null.
  72. // 3. Return record.[[HostDefined]].
  73. return record.visit(
  74. [](GC::Ref<JS::Script>& js_script) -> HTML::Script* {
  75. return verify_cast<HTML::ClassicScript>(js_script->host_defined());
  76. },
  77. [](GC::Ref<JS::Module>& js_module) -> HTML::Script* {
  78. return verify_cast<HTML::ModuleScript>(js_module->host_defined());
  79. },
  80. [](Empty) -> HTML::Script* {
  81. return nullptr;
  82. });
  83. }
  84. ErrorOr<void> initialize_main_thread_vm(HTML::EventLoop::Type type)
  85. {
  86. VERIFY(!s_main_thread_vm);
  87. s_main_thread_vm = TRY(JS::VM::create(make<WebEngineCustomData>()));
  88. s_main_thread_vm->on_unimplemented_property_access = [](auto const& object, auto const& property_key) {
  89. dbgln("FIXME: Unimplemented IDL interface: '{}.{}'", object.class_name(), property_key.to_string());
  90. };
  91. // NOTE: We intentionally leak the main thread JavaScript VM.
  92. // This avoids doing an exhaustive garbage collection on process exit.
  93. s_main_thread_vm->ref();
  94. auto& custom_data = verify_cast<WebEngineCustomData>(*s_main_thread_vm->custom_data());
  95. custom_data.event_loop = s_main_thread_vm->heap().allocate<HTML::EventLoop>(type);
  96. // These strings could potentially live on the VM similar to CommonPropertyNames.
  97. DOM::MutationType::initialize_strings();
  98. Editing::CommandNames::initialize_strings();
  99. HTML::AttributeNames::initialize_strings();
  100. HTML::CustomElementReactionNames::initialize_strings();
  101. HTML::EventNames::initialize_strings();
  102. HTML::TagNames::initialize_strings();
  103. MathML::TagNames::initialize_strings();
  104. MediaSourceExtensions::EventNames::initialize_strings();
  105. Namespace::initialize_strings();
  106. NavigationTiming::EntryNames::initialize_strings();
  107. PerformanceTimeline::EntryTypes::initialize_strings();
  108. SVG::AttributeNames::initialize_strings();
  109. SVG::TagNames::initialize_strings();
  110. UIEvents::EventNames::initialize_strings();
  111. UIEvents::InputTypes::initialize_strings();
  112. WebGL::EventNames::initialize_strings();
  113. XHR::EventNames::initialize_strings();
  114. XLink::AttributeNames::initialize_strings();
  115. // 8.1.5.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation
  116. s_main_thread_vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {
  117. // 1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }.
  118. if (is<HTML::WindowProxy>(object) || is<HTML::Location>(object))
  119. return s_main_thread_vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object"sv);
  120. // 2. Return NormalCompletion(unused).
  121. return {};
  122. };
  123. // FIXME: Implement 8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(callerrealm,-calleerealm)
  124. // 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
  125. // https://whatpr.org/html/9893/webappapis.html#the-hostpromiserejectiontracker-implementation
  126. s_main_thread_vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
  127. auto& vm = *s_main_thread_vm;
  128. // 1. Let script be the running script.
  129. // The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
  130. HTML::Script* script { nullptr };
  131. vm.running_execution_context().script_or_module.visit(
  132. [&script](GC::Ref<JS::Script>& js_script) {
  133. script = verify_cast<HTML::ClassicScript>(js_script->host_defined());
  134. },
  135. [&script](GC::Ref<JS::Module>& js_module) {
  136. script = verify_cast<HTML::ModuleScript>(js_module->host_defined());
  137. },
  138. [](Empty) {
  139. });
  140. // 2. If script is a classic script and script's muted errors is true, then return.
  141. // NOTE: is<T>() returns false if nullptr is passed.
  142. if (is<HTML::ClassicScript>(script)) {
  143. auto const& classic_script = static_cast<HTML::ClassicScript const&>(*script);
  144. if (classic_script.muted_errors() == HTML::ClassicScript::MutedErrors::Yes)
  145. return;
  146. }
  147. // 3. Let realm be the current realm.
  148. // 4. If script is not null, then set settings object to script's realm.
  149. auto& realm = script ? script->realm() : *vm.current_realm();
  150. // 5. Let global be realm's global object.
  151. auto* global_mixin = dynamic_cast<HTML::UniversalGlobalScopeMixin*>(&realm.global_object());
  152. VERIFY(global_mixin);
  153. auto& global = global_mixin->this_impl();
  154. switch (operation) {
  155. // 6. If operation is "reject",
  156. case JS::Promise::RejectionOperation::Reject:
  157. // 1. Append promise to global's about-to-be-notified rejected promises list.
  158. global_mixin->push_onto_about_to_be_notified_rejected_promises_list(promise);
  159. break;
  160. // 7. If operation is "handle",
  161. case JS::Promise::RejectionOperation::Handle: {
  162. // 1. If global's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.
  163. bool removed_about_to_be_notified_rejected_promise = global_mixin->remove_from_about_to_be_notified_rejected_promises_list(promise);
  164. if (removed_about_to_be_notified_rejected_promise)
  165. return;
  166. // 3. Remove promise from global's outstanding rejected promises weak set.
  167. bool removed_outstanding_rejected_promise = global_mixin->remove_from_outstanding_rejected_promises_weak_set(&promise);
  168. // 2. If global's outstanding rejected promises weak set does not contain promise, then return.
  169. // NOTE: This is done out of order because removed_outstanding_rejected_promise will be false if the promise wasn't in the set or true if it was and got removed.
  170. if (!removed_outstanding_rejected_promise)
  171. return;
  172. // 4. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent,
  173. // with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.
  174. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, GC::create_function(s_main_thread_vm->heap(), [&global, &promise] {
  175. // FIXME: This currently assumes that global is a WindowObject.
  176. auto& window = verify_cast<HTML::Window>(global);
  177. HTML::PromiseRejectionEventInit event_init {
  178. {}, // Initialize the inherited DOM::EventInit
  179. /* .promise = */ promise,
  180. /* .reason = */ promise.result(),
  181. };
  182. auto promise_rejection_event = HTML::PromiseRejectionEvent::create(HTML::relevant_realm(global), HTML::EventNames::rejectionhandled, event_init);
  183. window.dispatch_event(promise_rejection_event);
  184. }));
  185. break;
  186. }
  187. default:
  188. VERIFY_NOT_REACHED();
  189. }
  190. };
  191. // 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
  192. // https://whatpr.org/html/9893/webappapis.html#hostcalljobcallback
  193. s_main_thread_vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, ReadonlySpan<JS::Value> arguments_list) {
  194. auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data());
  195. // 1. Let incumbent realm be callback.[[HostDefined]].[[IncumbentRealm]].
  196. auto& incumbent_realm = callback_host_defined.incumbent_realm;
  197. // 2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]].
  198. auto* script_execution_context = callback_host_defined.active_script_context.ptr();
  199. // 3. Prepare to run a callback with incumbent realm.
  200. HTML::prepare_to_run_callback(incumbent_realm);
  201. // 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
  202. if (script_execution_context)
  203. s_main_thread_vm->push_execution_context(*script_execution_context);
  204. // 5. Let result be Call(callback.[[Callback]], V, argumentsList).
  205. auto result = JS::call(*s_main_thread_vm, callback.callback(), this_value, arguments_list);
  206. // 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
  207. if (script_execution_context) {
  208. VERIFY(&s_main_thread_vm->running_execution_context() == script_execution_context);
  209. s_main_thread_vm->pop_execution_context();
  210. }
  211. // 7. Clean up after running a callback with incumbent realm.
  212. HTML::clean_up_after_running_callback(incumbent_realm);
  213. // 8. Return result.
  214. return result;
  215. };
  216. // 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
  217. s_main_thread_vm->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) {
  218. // 1. Let global be finalizationRegistry.[[Realm]]'s global object.
  219. auto& global = finalization_registry.realm().global_object();
  220. // 2. Queue a global task on the JavaScript engine task source given global to perform the following steps:
  221. HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, GC::create_function(s_main_thread_vm->heap(), [&finalization_registry] {
  222. // 1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]].
  223. auto& entry = *finalization_registry.cleanup_callback().callback().realm();
  224. // 2. Check if we can run script with entry. If this returns "do not run", then return.
  225. if (HTML::can_run_script(entry) == HTML::RunScriptDecision::DoNotRun)
  226. return;
  227. // 3. Prepare to run script with entry.
  228. HTML::prepare_to_run_script(entry);
  229. // 4. Let result be the result of performing CleanupFinalizationRegistry(finalizationRegistry).
  230. auto result = finalization_registry.cleanup();
  231. // 5. Clean up after running script with entry.
  232. HTML::clean_up_after_running_script(entry);
  233. // 6. If result is an abrupt completion, then report the exception given by result.[[Value]].
  234. if (result.is_error())
  235. HTML::report_exception(result, entry);
  236. }));
  237. };
  238. // 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
  239. // // https://whatpr.org/html/9893/webappapis.html#hostenqueuepromisejob
  240. s_main_thread_vm->host_enqueue_promise_job = [](GC::Ref<GC::Function<JS::ThrowCompletionOr<JS::Value>()>> job, JS::Realm* realm) {
  241. auto& vm = *s_main_thread_vm;
  242. // IMPLEMENTATION DEFINED: The JS spec says we must take implementation defined steps to make the currently active script or module at the time of HostEnqueuePromiseJob being invoked
  243. // also be the active script or module of the job at the time of its invocation.
  244. // This means taking it here now and passing it through to the lambda.
  245. auto script_or_module = vm.get_active_script_or_module();
  246. // 1. Queue a microtask to perform the following steps:
  247. // This instance of "queue a microtask" uses the "implied document". The best fit for "implied document" here is "If the task is being queued by or for a script, then return the script's settings object's responsible document."
  248. // Do note that "implied document" from the spec is handwavy and the spec authors are trying to get rid of it: https://github.com/whatwg/html/issues/4980
  249. auto* script = active_script();
  250. auto& heap = realm ? realm->heap() : vm.heap();
  251. HTML::queue_a_microtask(script ? script->settings_object().responsible_document().ptr() : nullptr, GC::create_function(heap, [&vm, realm, job = move(job), script_or_module = move(script_or_module)] {
  252. // The dummy execution context has to be kept up here to keep it alive for the duration of the function.
  253. OwnPtr<JS::ExecutionContext> dummy_execution_context;
  254. if (realm) {
  255. // 1. If realm is not null, then check if we can run script with realm. If this returns "do not run" then return.
  256. if (HTML::can_run_script(*realm) == HTML::RunScriptDecision::DoNotRun)
  257. return;
  258. // 2. If realm is not null, then prepare to run script with realm.
  259. HTML::prepare_to_run_script(*realm);
  260. // IMPLEMENTATION DEFINED: Additionally to preparing to run a script, we also prepare to run a callback here. This matches WebIDL's
  261. // invoke_callback() / call_user_object_operation() functions, and prevents a crash in host_make_job_callback()
  262. // when getting the incumbent settings object.
  263. HTML::prepare_to_run_callback(*realm);
  264. // IMPLEMENTATION DEFINED: Per the previous "implementation defined" comment, we must now make the script or module the active script or module.
  265. // Since the only active execution context currently is the realm execution context of job settings, lets attach it here.
  266. HTML::execution_context_of_realm(*realm).script_or_module = script_or_module;
  267. } else {
  268. // FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
  269. // This is because JS::NativeFunction::call excepts something to be on the execution context stack to be able to get the caller context to initialize the environment.
  270. // Do note that the JS spec gives _no_ guarantee that the execution context stack has something on it if HostEnqueuePromiseJob was called with a null realm: https://tc39.es/ecma262/#job-preparedtoevaluatecode
  271. dummy_execution_context = JS::ExecutionContext::create();
  272. dummy_execution_context->script_or_module = script_or_module;
  273. vm.push_execution_context(*dummy_execution_context);
  274. }
  275. // 3. Let result be job().
  276. auto result = job->function()();
  277. // 4. If realm is not null, then clean up after running script with job settings.
  278. if (realm) {
  279. // IMPLEMENTATION DEFINED: Disassociate the realm execution context from the script or module.
  280. HTML::execution_context_of_realm(*realm).script_or_module = Empty {};
  281. // IMPLEMENTATION DEFINED: See comment above, we need to clean up the non-standard prepare_to_run_callback() call.
  282. HTML::clean_up_after_running_callback(*realm);
  283. HTML::clean_up_after_running_script(*realm);
  284. } else {
  285. // Pop off the dummy execution context. See the above FIXME block about why this is done.
  286. vm.pop_execution_context();
  287. }
  288. // 5. If result is an abrupt completion, then report the exception given by result.[[Value]].
  289. if (result.is_error())
  290. HTML::report_exception(result, *realm);
  291. }));
  292. };
  293. // 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
  294. // https://whatpr.org/html/9893/webappapis.html#hostmakejobcallback
  295. s_main_thread_vm->host_make_job_callback = [](JS::FunctionObject& callable) -> GC::Ref<JS::JobCallback> {
  296. // 1. Let incumbent realm be the incumbent realm.
  297. auto& incumbent_realm = HTML::incumbent_realm();
  298. // 2. Let active script be the active script.
  299. auto* script = active_script();
  300. // 3. Let script execution context be null.
  301. OwnPtr<JS::ExecutionContext> script_execution_context;
  302. // 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
  303. // its Realm field set to active script's realm, and its ScriptOrModule set to active script's record.
  304. if (script) {
  305. script_execution_context = JS::ExecutionContext::create();
  306. script_execution_context->function = nullptr;
  307. script_execution_context->realm = &script->realm();
  308. if (is<HTML::ClassicScript>(script)) {
  309. script_execution_context->script_or_module = GC::Ref<JS::Script>(*verify_cast<HTML::ClassicScript>(script)->script_record());
  310. } else if (is<HTML::ModuleScript>(script)) {
  311. if (is<HTML::JavaScriptModuleScript>(script)) {
  312. script_execution_context->script_or_module = GC::Ref<JS::Module>(*verify_cast<HTML::JavaScriptModuleScript>(script)->record());
  313. } else {
  314. // NOTE: Handle CSS and JSON module scripts once we have those.
  315. VERIFY_NOT_REACHED();
  316. }
  317. } else {
  318. VERIFY_NOT_REACHED();
  319. }
  320. }
  321. // 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentRealm]]: incumbent realm, [[ActiveScriptContext]]: script execution context } }.
  322. auto host_defined = adopt_own(*new WebEngineCustomJobCallbackData(incumbent_realm, move(script_execution_context)));
  323. return JS::JobCallback::create(*s_main_thread_vm, callable, move(host_defined));
  324. };
  325. // 8.1.6.7.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
  326. s_main_thread_vm->host_get_import_meta_properties = [](JS::SourceTextModule& module_record) {
  327. auto& realm = module_record.realm();
  328. auto& vm = realm.vm();
  329. // 1. Let moduleScript be moduleRecord.[[HostDefined]].
  330. auto& module_script = *verify_cast<HTML::Script>(module_record.host_defined());
  331. // 2. Assert: moduleScript's base URL is not null, as moduleScript is a JavaScript module script.
  332. VERIFY(module_script.base_url().is_valid());
  333. // 3. Let urlString be moduleScript's base URL, serialized.
  334. auto url_string = module_script.base_url().serialize();
  335. // 4. Let steps be the following steps, given the argument specifier:
  336. auto steps = [module_script = GC::Ref { module_script }](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  337. auto specifier = vm.argument(0);
  338. // 1. Set specifier to ? ToString(specifier).
  339. auto specifier_string = TRY(specifier.to_string(vm));
  340. // 2. Let url be the result of resolving a module specifier given moduleScript and specifier.
  341. auto url = TRY(Bindings::throw_dom_exception_if_needed(vm, [&] {
  342. return HTML::resolve_module_specifier(*module_script, specifier_string.to_byte_string());
  343. }));
  344. // 3. Return the serialization of url.
  345. return JS::PrimitiveString::create(vm, url.serialize());
  346. };
  347. // 4. Let resolveFunction be ! CreateBuiltinFunction(steps, 1, "resolve", « »).
  348. auto resolve_function = JS::NativeFunction::create(realm, move(steps), 1, vm.names.resolve);
  349. // 5. Return « Record { [[Key]]: "url", [[Value]]: urlString }, Record { [[Key]]: "resolve", [[Value]]: resolveFunction } ».
  350. HashMap<JS::PropertyKey, JS::Value> meta;
  351. meta.set("url", JS::PrimitiveString::create(vm, move(url_string)));
  352. meta.set("resolve", resolve_function);
  353. return meta;
  354. };
  355. // 8.1.6.7.2 HostGetSupportedImportAttributes(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
  356. s_main_thread_vm->host_get_supported_import_attributes = []() -> Vector<ByteString> {
  357. // 1. Return « "type" ».
  358. return { "type"sv };
  359. };
  360. // 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload), https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule
  361. // https://whatpr.org/html/9893/webappapis.html#hostloadimportedmodule
  362. s_main_thread_vm->host_load_imported_module = [](JS::ImportedModuleReferrer referrer, JS::ModuleRequest const& module_request, GC::Ptr<JS::GraphLoadingState::HostDefined> load_state, JS::ImportedModulePayload payload) -> void {
  363. auto& vm = *s_main_thread_vm;
  364. // 1. Let moduleMapRealm be the current realm.
  365. auto* module_map_realm = vm.current_realm();
  366. // 2. If moduleMapRealm's global object implements WorkletGlobalScope or ServiceWorkerGlobalScope and loadState is undefined, then:
  367. if ((is<HTML::WorkletGlobalScope>(module_map_realm->global_object()) || is<ServiceWorker::ServiceWorkerGlobalScope>(module_map_realm->global_object())) && !load_state) {
  368. // 1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.
  369. auto completion = JS::throw_completion(JS::TypeError::create(*module_map_realm, "Dynamic Import not available for Worklets or ServiceWorkers"_string));
  370. // 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  371. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  372. // 3. Return.
  373. return;
  374. }
  375. // 3. Let referencingScript be null.
  376. Optional<HTML::Script&> referencing_script;
  377. // 4. Let originalFetchOptions be the default script fetch options.
  378. auto original_fetch_options = HTML::default_script_fetch_options();
  379. // 5. Let fetchReferrer be "client".
  380. Fetch::Infrastructure::Request::ReferrerType fetch_referrer = Fetch::Infrastructure::Request::Referrer::Client;
  381. // 6. If referrer is a Script Record or a Cyclic Module Record, then:
  382. if (referrer.has<GC::Ref<JS::Script>>() || referrer.has<GC::Ref<JS::CyclicModule>>()) {
  383. // 1. Set referencingScript to referrer.[[HostDefined]].
  384. referencing_script = verify_cast<HTML::Script>(referrer.has<GC::Ref<JS::Script>>() ? *referrer.get<GC::Ref<JS::Script>>()->host_defined() : *referrer.get<GC::Ref<JS::CyclicModule>>()->host_defined());
  385. // 2. Set fetchReferrer to referencingScript's base URL.
  386. fetch_referrer = referencing_script->base_url();
  387. // FIXME: 3. Set originalFetchOptions to referencingScript's fetch options.
  388. // 4. Set moduleMapRealm to referencingScript's realm.
  389. module_map_realm = &referencing_script->realm();
  390. }
  391. // 7. If referrer is a Cyclic Module Record and moduleRequest is equal to the first element of referrer.[[RequestedModules]], then:
  392. if (referrer.has<GC::Ref<JS::CyclicModule>>()) {
  393. // FIXME: Why do we need to check requested modules is empty here?
  394. if (auto const& requested_modules = referrer.get<GC::Ref<JS::CyclicModule>>()->requested_modules(); !requested_modules.is_empty() && module_request == requested_modules.first()) {
  395. // 1. For each ModuleRequest record requested of referrer.[[RequestedModules]]:
  396. for (auto const& module_request : referrer.get<GC::Ref<JS::CyclicModule>>()->requested_modules()) {
  397. // 1. If moduleRequest.[[Attributes]] contains a Record entry such that entry.[[Key]] is not "type", then:
  398. for (auto const& attribute : module_request.attributes) {
  399. if (attribute.key == "type"sv)
  400. continue;
  401. // 1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: a new SyntaxError exception, [[Target]]: empty }.
  402. auto completion = JS::throw_completion(JS::SyntaxError::create(*module_map_realm, "Module request attributes must only contain a type attribute"_string));
  403. // 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  404. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  405. // 3. Return.
  406. return;
  407. }
  408. }
  409. // 2. Resolve a module specifier given referencingScript and moduleRequest.[[Specifier]], catching any
  410. // exceptions. If they throw an exception, let resolutionError be the thrown exception.
  411. auto maybe_exception = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier);
  412. // 3. If the previous step threw an exception, then:
  413. if (maybe_exception.is_exception()) {
  414. // 1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: resolutionError, [[Target]]: empty }.
  415. auto completion = dom_exception_to_throw_completion(main_thread_vm(), maybe_exception.exception());
  416. // 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  417. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  418. // 3. Return.
  419. return;
  420. }
  421. // 4. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  422. auto module_type = HTML::module_type_from_module_request(module_request);
  423. // 5. If the result of running the module type allowed steps given moduleType and moduleMapRealm is false, then:
  424. if (!HTML::module_type_allowed(*module_map_realm, module_type)) {
  425. // 1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: a new TypeError exception, [[Target]]: empty }.
  426. auto completion = JS::throw_completion(JS::SyntaxError::create(*module_map_realm, MUST(String::formatted("Module type '{}' is not supported", module_type))));
  427. // 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  428. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  429. // 3. Return
  430. return;
  431. }
  432. // Spec-Note: This step is essentially validating all of the requested module specifiers and type attributes
  433. // when the first call to HostLoadImportedModule for a static module dependency list is made, to
  434. // avoid further loading operations in the case any one of the dependencies has a static error.
  435. // We treat a module with unresolvable module specifiers or unsupported type attributes the same
  436. // as one that cannot be parsed; in both cases, a syntactic issue makes it impossible to ever
  437. // contemplate linking the module later.
  438. }
  439. }
  440. // 8. Disallow further import maps given moduleMapRealm.
  441. HTML::disallow_further_import_maps(*module_map_realm);
  442. // 9. Let url be the result of resolving a module specifier given referencingScript and moduleRequest.[[Specifier]],
  443. // catching any exceptions. If they throw an exception, let resolutionError be the thrown exception.
  444. auto url = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier);
  445. // 10. If the previous step threw an exception, then:
  446. if (url.is_exception()) {
  447. // 1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: resolutionError, [[Target]]: empty }.
  448. auto completion = dom_exception_to_throw_completion(main_thread_vm(), url.exception());
  449. // 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  450. HTML::TemporaryExecutionContext context { *module_map_realm };
  451. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  452. // 3. Return.
  453. return;
  454. }
  455. // 11. Let settingsObject be moduleMapRealm's principal realm's settings object.
  456. auto& settings_object = HTML::principal_realm_settings_object(HTML::principal_realm(*module_map_realm));
  457. // 12. Let fetchOptions be the result of getting the descendant script fetch options given originalFetchOptions, url, and settingsObject.
  458. auto fetch_options = HTML::get_descendant_script_fetch_options(original_fetch_options, url.value(), settings_object);
  459. // 13. Let destination be "script".
  460. auto destination = Fetch::Infrastructure::Request::Destination::Script;
  461. // 14. Let fetchClient be moduleMapRealm's principal realm's settings object.
  462. GC::Ref fetch_client { HTML::principal_realm_settings_object(HTML::principal_realm(*module_map_realm)) };
  463. // 14. If loadState is not undefined, then:
  464. HTML::PerformTheFetchHook perform_fetch;
  465. if (load_state) {
  466. auto& fetch_context = static_cast<HTML::FetchContext&>(*load_state);
  467. // 1. Set destination to loadState.[[Destination]].
  468. destination = fetch_context.destination;
  469. // 2. Set fetchClient to loadState.[[FetchClient]].
  470. fetch_client = fetch_context.fetch_client;
  471. // For step 13
  472. perform_fetch = fetch_context.perform_fetch;
  473. }
  474. auto on_single_fetch_complete = HTML::create_on_fetch_script_complete(module_map_realm->heap(), [referrer, module_map_realm, load_state, module_request, payload](GC::Ptr<HTML::Script> const& module_script) -> void {
  475. auto& realm = *module_map_realm;
  476. // onSingleFetchComplete given moduleScript is the following algorithm:
  477. // 1. Let completion be null.
  478. // NOTE: Our JS::Completion does not support non JS::Value types for its [[Value]], a such we
  479. // use JS::ThrowCompletionOr here.
  480. auto& vm = realm.vm();
  481. GC::Ptr<JS::Module> module = nullptr;
  482. auto completion = [&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Module>> {
  483. // 2. If moduleScript is null, then set completion to Completion Record { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.
  484. if (!module_script) {
  485. return JS::throw_completion(JS::TypeError::create(realm, ByteString::formatted("Loading imported module '{}' failed.", module_request.module_specifier)));
  486. }
  487. // 3. Otherwise, if moduleScript's parse error is not null, then:
  488. else if (!module_script->parse_error().is_null()) {
  489. // 1. Let parseError be moduleScript's parse error.
  490. auto parse_error = module_script->parse_error();
  491. // 2. Set completion to Completion Record { [[Type]]: throw, [[Value]]: parseError, [[Target]]: empty }.
  492. auto completion = JS::throw_completion(parse_error);
  493. // 3. If loadState is not undefined and loadState.[[ParseError]] is null, set loadState.[[ParseError]] to parseError.
  494. if (load_state) {
  495. auto& load_state_as_fetch_context = static_cast<HTML::FetchContext&>(*load_state);
  496. if (load_state_as_fetch_context.parse_error.is_null()) {
  497. load_state_as_fetch_context.parse_error = parse_error;
  498. }
  499. }
  500. return completion;
  501. }
  502. // 4. Otherwise, set completion to Completion Record { [[Type]]: normal, [[Value]]: moduleScript's record, [[Target]]: empty }.
  503. else {
  504. module = static_cast<HTML::JavaScriptModuleScript&>(*module_script).record();
  505. return JS::ThrowCompletionOr<GC::Ref<JS::Module>>(*module);
  506. }
  507. }();
  508. // 5. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  509. // NON-STANDARD: To ensure that LibJS can find the module on the stack, we push a new execution context.
  510. auto module_execution_context = JS::ExecutionContext::create();
  511. module_execution_context->realm = realm;
  512. if (module)
  513. module_execution_context->script_or_module = GC::Ref { *module };
  514. vm.push_execution_context(*module_execution_context);
  515. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  516. vm.pop_execution_context();
  517. });
  518. // 15. Fetch a single imported module script given url, fetchClient, destination, fetchOptions, moduleMapRealm, fetchReferrer,
  519. // moduleRequest, and onSingleFetchComplete as defined below.
  520. // If loadState is not undefined and loadState.[[PerformFetch]] is not null, pass loadState.[[PerformFetch]] along as well.
  521. HTML::fetch_single_imported_module_script(*module_map_realm, url.release_value(), *fetch_client, destination, fetch_options, *module_map_realm, fetch_referrer, module_request, perform_fetch, on_single_fetch_complete);
  522. };
  523. // https://whatpr.org/html/9893/webappapis.html#hostinitializeshadowrealm(realm,-context,-o)
  524. // 8.1.6.8 HostInitializeShadowRealm(realm, context, O)
  525. s_main_thread_vm->host_initialize_shadow_realm = [](JS::Realm& realm, NonnullOwnPtr<JS::ExecutionContext> context, JS::ShadowRealm& object) -> JS::ThrowCompletionOr<void> {
  526. // FIXME: 1. Set realm's is global prototype chain mutable to true.
  527. // 2. Let globalObject be a new ShadowRealmGlobalScope object with realm.
  528. auto global_object = HTML::ShadowRealmGlobalScope::create(realm);
  529. // 3. Let settings be a new synthetic realm settings object that this algorithm will subsequently initialize.
  530. auto settings = HTML::SyntheticRealmSettings {
  531. // 4. Set settings's execution context to context.
  532. .execution_context = move(context),
  533. // 5. Set settings's principal realm to O's associated realm's principal realm
  534. .principal_realm = HTML::principal_realm(object.shape().realm()),
  535. // 6. Set settings's module map to a new module map, initially empty.
  536. .module_map = realm.create<HTML::ModuleMap>(),
  537. };
  538. // 7. Set realm.[[HostDefined]] to settings.
  539. realm.set_host_defined(make<Bindings::SyntheticHostDefined>(move(settings), realm.create<Bindings::Intrinsics>(realm)));
  540. // 8. Set realm.[[GlobalObject]] to globalObject.
  541. realm.set_global_object(global_object);
  542. // 9. Set realm.[[GlobalEnv]] to NewGlobalEnvironment(globalObject, globalObject).
  543. realm.set_global_environment(realm.heap().allocate<JS::GlobalEnvironment>(global_object, global_object));
  544. // 10. Perform ? SetDefaultGlobalBindings(realm).
  545. set_default_global_bindings(realm);
  546. // NOTE: This needs to be done after initialization so that the realm has an intrinsics in its [[HostDefined]]
  547. global_object->initialize_web_interfaces();
  548. // 11. Return NormalCompletion(unused).
  549. return {};
  550. };
  551. s_main_thread_vm->host_unrecognized_date_string = [](StringView date) {
  552. dbgln("Unable to parse date string: \"{}\"", date);
  553. };
  554. return {};
  555. }
  556. JS::VM& main_thread_vm()
  557. {
  558. VERIFY(s_main_thread_vm);
  559. return *s_main_thread_vm;
  560. }
  561. // https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask
  562. void queue_mutation_observer_microtask(DOM::Document const& document)
  563. {
  564. auto& vm = main_thread_vm();
  565. auto& custom_data = verify_cast<WebEngineCustomData>(*vm.custom_data());
  566. // 1. If the surrounding agent’s mutation observer microtask queued is true, then return.
  567. if (custom_data.mutation_observer_microtask_queued)
  568. return;
  569. // 2. Set the surrounding agent’s mutation observer microtask queued to true.
  570. custom_data.mutation_observer_microtask_queued = true;
  571. // 3. Queue a microtask to notify mutation observers.
  572. // NOTE: This uses the implied document concept. In the case of mutation observers, it is always done in a node context, so document should be that node's document.
  573. // FIXME: Is it safe to pass custom_data through?
  574. HTML::queue_a_microtask(&document, GC::create_function(vm.heap(), [&custom_data, &heap = document.heap()]() {
  575. // 1. Set the surrounding agent’s mutation observer microtask queued to false.
  576. custom_data.mutation_observer_microtask_queued = false;
  577. // 2. Let notifySet be a clone of the surrounding agent’s mutation observers.
  578. GC::MarkedVector<DOM::MutationObserver*> notify_set(heap);
  579. for (auto& observer : custom_data.mutation_observers)
  580. notify_set.append(observer);
  581. // FIXME: 3. Let signalSet be a clone of the surrounding agent’s signal slots.
  582. // FIXME: 4. Empty the surrounding agent’s signal slots.
  583. // 5. For each mo of notifySet:
  584. for (auto& mutation_observer : notify_set) {
  585. // 1. Let records be a clone of mo’s record queue.
  586. // 2. Empty mo’s record queue.
  587. auto records = mutation_observer->take_records();
  588. // 3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from node’s registered observer list.
  589. for (auto& node : mutation_observer->node_list()) {
  590. // FIXME: Is this correct?
  591. if (node.is_null())
  592. continue;
  593. if (node->registered_observer_list()) {
  594. node->registered_observer_list()->remove_all_matching([&mutation_observer](DOM::RegisteredObserver& registered_observer) {
  595. return is<DOM::TransientRegisteredObserver>(registered_observer) && static_cast<DOM::TransientRegisteredObserver&>(registered_observer).observer().ptr() == mutation_observer;
  596. });
  597. }
  598. }
  599. // 4. If records is not empty, then invoke mo’s callback with « records, mo », and mo. If this throws an exception, catch it, and report the exception.
  600. if (!records.is_empty()) {
  601. auto& callback = mutation_observer->callback();
  602. auto& realm = callback.callback_context;
  603. auto wrapped_records = MUST(JS::Array::create(realm, 0));
  604. for (size_t i = 0; i < records.size(); ++i) {
  605. auto& record = records.at(i);
  606. auto property_index = JS::PropertyKey { i };
  607. MUST(wrapped_records->create_data_property(property_index, record.ptr()));
  608. }
  609. auto result = WebIDL::invoke_callback(callback, mutation_observer, wrapped_records, mutation_observer);
  610. if (result.is_abrupt())
  611. HTML::report_exception(result, realm);
  612. }
  613. }
  614. // FIXME: 6. For each slot of signalSet, fire an event named slotchange, with its bubbles attribute set to true, at slot.
  615. }));
  616. }
  617. // https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm
  618. NonnullOwnPtr<JS::ExecutionContext> create_a_new_javascript_realm(JS::VM& vm, Function<JS::Object*(JS::Realm&)> create_global_object, Function<JS::Object*(JS::Realm&)> create_global_this_value)
  619. {
  620. // 1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.
  621. // 2. Let realm execution context be the running JavaScript execution context.
  622. auto realm_execution_context = MUST(JS::Realm::initialize_host_defined_realm(vm, move(create_global_object), move(create_global_this_value)));
  623. // 3. Remove realm execution context from the JavaScript execution context stack.
  624. vm.execution_context_stack().remove_first_matching([&realm_execution_context](auto execution_context) {
  625. return execution_context == realm_execution_context.ptr();
  626. });
  627. // NO-OP: 4. Let realm be realm execution context's Realm component.
  628. // NO-OP: 5. Set realm's agent to agent.
  629. // FIXME: 6. If agent's agent cluster's cross-origin isolation mode is "none", then:
  630. // 1. Let global be realm's global object.
  631. // 2. Let status be ! global.[[Delete]]("SharedArrayBuffer").
  632. // 3. Assert: status is true.
  633. // 7. Return realm execution context.
  634. return realm_execution_context;
  635. }
  636. void WebEngineCustomData::spin_event_loop_until(GC::Root<GC::Function<bool()>> goal_condition)
  637. {
  638. Platform::EventLoopPlugin::the().spin_until(move(goal_condition));
  639. }
  640. // https://html.spec.whatwg.org/multipage/custom-elements.html#invoke-custom-element-reactions
  641. void invoke_custom_element_reactions(Vector<GC::Root<DOM::Element>>& element_queue)
  642. {
  643. // 1. While queue is not empty:
  644. while (!element_queue.is_empty()) {
  645. // 1. Let element be the result of dequeuing from queue.
  646. auto element = element_queue.take_first();
  647. // 2. Let reactions be element's custom element reaction queue.
  648. auto* reactions = element->custom_element_reaction_queue();
  649. // 3. Repeat until reactions is empty:
  650. if (!reactions)
  651. continue;
  652. while (!reactions->is_empty()) {
  653. // 1. Remove the first element of reactions, and let reaction be that element. Switch on reaction's type:
  654. auto reaction = reactions->take_first();
  655. reaction.visit(
  656. [&](DOM::CustomElementUpgradeReaction const& custom_element_upgrade_reaction) -> void {
  657. // -> upgrade reaction
  658. // Upgrade element using reaction's custom element definition.
  659. auto maybe_exception = element->upgrade_element(*custom_element_upgrade_reaction.custom_element_definition);
  660. // If this throws an exception, catch it, and report it for reaction's custom element definition's constructor's corresponding JavaScript object's associated realm's global object.
  661. if (maybe_exception.is_error()) {
  662. // FIXME: Should it be easier to get to report an exception from an IDL callback?
  663. auto& callback = custom_element_upgrade_reaction.custom_element_definition->constructor();
  664. auto& realm = callback.callback->shape().realm();
  665. auto& global = realm.global_object();
  666. auto* window_or_worker = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&global);
  667. VERIFY(window_or_worker);
  668. window_or_worker->report_an_exception(maybe_exception.error_value());
  669. }
  670. },
  671. [&](DOM::CustomElementCallbackReaction& custom_element_callback_reaction) -> void {
  672. // -> callback reaction
  673. // Invoke reaction's callback function with reaction's arguments, and with element as the callback this value.
  674. auto result = WebIDL::invoke_callback(*custom_element_callback_reaction.callback, element.ptr(), custom_element_callback_reaction.arguments);
  675. // FIXME: The error from CustomElementCallbackReaction is supposed
  676. // to use the new steps for IDL callback error reporting
  677. if (result.is_abrupt())
  678. HTML::report_exception(result, element->realm());
  679. });
  680. }
  681. }
  682. }
  683. }