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