WebContentConsoleClient.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * Copyright (c) 2021, Brandon Scott <xeon.productions@gmail.com>
  3. * Copyright (c) 2020, Hunter Salyer <thefalsehonesty@gmail.com>
  4. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2024, Gasim Gasimzada <gasim@gasimzada.net>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/MemoryStream.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibJS/MarkupGenerator.h>
  12. #include <LibJS/Print.h>
  13. #include <LibJS/Runtime/GlobalEnvironment.h>
  14. #include <LibJS/Runtime/ObjectEnvironment.h>
  15. #include <LibJS/Runtime/Realm.h>
  16. #include <LibJS/Runtime/VM.h>
  17. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  18. #include <LibWeb/HTML/Scripting/Environments.h>
  19. #include <LibWeb/HTML/Window.h>
  20. #include <WebContent/ConsoleGlobalEnvironmentExtensions.h>
  21. #include <WebContent/PageClient.h>
  22. #include <WebContent/WebContentConsoleClient.h>
  23. namespace WebContent {
  24. JS_DEFINE_ALLOCATOR(WebContentConsoleClient);
  25. WebContentConsoleClient::WebContentConsoleClient(JS::Console& console, JS::Realm& realm, PageClient& client)
  26. : ConsoleClient(console)
  27. , m_client(client)
  28. {
  29. auto& window = verify_cast<Web::HTML::Window>(realm.global_object());
  30. m_console_global_environment_extensions = realm.heap().allocate<ConsoleGlobalEnvironmentExtensions>(realm, realm, window);
  31. }
  32. WebContentConsoleClient::~WebContentConsoleClient() = default;
  33. void WebContentConsoleClient::visit_edges(JS::Cell::Visitor& visitor)
  34. {
  35. Base::visit_edges(visitor);
  36. visitor.visit(m_client);
  37. visitor.visit(m_console_global_environment_extensions);
  38. }
  39. void WebContentConsoleClient::handle_input(ByteString const& js_source)
  40. {
  41. if (!m_console_global_environment_extensions)
  42. return;
  43. auto& settings = Web::HTML::relevant_settings_object(*m_console_global_environment_extensions);
  44. auto script = Web::HTML::ClassicScript::create("(console)", js_source, settings.realm(), settings.api_base_url());
  45. auto with_scope = JS::new_object_environment(*m_console_global_environment_extensions, true, &settings.realm().global_environment());
  46. // FIXME: Add parse error printouts back once ClassicScript can report parse errors.
  47. auto result = script->run(Web::HTML::ClassicScript::RethrowErrors::No, with_scope);
  48. if (result.value().has_value()) {
  49. m_console_global_environment_extensions->set_most_recent_result(result.value().value());
  50. print_html(JS::MarkupGenerator::html_from_value(*result.value()).release_value_but_fixme_should_propagate_errors().to_byte_string());
  51. }
  52. }
  53. void WebContentConsoleClient::report_exception(JS::Error const& exception, bool in_promise)
  54. {
  55. print_html(JS::MarkupGenerator::html_from_error(exception, in_promise).release_value_but_fixme_should_propagate_errors().to_byte_string());
  56. }
  57. void WebContentConsoleClient::print_html(ByteString const& line)
  58. {
  59. m_message_log.append({ .type = ConsoleOutput::Type::HTML, .data = line });
  60. m_client->did_output_js_console_message(m_message_log.size() - 1);
  61. }
  62. void WebContentConsoleClient::clear_output()
  63. {
  64. m_message_log.append({ .type = ConsoleOutput::Type::Clear, .data = "" });
  65. m_client->did_output_js_console_message(m_message_log.size() - 1);
  66. }
  67. void WebContentConsoleClient::begin_group(ByteString const& label, bool start_expanded)
  68. {
  69. m_message_log.append({ .type = start_expanded ? ConsoleOutput::Type::BeginGroup : ConsoleOutput::Type::BeginGroupCollapsed, .data = label });
  70. m_client->did_output_js_console_message(m_message_log.size() - 1);
  71. }
  72. void WebContentConsoleClient::end_group()
  73. {
  74. m_message_log.append({ .type = ConsoleOutput::Type::EndGroup, .data = "" });
  75. m_client->did_output_js_console_message(m_message_log.size() - 1);
  76. }
  77. void WebContentConsoleClient::send_messages(i32 start_index)
  78. {
  79. // FIXME: Cap the number of messages we send at once?
  80. auto messages_to_send = m_message_log.size() - start_index;
  81. if (messages_to_send < 1) {
  82. // When the console is first created, it requests any messages that happened before
  83. // then, by requesting with start_index=0. If we don't have any messages at all, that
  84. // is still a valid request, and we can just ignore it.
  85. if (start_index != 0)
  86. m_client->console_peer_did_misbehave("Requested non-existent console message index.");
  87. return;
  88. }
  89. // FIXME: Replace with a single Vector of message structs
  90. Vector<ByteString> message_types;
  91. Vector<ByteString> messages;
  92. message_types.ensure_capacity(messages_to_send);
  93. messages.ensure_capacity(messages_to_send);
  94. for (size_t i = start_index; i < m_message_log.size(); i++) {
  95. auto& message = m_message_log[i];
  96. switch (message.type) {
  97. case ConsoleOutput::Type::HTML:
  98. message_types.append("html"sv);
  99. break;
  100. case ConsoleOutput::Type::Clear:
  101. message_types.append("clear"sv);
  102. break;
  103. case ConsoleOutput::Type::BeginGroup:
  104. message_types.append("group"sv);
  105. break;
  106. case ConsoleOutput::Type::BeginGroupCollapsed:
  107. message_types.append("groupCollapsed"sv);
  108. break;
  109. case ConsoleOutput::Type::EndGroup:
  110. message_types.append("groupEnd"sv);
  111. break;
  112. }
  113. messages.append(message.data);
  114. }
  115. m_client->did_get_js_console_messages(start_index, message_types, messages);
  116. }
  117. void WebContentConsoleClient::clear()
  118. {
  119. clear_output();
  120. }
  121. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  122. JS::ThrowCompletionOr<JS::Value> WebContentConsoleClient::printer(JS::Console::LogLevel log_level, PrinterArguments arguments)
  123. {
  124. auto styling = escape_html_entities(m_current_message_style.string_view());
  125. m_current_message_style.clear();
  126. if (log_level == JS::Console::LogLevel::Table) {
  127. auto& vm = m_console->realm().vm();
  128. auto table_args = arguments.get<JS::MarkedVector<JS::Value>>();
  129. auto& table = table_args.at(0).as_object();
  130. auto& columns = TRY(table.get(JS::PropertyKey("columns"))).as_array().indexed_properties();
  131. auto& rows = TRY(table.get(JS::PropertyKey("rows"))).as_array().indexed_properties();
  132. StringBuilder html;
  133. html.appendff("<div class=\"console-log-table\">");
  134. html.appendff("<table>");
  135. html.appendff("<thead>");
  136. html.appendff("<tr>");
  137. for (auto const& col : columns) {
  138. auto index = col.index();
  139. auto value = columns.storage()->get(index).value().value;
  140. html.appendff("<td>{}</td>", value);
  141. }
  142. html.appendff("</tr>");
  143. html.appendff("</thead>");
  144. html.appendff("<tbody>");
  145. for (auto const& row : rows) {
  146. auto row_index = row.index();
  147. auto& row_obj = rows.storage()->get(row_index).value().value.as_object();
  148. html.appendff("<tr>");
  149. for (auto const& col : columns) {
  150. auto col_index = col.index();
  151. auto col_name = columns.storage()->get(col_index).value().value;
  152. auto property_key = TRY(JS::PropertyKey::from_value(vm, col_name));
  153. auto cell = TRY(row_obj.get(property_key));
  154. html.appendff("<td>");
  155. if (TRY(cell.is_array(vm))) {
  156. AllocatingMemoryStream stream;
  157. JS::PrintContext ctx { vm, stream, true };
  158. TRY_OR_THROW_OOM(vm, stream.write_until_depleted(" "sv.bytes()));
  159. TRY_OR_THROW_OOM(vm, JS::print(cell, ctx));
  160. auto output = TRY_OR_THROW_OOM(vm, String::from_stream(stream, stream.used_buffer_size()));
  161. auto size = cell.as_array().indexed_properties().array_like_size();
  162. html.appendff("<details><summary>Array({})</summary>{}</details>", size, output);
  163. } else if (cell.is_object()) {
  164. AllocatingMemoryStream stream;
  165. JS::PrintContext ctx { vm, stream, true };
  166. TRY_OR_THROW_OOM(vm, stream.write_until_depleted(" "sv.bytes()));
  167. TRY_OR_THROW_OOM(vm, JS::print(cell, ctx));
  168. auto output = TRY_OR_THROW_OOM(vm, String::from_stream(stream, stream.used_buffer_size()));
  169. html.appendff("<details><summary>Object({{...}})</summary>{}</details>", output);
  170. } else if (cell.is_function() || cell.is_constructor()) {
  171. html.appendff("ƒ");
  172. } else if (!cell.is_undefined()) {
  173. html.appendff("{}", cell);
  174. }
  175. html.appendff("</td>");
  176. }
  177. html.appendff("</tr>");
  178. }
  179. html.appendff("</tbody>");
  180. html.appendff("</table>");
  181. html.appendff("</div>");
  182. print_html(html.string_view());
  183. auto output = TRY(generically_format_values(table_args));
  184. m_console->output_debug_message(log_level, output);
  185. return JS::js_undefined();
  186. }
  187. if (log_level == JS::Console::LogLevel::Trace) {
  188. auto trace = arguments.get<JS::Console::Trace>();
  189. StringBuilder html;
  190. if (!trace.label.is_empty())
  191. html.appendff("<span class='title' style='{}'>{}</span><br>", styling, escape_html_entities(trace.label));
  192. html.append("<span class='trace'>"sv);
  193. for (auto& function_name : trace.stack)
  194. html.appendff("-> {}<br>", escape_html_entities(function_name));
  195. html.append("</span>"sv);
  196. print_html(html.string_view());
  197. return JS::js_undefined();
  198. }
  199. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  200. auto group = arguments.get<JS::Console::Group>();
  201. begin_group(ByteString::formatted("<span style='{}'>{}</span>", styling, escape_html_entities(group.label)), log_level == JS::Console::LogLevel::Group);
  202. return JS::js_undefined();
  203. }
  204. auto output = TRY(generically_format_values(arguments.get<JS::MarkedVector<JS::Value>>()));
  205. m_console->output_debug_message(log_level, output);
  206. StringBuilder html;
  207. switch (log_level) {
  208. case JS::Console::LogLevel::Debug:
  209. html.appendff("<span class=\"debug\" style=\"{}\">(d) "sv, styling);
  210. break;
  211. case JS::Console::LogLevel::Error:
  212. html.appendff("<span class=\"error\" style=\"{}\">(e) "sv, styling);
  213. break;
  214. case JS::Console::LogLevel::Info:
  215. html.appendff("<span class=\"info\" style=\"{}\">(i) "sv, styling);
  216. break;
  217. case JS::Console::LogLevel::Log:
  218. html.appendff("<span class=\"log\" style=\"{}\"> "sv, styling);
  219. break;
  220. case JS::Console::LogLevel::Warn:
  221. case JS::Console::LogLevel::CountReset:
  222. html.appendff("<span class=\"warn\" style=\"{}\">(w) "sv, styling);
  223. break;
  224. default:
  225. html.appendff("<span style=\"{}\">"sv, styling);
  226. break;
  227. }
  228. html.append(escape_html_entities(output));
  229. html.append("</span>"sv);
  230. print_html(html.string_view());
  231. return JS::js_undefined();
  232. }
  233. }