Fetching.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (c) 2022, networkException <networkexception@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/URLParser.h>
  7. #include <LibWeb/HTML/Scripting/Environments.h>
  8. #include <LibWeb/HTML/Scripting/Fetching.h>
  9. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  10. #include <LibWeb/Loader/LoadRequest.h>
  11. #include <LibWeb/Loader/ResourceLoader.h>
  12. #include <LibWeb/MimeSniff/MimeType.h>
  13. namespace Web::HTML {
  14. // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request
  15. String module_type_from_module_request(JS::ModuleRequest const& module_request)
  16. {
  17. // 1. Let moduleType be "javascript".
  18. String module_type = "javascript"sv;
  19. // 2. If moduleRequest.[[Assertions]] has a Record entry such that entry.[[Key]] is "type", then:
  20. for (auto const& entry : module_request.assertions) {
  21. if (entry.key != "type"sv)
  22. continue;
  23. // 1. If entry.[[Value]] is "javascript", then set moduleType to null.
  24. if (entry.value == "javascript"sv)
  25. module_type = nullptr;
  26. // 2. Otherwise, set moduleType to entry.[[Value]].
  27. else
  28. module_type = entry.value;
  29. }
  30. // 3. Return moduleType.
  31. return module_type;
  32. }
  33. // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
  34. AK::URL resolve_module_specifier(JS::ModuleRequest const& module_request, AK::URL const& base_url)
  35. {
  36. auto specifier = module_request.module_specifier;
  37. // 1. Apply the URL parser to specifier. If the result is not failure, return the result.
  38. auto result = URLParser::parse(specifier);
  39. if (result.is_valid())
  40. return result;
  41. // 2. If specifier does not start with the character U+002F SOLIDUS (/), the two-character sequence U+002E FULL STOP,
  42. // U+002F SOLIDUS (./), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP, U+002F SOLIDUS (../), return failure.
  43. if (!specifier.starts_with("/"sv) && !specifier.starts_with("./"sv) && !specifier.starts_with("../"sv))
  44. return {};
  45. // 3. Return the result of applying the URL parser to specifier with base URL.
  46. return URLParser::parse(specifier, &base_url);
  47. }
  48. // https://html.spec.whatwg.org/multipage/webappapis.html#internal-module-script-graph-fetching-procedure
  49. void fetch_internal_module_script_graph(JS::ModuleRequest const& module_request, EnvironmentSettingsObject& fetch_client_settings_object, StringView destination, EnvironmentSettingsObject& module_script_settings_object, HashTable<ModuleLocationTuple> const& visited_set, AK::URL const& referrer, ModuleCallback on_complete)
  50. {
  51. // 1. Let url be the result of resolving a module specifier given referrer and moduleRequest.[[Specifier]].
  52. auto url = resolve_module_specifier(module_request, referrer);
  53. // 2. Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments.
  54. VERIFY(url.is_valid());
  55. // 3. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  56. auto module_type = module_type_from_module_request(module_request);
  57. // 4. Assert: visited set contains (url, moduleType).
  58. VERIFY(visited_set.contains({ url, module_type }));
  59. // 5. Fetch a single module script given url, fetch client settings object, destination, options,module map settings object, referrer,
  60. // moduleRequest, false, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  61. // FIXME: Pass options.
  62. fetch_single_module_script(url, fetch_client_settings_object, destination, module_script_settings_object, referrer, module_request, TopLevelModule::No, [on_complete = move(on_complete), &fetch_client_settings_object, destination, visited_set](auto const* result) mutable {
  63. // onSingleFetchComplete given result is the following algorithm:
  64. // 1. If result is null, run onComplete with null, and abort these steps.
  65. if (!result) {
  66. on_complete(nullptr);
  67. return;
  68. }
  69. // 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.
  70. // FIXME: Pass performFetch if given.
  71. fetch_descendants_of_a_module_script(*result, fetch_client_settings_object, destination, visited_set, move(on_complete));
  72. });
  73. }
  74. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-a-module-script
  75. void fetch_descendants_of_a_module_script(JavaScriptModuleScript const& module_script, EnvironmentSettingsObject& fetch_client_settings_object, StringView destination, HashTable<ModuleLocationTuple> visited_set, ModuleCallback on_complete)
  76. {
  77. // 1. If module script's record is null, run onComplete with module script and return.
  78. if (!module_script.record()) {
  79. on_complete(&module_script);
  80. return;
  81. }
  82. // 2. Let record be module script's record.
  83. auto const& record = module_script.record();
  84. // 3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, run onComplete with module script and return.
  85. // FIXME: Currently record is always a cyclic module.
  86. if (record->requested_modules().is_empty()) {
  87. on_complete(&module_script);
  88. return;
  89. }
  90. // 4. Let moduleRequests be a new empty list.
  91. Vector<JS::ModuleRequest> module_requests;
  92. // 5. For each ModuleRequest Record requested of record.[[RequestedModules]],
  93. for (auto const& requested : record->requested_modules()) {
  94. // 1. Let url be the result of resolving a module specifier given module script's base URL and requested.[[Specifier]].
  95. auto url = resolve_module_specifier(requested, module_script.base_url());
  96. // 2. Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments.
  97. VERIFY(url.is_valid());
  98. // 3. Let moduleType be the result of running the module type from module request steps given requested.
  99. auto module_type = module_type_from_module_request(requested);
  100. // 4. If visited set does not contain (url, moduleType), then:
  101. if (!visited_set.contains({ url, module_type })) {
  102. // 1. Append requested to moduleRequests.
  103. module_requests.append(requested);
  104. // 2. Append (url, moduleType) to visited set.
  105. visited_set.set({ url, module_type });
  106. }
  107. }
  108. // FIXME: 6. Let options be the descendant script fetch options for module script's fetch options.
  109. // FIXME: 7. Assert: options is not null, as module script is a JavaScript module script.
  110. // 8. Let pendingCount be the length of moduleRequests.
  111. auto pending_count = module_requests.size();
  112. // 9. If pendingCount is zero, run onComplete with module script.
  113. if (pending_count == 0) {
  114. on_complete(&module_script);
  115. return;
  116. }
  117. // 10. Let failed be false.
  118. auto context = DescendantFetchingContext::create();
  119. context->set_pending_count(pending_count);
  120. context->set_failed(false);
  121. context->set_on_complete(move(on_complete));
  122. // 11. For each moduleRequest in moduleRequests, perform the internal module script graph fetching procedure given moduleRequest,
  123. // fetch client settings object, destination, options, module script's settings object, visited set, module script's base URL,
  124. // and onInternalFetchingComplete as defined below. If performFetch was given, pass it along as well.
  125. for (auto const& module_request : module_requests) {
  126. // FIXME: Pass options and performFetch if given.
  127. fetch_internal_module_script_graph(module_request, fetch_client_settings_object, destination, const_cast<JavaScriptModuleScript&>(module_script).settings_object(), visited_set, module_script.base_url(), [context, &module_script](auto const* result) mutable {
  128. // onInternalFetchingComplete given result is the following algorithm:
  129. // 1. If failed is true, then abort these steps.
  130. if (context->failed())
  131. return;
  132. // 2. If result is null, then set failed to true, run onComplete with null, and abort these steps.
  133. if (!result) {
  134. context->set_failed(true);
  135. context->on_complete(nullptr);
  136. return;
  137. }
  138. // 3. Assert: pendingCount is greater than zero.
  139. VERIFY(context->pending_count() > 0);
  140. // 4. Decrement pendingCount by one.
  141. context->decrement_pending_count();
  142. // 5. If pendingCount is zero, run onComplete with module script.
  143. if (context->pending_count() == 0)
  144. context->on_complete(&module_script);
  145. });
  146. }
  147. }
  148. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
  149. void fetch_single_module_script(AK::URL const& url, EnvironmentSettingsObject&, StringView, EnvironmentSettingsObject& module_map_settings_object, AK::URL const&, Optional<JS::ModuleRequest> const& module_request, TopLevelModule, ModuleCallback on_complete)
  150. {
  151. // 1. Let moduleType be "javascript".
  152. String module_type = "javascript"sv;
  153. // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.
  154. if (module_request.has_value())
  155. module_type = module_type_from_module_request(*module_request);
  156. // 3. Assert: the result of running the module type allowed steps given moduleType and module map settings object is true.
  157. // Otherwise we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Assertions]]
  158. // in create a JavaScript module script or fetch an import() module script graph.
  159. VERIFY(module_map_settings_object.module_type_allowed(module_type));
  160. // 4. Let moduleMap be module map settings object's module map.
  161. auto& module_map = module_map_settings_object.module_map();
  162. // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes,
  163. // then queue a task on the networking task source to proceed with running the following steps.
  164. if (module_map.is_fetching(url, module_type)) {
  165. module_map.wait_for_change(url, module_type, [on_complete = move(on_complete)](auto entry) {
  166. // FIXME: This should queue a task.
  167. // FIXME: This should run other steps, for now we just assume the script loaded.
  168. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript);
  169. on_complete(entry.module_script);
  170. });
  171. return;
  172. }
  173. // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.
  174. auto entry = module_map.get(url, module_type);
  175. if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) {
  176. on_complete(entry->module_script);
  177. return;
  178. }
  179. // 7. Set moduleMap[(url, moduleType)] to "fetching".
  180. module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr });
  181. // FIXME: Implement non ad-hoc version of steps 8 to 20.
  182. auto request = LoadRequest::create_for_url_on_page(url, nullptr);
  183. ResourceLoader::the().load(
  184. request,
  185. [url, module_type, &module_map_settings_object, on_complete = move(on_complete), &module_map](StringView data, auto& response_headers, auto) {
  186. if (data.is_null()) {
  187. dbgln("Failed to load module {}", url);
  188. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  189. on_complete(nullptr);
  190. return;
  191. }
  192. auto content_type_header = response_headers.get("Content-Type");
  193. if (!content_type_header.has_value()) {
  194. dbgln("Module has no content type! {}", url);
  195. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  196. on_complete(nullptr);
  197. return;
  198. }
  199. if (MimeSniff::is_javascript_mime_type_essence_match(*content_type_header) && module_type == "javascript"sv) {
  200. auto module_script = JavaScriptModuleScript::create(url.basename(), data, module_map_settings_object, url);
  201. module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script });
  202. on_complete(module_script);
  203. return;
  204. }
  205. dbgln("Module has no JS content type! {} of type {}, with content {}", url, module_type, *content_type_header);
  206. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  207. on_complete(nullptr);
  208. },
  209. [module_type, url](auto&, auto) {
  210. dbgln("Failed to load module script");
  211. TODO();
  212. });
  213. }
  214. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
  215. void fetch_external_module_script_graph(AK::URL const& url, EnvironmentSettingsObject& settings_object, ModuleCallback on_complete)
  216. {
  217. // 1. Fetch a single module script given url, settings object, "script", options, settings object, "client", true, and with the following steps given result:
  218. // FIXME: Pass options.
  219. fetch_single_module_script(url, settings_object, "script"sv, settings_object, "client"sv, {}, TopLevelModule::Yes, [&settings_object, on_complete = move(on_complete), url](auto* result) mutable {
  220. // 1. If result is null, run onComplete given null, and abort these steps.
  221. if (!result) {
  222. on_complete(nullptr);
  223. return;
  224. }
  225. // 2. Let visited set be « (url, "javascript") ».
  226. HashTable<ModuleLocationTuple> visited_set;
  227. visited_set.set({ url, "javascript"sv });
  228. // 3. Fetch the descendants of and link result given settings object, "script", visited set, and onComplete.
  229. fetch_descendants_of_and_link_a_module_script(*result, settings_object, "script"sv, move(visited_set), move(on_complete));
  230. });
  231. }
  232. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-inline-module-script-graph
  233. void fetch_inline_module_script_graph(String const& filename, String const& source_text, AK::URL const& base_url, EnvironmentSettingsObject& settings_object, ModuleCallback on_complete)
  234. {
  235. // 1. Let script be the result of creating a JavaScript module script using source text, settings object, base URL, and options.
  236. auto script = JavaScriptModuleScript::create(filename, source_text.view(), settings_object, base_url);
  237. // 2. If script is null, run onComplete given null, and return.
  238. if (!script) {
  239. on_complete(nullptr);
  240. return;
  241. }
  242. // 3. Let visited set be an empty set.
  243. HashTable<ModuleLocationTuple> visited_set;
  244. // 4. Fetch the descendants of and link script, given settings object, the destination "script", visited set, and onComplete.
  245. fetch_descendants_of_and_link_a_module_script(*script, settings_object, "script"sv, visited_set, move(on_complete));
  246. }
  247. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-and-link-a-module-script
  248. void fetch_descendants_of_and_link_a_module_script(JavaScriptModuleScript const& module_script, EnvironmentSettingsObject& fetch_client_settings_object, StringView destination, HashTable<ModuleLocationTuple> const& visited_set, ModuleCallback on_complete)
  249. {
  250. // 1. Fetch the descendants of module script, given fetch client settings object, destination, visited set, and onFetchDescendantsComplete as defined below.
  251. // If performFetch was given, pass it along as well.
  252. // FIXME: Pass performFetch if given.
  253. fetch_descendants_of_a_module_script(module_script, fetch_client_settings_object, destination, visited_set, [&fetch_client_settings_object, on_complete = move(on_complete)](JavaScriptModuleScript const* result) {
  254. // onFetchDescendantsComplete given result is the following algorithm:
  255. // 1. If result is null, then run onComplete given result, and abort these steps.
  256. if (!result) {
  257. on_complete(nullptr);
  258. return;
  259. }
  260. // FIXME: 2. Let parse error be the result of finding the first parse error given result.
  261. // 3. If parse error is null, then:
  262. if (result->record()) {
  263. // 1. Let record be result's record.
  264. auto const& record = *result->record();
  265. // NOTE: Although the spec does not say this we have to have a proper execution context when linking so we modify the stack here.
  266. // FIXME: Determine whether we are missing something from the spec or the spec is missing this step.
  267. fetch_client_settings_object.realm().vm().push_execution_context(fetch_client_settings_object.realm_execution_context());
  268. // 2. Perform record.Link().
  269. auto linking_result = const_cast<JS::SourceTextModule&>(record).link(result->vm());
  270. fetch_client_settings_object.realm().vm().pop_execution_context();
  271. // TODO: If this throws an exception, set result's error to rethrow to that exception.
  272. if (linking_result.is_error())
  273. TODO();
  274. } else {
  275. // FIXME: 4. Otherwise, set result's error to rethrow to parse error.
  276. TODO();
  277. }
  278. // 5. Run onComplete given result.
  279. on_complete(result);
  280. });
  281. }
  282. }