WindowOrWorkerGlobalScope.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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/Scripting/Fetching.h>
  22. #include <LibWeb/HTML/StructuredSerialize.h>
  23. #include <LibWeb/HTML/Timer.h>
  24. #include <LibWeb/HTML/Window.h>
  25. #include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
  26. #include <LibWeb/HighResolutionTime/SupportedPerformanceTypes.h>
  27. #include <LibWeb/Infra/Base64.h>
  28. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  29. #include <LibWeb/PerformanceTimeline/PerformanceObserver.h>
  30. #include <LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h>
  31. #include <LibWeb/UserTiming/PerformanceMark.h>
  32. #include <LibWeb/UserTiming/PerformanceMeasure.h>
  33. #include <LibWeb/WebIDL/AbstractOperations.h>
  34. #include <LibWeb/WebIDL/DOMException.h>
  35. #include <LibWeb/WebIDL/ExceptionOr.h>
  36. namespace Web::HTML {
  37. WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;
  38. void WindowOrWorkerGlobalScopeMixin::initialize(JS::Realm&)
  39. {
  40. #define __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(entry_type, cpp_class) \
  41. m_performance_entry_buffer_map.set(entry_type, \
  42. PerformanceTimeline::PerformanceEntryTuple { \
  43. .performance_entry_buffer = {}, \
  44. .max_buffer_size = cpp_class::max_buffer_size(), \
  45. .available_from_timeline = cpp_class::available_from_timeline(), \
  46. .dropped_entries_count = 0, \
  47. });
  48. ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
  49. #undef __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
  50. }
  51. void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
  52. {
  53. for (auto& it : m_timers)
  54. visitor.visit(it.value);
  55. for (auto& observer : m_registered_performance_observer_objects)
  56. visitor.visit(observer);
  57. for (auto& entry : m_performance_entry_buffer_map)
  58. entry.value.visit_edges(visitor);
  59. }
  60. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  61. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::origin() const
  62. {
  63. auto& vm = this_impl().vm();
  64. // The origin getter steps are to return this's relevant settings object's origin, serialized.
  65. return TRY_OR_THROW_OOM(vm, String::from_deprecated_string(relevant_settings_object(this_impl()).origin().serialize()));
  66. }
  67. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  68. bool WindowOrWorkerGlobalScopeMixin::is_secure_context() const
  69. {
  70. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  71. return HTML::is_secure_context(relevant_settings_object(this_impl()));
  72. }
  73. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
  74. bool WindowOrWorkerGlobalScopeMixin::cross_origin_isolated() const
  75. {
  76. // The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.
  77. return relevant_settings_object(this_impl()).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes;
  78. }
  79. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  80. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::btoa(String const& data) const
  81. {
  82. auto& vm = this_impl().vm();
  83. auto& realm = *vm.current_realm();
  84. // The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.
  85. Vector<u8> byte_string;
  86. byte_string.ensure_capacity(data.bytes().size());
  87. for (u32 code_point : Utf8View(data)) {
  88. if (code_point > 0xff)
  89. return WebIDL::InvalidCharacterError::create(realm, "Data contains characters outside the range U+0000 and U+00FF"_fly_string);
  90. byte_string.append(code_point);
  91. }
  92. // 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,
  93. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  94. return TRY_OR_THROW_OOM(vm, encode_base64(byte_string.span()));
  95. }
  96. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  97. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::atob(String const& data) const
  98. {
  99. auto& vm = this_impl().vm();
  100. auto& realm = *vm.current_realm();
  101. // 1. Let decodedData be the result of running forgiving-base64 decode on data.
  102. auto decoded_data = Infra::decode_forgiving_base64(data.bytes_as_string_view());
  103. // 2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  104. if (decoded_data.is_error())
  105. return WebIDL::InvalidCharacterError::create(realm, "Input string is not valid base64 data"_fly_string);
  106. // 3. Return decodedData.
  107. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  108. auto decoder = TextCodec::decoder_for("windows-1252"sv);
  109. VERIFY(decoder.has_value());
  110. return TRY_OR_THROW_OOM(vm, decoder->to_utf8(decoded_data.value()));
  111. }
  112. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
  113. void WindowOrWorkerGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callback)
  114. {
  115. auto& vm = this_impl().vm();
  116. auto& realm = *vm.current_realm();
  117. JS::GCPtr<DOM::Document> document;
  118. if (is<Window>(this_impl()))
  119. document = &static_cast<Window&>(this_impl()).associated_document();
  120. // The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.
  121. HTML::queue_a_microtask(document, [&callback, &realm] {
  122. auto result = WebIDL::invoke_callback(callback, {});
  123. if (result.is_error())
  124. HTML::report_exception(result, realm);
  125. });
  126. }
  127. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  128. WebIDL::ExceptionOr<JS::Value> WindowOrWorkerGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  129. {
  130. auto& vm = this_impl().vm();
  131. (void)options;
  132. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  133. // FIXME: Use WithTransfer variant of the AO
  134. auto serialized = TRY(structured_serialize(vm, value));
  135. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  136. // FIXME: Use WithTransfer variant of the AO
  137. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl()), {}));
  138. // 3. Return deserializeRecord.[[Deserialized]].
  139. return deserialized;
  140. }
  141. JS::NonnullGCPtr<JS::Promise> WindowOrWorkerGlobalScopeMixin::fetch(Fetch::RequestInfo const& input, Fetch::RequestInit const& init) const
  142. {
  143. auto& vm = this_impl().vm();
  144. return Fetch::fetch(vm, input, init);
  145. }
  146. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  147. i32 WindowOrWorkerGlobalScopeMixin::set_timeout(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  148. {
  149. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  150. }
  151. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  152. i32 WindowOrWorkerGlobalScopeMixin::set_interval(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  153. {
  154. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  155. }
  156. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  157. void WindowOrWorkerGlobalScopeMixin::clear_timeout(i32 id)
  158. {
  159. m_timers.remove(id);
  160. }
  161. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  162. void WindowOrWorkerGlobalScopeMixin::clear_interval(i32 id)
  163. {
  164. m_timers.remove(id);
  165. }
  166. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  167. // With no active script fix from https://github.com/whatwg/html/pull/9712
  168. i32 WindowOrWorkerGlobalScopeMixin::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id)
  169. {
  170. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  171. // 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.
  172. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  173. // 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.
  174. // 4. If timeout is less than 0, then set timeout to 0.
  175. if (timeout < 0)
  176. timeout = 0;
  177. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  178. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  179. // FIXME: Implement this when step 9.3.2 is implemented.
  180. // 7. Let initiating script be the active script.
  181. auto const* initiating_script = Web::Bindings::active_script();
  182. // 8. Let task be a task that runs the following substeps:
  183. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id, initiating_script]() mutable {
  184. // 1. If id does not exist in global's map of active timers, then abort these steps.
  185. if (!m_timers.contains(id))
  186. return;
  187. handler.visit(
  188. // 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.
  189. [&](JS::Handle<WebIDL::CallbackType> const& callback) {
  190. if (auto result = WebIDL::invoke_callback(*callback, &this_impl(), arguments); result.is_error())
  191. report_exception(result, this_impl().realm());
  192. },
  193. // 3. Otherwise:
  194. [&](String const& source) {
  195. // 1. Assert: handler is a string.
  196. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  197. // 3. Let settings object be global's relevant settings object.
  198. auto& settings_object = relevant_settings_object(this_impl());
  199. // 4. Let fetch options be the default classic script fetch options.
  200. ScriptFetchOptions options {};
  201. // 5. Let base URL be settings object's API base URL.
  202. auto base_url = settings_object.api_base_url();
  203. // 6. If initiating script is not null, then:
  204. if (initiating_script) {
  205. // FIXME: 1. Set fetch options to a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce,
  206. // integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch
  207. // options's credentials mode, referrer policy is initiating script's fetch options's referrer policy, and fetch priority is "auto".
  208. // 2. Set base URL to initiating script's base URL.
  209. base_url = initiating_script->base_url();
  210. // Spec Note: The effect of these steps ensures that the string compilation done by setTimeout() and setInterval() behaves equivalently to that
  211. // done by eval(). That is, module script fetches via import() will behave the same in both contexts.
  212. }
  213. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  214. // FIXME: Pass fetch options.
  215. auto script = ClassicScript::create(base_url.basename(), source, settings_object, move(base_url));
  216. // 8. Run the classic script script.
  217. (void)script->run();
  218. });
  219. // 4. If id does not exist in global's map of active timers, then abort these steps.
  220. if (!m_timers.contains(id))
  221. return;
  222. switch (repeat) {
  223. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  224. case Repeat::Yes:
  225. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id);
  226. break;
  227. // 6. Otherwise, remove global's map of active timers[id].
  228. case Repeat::No:
  229. m_timers.remove(id);
  230. break;
  231. }
  232. };
  233. // FIXME: 9. Increment nesting level by one.
  234. // FIXME: 10. Set task's timer nesting level to nesting level.
  235. // 11. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  236. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  237. queue_global_task(Task::Source::TimerTask, this_impl(), move(task));
  238. };
  239. // 12. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  240. auto timer = Timer::create(this_impl(), timeout, move(completion_step), id);
  241. m_timers.set(id, timer);
  242. timer->start();
  243. // 13. Return id.
  244. return id;
  245. }
  246. // 1. https://www.w3.org/TR/performance-timeline/#dfn-relevant-performance-entry-tuple
  247. PerformanceTimeline::PerformanceEntryTuple& WindowOrWorkerGlobalScopeMixin::relevant_performance_entry_tuple(FlyString const& entry_type)
  248. {
  249. // 1. Let map be the performance entry buffer map associated with globalObject.
  250. // 2. Return the result of getting the value of an entry from map, given entryType as the key.
  251. auto tuple = m_performance_entry_buffer_map.get(entry_type);
  252. // This shouldn't be called with entry types that aren't in `ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES`.
  253. VERIFY(tuple.has_value());
  254. return tuple.value();
  255. }
  256. // https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry
  257. void WindowOrWorkerGlobalScopeMixin::queue_performance_entry(JS::NonnullGCPtr<PerformanceTimeline::PerformanceEntry> new_entry)
  258. {
  259. // 1. Let interested observers be an initially empty set of PerformanceObserver objects.
  260. Vector<JS::Handle<PerformanceTimeline::PerformanceObserver>> interested_observers;
  261. // 2. Let entryType be newEntry’s entryType value.
  262. auto const& entry_type = new_entry->entry_type();
  263. // 3. Let relevantGlobal be newEntry's relevant global object.
  264. // NOTE: Already is `this`.
  265. // 4. For each registered performance observer regObs in relevantGlobal's list of registered performance observer
  266. // objects:
  267. for (auto const& registered_observer : m_registered_performance_observer_objects) {
  268. // 1. If regObs's options list contains a PerformanceObserverInit options whose entryTypes member includes entryType
  269. // or whose type member equals to entryType:
  270. auto iterator = registered_observer->options_list().find_if([&entry_type](PerformanceTimeline::PerformanceObserverInit const& entry) {
  271. if (entry.entry_types.has_value())
  272. return entry.entry_types->contains_slow(String::from_utf8(entry_type).release_value_but_fixme_should_propagate_errors());
  273. VERIFY(entry.type.has_value());
  274. return entry.type.value() == entry_type;
  275. });
  276. if (!iterator.is_end()) {
  277. // 1. If should add entry with newEntry and options returns true, append regObs's observer to interested observers.
  278. if (new_entry->should_add_entry(*iterator) == PerformanceTimeline::ShouldAddEntry::Yes)
  279. interested_observers.append(registered_observer);
  280. }
  281. }
  282. // 5. For each observer in interested observers:
  283. for (auto const& observer : interested_observers) {
  284. // 1. Append newEntry to observer's observer buffer.
  285. observer->append_to_observer_buffer({}, new_entry);
  286. }
  287. // 6. Let tuple be the relevant performance entry tuple of entryType and relevantGlobal.
  288. auto& tuple = relevant_performance_entry_tuple(entry_type);
  289. // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple
  290. // as input.
  291. bool is_buffer_full = tuple.is_full();
  292. // 8. Let shouldAdd be the result of should add entry with newEntry as input.
  293. auto should_add = new_entry->should_add_entry();
  294. // 9. If isBufferFull is false and shouldAdd is true, append newEntry to tuple's performance entry buffer.
  295. if (!is_buffer_full && should_add == PerformanceTimeline::ShouldAddEntry::Yes)
  296. tuple.performance_entry_buffer.append(new_entry);
  297. // 10. Queue the PerformanceObserver task with relevantGlobal as input.
  298. queue_the_performance_observer_task();
  299. }
  300. void WindowOrWorkerGlobalScopeMixin::clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type)
  301. {
  302. auto& tuple = relevant_performance_entry_tuple(entry_type);
  303. tuple.performance_entry_buffer.clear();
  304. }
  305. void WindowOrWorkerGlobalScopeMixin::remove_entries_from_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type, String entry_name)
  306. {
  307. auto& tuple = relevant_performance_entry_tuple(entry_type);
  308. tuple.performance_entry_buffer.remove_all_matching([&entry_name](JS::Handle<PerformanceTimeline::PerformanceEntry> const& entry) {
  309. return entry->name() == entry_name;
  310. });
  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. void WindowOrWorkerGlobalScopeMixin::register_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, JS::NonnullGCPtr<PerformanceTimeline::PerformanceObserver> observer)
  351. {
  352. m_registered_performance_observer_objects.set(observer, AK::HashSetExistingEntryBehavior::Keep);
  353. }
  354. void WindowOrWorkerGlobalScopeMixin::unregister_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, JS::NonnullGCPtr<PerformanceTimeline::PerformanceObserver> observer)
  355. {
  356. m_registered_performance_observer_objects.remove(observer);
  357. }
  358. bool WindowOrWorkerGlobalScopeMixin::has_registered_performance_observer(JS::NonnullGCPtr<PerformanceTimeline::PerformanceObserver> observer)
  359. {
  360. return m_registered_performance_observer_objects.contains(observer);
  361. }
  362. // https://w3c.github.io/performance-timeline/#dfn-queue-the-performanceobserver-task
  363. void WindowOrWorkerGlobalScopeMixin::queue_the_performance_observer_task()
  364. {
  365. // 1. If relevantGlobal's performance observer task queued flag is set, terminate these steps.
  366. if (m_performance_observer_task_queued)
  367. return;
  368. // 2. Set relevantGlobal's performance observer task queued flag.
  369. m_performance_observer_task_queued = true;
  370. // 3. Queue a task that consists of running the following substeps. The task source for the queued task is the performance
  371. // timeline task source.
  372. queue_global_task(Task::Source::PerformanceTimeline, this_impl(), [this]() {
  373. auto& realm = this_impl().realm();
  374. // 1. Unset performance observer task queued flag of relevantGlobal.
  375. m_performance_observer_task_queued = false;
  376. // 2. Let notifyList be a copy of relevantGlobal's list of registered performance observer objects.
  377. auto notify_list = m_registered_performance_observer_objects;
  378. // 3. For each registered performance observer object registeredObserver in notifyList, run these steps:
  379. for (auto& registered_observer : notify_list) {
  380. // 1. Let po be registeredObserver's observer.
  381. // 2. Let entries be a copy of po’s observer buffer.
  382. // 4. Empty po’s observer buffer.
  383. auto entries = registered_observer->take_records();
  384. // 3. If entries is empty, return.
  385. // FIXME: Do they mean `continue`?
  386. if (entries.is_empty())
  387. continue;
  388. Vector<JS::NonnullGCPtr<PerformanceTimeline::PerformanceEntry>> entries_as_gc_ptrs;
  389. for (auto& entry : entries)
  390. entries_as_gc_ptrs.append(*entry);
  391. // 5. Let observerEntryList be a new PerformanceObserverEntryList, with its entry list set to entries.
  392. auto observer_entry_list = realm.heap().allocate<PerformanceTimeline::PerformanceObserverEntryList>(realm, realm, move(entries_as_gc_ptrs));
  393. // 6. Let droppedEntriesCount be null.
  394. Optional<u64> dropped_entries_count;
  395. // 7. If po's requires dropped entries is set, perform the following steps:
  396. if (registered_observer->requires_dropped_entries()) {
  397. // 1. Set droppedEntriesCount to 0.
  398. dropped_entries_count = 0;
  399. // 2. For each PerformanceObserverInit item in registeredObserver's options list:
  400. for (auto const& item : registered_observer->options_list()) {
  401. // 1. For each DOMString entryType that appears either as item's type or in item's entryTypes:
  402. auto increment_dropped_entries_count = [this, &dropped_entries_count](FlyString const& type) {
  403. // 1. Let map be relevantGlobal's performance entry buffer map.
  404. auto const& map = m_performance_entry_buffer_map;
  405. // 2. Let tuple be the result of getting the value of entry on map given entryType as key.
  406. auto const& tuple = map.get(type);
  407. VERIFY(tuple.has_value());
  408. // 3. Increase droppedEntriesCount by tuple's dropped entries count.
  409. dropped_entries_count.value() += tuple->dropped_entries_count;
  410. };
  411. if (item.type.has_value()) {
  412. increment_dropped_entries_count(item.type.value());
  413. } else {
  414. VERIFY(item.entry_types.has_value());
  415. for (auto const& type : item.entry_types.value())
  416. increment_dropped_entries_count(type);
  417. }
  418. }
  419. // 3. Set po's requires dropped entries to false.
  420. registered_observer->unset_requires_dropped_entries({});
  421. }
  422. // 8. Let callbackOptions be a PerformanceObserverCallbackOptions with its droppedEntriesCount set to
  423. // droppedEntriesCount if droppedEntriesCount is not null, otherwise unset.
  424. auto callback_options = JS::Object::create(realm, realm.intrinsics().object_prototype());
  425. if (dropped_entries_count.has_value())
  426. MUST(callback_options->create_data_property("droppedEntriesCount", JS::Value(dropped_entries_count.value())));
  427. // 9. Call po’s observer callback with observerEntryList as the first argument, with po as the second
  428. // argument and as callback this value, and with callbackOptions as the third argument.
  429. // If this throws an exception, report the exception.
  430. auto completion = WebIDL::invoke_callback(registered_observer->callback(), registered_observer, observer_entry_list, registered_observer, callback_options);
  431. if (completion.is_abrupt())
  432. HTML::report_exception(completion, realm);
  433. }
  434. });
  435. }
  436. }