URLSearchParams.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Utf8View.h>
  9. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  10. #include <LibWeb/Bindings/Intrinsics.h>
  11. #include <LibWeb/URL/URL.h>
  12. #include <LibWeb/URL/URLSearchParams.h>
  13. namespace Web::URL {
  14. URLSearchParams::URLSearchParams(JS::Realm& realm, Vector<QueryParam> list)
  15. : PlatformObject(realm)
  16. , m_list(move(list))
  17. {
  18. }
  19. URLSearchParams::~URLSearchParams() = default;
  20. JS::ThrowCompletionOr<void> URLSearchParams::initialize(JS::Realm& realm)
  21. {
  22. MUST_OR_THROW_OOM(Base::initialize(realm));
  23. set_prototype(&Bindings::ensure_web_prototype<Bindings::URLSearchParamsPrototype>(realm, "URLSearchParams"));
  24. return {};
  25. }
  26. void URLSearchParams::visit_edges(Cell::Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(m_url);
  30. }
  31. ErrorOr<String> url_encode(Vector<QueryParam> const& pairs, AK::URL::PercentEncodeSet percent_encode_set)
  32. {
  33. StringBuilder builder;
  34. for (size_t i = 0; i < pairs.size(); ++i) {
  35. TRY(builder.try_append(AK::URL::percent_encode(pairs[i].name, percent_encode_set, AK::URL::SpaceAsPlus::Yes)));
  36. TRY(builder.try_append('='));
  37. TRY(builder.try_append(AK::URL::percent_encode(pairs[i].value, percent_encode_set, AK::URL::SpaceAsPlus::Yes)));
  38. if (i != pairs.size() - 1)
  39. TRY(builder.try_append('&'));
  40. }
  41. return builder.to_string();
  42. }
  43. ErrorOr<Vector<QueryParam>> url_decode(StringView input)
  44. {
  45. // 1. Let sequences be the result of splitting input on 0x26 (&).
  46. auto sequences = input.split_view('&');
  47. // 2. Let output be an initially empty list of name-value tuples where both name and value hold a string.
  48. Vector<QueryParam> output;
  49. // 3. For each byte sequence bytes in sequences:
  50. for (auto bytes : sequences) {
  51. // 1. If bytes is the empty byte sequence, then continue.
  52. if (bytes.is_empty())
  53. continue;
  54. StringView name;
  55. StringView value;
  56. // 2. If bytes contains a 0x3D (=), then let name be the bytes from the start of bytes up to but excluding its first 0x3D (=), and let value be the bytes, if any, after the first 0x3D (=) up to the end of bytes. If 0x3D (=) is the first byte, then name will be the empty byte sequence. If it is the last, then value will be the empty byte sequence.
  57. if (auto index = bytes.find('='); index.has_value()) {
  58. name = bytes.substring_view(0, *index);
  59. value = bytes.substring_view(*index + 1);
  60. }
  61. // 3. Otherwise, let name have the value of bytes and let value be the empty byte sequence.
  62. else {
  63. name = bytes;
  64. value = ""sv;
  65. }
  66. // 4. Replace any 0x2B (+) in name and value with 0x20 (SP).
  67. auto space_decoded_name = name.replace("+"sv, " "sv, ReplaceMode::All);
  68. // 5. Let nameString and valueString be the result of running UTF-8 decode without BOM on the percent-decoding of name and value, respectively.
  69. auto name_string = TRY(String::from_deprecated_string(AK::URL::percent_decode(space_decoded_name)));
  70. auto value_string = TRY(String::from_deprecated_string(AK::URL::percent_decode(value)));
  71. TRY(output.try_empend(move(name_string), move(value_string)));
  72. }
  73. return output;
  74. }
  75. WebIDL::ExceptionOr<JS::NonnullGCPtr<URLSearchParams>> URLSearchParams::create(JS::Realm& realm, Vector<QueryParam> list)
  76. {
  77. return MUST_OR_THROW_OOM(realm.heap().allocate<URLSearchParams>(realm, realm, move(list)));
  78. }
  79. // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  80. // https://url.spec.whatwg.org/#urlsearchparams-initialize
  81. WebIDL::ExceptionOr<JS::NonnullGCPtr<URLSearchParams>> URLSearchParams::construct_impl(JS::Realm& realm, Variant<Vector<Vector<String>>, OrderedHashMap<String, String>, String> const& init)
  82. {
  83. auto& vm = realm.vm();
  84. // 1. If init is a string and starts with U+003F (?), then remove the first code point from init.
  85. // NOTE: We do this when we know that it's a string on step 3 of initialization.
  86. // 2. Initialize this with init.
  87. // URLSearchParams init from this point forward
  88. // 1. If init is a sequence, then for each pair in init:
  89. if (init.has<Vector<Vector<String>>>()) {
  90. auto const& init_sequence = init.get<Vector<Vector<String>>>();
  91. Vector<QueryParam> list;
  92. list.ensure_capacity(init_sequence.size());
  93. for (auto const& pair : init_sequence) {
  94. // a. If pair does not contain exactly two items, then throw a TypeError.
  95. if (pair.size() != 2)
  96. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, TRY_OR_THROW_OOM(vm, String::formatted("Expected only 2 items in pair, got {}", pair.size())) };
  97. // b. Append a new name-value pair whose name is pair’s first item, and value is pair’s second item, to query’s list.
  98. list.append(QueryParam { .name = pair[0], .value = pair[1] });
  99. }
  100. return URLSearchParams::create(realm, move(list));
  101. }
  102. // 2. Otherwise, if init is a record, then for each name → value of init, append a new name-value pair whose name is name and value is value, to query’s list.
  103. if (init.has<OrderedHashMap<String, String>>()) {
  104. auto const& init_record = init.get<OrderedHashMap<String, String>>();
  105. Vector<QueryParam> list;
  106. list.ensure_capacity(init_record.size());
  107. for (auto const& pair : init_record)
  108. list.append(QueryParam { .name = pair.key, .value = pair.value });
  109. return URLSearchParams::create(realm, move(list));
  110. }
  111. // 3. Otherwise:
  112. // a. Assert: init is a string.
  113. // NOTE: `get` performs `VERIFY(has<T>())`
  114. auto const& init_string = init.get<String>();
  115. // See NOTE at the start of this function.
  116. auto init_string_view = init_string.bytes_as_string_view();
  117. auto stripped_init = init_string_view.substring_view(init_string_view.starts_with('?'));
  118. // b. Set query’s list to the result of parsing init.
  119. return URLSearchParams::create(realm, TRY_OR_THROW_OOM(vm, url_decode(stripped_init)));
  120. }
  121. // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  122. size_t URLSearchParams::size() const
  123. {
  124. // The size getter steps are to return this’s list’s size.
  125. return m_list.size();
  126. }
  127. WebIDL::ExceptionOr<void> URLSearchParams::append(String const& name, String const& value)
  128. {
  129. auto& vm = realm().vm();
  130. // 1. Append a new name-value pair whose name is name and value is value, to list.
  131. TRY_OR_THROW_OOM(vm, m_list.try_empend(name, value));
  132. // 2. Update this.
  133. TRY(update());
  134. return {};
  135. }
  136. WebIDL::ExceptionOr<void> URLSearchParams::update()
  137. {
  138. // 1. If query’s URL object is null, then return.
  139. if (!m_url)
  140. return {};
  141. // 2. Let serializedQuery be the serialization of query’s list.
  142. auto serialized_query = TRY(to_string());
  143. // 3. If serializedQuery is the empty string, then set serializedQuery to null.
  144. if (serialized_query.is_empty())
  145. serialized_query = {};
  146. // 4. Set query’s URL object’s URL’s query to serializedQuery.
  147. m_url->set_query({}, move(serialized_query));
  148. return {};
  149. }
  150. WebIDL::ExceptionOr<void> URLSearchParams::delete_(String const& name)
  151. {
  152. // 1. Remove all name-value pairs whose name is name from list.
  153. m_list.remove_all_matching([&name](auto& entry) {
  154. return entry.name == name;
  155. });
  156. // 2. Update this.
  157. TRY(update());
  158. return {};
  159. }
  160. Optional<String> URLSearchParams::get(String const& name)
  161. {
  162. // return the value of the first name-value pair whose name is name in this’s list, if there is such a pair, and null otherwise.
  163. auto result = m_list.find_if([&name](auto& entry) {
  164. return entry.name == name;
  165. });
  166. if (result.is_end())
  167. return {};
  168. return result->value;
  169. }
  170. // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  171. WebIDL::ExceptionOr<Vector<String>> URLSearchParams::get_all(String const& name)
  172. {
  173. auto& vm = realm().vm();
  174. // return the values of all name-value pairs whose name is name, in this’s list, in list order, and the empty sequence otherwise.
  175. Vector<String> values;
  176. for (auto& entry : m_list) {
  177. if (entry.name == name)
  178. TRY_OR_THROW_OOM(vm, values.try_append(entry.value));
  179. }
  180. return values;
  181. }
  182. bool URLSearchParams::has(String const& name)
  183. {
  184. // return true if there is a name-value pair whose name is name in this’s list, and false otherwise.
  185. return !m_list.find_if([&name](auto& entry) {
  186. return entry.name == name;
  187. })
  188. .is_end();
  189. }
  190. WebIDL::ExceptionOr<void> URLSearchParams::set(String const& name, String const& value)
  191. {
  192. auto& vm = realm().vm();
  193. // 1. If this’s list contains any name-value pairs whose name is name, then set the value of the first such name-value pair to value and remove the others.
  194. auto existing = m_list.find_if([&name](auto& entry) {
  195. return entry.name == name;
  196. });
  197. if (!existing.is_end()) {
  198. existing->value = value;
  199. m_list.remove_all_matching([&name, &existing](auto& entry) {
  200. return &entry != &*existing && entry.name == name;
  201. });
  202. }
  203. // 2. Otherwise, append a new name-value pair whose name is name and value is value, to this’s list.
  204. else {
  205. TRY_OR_THROW_OOM(vm, m_list.try_empend(name, value));
  206. }
  207. // 3. Update this.
  208. TRY(update());
  209. return {};
  210. }
  211. WebIDL::ExceptionOr<void> URLSearchParams::sort()
  212. {
  213. // 1. Sort all name-value pairs, if any, by their names. Sorting must be done by comparison of code units. The relative order between name-value pairs with equal names must be preserved.
  214. quick_sort(m_list.begin(), m_list.end(), [](auto& a, auto& b) {
  215. Utf8View a_code_points { a.name };
  216. Utf8View b_code_points { b.name };
  217. if (a_code_points.starts_with(b_code_points))
  218. return false;
  219. if (b_code_points.starts_with(a_code_points))
  220. return true;
  221. for (auto k = a_code_points.begin(), l = b_code_points.begin();
  222. k != a_code_points.end() && l != b_code_points.end();
  223. ++k, ++l) {
  224. if (*k != *l) {
  225. if (*k < *l) {
  226. return true;
  227. } else {
  228. return false;
  229. }
  230. }
  231. }
  232. VERIFY_NOT_REACHED();
  233. });
  234. // 2. Update this.
  235. TRY(update());
  236. return {};
  237. }
  238. WebIDL::ExceptionOr<String> URLSearchParams::to_string() const
  239. {
  240. auto& vm = realm().vm();
  241. // return the serialization of this’s list.
  242. return TRY_OR_THROW_OOM(vm, url_encode(m_list, AK::URL::PercentEncodeSet::ApplicationXWWWFormUrlencoded));
  243. }
  244. JS::ThrowCompletionOr<void> URLSearchParams::for_each(ForEachCallback callback)
  245. {
  246. for (auto i = 0u; i < m_list.size(); ++i) {
  247. auto& query_param = m_list[i]; // We are explicitly iterating over the indices here as the callback might delete items from the list
  248. TRY(callback(query_param.name, query_param.value));
  249. }
  250. return {};
  251. }
  252. }