Fetching.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. /*
  2. * Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
  3. * Copyright (c) 2024, Tim Ledbetter <timledbetter@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCore/EventLoop.h>
  8. #include <LibJS/Heap/HeapFunction.h>
  9. #include <LibJS/Runtime/ModuleRequest.h>
  10. #include <LibTextCodec/Decoder.h>
  11. #include <LibWeb/DOM/Document.h>
  12. #include <LibWeb/DOMURL/DOMURL.h>
  13. #include <LibWeb/Fetch/Fetching/Fetching.h>
  14. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  15. #include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
  16. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  17. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  18. #include <LibWeb/Fetch/Infrastructure/URL.h>
  19. #include <LibWeb/HTML/HTMLScriptElement.h>
  20. #include <LibWeb/HTML/PotentialCORSRequest.h>
  21. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  22. #include <LibWeb/HTML/Scripting/Environments.h>
  23. #include <LibWeb/HTML/Scripting/Fetching.h>
  24. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  25. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  26. #include <LibWeb/HTML/Window.h>
  27. #include <LibWeb/Infra/Strings.h>
  28. #include <LibWeb/MimeSniff/MimeType.h>
  29. namespace Web::HTML {
  30. JS_DEFINE_ALLOCATOR(FetchContext);
  31. OnFetchScriptComplete create_on_fetch_script_complete(JS::Heap& heap, Function<void(JS::GCPtr<Script>)> function)
  32. {
  33. return JS::create_heap_function(heap, move(function));
  34. }
  35. PerformTheFetchHook create_perform_the_fetch_hook(JS::Heap& heap, Function<WebIDL::ExceptionOr<void>(JS::NonnullGCPtr<Fetch::Infrastructure::Request>, TopLevelModule, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction)> function)
  36. {
  37. return JS::create_heap_function(heap, move(function));
  38. }
  39. ScriptFetchOptions default_script_fetch_options()
  40. {
  41. // The default script fetch options are a script fetch options whose cryptographic nonce is the empty string,
  42. // integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is "same-origin",
  43. // referrer policy is the empty string, and fetch priority is "auto".
  44. return ScriptFetchOptions {
  45. .cryptographic_nonce = {},
  46. .integrity_metadata = {},
  47. .parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
  48. .credentials_mode = Fetch::Infrastructure::Request::CredentialsMode::SameOrigin,
  49. .referrer_policy = {},
  50. .fetch_priority = Fetch::Infrastructure::Request::Priority::Auto
  51. };
  52. }
  53. // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request
  54. ByteString module_type_from_module_request(JS::ModuleRequest const& module_request)
  55. {
  56. // 1. Let moduleType be "javascript".
  57. ByteString module_type = "javascript"sv;
  58. // 2. If moduleRequest.[[Attributes]] has a Record entry such that entry.[[Key]] is "type", then:
  59. for (auto const& entry : module_request.attributes) {
  60. if (entry.key != "type"sv)
  61. continue;
  62. // 1. If entry.[[Value]] is "javascript", then set moduleType to null.
  63. if (entry.value == "javascript"sv)
  64. module_type = nullptr;
  65. // 2. Otherwise, set moduleType to entry.[[Value]].
  66. else
  67. module_type = entry.value;
  68. }
  69. // 3. Return moduleType.
  70. return module_type;
  71. }
  72. // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
  73. // https://whatpr.org/html/9893/webappapis.html#resolve-a-module-specifier
  74. WebIDL::ExceptionOr<URL::URL> resolve_module_specifier(Optional<Script&> referring_script, ByteString const& specifier)
  75. {
  76. // 1. Let settingsObject and baseURL be null.
  77. Optional<EnvironmentSettingsObject&> settings_object;
  78. Optional<URL::URL const&> base_url;
  79. // 2. If referringScript is not null, then:
  80. if (referring_script.has_value()) {
  81. // 1. Set settingsObject to referringScript's settings object.
  82. settings_object = referring_script->settings_object();
  83. // 2. Set baseURL to referringScript's base URL.
  84. base_url = referring_script->base_url();
  85. }
  86. // 3. Otherwise:
  87. else {
  88. // 1. Assert: there is a current principal settings object.
  89. // NOTE: This is handled by the current_principal_settings_object() accessor.
  90. // 2. Set settingsObject to the current principal settings object.
  91. settings_object = current_principal_settings_object();
  92. // 3. Set baseURL to settingsObject's API base URL.
  93. base_url = settings_object->api_base_url();
  94. }
  95. // 4. Let importMap be an empty import map.
  96. ImportMap import_map;
  97. // 5. If settingsObject's global object implements Window, then set importMap to settingsObject's global object's import map.
  98. if (is<Window>(settings_object->global_object()))
  99. import_map = verify_cast<Window>(settings_object->global_object()).import_map();
  100. // 6. Let baseURLString be baseURL, serialized.
  101. auto base_url_string = base_url->serialize();
  102. // 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.
  103. auto as_url = resolve_url_like_module_specifier(specifier, *base_url);
  104. // 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier.
  105. auto normalized_specifier = as_url.has_value() ? as_url->serialize() : specifier;
  106. // 9. For each scopePrefix → scopeImports of importMap's scopes:
  107. for (auto const& entry : import_map.scopes()) {
  108. // FIXME: Clarify if the serialization steps need to be run here. The steps below assume
  109. // scopePrefix to be a string.
  110. auto const& scope_prefix = entry.key.serialize();
  111. auto const& scope_imports = entry.value;
  112. // 1. If scopePrefix is baseURLString, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of baseURLString, then:
  113. if (scope_prefix == base_url_string || (scope_prefix.ends_with("/"sv) && Infra::is_code_unit_prefix(scope_prefix, base_url_string))) {
  114. // 1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports.
  115. auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, scope_imports));
  116. // 2. If scopeImportsMatch is not null, then return scopeImportsMatch.
  117. if (scope_imports_match.has_value())
  118. return scope_imports_match.release_value();
  119. }
  120. }
  121. // 10. Let topLevelImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports.
  122. auto top_level_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, import_map.imports()));
  123. // 11. If topLevelImportsMatch is not null, then return topLevelImportsMatch.
  124. if (top_level_imports_match.has_value())
  125. return top_level_imports_match.release_value();
  126. // 12. If asURL is not null, then return asURL.
  127. if (as_url.has_value())
  128. return as_url.release_value();
  129. // 13. Throw a TypeError indicating that specifier was a bare specifier, but was not remapped to anything by importMap.
  130. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Failed to resolve non relative module specifier '{}' from an import map.", specifier).release_value_but_fixme_should_propagate_errors() };
  131. }
  132. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-an-imports-match
  133. WebIDL::ExceptionOr<Optional<URL::URL>> resolve_imports_match(ByteString const& normalized_specifier, Optional<URL::URL> as_url, ModuleSpecifierMap const& specifier_map)
  134. {
  135. // 1. For each specifierKey → resolutionResult of specifierMap:
  136. for (auto const& [specifier_key, resolution_result] : specifier_map) {
  137. // 1. If specifierKey is normalizedSpecifier, then:
  138. if (specifier_key == normalized_specifier) {
  139. // 1. If resolutionResult is null, then throw a TypeError indicating that resolution of specifierKey was blocked by a null entry.
  140. if (!resolution_result.has_value())
  141. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() };
  142. // 2. Assert: resolutionResult is a URL.
  143. VERIFY(resolution_result->is_valid());
  144. // 3. Return resolutionResult.
  145. return resolution_result;
  146. }
  147. // 2. If all of the following are true:
  148. if (
  149. // - specifierKey ends with U+002F (/);
  150. specifier_key.ends_with("/"sv) &&
  151. // - specifierKey is a code unit prefix of normalizedSpecifier; and
  152. Infra::is_code_unit_prefix(specifier_key, normalized_specifier) &&
  153. // - either asURL is null, or asURL is special,
  154. (!as_url.has_value() || as_url->is_special())
  155. // then:
  156. ) {
  157. // 1. If resolutionResult is null, then throw a TypeError indicating that the resolution of specifierKey was blocked by a null entry.
  158. if (!resolution_result.has_value())
  159. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() };
  160. // 2. Assert: resolutionResult is a URL.
  161. VERIFY(resolution_result->is_valid());
  162. // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix.
  163. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix.
  164. auto after_prefix = normalized_specifier.substring(specifier_key.length());
  165. // 4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing.
  166. VERIFY(resolution_result->serialize().ends_with("/"sv));
  167. // 5. Let url be the result of URL parsing afterPrefix with resolutionResult.
  168. auto url = DOMURL::parse(after_prefix, *resolution_result);
  169. // 6. If url is failure, then throw a TypeError indicating that resolution of normalizedSpecifier was blocked since the afterPrefix portion
  170. // could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.
  171. if (!url.is_valid())
  172. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Could not resolve '{}' as the after prefix portion could not be URL-parsed.", normalized_specifier).release_value_but_fixme_should_propagate_errors() };
  173. // 7. Assert: url is a URL.
  174. VERIFY(url.is_valid());
  175. // 8. If the serialization of resolutionResult is not a code unit prefix of the serialization of url, then throw a TypeError indicating
  176. // that the resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.
  177. if (!Infra::is_code_unit_prefix(resolution_result->serialize(), url.serialize()))
  178. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Could not resolve '{}' as it backtracks above its prefix specifierKey.", normalized_specifier).release_value_but_fixme_should_propagate_errors() };
  179. // 9. Return url.
  180. return url;
  181. }
  182. }
  183. // 2. Return null.
  184. return Optional<URL::URL> {};
  185. }
  186. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-url-like-module-specifier
  187. Optional<URL::URL> resolve_url_like_module_specifier(ByteString const& specifier, URL::URL const& base_url)
  188. {
  189. // 1. If specifier starts with "/", "./", or "../", then:
  190. if (specifier.starts_with("/"sv) || specifier.starts_with("./"sv) || specifier.starts_with("../"sv)) {
  191. // 1. Let url be the result of URL parsing specifier with baseURL.
  192. auto url = DOMURL::parse(specifier, base_url);
  193. // 2. If url is failure, then return null.
  194. if (!url.is_valid())
  195. return {};
  196. // 3. Return url.
  197. return url;
  198. }
  199. // 2. Let url be the result of URL parsing specifier (with no base URL).
  200. auto url = DOMURL::parse(specifier);
  201. // 3. If url is failure, then return null.
  202. if (!url.is_valid())
  203. return {};
  204. // 4. Return url.
  205. return url;
  206. }
  207. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-classic-script-request
  208. static void set_up_classic_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  209. {
  210. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  211. // integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer
  212. // policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.
  213. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  214. request.set_integrity_metadata(options.integrity_metadata);
  215. request.set_parser_metadata(options.parser_metadata);
  216. request.set_referrer_policy(options.referrer_policy);
  217. request.set_render_blocking(options.render_blocking);
  218. request.set_priority(options.fetch_priority);
  219. }
  220. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-module-script-request
  221. static void set_up_module_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  222. {
  223. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  224. // integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials
  225. // mode, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its
  226. // priority to options's fetch priority.
  227. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  228. request.set_integrity_metadata(options.integrity_metadata);
  229. request.set_parser_metadata(options.parser_metadata);
  230. request.set_credentials_mode(options.credentials_mode);
  231. request.set_referrer_policy(options.referrer_policy);
  232. request.set_render_blocking(options.render_blocking);
  233. request.set_priority(options.fetch_priority);
  234. }
  235. // https://html.spec.whatwg.org/multipage/webappapis.html#get-the-descendant-script-fetch-options
  236. WebIDL::ExceptionOr<ScriptFetchOptions> get_descendant_script_fetch_options(ScriptFetchOptions const& original_options, URL::URL const& url, EnvironmentSettingsObject& settings_object)
  237. {
  238. // 1. Let newOptions be a copy of originalOptions.
  239. auto new_options = original_options;
  240. // 2. Let integrity be the empty string.
  241. String integrity;
  242. // 3. If settingsObject's global object is a Window object, then set integrity to the result of resolving a module integrity metadata with url and settingsObject.
  243. if (is<Window>(settings_object.global_object()))
  244. integrity = TRY(resolve_a_module_integrity_metadata(url, settings_object));
  245. // 4. Set newOptions's integrity metadata to integrity.
  246. new_options.integrity_metadata = integrity;
  247. // 5. Set newOptions's fetch priority to "auto".
  248. new_options.fetch_priority = Fetch::Infrastructure::Request::Priority::Auto;
  249. // 6. Return newOptions.
  250. return new_options;
  251. }
  252. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-module-integrity-metadata
  253. WebIDL::ExceptionOr<String> resolve_a_module_integrity_metadata(const URL::URL& url, EnvironmentSettingsObject& settings_object)
  254. {
  255. // 1. Assert: settingsObject's global object is a Window object.
  256. VERIFY(is<Window>(settings_object.global_object()));
  257. // 2. Let map be settingsObject's global object's import map.
  258. auto map = static_cast<Window const&>(settings_object.global_object()).import_map();
  259. // 3. If map's integrity[url] does not exist, then return the empty string.
  260. // 4. Return map's integrity[url].
  261. return MUST(String::from_byte_string(map.integrity().get(url).value_or("")));
  262. }
  263. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
  264. WebIDL::ExceptionOr<void> fetch_classic_script(JS::NonnullGCPtr<HTMLScriptElement> element, URL::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions options, CORSSettingAttribute cors_setting, String character_encoding, OnFetchScriptComplete on_complete)
  265. {
  266. auto& realm = element->realm();
  267. auto& vm = realm.vm();
  268. // 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.
  269. auto request = create_potential_CORS_request(vm, url, Fetch::Infrastructure::Request::Destination::Script, cors_setting);
  270. // 2. Set request's client to settings object.
  271. request->set_client(&settings_object);
  272. // 3. Set request's initiator type to "script".
  273. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  274. // 4. Set up the classic script request given request and options.
  275. set_up_classic_script_request(*request, options);
  276. // 5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure,
  277. // or a byte sequence bodyBytes:
  278. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  279. fetch_algorithms_input.process_response_consume_body = [&settings_object, options = move(options), character_encoding = move(character_encoding), on_complete = move(on_complete)](auto response, auto body_bytes) {
  280. // 1. Set response to response's unsafe response.
  281. response = response->unsafe_response();
  282. // 2. If either of the following conditions are met:
  283. // - bodyBytes is null or failure; or
  284. // - response's status is not an ok status,
  285. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  286. // then run onComplete given null, and abort these steps.
  287. on_complete->function()(nullptr);
  288. return;
  289. }
  290. // 3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.
  291. auto potential_mime_type_for_encoding = response->header_list()->extract_mime_type();
  292. // 4. Set character encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding
  293. // and character encoding.
  294. auto extracted_character_encoding = Fetch::Infrastructure::legacy_extract_an_encoding(potential_mime_type_for_encoding, character_encoding);
  295. // 5. Let source text be the result of decoding bodyBytes to Unicode, using character encoding as the fallback
  296. // encoding.
  297. auto fallback_decoder = TextCodec::decoder_for(extracted_character_encoding);
  298. VERIFY(fallback_decoder.has_value());
  299. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*fallback_decoder, body_bytes.template get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  300. // 6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.
  301. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  302. // 7. Let script be the result of creating a classic script given source text, settings object's realm, response's URL,
  303. // options, and muted errors.
  304. // FIXME: Pass options.
  305. auto response_url = response->url().value_or({});
  306. auto script = ClassicScript::create(response_url.to_byte_string(), source_text, settings_object.realm(), response_url, 1, muted_errors);
  307. // 8. Run onComplete given script.
  308. on_complete->function()(script);
  309. };
  310. TRY(Fetch::Fetching::fetch(element->realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  311. return {};
  312. }
  313. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-worker-script
  314. WebIDL::ExceptionOr<void> fetch_classic_worker_script(URL::URL const& url, EnvironmentSettingsObject& fetch_client, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  315. {
  316. auto& realm = settings_object.realm();
  317. auto& vm = realm.vm();
  318. // 1. Let request be a new request whose URL is url, client is fetchClient, destination is destination, initiator type is "other",
  319. // mode is "same-origin", credentials mode is "same-origin", parser metadata is "not parser-inserted",
  320. // and whose use-URL-credentials flag is set.
  321. auto request = Fetch::Infrastructure::Request::create(vm);
  322. request->set_url(url);
  323. request->set_client(&fetch_client);
  324. request->set_destination(destination);
  325. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Other);
  326. // FIXME: Use proper SameOrigin CORS mode once Origins are set properly in WorkerHost processes
  327. request->set_mode(Fetch::Infrastructure::Request::Mode::NoCORS);
  328. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::SameOrigin);
  329. request->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);
  330. request->set_use_url_credentials(true);
  331. auto process_response_consume_body = [&settings_object, on_complete = move(on_complete)](auto response, auto body_bytes) {
  332. // 1. Set response to response's unsafe response.
  333. response = response->unsafe_response();
  334. // 2. If either of the following conditions are met:
  335. // - bodyBytes is null or failure; or
  336. // - response's status is not an ok status,
  337. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  338. // then run onComplete given null, and abort these steps.
  339. on_complete->function()(nullptr);
  340. return;
  341. }
  342. // 3. If all of the following are true:
  343. // - response's URL's scheme is an HTTP(S) scheme; and
  344. // - the result of extracting a MIME type from response's header list is not a JavaScript MIME type,
  345. auto maybe_mime_type = response->header_list()->extract_mime_type();
  346. auto mime_type_is_javascript = maybe_mime_type.has_value() && maybe_mime_type->is_javascript();
  347. if (response->url().has_value() && Fetch::Infrastructure::is_http_or_https_scheme(response->url()->scheme()) && !mime_type_is_javascript) {
  348. auto mime_type_serialized = maybe_mime_type.has_value() ? maybe_mime_type->serialized() : "unknown"_string;
  349. dbgln("Invalid non-javascript mime type \"{}\" for worker script at {}", mime_type_serialized, response->url().value());
  350. // then run onComplete given null, and abort these steps.
  351. on_complete->function()(nullptr);
  352. return;
  353. }
  354. // NOTE: Other fetch schemes are exempted from MIME type checking for historical web-compatibility reasons.
  355. // We might be able to tighten this in the future; see https://github.com/whatwg/html/issues/3255.
  356. // 4. Let sourceText be the result of UTF-8 decoding bodyBytes.
  357. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  358. VERIFY(decoder.has_value());
  359. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, body_bytes.template get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  360. // 5. Let script be the result of creating a classic script using sourceText, settingsObject's realm,
  361. // response's URL, and the default classic script fetch options.
  362. auto response_url = response->url().value_or({});
  363. auto script = ClassicScript::create(response_url.to_byte_string(), source_text, settings_object.realm(), response_url);
  364. // 6. Run onComplete given script.
  365. on_complete->function()(script);
  366. };
  367. // 2. If performFetch was given, run performFetch with request, true, and with processResponseConsumeBody as defined below.
  368. if (perform_fetch != nullptr) {
  369. TRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));
  370. }
  371. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  372. else {
  373. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  374. fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);
  375. TRY(Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  376. }
  377. return {};
  378. }
  379. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-worker-imported-script
  380. WebIDL::ExceptionOr<JS::NonnullGCPtr<ClassicScript>> fetch_a_classic_worker_imported_script(URL::URL const& url, HTML::EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch)
  381. {
  382. auto& realm = settings_object.realm();
  383. auto& vm = realm.vm();
  384. // 1. Let response be null.
  385. JS::GCPtr<Fetch::Infrastructure::Response> response = nullptr;
  386. // 2. Let bodyBytes be null.
  387. Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes;
  388. // 3. Let request be a new request whose URL is url, client is settingsObject, destination is "script", initiator type is "other",
  389. // parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.
  390. auto request = Fetch::Infrastructure::Request::create(vm);
  391. request->set_url(url);
  392. request->set_client(&settings_object);
  393. request->set_destination(Fetch::Infrastructure::Request::Destination::Script);
  394. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Other);
  395. request->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);
  396. request->set_use_url_credentials(true);
  397. auto process_response_consume_body = [&response, &body_bytes](JS::NonnullGCPtr<Fetch::Infrastructure::Response> res, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bb) {
  398. // 1. Set bodyBytes to bb.
  399. body_bytes = move(bb);
  400. // 2. Set response to res.
  401. response = res;
  402. };
  403. // 4. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.
  404. if (perform_fetch) {
  405. TRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));
  406. }
  407. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  408. else {
  409. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  410. fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);
  411. TRY(Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  412. }
  413. // 5. Pause until response is not null.
  414. auto& event_loop = settings_object.responsible_event_loop();
  415. event_loop.spin_until(JS::create_heap_function(vm.heap(), [&]() -> bool {
  416. return response;
  417. }));
  418. // 6. Set response to response's unsafe response.
  419. response = response->unsafe_response();
  420. // 7. If any of the following are true:
  421. // - bodyBytes is null or failure;
  422. // - response's status is not an ok status; or
  423. // - the result of extracting a MIME type from response's header list is not a JavaScript MIME type,
  424. // then throw a "NetworkError" DOMException.
  425. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>()
  426. || !Fetch::Infrastructure::is_ok_status(response->status())
  427. || !response->header_list()->extract_mime_type().has_value() || !response->header_list()->extract_mime_type()->is_javascript()) {
  428. return WebIDL::NetworkError::create(realm, "Network error"_string);
  429. }
  430. // 8. Let sourceText be the result of UTF-8 decoding bodyBytes.
  431. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  432. VERIFY(decoder.has_value());
  433. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, body_bytes.get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  434. // 9. Let mutedErrors be true if response was CORS-cross-origin, and false otherwise.
  435. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  436. // 10. Let script be the result of creating a classic script given sourceText, settingsObject's realm, response's URL, the default classic script fetch options, and mutedErrors.
  437. auto response_url = response->url().value_or({});
  438. auto script = ClassicScript::create(response_url.to_byte_string(), source_text, settings_object.realm(), response_url, 1, muted_errors);
  439. // 11. Return script.
  440. return script;
  441. }
  442. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-worker-script-tree
  443. WebIDL::ExceptionOr<void> fetch_module_worker_script_graph(URL::URL const& url, EnvironmentSettingsObject& fetch_client, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  444. {
  445. return fetch_worklet_module_worker_script_graph(url, fetch_client, destination, settings_object, move(perform_fetch), move(on_complete));
  446. }
  447. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-worklet/module-worker-script-graph
  448. // https://whatpr.org/html/9893/webappapis.html#fetch-a-worklet/module-worker-script-graph
  449. WebIDL::ExceptionOr<void> fetch_worklet_module_worker_script_graph(URL::URL const& url, EnvironmentSettingsObject& fetch_client, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  450. {
  451. auto& realm = settings_object.realm();
  452. auto& vm = realm.vm();
  453. // 1. Let options be a script fetch options whose cryptographic nonce is the empty string,
  454. // integrity metadata is the empty string, parser metadata is "not-parser-inserted",
  455. // credentials mode is credentialsMode, referrer policy is the empty string, and fetch priority is "auto".
  456. // FIXME: credentialsMode
  457. auto options = ScriptFetchOptions {
  458. .cryptographic_nonce = String {},
  459. .integrity_metadata = String {},
  460. .parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
  461. .credentials_mode = Fetch::Infrastructure::Request::CredentialsMode::SameOrigin,
  462. .referrer_policy = ReferrerPolicy::ReferrerPolicy::EmptyString,
  463. .fetch_priority = Fetch::Infrastructure::Request::Priority::Auto
  464. };
  465. // onSingleFetchComplete given result is the following algorithm:
  466. auto on_single_fetch_complete = create_on_fetch_script_complete(vm.heap(), [&realm, &fetch_client, destination, perform_fetch = perform_fetch, on_complete = move(on_complete)](auto result) mutable {
  467. // 1. If result is null, run onComplete with null, and abort these steps.
  468. if (!result) {
  469. dbgln("on single fetch complete with nool");
  470. on_complete->function()(nullptr);
  471. return;
  472. }
  473. // 2. Fetch the descendants of and link result given fetchClient, destination, and onComplete. If performFetch was given, pass it along as well.
  474. fetch_descendants_of_and_link_a_module_script(realm, verify_cast<JavaScriptModuleScript>(*result), fetch_client, destination, move(perform_fetch), on_complete);
  475. });
  476. // 2. Fetch a single module script given url, fetchClient, destination, options, settingsObject's realm, "client", true,
  477. // and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  478. fetch_single_module_script(realm, url, fetch_client, destination, options, settings_object.realm(), Fetch::Infrastructure::Request::Referrer::Client, {}, TopLevelModule::Yes, move(perform_fetch), on_single_fetch_complete);
  479. return {};
  480. }
  481. // https://html.spec.whatwg.org/multipage/webappapis.html#internal-module-script-graph-fetching-procedure
  482. void fetch_internal_module_script_graph(JS::Realm& realm, JS::ModuleRequest const& module_request, EnvironmentSettingsObject& fetch_client_settings_object, Fetch::Infrastructure::Request::Destination destination, ScriptFetchOptions const& options, Script& referring_script, HashTable<ModuleLocationTuple> const& visited_set, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  483. {
  484. // 1. Let url be the result of resolving a module specifier given referringScript and moduleRequest.[[Specifier]].
  485. auto url = MUST(resolve_module_specifier(referring_script, module_request.module_specifier));
  486. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  487. // NOTE: Handled by MUST above.
  488. // 3. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  489. auto module_type = module_type_from_module_request(module_request);
  490. // 4. Assert: visited set contains (url, moduleType).
  491. VERIFY(visited_set.contains({ url, module_type }));
  492. // onSingleFetchComplete given result is the following algorithm:
  493. auto on_single_fetch_complete = create_on_fetch_script_complete(realm.heap(), [&realm, perform_fetch, on_complete, &fetch_client_settings_object, destination, visited_set](auto result) mutable {
  494. // 1. If result is null, run onComplete with null, and abort these steps.
  495. if (!result) {
  496. on_complete->function()(nullptr);
  497. return;
  498. }
  499. // 2. Fetch the descendants of result given fetch client settings object, destination, visited set, and with onComplete. If performFetch was given, pass it along as well.
  500. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  501. fetch_descendants_of_a_module_script(realm, module_script, fetch_client_settings_object, destination, visited_set, perform_fetch, on_complete);
  502. });
  503. // 5. Fetch a single module script given url, fetch client settings object, destination, options, referringScript's settings object's realm,
  504. // referringScript's base URL, moduleRequest, false, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  505. fetch_single_module_script(realm, url, fetch_client_settings_object, destination, options, referring_script.realm(), referring_script.base_url(), module_request, TopLevelModule::No, perform_fetch, on_single_fetch_complete);
  506. }
  507. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-a-module-script
  508. void fetch_descendants_of_a_module_script(JS::Realm& realm, JavaScriptModuleScript& module_script, EnvironmentSettingsObject& fetch_client_settings_object, Fetch::Infrastructure::Request::Destination destination, HashTable<ModuleLocationTuple> visited_set, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  509. {
  510. // 1. If module script's record is null, run onComplete with module script and return.
  511. if (!module_script.record()) {
  512. on_complete->function()(&module_script);
  513. return;
  514. }
  515. // 2. Let record be module script's record.
  516. auto const& record = module_script.record();
  517. // 3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, run onComplete with module script and return.
  518. // FIXME: Currently record is always a cyclic module.
  519. if (record->requested_modules().is_empty()) {
  520. on_complete->function()(&module_script);
  521. return;
  522. }
  523. // 4. Let moduleRequests be a new empty list.
  524. Vector<JS::ModuleRequest> module_requests;
  525. // 5. For each ModuleRequest Record requested of record.[[RequestedModules]],
  526. for (auto const& requested : record->requested_modules()) {
  527. // 1. Let url be the result of resolving a module specifier given module script and requested.[[Specifier]].
  528. auto url = MUST(resolve_module_specifier(module_script, requested.module_specifier));
  529. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  530. // NOTE: Handled by MUST above.
  531. // 3. Let moduleType be the result of running the module type from module request steps given requested.
  532. auto module_type = module_type_from_module_request(requested);
  533. // 4. If visited set does not contain (url, moduleType), then:
  534. if (!visited_set.contains({ url, module_type })) {
  535. // 1. Append requested to moduleRequests.
  536. module_requests.append(requested);
  537. // 2. Append (url, moduleType) to visited set.
  538. visited_set.set({ url, module_type });
  539. }
  540. }
  541. // FIXME: 6. Let options be the descendant script fetch options for module script's fetch options.
  542. ScriptFetchOptions options;
  543. // FIXME: 7. Assert: options is not null, as module script is a JavaScript module script.
  544. // 8. Let pendingCount be the length of moduleRequests.
  545. auto pending_count = module_requests.size();
  546. // 9. If pendingCount is zero, run onComplete with module script.
  547. if (pending_count == 0) {
  548. on_complete->function()(&module_script);
  549. return;
  550. }
  551. // 10. Let failed be false.
  552. bool failed = false;
  553. // 11. For each moduleRequest in moduleRequests, perform the internal module script graph fetching procedure given moduleRequest,
  554. // fetch client settings object, destination, options, module script, visited set, and onInternalFetchingComplete as defined below.
  555. // If performFetch was given, pass it along as well.
  556. for (auto const& module_request : module_requests) {
  557. // onInternalFetchingComplete given result is the following algorithm:
  558. auto on_internal_fetching_complete = create_on_fetch_script_complete(realm.heap(), [failed, pending_count, &module_script, on_complete](auto result) mutable {
  559. // 1. If failed is true, then abort these steps.
  560. if (failed)
  561. return;
  562. // 2. If result is null, then set failed to true, run onComplete with null, and abort these steps.
  563. if (!result) {
  564. failed = true;
  565. on_complete->function()(nullptr);
  566. return;
  567. }
  568. // 3. Assert: pendingCount is greater than zero.
  569. VERIFY(pending_count > 0);
  570. // 4. Decrement pendingCount by one.
  571. --pending_count;
  572. // 5. If pendingCount is zero, run onComplete with module script.
  573. if (pending_count == 0)
  574. on_complete->function()(&module_script);
  575. });
  576. fetch_internal_module_script_graph(realm, module_request, fetch_client_settings_object, destination, options, module_script, visited_set, perform_fetch, on_internal_fetching_complete);
  577. }
  578. }
  579. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-destination-from-module-type
  580. Fetch::Infrastructure::Request::Destination fetch_destination_from_module_type(Fetch::Infrastructure::Request::Destination default_destination, ByteString const& module_type)
  581. {
  582. // 1. If moduleType is "json", then return "json".
  583. if (module_type == "json"sv)
  584. return Fetch::Infrastructure::Request::Destination::JSON;
  585. // 2. If moduleType is "css", then return "style".
  586. if (module_type == "css"sv)
  587. return Fetch::Infrastructure::Request::Destination::Style;
  588. // 3. Return defaultDestination.
  589. return default_destination;
  590. }
  591. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
  592. // https://whatpr.org/html/9893/webappapis.html#fetch-a-single-module-script
  593. void fetch_single_module_script(JS::Realm& realm,
  594. URL::URL const& url,
  595. EnvironmentSettingsObject& fetch_client,
  596. Fetch::Infrastructure::Request::Destination destination,
  597. ScriptFetchOptions const& options,
  598. JS::Realm& module_map_realm,
  599. Web::Fetch::Infrastructure::Request::ReferrerType const& referrer,
  600. Optional<JS::ModuleRequest> const& module_request,
  601. TopLevelModule is_top_level,
  602. PerformTheFetchHook perform_fetch,
  603. OnFetchScriptComplete on_complete)
  604. {
  605. // 1. Let moduleType be "javascript".
  606. ByteString module_type = "javascript"sv;
  607. // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.
  608. if (module_request.has_value())
  609. module_type = module_type_from_module_request(*module_request);
  610. // 3. Assert: the result of running the module type allowed steps given moduleType and moduleMapRealm is true.
  611. // Otherwise we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Assertions]]
  612. // in create a JavaScript module script or fetch a single imported module script.
  613. VERIFY(module_type_allowed(module_map_realm, module_type));
  614. // 4. Let moduleMap be moduleMapRealm's module map.
  615. auto& module_map = module_map_of_realm(module_map_realm);
  616. // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes,
  617. // then queue a task on the networking task source to proceed with running the following steps.
  618. if (module_map.is_fetching(url, module_type)) {
  619. module_map.wait_for_change(realm.heap(), url, module_type, [on_complete, &realm](auto entry) -> void {
  620. HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), JS::create_heap_function(realm.heap(), [on_complete, entry] {
  621. // FIXME: This should run other steps, for now we just assume the script loaded.
  622. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript || entry.type == ModuleMap::EntryType::Failed);
  623. on_complete->function()(entry.module_script);
  624. }));
  625. });
  626. return;
  627. }
  628. // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.
  629. auto entry = module_map.get(url, module_type);
  630. if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) {
  631. on_complete->function()(entry->module_script);
  632. return;
  633. }
  634. // 7. Set moduleMap[(url, moduleType)] to "fetching".
  635. module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr });
  636. // 8. Let request be a new request whose URL is url, mode is "cors", referrer is referrer, and client is fetchClient.
  637. auto request = Fetch::Infrastructure::Request::create(realm.vm());
  638. request->set_url(url);
  639. request->set_mode(Fetch::Infrastructure::Request::Mode::CORS);
  640. request->set_referrer(referrer);
  641. request->set_client(&fetch_client);
  642. // 9. Set request's destination to the result of running the fetch destination from module type steps given destination and moduleType.
  643. request->set_destination(fetch_destination_from_module_type(destination, module_type));
  644. // 10. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin".
  645. if ((destination == Fetch::Infrastructure::Request::Destination::Worker || destination == Fetch::Infrastructure::Request::Destination::SharedWorker || destination == Fetch::Infrastructure::Request::Destination::ServiceWorker) && is_top_level == TopLevelModule::Yes)
  646. request->set_mode(Fetch::Infrastructure::Request::Mode::SameOrigin);
  647. // 11. Set request's initiator type to "script".
  648. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  649. // 12. Set up the module script request given request and options.
  650. set_up_module_script_request(request, options);
  651. // 13. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.
  652. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  653. // In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:
  654. auto process_response_consume_body = [&module_map, url, module_type, &module_map_realm, on_complete](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
  655. // 1. If either of the following conditions are met:
  656. // - bodyBytes is null or failure; or
  657. // - response's status is not an ok status,
  658. if (body_bytes.has<Empty>() || body_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  659. // then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.
  660. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  661. on_complete->function()(nullptr);
  662. return;
  663. }
  664. // 2. Let sourceText be the result of UTF-8 decoding bodyBytes.
  665. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  666. VERIFY(decoder.has_value());
  667. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, body_bytes.get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  668. // 3. Let mimeType be the result of extracting a MIME type from response's header list.
  669. auto mime_type = response->header_list()->extract_mime_type();
  670. // 4. Let moduleScript be null.
  671. JS::GCPtr<JavaScriptModuleScript> module_script;
  672. // FIXME: 5. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]
  673. // FIXME: 6. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.
  674. // 7. If mimeType is a JavaScript MIME type and moduleType is "javascript", then set moduleScript to the result of creating a JavaScript module script given sourceText, moduleMapRealm, response's URL, and options.
  675. // FIXME: Pass options.
  676. if (mime_type->is_javascript() && module_type == "javascript")
  677. module_script = JavaScriptModuleScript::create(url.basename(), source_text, module_map_realm, response->url().value_or({})).release_value_but_fixme_should_propagate_errors();
  678. // FIXME: 8. If the MIME type essence of mimeType is "text/css" and moduleType is "css", then set moduleScript to the result of creating a CSS module script given sourceText and settingsObject.
  679. // FIXME: 9. If mimeType is a JSON MIME type and moduleType is "json", then set moduleScript to the result of creating a JSON module script given sourceText and settingsObject.
  680. // 10. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.
  681. module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script });
  682. on_complete->function()(module_script);
  683. };
  684. if (perform_fetch != nullptr) {
  685. perform_fetch->function()(request, is_top_level, move(process_response_consume_body)).release_value_but_fixme_should_propagate_errors();
  686. } else {
  687. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  688. fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);
  689. Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(realm.vm(), move(fetch_algorithms_input))).release_value_but_fixme_should_propagate_errors();
  690. }
  691. }
  692. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
  693. // https://whatpr.org/html/9893/webappapis.html#fetch-a-module-script-tree
  694. void fetch_external_module_script_graph(JS::Realm& realm, URL::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions const& options, OnFetchScriptComplete on_complete)
  695. {
  696. // 1. Disallow further import maps given settingsObject's realm.
  697. disallow_further_import_maps(settings_object.realm());
  698. auto steps = create_on_fetch_script_complete(realm.heap(), [&realm, &settings_object, on_complete, url](auto result) mutable {
  699. // 1. If result is null, run onComplete given null, and abort these steps.
  700. if (!result) {
  701. on_complete->function()(nullptr);
  702. return;
  703. }
  704. // 2. Fetch the descendants of and link result given settingsObject, "script", and onComplete.
  705. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  706. fetch_descendants_of_and_link_a_module_script(realm, module_script, settings_object, Fetch::Infrastructure::Request::Destination::Script, nullptr, on_complete);
  707. });
  708. // 2. Fetch a single module script given url, settingsObject, "script", options, settingsObject's realm, "client", true, and with the following steps given result:
  709. fetch_single_module_script(realm, url, settings_object, Fetch::Infrastructure::Request::Destination::Script, options, settings_object.realm(), Web::Fetch::Infrastructure::Request::Referrer::Client, {}, TopLevelModule::Yes, nullptr, steps);
  710. }
  711. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-inline-module-script-graph
  712. // https://whatpr.org/html/9893/webappapis.html#fetch-an-inline-module-script-graph
  713. void fetch_inline_module_script_graph(JS::Realm& realm, ByteString const& filename, ByteString const& source_text, URL::URL const& base_url, EnvironmentSettingsObject& settings_object, OnFetchScriptComplete on_complete)
  714. {
  715. // 1. Disallow further import maps given settingsObject's realm.
  716. disallow_further_import_maps(settings_object.realm());
  717. // 2. Let script be the result of creating a JavaScript module script using sourceText, settingsObject's realm, baseURL, and options.
  718. auto script = JavaScriptModuleScript::create(filename, source_text.view(), settings_object.realm(), base_url).release_value_but_fixme_should_propagate_errors();
  719. // 3. If script is null, run onComplete given null, and return.
  720. if (!script) {
  721. on_complete->function()(nullptr);
  722. return;
  723. }
  724. // 5. Fetch the descendants of and link script, given settingsObject, "script", and onComplete.
  725. fetch_descendants_of_and_link_a_module_script(realm, *script, settings_object, Fetch::Infrastructure::Request::Destination::Script, nullptr, on_complete);
  726. }
  727. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-imported-module-script
  728. void fetch_single_imported_module_script(JS::Realm& realm,
  729. URL::URL const& url,
  730. EnvironmentSettingsObject& fetch_client,
  731. Fetch::Infrastructure::Request::Destination destination,
  732. ScriptFetchOptions const& options,
  733. JS::Realm& module_map_realm,
  734. Fetch::Infrastructure::Request::ReferrerType referrer,
  735. JS::ModuleRequest const& module_request,
  736. PerformTheFetchHook perform_fetch,
  737. OnFetchScriptComplete on_complete)
  738. {
  739. // 1. Assert: moduleRequest.[[Attributes]] does not contain any Record entry such that entry.[[Key]] is not "type",
  740. // because we only asked for "type" attributes in HostGetSupportedImportAttributes.
  741. for (auto const& entry : module_request.attributes)
  742. VERIFY(entry.key == "type"sv);
  743. // 2. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  744. auto module_type = module_type_from_module_request(module_request);
  745. // 3. If the result of running the module type allowed steps given moduleType and moduleMapRealm is false,
  746. // then run onComplete given null, and return.
  747. if (!module_type_allowed(module_map_realm, module_type)) {
  748. on_complete->function()(nullptr);
  749. return;
  750. }
  751. // 4. Fetch a single module script given url, fetchClient, destination, options, moduleMapRealm, referrer, moduleRequest, false,
  752. // and onComplete. If performFetch was given, pass it along as well.
  753. fetch_single_module_script(realm, url, fetch_client, destination, options, module_map_realm, referrer, module_request, TopLevelModule::No, perform_fetch, on_complete);
  754. }
  755. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-and-link-a-module-script
  756. void fetch_descendants_of_and_link_a_module_script(JS::Realm& realm,
  757. JavaScriptModuleScript& module_script,
  758. EnvironmentSettingsObject& fetch_client,
  759. Fetch::Infrastructure::Request::Destination destination,
  760. PerformTheFetchHook perform_fetch,
  761. OnFetchScriptComplete on_complete)
  762. {
  763. // 1. Let record be moduleScript's record.
  764. auto* record = module_script.record();
  765. // 2. If record is null, then:
  766. if (!record) {
  767. // 1. Set moduleScript's error to rethrow to moduleScript's parse error.
  768. module_script.set_error_to_rethrow(module_script.parse_error());
  769. // 2. Run onComplete given moduleScript.
  770. on_complete->function()(module_script);
  771. // 3. Return.
  772. return;
  773. }
  774. // 3. Let state be Record { [[ParseError]]: null, [[Destination]]: destination, [[PerformFetch]]: null, [[FetchClient]]: fetchClient }.
  775. auto state = realm.heap().allocate<FetchContext>(JS::js_null(), destination, nullptr, fetch_client);
  776. // 4. If performFetch was given, set state.[[PerformFetch]] to performFetch.
  777. state->perform_fetch = perform_fetch;
  778. // FIXME: These should most likely be steps in the spec.
  779. // NOTE: For reasons beyond my understanding, we cannot use TemporaryExecutionContext here.
  780. // Calling perform_a_microtask_checkpoint() on the fetch_client's responsible_event_loop
  781. // prevents this from functioning properly. HTMLParser::the_end would be run before
  782. // HTMLScriptElement::prepare_script had a chance to setup the callback to mark_done properly,
  783. // resulting in the event loop hanging forever awaiting for the script to be ready for parser
  784. // execution.
  785. realm.vm().push_execution_context(fetch_client.realm_execution_context());
  786. prepare_to_run_callback(realm);
  787. // 5. Let loadingPromise be record.LoadRequestedModules(state).
  788. auto& loading_promise = record->load_requested_modules(state);
  789. // 6. Upon fulfillment of loadingPromise, run the following steps:
  790. WebIDL::upon_fulfillment(loading_promise, JS::create_heap_function(realm.heap(), [&realm, record, &module_script, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  791. // 1. Perform record.Link().
  792. auto linking_result = record->link(realm.vm());
  793. // If this throws an exception, set result's error to rethrow to that exception.
  794. if (linking_result.is_throw_completion())
  795. module_script.set_error_to_rethrow(linking_result.release_error().value().value());
  796. // 2. Run onComplete given moduleScript.
  797. on_complete->function()(module_script);
  798. return JS::js_undefined();
  799. }));
  800. // 7. Upon rejection of loadingPromise, run the following steps:
  801. WebIDL::upon_rejection(loading_promise, JS::create_heap_function(realm.heap(), [state, &module_script, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  802. // 1. If state.[[ParseError]] is not null, set moduleScript's error to rethrow to state.[[ParseError]] and run
  803. // onComplete given moduleScript.
  804. if (!state->parse_error.is_null()) {
  805. module_script.set_error_to_rethrow(state->parse_error);
  806. on_complete->function()(module_script);
  807. }
  808. // 2. Otherwise, run onComplete given null.
  809. else {
  810. on_complete->function()(nullptr);
  811. }
  812. return JS::js_undefined();
  813. }));
  814. clean_up_after_running_callback(realm);
  815. realm.vm().pop_execution_context();
  816. }
  817. }