URLSearchParams.cpp 9.8 KB

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