WindowOrWorkerGlobalScope.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Base64.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/String.h>
  11. #include <AK/Utf8View.h>
  12. #include <AK/Vector.h>
  13. #include <LibTextCodec/Decoder.h>
  14. #include <LibWeb/Bindings/MainThreadVM.h>
  15. #include <LibWeb/Fetch/FetchMethod.h>
  16. #include <LibWeb/Forward.h>
  17. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  18. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  19. #include <LibWeb/HTML/Scripting/Environments.h>
  20. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  21. #include <LibWeb/HTML/StructuredSerialize.h>
  22. #include <LibWeb/HTML/Timer.h>
  23. #include <LibWeb/HTML/Window.h>
  24. #include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
  25. #include <LibWeb/Infra/Base64.h>
  26. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  27. #include <LibWeb/UserTiming/PerformanceMark.h>
  28. #include <LibWeb/WebIDL/AbstractOperations.h>
  29. #include <LibWeb/WebIDL/DOMException.h>
  30. #include <LibWeb/WebIDL/ExceptionOr.h>
  31. namespace Web::HTML {
  32. WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;
  33. // Please keep these in alphabetical order based on the entry type :^)
  34. #define ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES \
  35. __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::mark, UserTiming::PerformanceMark)
  36. JS::ThrowCompletionOr<void> WindowOrWorkerGlobalScopeMixin::initialize(JS::Realm& realm)
  37. {
  38. auto& vm = realm.vm();
  39. #define __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(entry_type, cpp_class) \
  40. TRY_OR_THROW_OOM(vm, m_performance_entry_buffer_map.try_set(entry_type, PerformanceTimeline::PerformanceEntryTuple { \
  41. .performance_entry_buffer = {}, \
  42. .max_buffer_size = cpp_class::max_buffer_size(), \
  43. .available_from_timeline = cpp_class::available_from_timeline(), \
  44. .dropped_entries_count = 0, \
  45. }));
  46. ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
  47. #undef __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
  48. return {};
  49. }
  50. void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
  51. {
  52. for (auto& it : m_timers)
  53. visitor.visit(it.value);
  54. }
  55. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  56. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::origin() const
  57. {
  58. auto& vm = this_impl().vm();
  59. // The origin getter steps are to return this's relevant settings object's origin, serialized.
  60. return TRY_OR_THROW_OOM(vm, String::from_deprecated_string(relevant_settings_object(this_impl()).origin().serialize()));
  61. }
  62. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  63. bool WindowOrWorkerGlobalScopeMixin::is_secure_context() const
  64. {
  65. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  66. return HTML::is_secure_context(relevant_settings_object(this_impl()));
  67. }
  68. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
  69. bool WindowOrWorkerGlobalScopeMixin::cross_origin_isolated() const
  70. {
  71. // The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.
  72. return relevant_settings_object(this_impl()).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes;
  73. }
  74. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  75. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::btoa(String const& data) const
  76. {
  77. auto& vm = this_impl().vm();
  78. auto& realm = *vm.current_realm();
  79. // The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.
  80. Vector<u8> byte_string;
  81. byte_string.ensure_capacity(data.bytes().size());
  82. for (u32 code_point : Utf8View(data)) {
  83. if (code_point > 0xff)
  84. return WebIDL::InvalidCharacterError::create(realm, "Data contains characters outside the range U+0000 and U+00FF");
  85. byte_string.append(code_point);
  86. }
  87. // Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data,
  88. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  89. return TRY_OR_THROW_OOM(vm, encode_base64(byte_string.span()));
  90. }
  91. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  92. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::atob(String const& data) const
  93. {
  94. auto& vm = this_impl().vm();
  95. auto& realm = *vm.current_realm();
  96. // 1. Let decodedData be the result of running forgiving-base64 decode on data.
  97. auto decoded_data = Infra::decode_forgiving_base64(data.bytes_as_string_view());
  98. // 2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  99. if (decoded_data.is_error())
  100. return WebIDL::InvalidCharacterError::create(realm, "Input string is not valid base64 data");
  101. // 3. Return decodedData.
  102. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  103. auto decoder = TextCodec::decoder_for("windows-1252"sv);
  104. VERIFY(decoder.has_value());
  105. return TRY_OR_THROW_OOM(vm, decoder->to_utf8(decoded_data.value()));
  106. }
  107. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
  108. void WindowOrWorkerGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callback)
  109. {
  110. auto& vm = this_impl().vm();
  111. auto& realm = *vm.current_realm();
  112. JS::GCPtr<DOM::Document> document;
  113. if (is<Window>(this_impl()))
  114. document = &static_cast<Window&>(this_impl()).associated_document();
  115. // The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.
  116. HTML::queue_a_microtask(document, [&callback, &realm] {
  117. auto result = WebIDL::invoke_callback(callback, {});
  118. if (result.is_error())
  119. HTML::report_exception(result, realm);
  120. });
  121. }
  122. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  123. WebIDL::ExceptionOr<JS::Value> WindowOrWorkerGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  124. {
  125. auto& vm = this_impl().vm();
  126. (void)options;
  127. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  128. // FIXME: Use WithTransfer variant of the AO
  129. auto serialized = TRY(structured_serialize(vm, value));
  130. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  131. // FIXME: Use WithTransfer variant of the AO
  132. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl()), {}));
  133. // 3. Return deserializeRecord.[[Deserialized]].
  134. return deserialized;
  135. }
  136. JS::NonnullGCPtr<JS::Promise> WindowOrWorkerGlobalScopeMixin::fetch(Fetch::RequestInfo const& input, Fetch::RequestInit const& init) const
  137. {
  138. auto& vm = this_impl().vm();
  139. return Fetch::fetch(vm, input, init);
  140. }
  141. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  142. i32 WindowOrWorkerGlobalScopeMixin::set_timeout(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  143. {
  144. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  145. }
  146. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  147. i32 WindowOrWorkerGlobalScopeMixin::set_interval(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  148. {
  149. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  150. }
  151. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  152. void WindowOrWorkerGlobalScopeMixin::clear_timeout(i32 id)
  153. {
  154. m_timers.remove(id);
  155. }
  156. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  157. void WindowOrWorkerGlobalScopeMixin::clear_interval(i32 id)
  158. {
  159. m_timers.remove(id);
  160. }
  161. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  162. i32 WindowOrWorkerGlobalScopeMixin::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id, Optional<AK::URL> base_url)
  163. {
  164. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  165. // 2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of active timers.
  166. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  167. // FIXME: 3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.
  168. // 4. If timeout is less than 0, then set timeout to 0.
  169. if (timeout < 0)
  170. timeout = 0;
  171. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  172. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  173. // FIXME: Implement this when step 9.3.2 is implemented.
  174. // FIXME: The active script becomes null on repeated setInterval callbacks. In JS::VM::get_active_script_or_module,
  175. // the execution context stack is empty on the repeated invocations, thus it returns null. We will need
  176. // to figure out why it becomes empty. But all we need from the active script is the base URL, so we
  177. // grab it on the first invocation an reuse it on repeated invocations.
  178. if (!base_url.has_value()) {
  179. // 7. Let initiating script be the active script.
  180. auto const* initiating_script = Web::Bindings::active_script();
  181. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  182. VERIFY(initiating_script);
  183. base_url = initiating_script->base_url();
  184. }
  185. // 9. Let task be a task that runs the following substeps:
  186. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id, base_url = move(base_url)]() mutable {
  187. // 1. If id does not exist in global's map of active timers, then abort these steps.
  188. if (!m_timers.contains(id))
  189. return;
  190. handler.visit(
  191. // 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
  192. [&](JS::Handle<WebIDL::CallbackType> const& callback) {
  193. if (auto result = WebIDL::invoke_callback(*callback, &this_impl(), arguments); result.is_error())
  194. report_exception(result, this_impl().realm());
  195. },
  196. // 3. Otherwise:
  197. [&](String const& source) {
  198. // 1. Assert: handler is a string.
  199. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  200. // 3. Let settings object be global's relevant settings object.
  201. auto& settings_object = relevant_settings_object(this_impl());
  202. // 4. Let base URL be initiating script's base URL.
  203. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  204. VERIFY(base_url.has_value());
  205. // 6. Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, and referrer policy is initiating script's fetch options's referrer policy.
  206. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  207. auto script = ClassicScript::create(base_url->basename(), source, settings_object, *base_url);
  208. // 8. Run the classic script script.
  209. (void)script->run();
  210. });
  211. // 4. If id does not exist in global's map of active timers, then abort these steps.
  212. if (!m_timers.contains(id))
  213. return;
  214. switch (repeat) {
  215. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  216. case Repeat::Yes:
  217. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id, move(base_url));
  218. break;
  219. // 6. Otherwise, remove global's map of active timers[id].
  220. case Repeat::No:
  221. m_timers.remove(id);
  222. break;
  223. }
  224. };
  225. // FIXME: 10. Increment nesting level by one.
  226. // FIXME: 11. Set task's timer nesting level to nesting level.
  227. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  228. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  229. queue_global_task(Task::Source::TimerTask, this_impl(), move(task));
  230. };
  231. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  232. auto timer = Timer::create(this_impl(), timeout, move(completion_step), id);
  233. m_timers.set(id, timer);
  234. timer->start();
  235. // 14. Return id.
  236. return id;
  237. }
  238. // 1. https://www.w3.org/TR/performance-timeline/#dfn-relevant-performance-entry-tuple
  239. PerformanceTimeline::PerformanceEntryTuple& WindowOrWorkerGlobalScopeMixin::relevant_performance_entry_tuple(FlyString const& entry_type)
  240. {
  241. // 1. Let map be the performance entry buffer map associated with globalObject.
  242. // 2. Return the result of getting the value of an entry from map, given entryType as the key.
  243. auto tuple = m_performance_entry_buffer_map.get(entry_type);
  244. // This shouldn't be called with entry types that aren't in `ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES`.
  245. VERIFY(tuple.has_value());
  246. return tuple.value();
  247. }
  248. // https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry
  249. WebIDL::ExceptionOr<void> WindowOrWorkerGlobalScopeMixin::queue_performance_entry(JS::NonnullGCPtr<PerformanceTimeline::PerformanceEntry> new_entry)
  250. {
  251. auto& vm = new_entry->vm();
  252. // FIXME: 1. Let interested observers be an initially empty set of PerformanceObserver objects.
  253. // 2. Let entryType be newEntry’s entryType value.
  254. auto const& entry_type = new_entry->entry_type();
  255. // 3. Let relevantGlobal be newEntry's relevant global object.
  256. // NOTE: Already is `this`.
  257. // FIXME: 4. For each registered performance observer regObs in relevantGlobal's list of registered performance observer
  258. // objects:
  259. // 1. If regObs's options list contains a PerformanceObserverInit options whose entryTypes member includes entryType
  260. // or whose type member equals to entryType:
  261. // 1. If should add entry with newEntry and options returns true, append regObs's observer to interested observers.
  262. // FIXME: 5. For each observer in interested observers:
  263. // 1. Append newEntry to observer's observer buffer.
  264. // 6. Let tuple be the relevant performance entry tuple of entryType and relevantGlobal.
  265. auto& tuple = relevant_performance_entry_tuple(entry_type);
  266. // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple
  267. // as input.
  268. bool is_buffer_full = tuple.is_full();
  269. // 8. Let shouldAdd be the result of should add entry with newEntry as input.
  270. auto should_add = new_entry->should_add_entry();
  271. // 9. If isBufferFull is false and shouldAdd is true, append newEntry to tuple's performance entry buffer.
  272. if (!is_buffer_full && should_add == PerformanceTimeline::ShouldAddEntry::Yes)
  273. TRY_OR_THROW_OOM(vm, tuple.performance_entry_buffer.try_append(JS::make_handle(new_entry)));
  274. // FIXME: 10. Queue the PerformanceObserver task with relevantGlobal as input.
  275. return {};
  276. }
  277. void WindowOrWorkerGlobalScopeMixin::clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type)
  278. {
  279. auto& tuple = relevant_performance_entry_tuple(entry_type);
  280. tuple.performance_entry_buffer.clear();
  281. }
  282. void WindowOrWorkerGlobalScopeMixin::remove_entries_from_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type, String entry_name)
  283. {
  284. auto& tuple = relevant_performance_entry_tuple(entry_type);
  285. tuple.performance_entry_buffer.remove_all_matching([&entry_name](JS::Handle<PerformanceTimeline::PerformanceEntry> const& entry) {
  286. return entry->name() == entry_name;
  287. });
  288. }
  289. // https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-by-name-and-type
  290. static ErrorOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> filter_buffer_by_name_and_type(Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> const& buffer, Optional<String> name, Optional<String> type)
  291. {
  292. // 1. Let result be an initially empty list.
  293. Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> result;
  294. // 2. For each PerformanceEntry entry in buffer, run the following steps:
  295. for (auto const& entry : buffer) {
  296. // 1. If type is not null and if type is not identical to entry's entryType attribute, continue to next entry.
  297. if (type.has_value() && type.value() != entry->entry_type())
  298. continue;
  299. // 2. If name is not null and if name is not identical to entry's name attribute, continue to next entry.
  300. if (name.has_value() && name.value() != entry->name())
  301. continue;
  302. // 3. append entry to result.
  303. TRY(result.try_append(entry));
  304. }
  305. // 3. Sort results's entries in chronological order with respect to startTime
  306. quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
  307. return left_entry->start_time() < right_entry->start_time();
  308. });
  309. // 4. Return result.
  310. return result;
  311. }
  312. // https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-map-by-name-and-type
  313. ErrorOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> WindowOrWorkerGlobalScopeMixin::filter_buffer_map_by_name_and_type(Optional<String> name, Optional<String> type) const
  314. {
  315. // 1. Let result be an initially empty list.
  316. Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> result;
  317. // 2. Let map be the performance entry buffer map associated with the relevant global object of this.
  318. auto const& map = m_performance_entry_buffer_map;
  319. // 3. Let tuple list be an empty list.
  320. Vector<PerformanceTimeline::PerformanceEntryTuple const&> tuple_list;
  321. // 4. If type is not null, append the result of getting the value of entry on map given type as key to tuple list.
  322. // Otherwise, assign the result of get the values on map to tuple list.
  323. if (type.has_value()) {
  324. auto maybe_tuple = map.get(type.value());
  325. if (maybe_tuple.has_value())
  326. TRY(tuple_list.try_append(maybe_tuple.release_value()));
  327. } else {
  328. for (auto const& it : map)
  329. TRY(tuple_list.try_append(it.value));
  330. }
  331. // 5. For each tuple in tuple list, run the following steps:
  332. for (auto const& tuple : tuple_list) {
  333. // 1. Let buffer be tuple's performance entry buffer.
  334. auto const& buffer = tuple.performance_entry_buffer;
  335. // 2. If tuple's availableFromTimeline is false, continue to the next tuple.
  336. if (tuple.available_from_timeline == PerformanceTimeline::AvailableFromTimeline::No)
  337. continue;
  338. // 3. Let entries be the result of running filter buffer by name and type with buffer, name and type as inputs.
  339. auto entries = TRY(filter_buffer_by_name_and_type(buffer, name, type));
  340. // 4. For each entry in entries, append entry to result.
  341. TRY(result.try_extend(entries));
  342. }
  343. // 6. Sort results's entries in chronological order with respect to startTime
  344. quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
  345. return left_entry->start_time() < right_entry->start_time();
  346. });
  347. // 7. Return result.
  348. return result;
  349. }
  350. }