Fetching.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. /*
  2. * Copyright (c) 2022, networkException <networkexception@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/ModuleRequest.h>
  7. #include <LibTextCodec/Decoder.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/Fetch/Fetching/Fetching.h>
  10. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  11. #include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
  12. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  13. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  14. #include <LibWeb/HTML/HTMLScriptElement.h>
  15. #include <LibWeb/HTML/PotentialCORSRequest.h>
  16. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  17. #include <LibWeb/HTML/Scripting/Environments.h>
  18. #include <LibWeb/HTML/Scripting/Fetching.h>
  19. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  20. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/Infra/Strings.h>
  23. #include <LibWeb/MimeSniff/MimeType.h>
  24. #include <LibWeb/URL/URL.h>
  25. namespace Web::HTML {
  26. // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request
  27. DeprecatedString module_type_from_module_request(JS::ModuleRequest const& module_request)
  28. {
  29. // 1. Let moduleType be "javascript".
  30. DeprecatedString module_type = "javascript"sv;
  31. // 2. If moduleRequest.[[Assertions]] has a Record entry such that entry.[[Key]] is "type", then:
  32. for (auto const& entry : module_request.assertions) {
  33. if (entry.key != "type"sv)
  34. continue;
  35. // 1. If entry.[[Value]] is "javascript", then set moduleType to null.
  36. if (entry.value == "javascript"sv)
  37. module_type = nullptr;
  38. // 2. Otherwise, set moduleType to entry.[[Value]].
  39. else
  40. module_type = entry.value;
  41. }
  42. // 3. Return moduleType.
  43. return module_type;
  44. }
  45. // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
  46. WebIDL::ExceptionOr<AK::URL> resolve_module_specifier(Optional<Script&> referring_script, DeprecatedString const& specifier)
  47. {
  48. // 1. Let settingsObject and baseURL be null.
  49. Optional<EnvironmentSettingsObject&> settings_object;
  50. Optional<AK::URL const&> base_url;
  51. // 2. If referringScript is not null, then:
  52. if (referring_script.has_value()) {
  53. // 1. Set settingsObject to referringScript's settings object.
  54. settings_object = referring_script->settings_object();
  55. // 2. Set baseURL to referringScript's base URL.
  56. base_url = referring_script->base_url();
  57. }
  58. // 3. Otherwise:
  59. else {
  60. // 1. Assert: there is a current settings object.
  61. // NOTE: This is handled by the current_settings_object() accessor.
  62. // 2. Set settingsObject to the current settings object.
  63. settings_object = current_settings_object();
  64. // 3. Set baseURL to settingsObject's API base URL.
  65. base_url = settings_object->api_base_url();
  66. }
  67. // 4. Let importMap be an empty import map.
  68. ImportMap import_map;
  69. // 5. If settingsObject's global object implements Window, then set importMap to settingsObject's global object's import map.
  70. if (is<Window>(settings_object->global_object()))
  71. import_map = verify_cast<Window>(settings_object->global_object()).import_map();
  72. // 6. Let baseURLString be baseURL, serialized.
  73. auto base_url_string = base_url->serialize();
  74. // 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.
  75. auto as_url = resolve_url_like_module_specifier(specifier, *base_url);
  76. // 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier.
  77. auto normalized_specifier = as_url.has_value() ? as_url->serialize() : specifier;
  78. // 9. For each scopePrefix → scopeImports of importMap's scopes:
  79. for (auto const& entry : import_map.scopes()) {
  80. // FIXME: Clarify if the serialization steps need to be run here. The steps below assume
  81. // scopePrefix to be a string.
  82. auto const& scope_prefix = entry.key.serialize();
  83. auto const& scope_imports = entry.value;
  84. // 1. If scopePrefix is baseURLString, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of baseURLString, then:
  85. if (scope_prefix == base_url_string || (scope_prefix.ends_with("/"sv) && Infra::is_code_unit_prefix(scope_prefix, base_url_string))) {
  86. // 1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports.
  87. auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, scope_imports));
  88. // 2. If scopeImportsMatch is not null, then return scopeImportsMatch.
  89. if (scope_imports_match.has_value())
  90. return scope_imports_match.release_value();
  91. }
  92. }
  93. // 10. Let topLevelImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports.
  94. auto top_level_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, import_map.imports()));
  95. // 11. If topLevelImportsMatch is not null, then return topLevelImportsMatch.
  96. if (top_level_imports_match.has_value())
  97. return top_level_imports_match.release_value();
  98. // 12. If asURL is not null, then return asURL.
  99. if (as_url.has_value())
  100. return as_url.release_value();
  101. // 13. Throw a TypeError indicating that specifier was a bare specifier, but was not remapped to anything by importMap.
  102. 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() };
  103. }
  104. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-an-imports-match
  105. WebIDL::ExceptionOr<Optional<AK::URL>> resolve_imports_match(DeprecatedString const& normalized_specifier, Optional<AK::URL> as_url, ModuleSpecifierMap const& specifier_map)
  106. {
  107. // 1. For each specifierKey → resolutionResult of specifierMap:
  108. for (auto const& [specifier_key, resolution_result] : specifier_map) {
  109. // 1. If specifierKey is normalizedSpecifier, then:
  110. if (specifier_key == normalized_specifier) {
  111. // 1. If resolutionResult is null, then throw a TypeError indicating that resolution of specifierKey was blocked by a null entry.
  112. if (!resolution_result.has_value())
  113. 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() };
  114. // 2. Assert: resolutionResult is a URL.
  115. VERIFY(resolution_result->is_valid());
  116. // 3. Return resolutionResult.
  117. return resolution_result;
  118. }
  119. // 2. If all of the following are true:
  120. if (
  121. // - specifierKey ends with U+002F (/);
  122. specifier_key.ends_with("/"sv) &&
  123. // - specifierKey is a code unit prefix of normalizedSpecifier; and
  124. Infra::is_code_unit_prefix(specifier_key, normalized_specifier) &&
  125. // - either asURL is null, or asURL is special,
  126. (!as_url.has_value() || as_url->is_special())
  127. // then:
  128. ) {
  129. // 1. If resolutionResult is null, then throw a TypeError indicating that the resolution of specifierKey was blocked by a null entry.
  130. if (!resolution_result.has_value())
  131. 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() };
  132. // 2. Assert: resolutionResult is a URL.
  133. VERIFY(resolution_result->is_valid());
  134. // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix.
  135. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix.
  136. auto after_prefix = normalized_specifier.substring(specifier_key.length());
  137. // 4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing.
  138. VERIFY(resolution_result->serialize().ends_with("/"sv));
  139. // 5. Let url be the result of URL parsing afterPrefix with resolutionResult.
  140. auto url = URL::parse(after_prefix, *resolution_result);
  141. // 6. If url is failure, then throw a TypeError indicating that resolution of normalizedSpecifier was blocked since the afterPrefix portion
  142. // could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.
  143. if (!url.is_valid())
  144. 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() };
  145. // 7. Assert: url is a URL.
  146. VERIFY(url.is_valid());
  147. // 8. If the serialization of resolutionResult is not a code unit prefix of the serialization of url, then throw a TypeError indicating
  148. // that the resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.
  149. if (!Infra::is_code_unit_prefix(resolution_result->serialize(), url.serialize()))
  150. 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() };
  151. // 9. Return url.
  152. return url;
  153. }
  154. }
  155. // 2. Return null.
  156. return Optional<AK::URL> {};
  157. }
  158. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-url-like-module-specifier
  159. Optional<AK::URL> resolve_url_like_module_specifier(DeprecatedString const& specifier, AK::URL const& base_url)
  160. {
  161. // 1. If specifier starts with "/", "./", or "../", then:
  162. if (specifier.starts_with("/"sv) || specifier.starts_with("./"sv) || specifier.starts_with("../"sv)) {
  163. // 1. Let url be the result of URL parsing specifier with baseURL.
  164. auto url = URL::parse(specifier, base_url);
  165. // 2. If url is failure, then return null.
  166. if (!url.is_valid())
  167. return {};
  168. // 3. Return url.
  169. return url;
  170. }
  171. // 2. Let url be the result of URL parsing specifier (with no base URL).
  172. auto url = URL::parse(specifier);
  173. // 3. If url is failure, then return null.
  174. if (!url.is_valid())
  175. return {};
  176. // 4. Return url.
  177. return url;
  178. }
  179. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-classic-script-request
  180. static void set_up_classic_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  181. {
  182. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  183. // integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer
  184. // policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.
  185. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  186. request.set_integrity_metadata(options.integrity_metadata);
  187. request.set_parser_metadata(options.parser_metadata);
  188. request.set_referrer_policy(options.referrer_policy);
  189. request.set_render_blocking(options.render_blocking);
  190. request.set_priority(options.fetch_priority);
  191. }
  192. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-module-script-request
  193. static void set_up_module_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  194. {
  195. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  196. // integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials
  197. // mode, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its
  198. // priority to options's fetch priority.
  199. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  200. request.set_integrity_metadata(options.integrity_metadata);
  201. request.set_parser_metadata(options.parser_metadata);
  202. request.set_credentials_mode(options.credentials_mode);
  203. request.set_referrer_policy(options.referrer_policy);
  204. request.set_render_blocking(options.render_blocking);
  205. request.set_priority(options.fetch_priority);
  206. }
  207. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
  208. WebIDL::ExceptionOr<void> fetch_classic_script(JS::NonnullGCPtr<HTMLScriptElement> element, AK::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions options, CORSSettingAttribute cors_setting, String character_encoding, OnFetchScriptComplete on_complete)
  209. {
  210. auto& realm = element->realm();
  211. auto& vm = realm.vm();
  212. // 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.
  213. auto request = create_potential_CORS_request(vm, url, Fetch::Infrastructure::Request::Destination::Script, cors_setting);
  214. // 2. Set request's client to settings object.
  215. request->set_client(&settings_object);
  216. // 3. Set request's initiator type to "script".
  217. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  218. // 4. Set up the classic script request given request and options.
  219. set_up_classic_script_request(*request, options);
  220. // 5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure,
  221. // or a byte sequence bodyBytes:
  222. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  223. 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) {
  224. // 1. Set response to response's unsafe response.
  225. response = response->unsafe_response();
  226. // 2. If either of the following conditions are met:
  227. // - bodyBytes is null or failure; or
  228. // - response's status is not an ok status,
  229. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  230. // then run onComplete given null, and abort these steps.
  231. on_complete(nullptr);
  232. return;
  233. }
  234. // 3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.
  235. auto potential_mime_type_for_encoding = response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  236. // 4. Set character encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding
  237. // and character encoding.
  238. auto extracted_character_encoding = Fetch::Infrastructure::legacy_extract_an_encoding(potential_mime_type_for_encoding, character_encoding);
  239. // 5. Let source text be the result of decoding bodyBytes to Unicode, using character encoding as the fallback
  240. // encoding.
  241. auto fallback_decoder = TextCodec::decoder_for(extracted_character_encoding);
  242. VERIFY(fallback_decoder.has_value());
  243. 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();
  244. // 6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.
  245. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  246. // 7. Let script be the result of creating a classic script given source text, settings object, response's URL,
  247. // options, and muted errors.
  248. // FIXME: Pass options.
  249. auto response_url = response->url().value_or({});
  250. auto script = ClassicScript::create(response_url.to_deprecated_string(), source_text, settings_object, response_url, 1, muted_errors);
  251. // 8. Run onComplete given script.
  252. on_complete(script);
  253. };
  254. TRY(Fetch::Fetching::fetch(element->realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  255. return {};
  256. }
  257. // https://html.spec.whatwg.org/multipage/webappapis.html#internal-module-script-graph-fetching-procedure
  258. 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, OnFetchScriptComplete on_complete)
  259. {
  260. // 1. Let url be the result of resolving a module specifier given referringScript and moduleRequest.[[Specifier]].
  261. auto url = MUST(resolve_module_specifier(referring_script, module_request.module_specifier));
  262. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  263. // NOTE: Handled by MUST above.
  264. // 3. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  265. auto module_type = module_type_from_module_request(module_request);
  266. // 4. Assert: visited set contains (url, moduleType).
  267. VERIFY(visited_set.contains({ url, module_type }));
  268. // 5. Fetch a single module script given url, fetch client settings object, destination, options, referringScript's settings object,
  269. // referringScript's base URL, moduleRequest, false, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  270. // FIXME: Pass performFetch if given.
  271. fetch_single_module_script(realm, url, fetch_client_settings_object, destination, options, referring_script.settings_object(), referring_script.base_url(), module_request, TopLevelModule::No, [&realm, on_complete = move(on_complete), &fetch_client_settings_object, destination, visited_set](auto result) mutable {
  272. // onSingleFetchComplete given result is the following algorithm:
  273. // 1. If result is null, run onComplete with null, and abort these steps.
  274. if (!result) {
  275. on_complete(nullptr);
  276. return;
  277. }
  278. // 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.
  279. // FIXME: Pass performFetch if given.
  280. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  281. fetch_descendants_of_a_module_script(realm, module_script, fetch_client_settings_object, destination, visited_set, move(on_complete));
  282. });
  283. }
  284. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-a-module-script
  285. 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, OnFetchScriptComplete on_complete)
  286. {
  287. // 1. If module script's record is null, run onComplete with module script and return.
  288. if (!module_script.record()) {
  289. on_complete(&module_script);
  290. return;
  291. }
  292. // 2. Let record be module script's record.
  293. auto const& record = module_script.record();
  294. // 3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, run onComplete with module script and return.
  295. // FIXME: Currently record is always a cyclic module.
  296. if (record->requested_modules().is_empty()) {
  297. on_complete(&module_script);
  298. return;
  299. }
  300. // 4. Let moduleRequests be a new empty list.
  301. Vector<JS::ModuleRequest> module_requests;
  302. // 5. For each ModuleRequest Record requested of record.[[RequestedModules]],
  303. for (auto const& requested : record->requested_modules()) {
  304. // 1. Let url be the result of resolving a module specifier given module script and requested.[[Specifier]].
  305. auto url = MUST(resolve_module_specifier(module_script, requested.module_specifier));
  306. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  307. // NOTE: Handled by MUST above.
  308. // 3. Let moduleType be the result of running the module type from module request steps given requested.
  309. auto module_type = module_type_from_module_request(requested);
  310. // 4. If visited set does not contain (url, moduleType), then:
  311. if (!visited_set.contains({ url, module_type })) {
  312. // 1. Append requested to moduleRequests.
  313. module_requests.append(requested);
  314. // 2. Append (url, moduleType) to visited set.
  315. visited_set.set({ url, module_type });
  316. }
  317. }
  318. // FIXME: 6. Let options be the descendant script fetch options for module script's fetch options.
  319. ScriptFetchOptions options;
  320. // FIXME: 7. Assert: options is not null, as module script is a JavaScript module script.
  321. // 8. Let pendingCount be the length of moduleRequests.
  322. auto pending_count = module_requests.size();
  323. // 9. If pendingCount is zero, run onComplete with module script.
  324. if (pending_count == 0) {
  325. on_complete(&module_script);
  326. return;
  327. }
  328. // 10. Let failed be false.
  329. auto context = DescendantFetchingContext::create();
  330. context->set_pending_count(pending_count);
  331. context->set_failed(false);
  332. context->set_on_complete(move(on_complete));
  333. // 11. For each moduleRequest in moduleRequests, perform the internal module script graph fetching procedure given moduleRequest,
  334. // fetch client settings object, destination, options, module script, visited set, and onInternalFetchingComplete as defined below.
  335. // If performFetch was given, pass it along as well.
  336. for (auto const& module_request : module_requests) {
  337. // FIXME: Pass performFetch if given.
  338. fetch_internal_module_script_graph(realm, module_request, fetch_client_settings_object, destination, options, module_script, visited_set, [context, &module_script](auto result) mutable {
  339. // onInternalFetchingComplete given result is the following algorithm:
  340. // 1. If failed is true, then abort these steps.
  341. if (context->failed())
  342. return;
  343. // 2. If result is null, then set failed to true, run onComplete with null, and abort these steps.
  344. if (!result) {
  345. context->set_failed(true);
  346. context->on_complete(nullptr);
  347. return;
  348. }
  349. // 3. Assert: pendingCount is greater than zero.
  350. VERIFY(context->pending_count() > 0);
  351. // 4. Decrement pendingCount by one.
  352. context->decrement_pending_count();
  353. // 5. If pendingCount is zero, run onComplete with module script.
  354. if (context->pending_count() == 0)
  355. context->on_complete(&module_script);
  356. });
  357. }
  358. }
  359. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
  360. void fetch_single_module_script(JS::Realm& realm,
  361. AK::URL const& url,
  362. EnvironmentSettingsObject& fetch_client,
  363. Fetch::Infrastructure::Request::Destination destination,
  364. ScriptFetchOptions const& options,
  365. EnvironmentSettingsObject& settings_object,
  366. Web::Fetch::Infrastructure::Request::ReferrerType const& referrer,
  367. Optional<JS::ModuleRequest> const& module_request,
  368. TopLevelModule is_top_level,
  369. OnFetchScriptComplete on_complete)
  370. {
  371. // 1. Let moduleType be "javascript".
  372. DeprecatedString module_type = "javascript"sv;
  373. // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.
  374. if (module_request.has_value())
  375. module_type = module_type_from_module_request(*module_request);
  376. // 3. Assert: the result of running the module type allowed steps given moduleType and settingsObject is true.
  377. // Otherwise we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Assertions]]
  378. // in create a JavaScript module script or fetch a single imported module script.
  379. VERIFY(settings_object.module_type_allowed(module_type));
  380. // 4. Let moduleMap be settingsObject's module map.
  381. auto& module_map = settings_object.module_map();
  382. // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes,
  383. // then queue a task on the networking task source to proceed with running the following steps.
  384. if (module_map.is_fetching(url, module_type)) {
  385. module_map.wait_for_change(url, module_type, [on_complete = move(on_complete)](auto entry) {
  386. // FIXME: This should queue a task.
  387. // FIXME: This should run other steps, for now we just assume the script loaded.
  388. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript);
  389. on_complete(entry.module_script);
  390. });
  391. return;
  392. }
  393. // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.
  394. auto entry = module_map.get(url, module_type);
  395. if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) {
  396. on_complete(entry->module_script);
  397. return;
  398. }
  399. // 7. Set moduleMap[(url, moduleType)] to "fetching".
  400. module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr });
  401. // 8. Let request be a new request whose URL is url, destination is destination, mode is "cors", referrer is referrer, and client is fetchClient.
  402. auto request = Fetch::Infrastructure::Request::create(realm.vm());
  403. request->set_url(url);
  404. request->set_destination(destination);
  405. request->set_mode(Fetch::Infrastructure::Request::Mode::CORS);
  406. request->set_referrer(referrer);
  407. request->set_client(&fetch_client);
  408. // 9. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin".
  409. if ((destination == Fetch::Infrastructure::Request::Destination::Worker || destination == Fetch::Infrastructure::Request::Destination::SharedWorker || destination == Fetch::Infrastructure::Request::Destination::ServiceWorker) && is_top_level == TopLevelModule::Yes)
  410. request->set_mode(Fetch::Infrastructure::Request::Mode::SameOrigin);
  411. // 10. Set request's initiator type to "script".
  412. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  413. // 11. Set up the module script request given request and options.
  414. set_up_module_script_request(request, options);
  415. // 12. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.
  416. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  417. // In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:
  418. // FIXME: Run performFetch if given.
  419. Web::Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  420. fetch_algorithms_input.process_response_consume_body = [&module_map, url, module_type, &settings_object, on_complete = move(on_complete)](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
  421. // 1. If either of the following conditions are met:
  422. // - bodyBytes is null or failure; or
  423. // - response's status is not an ok status,
  424. if (body_bytes.has<Empty>() || body_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  425. // then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.
  426. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  427. on_complete(nullptr);
  428. return;
  429. }
  430. // 2. 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. // 3. Let mimeType be the result of extracting a MIME type from response's header list.
  435. auto mime_type = response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  436. // 4. Let moduleScript be null.
  437. JS::GCPtr<JavaScriptModuleScript> module_script;
  438. // FIXME: 5. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]
  439. // FIXME: 6. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.
  440. // 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, settingsObject, response's URL, and options.
  441. // FIXME: Pass options.
  442. if (mime_type->is_javascript() && module_type == "javascript")
  443. module_script = JavaScriptModuleScript::create(url.basename(), source_text, settings_object, response->url().value_or({})).release_value_but_fixme_should_propagate_errors();
  444. // 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.
  445. // 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.
  446. // 10. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.
  447. module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script });
  448. on_complete(module_script);
  449. };
  450. Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(realm.vm(), move(fetch_algorithms_input))).release_value_but_fixme_should_propagate_errors();
  451. }
  452. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
  453. void fetch_external_module_script_graph(JS::Realm& realm, AK::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions const& options, OnFetchScriptComplete on_complete)
  454. {
  455. // 1. Disallow further import maps given settings object.
  456. settings_object.disallow_further_import_maps();
  457. // 2. Fetch a single module script given url, settings object, "script", options, settings object, "client", true, and with the following steps given result:
  458. fetch_single_module_script(realm, url, settings_object, Fetch::Infrastructure::Request::Destination::Script, options, settings_object, Web::Fetch::Infrastructure::Request::Referrer::Client, {}, TopLevelModule::Yes, [&realm, &settings_object, on_complete = move(on_complete), url](auto result) mutable {
  459. // 1. If result is null, run onComplete given null, and abort these steps.
  460. if (!result) {
  461. on_complete(nullptr);
  462. return;
  463. }
  464. // 2. Let visited set be « (url, "javascript") ».
  465. HashTable<ModuleLocationTuple> visited_set;
  466. visited_set.set({ url, "javascript"sv });
  467. // 3. Fetch the descendants of and link result given settings object, "script", visited set, and onComplete.
  468. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  469. fetch_descendants_of_and_link_a_module_script(realm, module_script, settings_object, Fetch::Infrastructure::Request::Destination::Script, move(visited_set), move(on_complete));
  470. });
  471. }
  472. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-inline-module-script-graph
  473. void fetch_inline_module_script_graph(JS::Realm& realm, DeprecatedString const& filename, DeprecatedString const& source_text, AK::URL const& base_url, EnvironmentSettingsObject& settings_object, OnFetchScriptComplete on_complete)
  474. {
  475. // 1. Disallow further import maps given settings object.
  476. settings_object.disallow_further_import_maps();
  477. // 2. Let script be the result of creating a JavaScript module script using source text, settings object, base URL, and options.
  478. auto script = JavaScriptModuleScript::create(filename, source_text.view(), settings_object, base_url).release_value_but_fixme_should_propagate_errors();
  479. // 3. If script is null, run onComplete given null, and return.
  480. if (!script) {
  481. on_complete(nullptr);
  482. return;
  483. }
  484. // 4. Let visited set be an empty set.
  485. HashTable<ModuleLocationTuple> visited_set;
  486. // 5. Fetch the descendants of and link script, given settings object, the destination "script", visited set, and onComplete.
  487. fetch_descendants_of_and_link_a_module_script(realm, *script, settings_object, Fetch::Infrastructure::Request::Destination::Script, visited_set, move(on_complete));
  488. }
  489. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-and-link-a-module-script
  490. void fetch_descendants_of_and_link_a_module_script(JS::Realm& realm, JavaScriptModuleScript& module_script, EnvironmentSettingsObject& fetch_client_settings_object, Fetch::Infrastructure::Request::Destination destination, HashTable<ModuleLocationTuple> const& visited_set, OnFetchScriptComplete on_complete)
  491. {
  492. // 1. Fetch the descendants of module script, given fetch client settings object, destination, visited set, and onFetchDescendantsComplete as defined below.
  493. // If performFetch was given, pass it along as well.
  494. // FIXME: Pass performFetch if given.
  495. fetch_descendants_of_a_module_script(realm, module_script, fetch_client_settings_object, destination, visited_set, [&fetch_client_settings_object, on_complete = move(on_complete)](auto result) {
  496. // onFetchDescendantsComplete given result is the following algorithm:
  497. // 1. If result is null, then run onComplete given result, and abort these steps.
  498. if (!result) {
  499. on_complete(nullptr);
  500. return;
  501. }
  502. TemporaryExecutionContext execution_context { fetch_client_settings_object };
  503. // FIXME: 2. Let parse error be the result of finding the first parse error given result.
  504. // 3. If parse error is null, then:
  505. if (auto& module_script = verify_cast<JavaScriptModuleScript>(*result); module_script.record()) {
  506. // 1. Let record be result's record.
  507. auto const& record = *module_script.record();
  508. // 2. Perform record.Link().
  509. auto linking_result = const_cast<JS::SourceTextModule&>(record).link(result->vm());
  510. // If this throws an exception, set result's error to rethrow to that exception.
  511. if (linking_result.is_throw_completion()) {
  512. result->set_error_to_rethrow(linking_result.release_error().value().value());
  513. }
  514. } else {
  515. // FIXME: 4. Otherwise, set result's error to rethrow to parse error.
  516. TODO();
  517. }
  518. // 5. Run onComplete given result.
  519. on_complete(result);
  520. });
  521. }
  522. }