@dvaji/cheerox 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/CONTRIBUTING.md +74 -0
  2. package/Cargo.lock +1094 -0
  3. package/Cargo.toml +46 -0
  4. package/LICENSE +21 -0
  5. package/README.md +121 -2
  6. package/RELEASING.md +114 -0
  7. package/THIRD_PARTY_NOTICES.md +7579 -0
  8. package/build.rs +3 -0
  9. package/cheerox.darwin-arm64.node +0 -0
  10. package/cheerox.darwin-x64.node +0 -0
  11. package/cheerox.linux-arm64-gnu.node +0 -0
  12. package/cheerox.linux-arm64-musl.node +0 -0
  13. package/cheerox.linux-x64-gnu.node +0 -0
  14. package/cheerox.linux-x64-musl.node +0 -0
  15. package/cheerox.win32-arm64-msvc.node +0 -0
  16. package/cheerox.win32-x64-msvc.node +0 -0
  17. package/dist/cheerio-compat-BS--qPzw.mjs +1648 -0
  18. package/dist/cheerio-compat-BS--qPzw.mjs.map +1 -0
  19. package/dist/cheerio-compat-DRLPzBdX.d.mts +88 -0
  20. package/dist/cheerio-compat-DRsINTwV.d.cts +88 -0
  21. package/dist/cheerio-compat-DRsINTwV.d.ts +88 -0
  22. package/dist/cheerio-compat-DSwBAJ1s.cjs +1719 -0
  23. package/dist/cheerio-compat-DSwBAJ1s.cjs.map +1 -0
  24. package/dist/cheerio-compat.cjs +18 -0
  25. package/dist/cheerio-compat.d.cts +2 -0
  26. package/dist/cheerio-compat.d.mts +2 -0
  27. package/dist/cheerio-compat.d.ts +2 -0
  28. package/dist/cheerio-compat.mjs +1 -0
  29. package/dist/index.cjs +13 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +28 -0
  32. package/dist/index.d.mts +6 -0
  33. package/dist/index.d.ts +28 -0
  34. package/dist/index.mjs +53 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/legacy-parse.cjs +5 -0
  37. package/dist/legacy-parse.d.mts +8 -0
  38. package/dist/legacy-parse.d.ts +7 -0
  39. package/dist/legacy-parse.mjs +1 -0
  40. package/dist/modern-B7hyW4cI.d.cts +102 -0
  41. package/dist/modern-B7hyW4cI.d.ts +102 -0
  42. package/dist/modern-CHQGP0Yt.cjs +2858 -0
  43. package/dist/modern-CHQGP0Yt.cjs.map +1 -0
  44. package/dist/modern-CJvSD_y5.d.mts +102 -0
  45. package/dist/modern-CvXcTn82.mjs +2769 -0
  46. package/dist/modern-CvXcTn82.mjs.map +1 -0
  47. package/dist/modern.cjs +19 -0
  48. package/dist/modern.d.cts +3 -0
  49. package/dist/modern.d.mts +3 -0
  50. package/dist/modern.d.ts +3 -0
  51. package/dist/modern.mjs +3 -0
  52. package/dist/nodes-jbWWhssj.cjs +4210 -0
  53. package/dist/nodes-jbWWhssj.cjs.map +1 -0
  54. package/dist/nodes-sYxb5qyZ.mjs +3803 -0
  55. package/dist/nodes-sYxb5qyZ.mjs.map +1 -0
  56. package/dist/slim.cjs +16 -0
  57. package/dist/slim.cjs.map +1 -0
  58. package/dist/slim.d.cts +6 -0
  59. package/dist/slim.d.mts +6 -0
  60. package/dist/slim.d.ts +6 -0
  61. package/dist/slim.mjs +12 -0
  62. package/dist/slim.mjs.map +1 -0
  63. package/dist/types-CA01Zg3r.d.cts +526 -0
  64. package/dist/types-CA01Zg3r.d.mts +526 -0
  65. package/dist/types-CA01Zg3r.d.ts +526 -0
  66. package/dist/utils.cjs +31 -0
  67. package/dist/utils.cjs.map +1 -0
  68. package/dist/utils.d.cts +8 -0
  69. package/dist/utils.d.mts +8 -0
  70. package/dist/utils.d.ts +8 -0
  71. package/dist/utils.mjs +25 -0
  72. package/dist/utils.mjs.map +1 -0
  73. package/native/src/arena.rs +2109 -0
  74. package/native/src/attributes.rs +946 -0
  75. package/native/src/codec.rs +298 -0
  76. package/native/src/diagnostics.rs +1249 -0
  77. package/native/src/document_order.rs +711 -0
  78. package/native/src/extraction.rs +321 -0
  79. package/native/src/gc.rs +175 -0
  80. package/native/src/hook_sink.rs +801 -0
  81. package/native/src/hook_stream.rs +513 -0
  82. package/native/src/id_hash.rs +42 -0
  83. package/native/src/immutable.rs +333 -0
  84. package/native/src/lib.rs +4119 -0
  85. package/native/src/location.rs +392 -0
  86. package/native/src/markup_tokenizer.rs +668 -0
  87. package/native/src/runtime.rs +368 -0
  88. package/native/src/selector.rs +1596 -0
  89. package/native/src/sink.rs +274 -0
  90. package/native/src/snapshot.rs +672 -0
  91. package/native/src/stream.rs +334 -0
  92. package/native/src/tokenizer.rs +581 -0
  93. package/native/src/tracker.rs +232 -0
  94. package/native/vendor/README.md +26 -0
  95. package/native/vendor/html5ever-0.35.0/.cargo_vcs_info.json +6 -0
  96. package/native/vendor/html5ever-0.35.0/Cargo.lock +828 -0
  97. package/native/vendor/html5ever-0.35.0/Cargo.toml +85 -0
  98. package/native/vendor/html5ever-0.35.0/LICENSE-APACHE +201 -0
  99. package/native/vendor/html5ever-0.35.0/LICENSE-MIT +25 -0
  100. package/native/vendor/html5ever-0.35.0/README.md +60 -0
  101. package/native/vendor/html5ever-0.35.0/benches/html5ever.rs +86 -0
  102. package/native/vendor/html5ever-0.35.0/data/bench/lipsum-zh.html +19 -0
  103. package/native/vendor/html5ever-0.35.0/data/bench/lipsum.html +40 -0
  104. package/native/vendor/html5ever-0.35.0/data/bench/medium-fragment.html +24 -0
  105. package/native/vendor/html5ever-0.35.0/data/bench/small-fragment.html +7 -0
  106. package/native/vendor/html5ever-0.35.0/data/bench/strong.html +1 -0
  107. package/native/vendor/html5ever-0.35.0/data/bench/tiny-fragment.html +1 -0
  108. package/native/vendor/html5ever-0.35.0/examples/arena.rs +356 -0
  109. package/native/vendor/html5ever-0.35.0/examples/capi/tokenize.c +74 -0
  110. package/native/vendor/html5ever-0.35.0/examples/noop-tokenize.rs +47 -0
  111. package/native/vendor/html5ever-0.35.0/examples/noop-tree-builder.rs +132 -0
  112. package/native/vendor/html5ever-0.35.0/examples/print-tree-actions.rs +185 -0
  113. package/native/vendor/html5ever-0.35.0/examples/tokenize.rs +111 -0
  114. package/native/vendor/html5ever-0.35.0/src/driver.rs +148 -0
  115. package/native/vendor/html5ever-0.35.0/src/lib.rs +30 -0
  116. package/native/vendor/html5ever-0.35.0/src/macros.rs +34 -0
  117. package/native/vendor/html5ever-0.35.0/src/serialize/mod.rs +255 -0
  118. package/native/vendor/html5ever-0.35.0/src/tokenizer/char_ref/mod.rs +530 -0
  119. package/native/vendor/html5ever-0.35.0/src/tokenizer/interface.rs +99 -0
  120. package/native/vendor/html5ever-0.35.0/src/tokenizer/mod.rs +2628 -0
  121. package/native/vendor/html5ever-0.35.0/src/tokenizer/states.rs +97 -0
  122. package/native/vendor/html5ever-0.35.0/src/tree_builder/data.rs +170 -0
  123. package/native/vendor/html5ever-0.35.0/src/tree_builder/mod.rs +1848 -0
  124. package/native/vendor/html5ever-0.35.0/src/tree_builder/rules.rs +1494 -0
  125. package/native/vendor/html5ever-0.35.0/src/tree_builder/tag_sets.rs +114 -0
  126. package/native/vendor/html5ever-0.35.0/src/tree_builder/types.rs +91 -0
  127. package/native/vendor/html5ever-0.35.0/src/util/str.rs +52 -0
  128. package/native/vendor/html5gum-0.8.4/Cargo.lock +1006 -0
  129. package/native/vendor/html5gum-0.8.4/Cargo.toml +109 -0
  130. package/native/vendor/html5gum-0.8.4/LICENSE +19 -0
  131. package/native/vendor/html5gum-0.8.4/README.md +110 -0
  132. package/native/vendor/html5gum-0.8.4/benches/files/0050.html +2131 -0
  133. package/native/vendor/html5gum-0.8.4/benches/files/6D30.html +1004 -0
  134. package/native/vendor/html5gum-0.8.4/benches/files.rs +32 -0
  135. package/native/vendor/html5gum-0.8.4/benches/patterns.rs +31 -0
  136. package/native/vendor/html5gum-0.8.4/src/arrayvec.rs +29 -0
  137. package/native/vendor/html5gum-0.8.4/src/char_validator.rs +134 -0
  138. package/native/vendor/html5gum-0.8.4/src/emitters/callback.rs +676 -0
  139. package/native/vendor/html5gum-0.8.4/src/emitters/default.rs +207 -0
  140. package/native/vendor/html5gum-0.8.4/src/emitters/emitter.rs +344 -0
  141. package/native/vendor/html5gum-0.8.4/src/emitters/html5ever.rs +306 -0
  142. package/native/vendor/html5gum-0.8.4/src/emitters/mod.rs +25 -0
  143. package/native/vendor/html5gum-0.8.4/src/entities.rs +3342 -0
  144. package/native/vendor/html5gum-0.8.4/src/error.rs +96 -0
  145. package/native/vendor/html5gum-0.8.4/src/htmlstring.rs +130 -0
  146. package/native/vendor/html5gum-0.8.4/src/lib.rs +66 -0
  147. package/native/vendor/html5gum-0.8.4/src/machine.rs +2136 -0
  148. package/native/vendor/html5gum-0.8.4/src/machine_helper.rs +277 -0
  149. package/native/vendor/html5gum-0.8.4/src/read_helper.rs +244 -0
  150. package/native/vendor/html5gum-0.8.4/src/reader.rs +440 -0
  151. package/native/vendor/html5gum-0.8.4/src/span.rs +98 -0
  152. package/native/vendor/html5gum-0.8.4/src/state.rs +16 -0
  153. package/native/vendor/html5gum-0.8.4/src/testutils.rs +71 -0
  154. package/native/vendor/html5gum-0.8.4/src/tokenizer.rs +189 -0
  155. package/native/vendor/html5gum-0.8.4/src/utils.rs +88 -0
  156. package/native/vendor/markup5ever-0.35.0/.cargo_vcs_info.json +6 -0
  157. package/native/vendor/markup5ever-0.35.0/Cargo.toml +45 -0
  158. package/native/vendor/markup5ever-0.35.0/LICENSE-APACHE +201 -0
  159. package/native/vendor/markup5ever-0.35.0/LICENSE-MIT +25 -0
  160. package/native/vendor/markup5ever-0.35.0/interface/mod.rs +422 -0
  161. package/native/vendor/markup5ever-0.35.0/interface/tree_builder.rs +280 -0
  162. package/native/vendor/markup5ever-0.35.0/lib.rs +59 -0
  163. package/native/vendor/markup5ever-0.35.0/serialize.rs +77 -0
  164. package/native/vendor/markup5ever-0.35.0/util/buffer_queue.rs +333 -0
  165. package/native/vendor/markup5ever-0.35.0/util/smallcharset.rs +88 -0
  166. package/package.json +167 -4
  167. package/scripts/check-native.mjs +15 -0
  168. package/scripts/check-release.mjs +234 -0
  169. package/scripts/fix-declarations.mjs +39 -0
  170. package/scripts/generate-notices.mjs +188 -0
  171. package/scripts/notices/README.md +13 -0
  172. package/scripts/notices/cheerio-MIT.txt +21 -0
  173. package/scripts/notices/html5ever-AUTHORS.txt +20 -0
  174. package/scripts/notices/html5ever-COPYRIGHT.txt +8 -0
  175. package/scripts/notices/html5ever-LICENSE-APACHE.txt +201 -0
  176. package/scripts/notices/html5ever-LICENSE-MIT.txt +25 -0
  177. package/scripts/notices/htmlparser2-MIT.txt +18 -0
  178. package/scripts/notices/napi-rs-MIT.txt +43 -0
  179. package/scripts/notices/neon-MIT.txt +19 -0
  180. package/scripts/notices/runtime-01c266bced4a434da005.txt +3 -0
  181. package/scripts/notices/runtime-0a54e647fe54104658b5.txt +14 -0
  182. package/scripts/notices/runtime-0b74dfa0bcee5c420c6b.txt +25 -0
  183. package/scripts/notices/runtime-0d542e0c8804e39aa7f3.txt +177 -0
  184. package/scripts/notices/runtime-0f96a83840e146e43c0e.txt +21 -0
  185. package/scripts/notices/runtime-123a331b5dbf04c30097.txt +25 -0
  186. package/scripts/notices/runtime-172020dbfd5b53a226df.txt +34 -0
  187. package/scripts/notices/runtime-209fbbe0ad52d9235e37.txt +26 -0
  188. package/scripts/notices/runtime-23f18e03dc49df91622f.txt +23 -0
  189. package/scripts/notices/runtime-268872b9816f90fd8e85.txt +220 -0
  190. package/scripts/notices/runtime-35242e7a83f69875e6ed.txt +176 -0
  191. package/scripts/notices/runtime-378f5840b258e2779c39.txt +25 -0
  192. package/scripts/notices/runtime-4108245a1f2df9d4e94d.txt +25 -0
  193. package/scripts/notices/runtime-4455bf75a91154108304.txt +21 -0
  194. package/scripts/notices/runtime-553fffcd9b1cb158bc3e.txt +13 -0
  195. package/scripts/notices/runtime-62c7a1e35f56406896d7.txt +176 -0
  196. package/scripts/notices/runtime-6485b8ed310d3f0340bf.txt +25 -0
  197. package/scripts/notices/runtime-69fef7b0f322a6555415.txt +201 -0
  198. package/scripts/notices/runtime-6df43f6f4b5d4587f3d8.txt +187 -0
  199. package/scripts/notices/runtime-799e9ca9d179295ef372.txt +24 -0
  200. package/scripts/notices/runtime-7b63ecd5f1902af1b637.txt +25 -0
  201. package/scripts/notices/runtime-7bc7d5de2a0b793d4e1a.txt +21 -0
  202. package/scripts/notices/runtime-7e12e5df4bae12cb2158.txt +24 -0
  203. package/scripts/notices/runtime-861399f8c21c042b1105.txt +12 -0
  204. package/scripts/notices/runtime-8ada45cd9f843acf64e4.txt +201 -0
  205. package/scripts/notices/runtime-90eb64f0279b0d9432ac.txt +12 -0
  206. package/scripts/notices/runtime-a60eea817514531668d7.txt +201 -0
  207. package/scripts/notices/runtime-a7c936ff1ed8fa340172.txt +25 -0
  208. package/scripts/notices/runtime-ab6eec6caf0fa5775e41.txt +275 -0
  209. package/scripts/notices/runtime-b1181a40b2a7b25cf66f.txt +19 -0
  210. package/scripts/notices/runtime-b71bd43a069ca0641a9e.txt +25 -0
  211. package/scripts/notices/runtime-c16f8dcf1a368b83be78.txt +201 -0
  212. package/scripts/notices/runtime-c2cfccb812fe482101a8.txt +21 -0
  213. package/scripts/notices/runtime-e99d88d232bf57d70f0f.txt +25 -0
  214. package/scripts/notices/runtime-f32fb3b417a194167cfa.txt +9 -0
  215. package/scripts/notices/runtime-f5062c9a188d81dfe66b.txt +39 -0
  216. package/scripts/notices/runtime-f9070a832833fa7488fd.txt +4 -0
  217. package/scripts/notices/runtime-fab3dd6bdab226f1c086.txt +373 -0
  218. package/scripts/notices/runtime-fba3318d0c600380177e.txt +62 -0
  219. package/scripts/notices/runtime-ff8f68cb076caf8cefe7.txt +25 -0
  220. package/scripts/notices/runtime-ff92bed461f50338dd70.txt +74 -0
  221. package/scripts/notices/runtime.json +1632 -0
  222. package/scripts/notices/sources.json +561 -0
  223. package/scripts/notices/xray-MIT.txt +21 -0
  224. package/src/attribute-object.ts +71 -0
  225. package/src/attributes.ts +308 -0
  226. package/src/cheerio-compat/css.ts +58 -0
  227. package/src/cheerio-compat/render.ts +106 -0
  228. package/src/cheerio-compat/selectors.ts +51 -0
  229. package/src/cheerio-compat/types.ts +52 -0
  230. package/src/cheerio-compat.ts +2055 -0
  231. package/src/codec.ts +96 -0
  232. package/src/dom.ts +87 -0
  233. package/src/extract-plan.ts +97 -0
  234. package/src/extract.ts +322 -0
  235. package/src/hooks.ts +369 -0
  236. package/src/index.ts +48 -0
  237. package/src/io.ts +491 -0
  238. package/src/match.ts +207 -0
  239. package/src/modern.ts +259 -0
  240. package/src/native.ts +149 -0
  241. package/src/nodes.ts +831 -0
  242. package/src/parse.ts +53 -0
  243. package/src/parser-types.ts +157 -0
  244. package/src/router.ts +1129 -0
  245. package/src/selection.ts +682 -0
  246. package/src/slim.ts +12 -0
  247. package/src/snapshot.ts +291 -0
  248. package/src/transport.ts +113 -0
  249. package/src/types.ts +186 -0
  250. package/src/utils.ts +29 -0
  251. package/src/workers.ts +21 -0
  252. package/tsconfig.json +15 -0
  253. package/tsdown.config.mjs +17 -0
@@ -0,0 +1,2109 @@
1
+ //! Mutable, stable-ID DOM storage. All mutations stay on the native side.
2
+ use std::borrow::Cow;
3
+ use std::collections::{HashMap, HashSet};
4
+
5
+ use napi::{Error, Result, Status};
6
+ use serde::{Deserialize, Serialize};
7
+ use serde_json::{json, Map, Value};
8
+
9
+ #[derive(Clone, Debug, Serialize, Deserialize)]
10
+ pub(crate) struct DomNode {
11
+ #[serde(default)]
12
+ pub id: u32,
13
+ #[serde(rename = "type", default = "root_kind")]
14
+ pub kind: Cow<'static, str>,
15
+ #[serde(default, skip_serializing_if = "Option::is_none")]
16
+ pub name: Option<String>,
17
+ #[serde(default, skip_serializing_if = "Option::is_none")]
18
+ pub data: Option<String>,
19
+ #[serde(default)]
20
+ pub attribs: Attributes,
21
+ #[serde(default, with = "child_ids")]
22
+ pub children: smallvec::SmallVec<[u32; 2]>,
23
+ #[serde(default)]
24
+ pub parent: Option<u32>,
25
+ #[serde(default)]
26
+ pub prev: Option<u32>,
27
+ #[serde(default)]
28
+ pub next: Option<u32>,
29
+ /// Element namespace; borrowed for the namespaces HTML parsing produces.
30
+ #[serde(default, skip_serializing_if = "Option::is_none")]
31
+ pub namespace: Option<Cow<'static, str>>,
32
+ /// parse5's per-attribute namespace and prefix maps, when the node has them.
33
+ #[serde(
34
+ rename = "attribsNamespace",
35
+ default,
36
+ skip_serializing_if = "Option::is_none"
37
+ )]
38
+ pub attribs_namespace: Option<Box<Map<String, Value>>>,
39
+ #[serde(
40
+ rename = "attribsPrefix",
41
+ default,
42
+ skip_serializing_if = "Option::is_none"
43
+ )]
44
+ pub attribs_prefix: Option<Box<Map<String, Value>>>,
45
+ #[serde(flatten)]
46
+ pub extras: FieldMap,
47
+ }
48
+
49
+ // Keep the wire representation as an ordinary array without enabling
50
+ // smallvec's serde feature for every transitive dependency.
51
+ mod child_ids {
52
+ use serde::{Deserialize, Serialize};
53
+ use smallvec::SmallVec;
54
+
55
+ pub fn serialize<S: serde::Serializer>(
56
+ ids: &SmallVec<[u32; 2]>,
57
+ serializer: S,
58
+ ) -> Result<S::Ok, S::Error> {
59
+ ids.as_slice().serialize(serializer)
60
+ }
61
+
62
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(
63
+ deserializer: D,
64
+ ) -> Result<SmallVec<[u32; 2]>, D::Error> {
65
+ Vec::<u32>::deserialize(deserializer).map(Into::into)
66
+ }
67
+ }
68
+
69
+ /// An element's attributes in insertion order. Elements have few, so a list
70
+ /// searched linearly costs one allocation and no hashing, where a map costs
71
+ /// three and a hash per name.
72
+ #[derive(Clone, Debug, Default, PartialEq)]
73
+ pub(crate) struct Attributes(Vec<(String, Value)>);
74
+
75
+ impl Attributes {
76
+ pub(crate) fn with_capacity(capacity: usize) -> Self {
77
+ Self(Vec::with_capacity(capacity))
78
+ }
79
+
80
+ pub(crate) fn get(&self, name: &str) -> Option<&Value> {
81
+ self.0
82
+ .iter()
83
+ .find(|(key, _)| key == name)
84
+ .map(|(_, value)| value)
85
+ }
86
+
87
+ pub(crate) fn contains_key(&self, name: &str) -> bool {
88
+ self.0.iter().any(|(key, _)| key == name)
89
+ }
90
+
91
+ /// Sets `name`, in place if present, as a map insert does.
92
+ pub(crate) fn insert(&mut self, name: String, value: Value) -> Option<Value> {
93
+ match self.0.iter_mut().find(|(key, _)| *key == name) {
94
+ Some((_, slot)) => Some(std::mem::replace(slot, value)),
95
+ None => {
96
+ self.0.push((name, value));
97
+ None
98
+ }
99
+ }
100
+ }
101
+
102
+ /// Adds `name` unless present, keeping the first value as htmlparser2 does.
103
+ /// Past a few attributes, the caller dedupes with a set instead.
104
+ pub(crate) fn push_unique(&mut self, name: String, value: Value) {
105
+ if !self.contains_key(&name) {
106
+ self.0.push((name, value));
107
+ }
108
+ }
109
+
110
+ pub(crate) fn push(&mut self, name: String, value: Value) {
111
+ self.0.push((name, value));
112
+ }
113
+
114
+ /// Removes `name`, keeping the order of the rest.
115
+ pub(crate) fn shift_remove(&mut self, name: &str) -> Option<Value> {
116
+ let index = self.0.iter().position(|(key, _)| key == name)?;
117
+ Some(self.0.remove(index).1)
118
+ }
119
+
120
+ pub(crate) fn len(&self) -> usize {
121
+ self.0.len()
122
+ }
123
+
124
+ pub(crate) fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
125
+ self.into_iter()
126
+ }
127
+
128
+ pub(crate) fn values(&self) -> impl Iterator<Item = &Value> {
129
+ self.0.iter().map(|(_, value)| value)
130
+ }
131
+
132
+ pub(crate) fn to_map(&self) -> Map<String, Value> {
133
+ self.0.iter().cloned().collect()
134
+ }
135
+ }
136
+
137
+ impl From<Map<String, Value>> for Attributes {
138
+ fn from(map: Map<String, Value>) -> Self {
139
+ Self(map.into_iter().collect())
140
+ }
141
+ }
142
+
143
+ impl<'a> IntoIterator for &'a Attributes {
144
+ type Item = (&'a String, &'a Value);
145
+ type IntoIter = std::iter::Map<
146
+ std::slice::Iter<'a, (String, Value)>,
147
+ fn(&'a (String, Value)) -> (&'a String, &'a Value),
148
+ >;
149
+ fn into_iter(self) -> Self::IntoIter {
150
+ self.0.iter().map(|(key, value)| (key, value))
151
+ }
152
+ }
153
+
154
+ impl IntoIterator for Attributes {
155
+ type Item = (String, Value);
156
+ type IntoIter = std::vec::IntoIter<(String, Value)>;
157
+ fn into_iter(self) -> Self::IntoIter {
158
+ self.0.into_iter()
159
+ }
160
+ }
161
+
162
+ impl Serialize for Attributes {
163
+ fn serialize<S: serde::Serializer>(
164
+ &self,
165
+ serializer: S,
166
+ ) -> std::result::Result<S::Ok, S::Error> {
167
+ use serde::ser::SerializeMap;
168
+ let mut map = serializer.serialize_map(Some(self.0.len()))?;
169
+ for (key, value) in &self.0 {
170
+ map.serialize_entry(key, value)?;
171
+ }
172
+ map.end()
173
+ }
174
+ }
175
+
176
+ impl<'de> Deserialize<'de> for Attributes {
177
+ fn deserialize<D: serde::Deserializer<'de>>(
178
+ deserializer: D,
179
+ ) -> std::result::Result<Self, D::Error> {
180
+ Map::deserialize(deserializer).map(Self::from)
181
+ }
182
+ }
183
+
184
+ /// A string-keyed map that most nodes leave empty, boxed so that an empty
185
+ /// one costs a pointer instead of a whole map in every node.
186
+ #[derive(Clone, Debug, Default)]
187
+ pub(crate) struct FieldMap(Option<Box<Map<String, Value>>>);
188
+
189
+ static EMPTY_FIELDS: std::sync::LazyLock<Map<String, Value>> = std::sync::LazyLock::new(Map::new);
190
+
191
+ impl std::ops::Deref for FieldMap {
192
+ type Target = Map<String, Value>;
193
+ fn deref(&self) -> &Self::Target {
194
+ self.0.as_deref().unwrap_or(&EMPTY_FIELDS)
195
+ }
196
+ }
197
+
198
+ impl std::ops::DerefMut for FieldMap {
199
+ fn deref_mut(&mut self) -> &mut Self::Target {
200
+ self.0.get_or_insert_with(Box::default)
201
+ }
202
+ }
203
+
204
+ impl From<Map<String, Value>> for FieldMap {
205
+ fn from(map: Map<String, Value>) -> Self {
206
+ Self((!map.is_empty()).then(|| Box::new(map)))
207
+ }
208
+ }
209
+
210
+ /// Removals and lookups for writing leave an empty map unallocated; other
211
+ /// writes go through `DerefMut`, which allocates it.
212
+ impl FieldMap {
213
+ pub(crate) fn into_map(self) -> Map<String, Value> {
214
+ self.0.map_or_else(Map::new, |map| *map)
215
+ }
216
+
217
+ pub(crate) fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
218
+ self.0.as_mut()?.get_mut(key)
219
+ }
220
+
221
+ pub(crate) fn remove(&mut self, key: &str) -> Option<Value> {
222
+ self.0.as_mut()?.remove(key)
223
+ }
224
+ }
225
+
226
+ impl<'a> IntoIterator for &'a FieldMap {
227
+ type Item = (&'a String, &'a Value);
228
+ type IntoIter = serde_json::map::Iter<'a>;
229
+ fn into_iter(self) -> Self::IntoIter {
230
+ (**self).iter()
231
+ }
232
+ }
233
+
234
+ impl<'a> IntoIterator for &'a mut FieldMap {
235
+ type Item = (&'a String, &'a mut Value);
236
+ type IntoIter = serde_json::map::IterMut<'a>;
237
+ fn into_iter(self) -> Self::IntoIter {
238
+ (**self).iter_mut()
239
+ }
240
+ }
241
+
242
+ impl IntoIterator for FieldMap {
243
+ type Item = (String, Value);
244
+ type IntoIter = serde_json::map::IntoIter;
245
+ fn into_iter(self) -> Self::IntoIter {
246
+ self.into_map().into_iter()
247
+ }
248
+ }
249
+
250
+ impl Serialize for FieldMap {
251
+ fn serialize<S: serde::Serializer>(
252
+ &self,
253
+ serializer: S,
254
+ ) -> std::result::Result<S::Ok, S::Error> {
255
+ (**self).serialize(serializer)
256
+ }
257
+ }
258
+
259
+ impl<'de> Deserialize<'de> for FieldMap {
260
+ fn deserialize<D: serde::Deserializer<'de>>(
261
+ deserializer: D,
262
+ ) -> std::result::Result<Self, D::Error> {
263
+ Map::deserialize(deserializer).map(Self::from)
264
+ }
265
+ }
266
+
267
+ fn root_kind() -> Cow<'static, str> {
268
+ Cow::Borrowed("root")
269
+ }
270
+
271
+ pub(crate) const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
272
+
273
+ /// A namespace, borrowed for the ones HTML parsing produces.
274
+ pub(crate) fn namespace_name(namespace: &str) -> Cow<'static, str> {
275
+ match namespace {
276
+ HTML_NAMESPACE => Cow::Borrowed(HTML_NAMESPACE),
277
+ "http://www.w3.org/2000/svg" => Cow::Borrowed("http://www.w3.org/2000/svg"),
278
+ "http://www.w3.org/1998/Math/MathML" => Cow::Borrowed("http://www.w3.org/1998/Math/MathML"),
279
+ "http://www.w3.org/1999/xlink" => Cow::Borrowed("http://www.w3.org/1999/xlink"),
280
+ "http://www.w3.org/XML/1998/namespace" => {
281
+ Cow::Borrowed("http://www.w3.org/XML/1998/namespace")
282
+ }
283
+ "http://www.w3.org/2000/xmlns/" => Cow::Borrowed("http://www.w3.org/2000/xmlns/"),
284
+ other => Cow::Owned(other.to_owned()),
285
+ }
286
+ }
287
+
288
+ /// A node type, borrowed for the types the DOM defines.
289
+ pub(crate) fn node_kind(kind: &str) -> Cow<'static, str> {
290
+ match kind {
291
+ "tag" => Cow::Borrowed("tag"),
292
+ "text" => Cow::Borrowed("text"),
293
+ "root" => Cow::Borrowed("root"),
294
+ "script" => Cow::Borrowed("script"),
295
+ "style" => Cow::Borrowed("style"),
296
+ "comment" => Cow::Borrowed("comment"),
297
+ "directive" => Cow::Borrowed("directive"),
298
+ "cdata" => Cow::Borrowed("cdata"),
299
+ "doctype" => Cow::Borrowed("doctype"),
300
+ other => Cow::Owned(other.to_owned()),
301
+ }
302
+ }
303
+
304
+ impl DomNode {
305
+ pub(crate) fn new(kind: impl Into<Cow<'static, str>>) -> Self {
306
+ Self {
307
+ id: 0,
308
+ kind: kind.into(),
309
+ name: None,
310
+ data: None,
311
+ attribs: Attributes::default(),
312
+ children: smallvec::SmallVec::new(),
313
+ parent: None,
314
+ prev: None,
315
+ next: None,
316
+ namespace: None,
317
+ attribs_namespace: None,
318
+ attribs_prefix: None,
319
+ extras: FieldMap::default(),
320
+ }
321
+ }
322
+ pub(crate) fn is_element(&self) -> bool {
323
+ matches!(self.kind.as_ref(), "tag" | "script" | "style")
324
+ }
325
+ pub(crate) fn content_bytes(&self) -> usize {
326
+ let attributes: usize = self
327
+ .attribs
328
+ .values()
329
+ .filter_map(Value::as_str)
330
+ .map(str::len)
331
+ .sum();
332
+ self.data.as_ref().map_or(0, String::len) + attributes
333
+ }
334
+ }
335
+
336
+ #[derive(Clone, Debug)]
337
+ pub(crate) struct DomArena {
338
+ pub nodes: Vec<DomNode>,
339
+ pub options: Value,
340
+ pub free: Vec<u32>,
341
+ /// Parents whose child lists changed since JavaScript last asked, so it
342
+ /// can refresh the child arrays it holds without rereading every node.
343
+ pub touched: Vec<u32>,
344
+ /// Too many changes were recorded to list; every parent counts as touched.
345
+ pub touched_overflow: bool,
346
+ /// Whether parsing records start and end indices, read once per parse.
347
+ pub parse_indices: Option<(bool, bool)>,
348
+ /// Nodes removed from a parent since the last collection.
349
+ pub detached_since_collection: u32,
350
+ /// Live nodes after the last collection, or when the arena was built.
351
+ pub collected_live: u32,
352
+ /// Elements by ASCII-lowercased name, in document order, as parsing
353
+ /// created them; dropped before any write, which may reorder ids.
354
+ pub name_index: Option<NameIndex>,
355
+ }
356
+
357
+ pub(crate) type NameIndex = crate::id_hash::IdMap<String, Vec<u32>>;
358
+
359
+ const TOUCHED_LIMIT: usize = 1 << 16;
360
+
361
+ impl DomArena {
362
+ /// An arena over records whose ids and links are already consistent, as
363
+ /// a parse tree's conversion produces them.
364
+ pub(crate) fn from_linked_records(nodes: Vec<DomNode>, options: Value) -> Self {
365
+ let slots = nodes.len() as u32;
366
+ Self {
367
+ nodes,
368
+ options,
369
+ free: Vec::new(),
370
+ touched: Vec::new(),
371
+ touched_overflow: false,
372
+ parse_indices: None,
373
+ detached_since_collection: 0,
374
+ collected_live: slots,
375
+ name_index: None,
376
+ }
377
+ }
378
+ pub(crate) fn from_records(mut nodes: Vec<DomNode>, options: Value) -> Self {
379
+ for (id, node) in nodes.iter_mut().enumerate() {
380
+ node.id = id as u32;
381
+ }
382
+ let slots = nodes.len() as u32;
383
+ let mut arena = Self {
384
+ nodes,
385
+ options,
386
+ free: Vec::new(),
387
+ touched: Vec::new(),
388
+ touched_overflow: false,
389
+ parse_indices: None,
390
+ detached_since_collection: 0,
391
+ collected_live: slots,
392
+ name_index: None,
393
+ };
394
+ for id in 0..arena.nodes.len() {
395
+ arena.relink(id as u32);
396
+ }
397
+ arena.take_touched();
398
+ arena
399
+ }
400
+ pub(crate) fn touch(&mut self, parent: u32) {
401
+ if self.touched_overflow {
402
+ return;
403
+ }
404
+ if self.touched.len() >= TOUCHED_LIMIT {
405
+ self.touched = Vec::new();
406
+ self.touched_overflow = true;
407
+ } else {
408
+ self.touched.push(parent);
409
+ }
410
+ }
411
+ /// The parents touched since the last call, or `None` when too many were.
412
+ pub(crate) fn take_touched(&mut self) -> Option<Vec<u32>> {
413
+ let touched = std::mem::take(&mut self.touched);
414
+ let overflow = std::mem::replace(&mut self.touched_overflow, false);
415
+ (!overflow).then_some(touched)
416
+ }
417
+ fn note_detached(&mut self) {
418
+ self.detached_since_collection = self.detached_since_collection.saturating_add(1);
419
+ }
420
+ /// Every live node that `root` does not reach through child links.
421
+ pub(crate) fn detached_slots(&self, root: u32) -> Vec<u32> {
422
+ let mut attached = vec![false; self.nodes.len()];
423
+ let mut stack = vec![root];
424
+ while let Some(id) = stack.pop() {
425
+ let Some(node) = self.node(id) else { continue };
426
+ if std::mem::replace(&mut attached[id as usize], true) {
427
+ continue;
428
+ }
429
+ stack.extend(node.children.iter().copied());
430
+ }
431
+ (0..self.nodes.len() as u32)
432
+ .filter(|id| !attached[*id as usize] && self.node(*id).is_some())
433
+ .collect()
434
+ }
435
+ /// Whether removed nodes may have left enough garbage to collect: the
436
+ /// live slots have grown by half since the last collection.
437
+ pub(crate) fn is_collection_due(&self) -> bool {
438
+ let live = self.nodes.len().saturating_sub(self.free.len()) as u64;
439
+ self.detached_since_collection > 0 && live >= u64::from(self.collected_live) * 3 / 2 + 256
440
+ }
441
+ pub(crate) fn node(&self, id: u32) -> Option<&DomNode> {
442
+ self.nodes
443
+ .get(id as usize)
444
+ .filter(|node| node.kind != "released")
445
+ }
446
+ pub(crate) fn node_mut(&mut self, id: u32) -> Option<&mut DomNode> {
447
+ self.nodes
448
+ .get_mut(id as usize)
449
+ .filter(|node| node.kind != "released")
450
+ }
451
+ pub(crate) fn xml_mode(&self) -> bool {
452
+ xml_mode(&self.options)
453
+ }
454
+ pub(crate) fn push(&mut self, mut node: DomNode) -> u32 {
455
+ while let Some(id) = self.free.pop() {
456
+ if self
457
+ .nodes
458
+ .get(id as usize)
459
+ .is_some_and(|old| old.kind == "released")
460
+ {
461
+ node.id = id;
462
+ self.nodes[id as usize] = node;
463
+ return id;
464
+ }
465
+ }
466
+ let id = self.nodes.len() as u32;
467
+ node.id = id;
468
+ self.nodes.push(node);
469
+ id
470
+ }
471
+ pub(crate) fn attr(&self, id: u32, name: &str) -> Option<&str> {
472
+ self.node(id)?.attribs.get(name)?.as_str()
473
+ }
474
+ pub(crate) fn set_attr(&mut self, ids: &[u32], name: &str, value: Option<&str>) {
475
+ for id in ids {
476
+ if let Some(node) = self.nodes.get_mut(*id as usize) {
477
+ if node.is_element() {
478
+ match value {
479
+ Some(value) => {
480
+ node.attribs
481
+ .insert(name.into(), Value::String(value.into()));
482
+ }
483
+ None => {
484
+ node.attribs.shift_remove(name);
485
+ }
486
+ }
487
+ }
488
+ }
489
+ }
490
+ }
491
+ pub(crate) fn relink(&mut self, parent: u32) {
492
+ self.touch(parent);
493
+ let children = self
494
+ .nodes
495
+ .get(parent as usize)
496
+ .map(|node| node.children.clone())
497
+ .unwrap_or_default();
498
+ for (index, child) in children.iter().enumerate() {
499
+ if let Some(node) = self.nodes.get_mut(*child as usize) {
500
+ node.parent = Some(parent);
501
+ node.prev = index
502
+ .checked_sub(1)
503
+ .and_then(|index| children.get(index))
504
+ .copied();
505
+ node.next = children.get(index + 1).copied();
506
+ }
507
+ }
508
+ }
509
+ pub(crate) fn detach(&mut self, id: u32) {
510
+ if let Some(parent) = self.node(id).and_then(|node| node.parent) {
511
+ self.note_detached();
512
+ if let Some(node) = self.nodes.get_mut(parent as usize) {
513
+ node.children.retain(|child| *child != id);
514
+ }
515
+ self.relink(parent);
516
+ }
517
+ if let Some(node) = self.nodes.get_mut(id as usize) {
518
+ node.parent = None;
519
+ node.prev = None;
520
+ node.next = None;
521
+ }
522
+ }
523
+ pub(crate) fn detach_many(&mut self, ids: &[u32]) {
524
+ if ids.len() < 2 {
525
+ if let Some(id) = ids.first() {
526
+ self.detach(*id);
527
+ }
528
+ return;
529
+ }
530
+ let removed: HashSet<_> = ids.iter().copied().collect();
531
+ for id in ids {
532
+ if self.node(*id).is_some_and(|node| node.parent.is_some()) {
533
+ self.note_detached();
534
+ }
535
+ }
536
+ let parents: HashSet<_> = ids
537
+ .iter()
538
+ .filter_map(|id| self.node(*id).and_then(|node| node.parent))
539
+ .collect();
540
+ for parent in parents {
541
+ if let Some(node) = self.nodes.get_mut(parent as usize) {
542
+ node.children.retain(|child| !removed.contains(child));
543
+ }
544
+ self.relink(parent);
545
+ }
546
+ for id in removed {
547
+ if let Some(node) = self.nodes.get_mut(id as usize) {
548
+ node.parent = None;
549
+ node.prev = None;
550
+ node.next = None;
551
+ }
552
+ }
553
+ }
554
+ pub(crate) fn set_children(&mut self, parent: u32, children: &[u32]) {
555
+ if self.node(parent).is_none() {
556
+ return;
557
+ }
558
+ if !self
559
+ .node(parent)
560
+ .is_some_and(|node| node.is_element() || node.kind == "root" || node.kind == "cdata")
561
+ {
562
+ return;
563
+ }
564
+ let old = std::mem::take(&mut self.nodes[parent as usize].children);
565
+ self.detach_many(&old);
566
+ let mut seen = HashSet::new();
567
+ let mut children: Vec<_> = children
568
+ .iter()
569
+ .rev()
570
+ .copied()
571
+ .filter(|id| *id != parent && self.node(*id).is_some() && seen.insert(*id))
572
+ .collect();
573
+ children.reverse();
574
+ self.detach_many(&children);
575
+ self.nodes[parent as usize].children = children.into();
576
+ self.relink(parent);
577
+ }
578
+ pub(crate) fn text(&self, ids: &[u32]) -> String {
579
+ let mut output = String::new();
580
+ for id in ids {
581
+ let mut stack = vec![*id];
582
+ let mut visited = HashSet::new();
583
+ while let Some(id) = stack.pop() {
584
+ if !visited.insert(id) {
585
+ continue;
586
+ }
587
+ if let Some(node) = self.node(id) {
588
+ if node.kind == "text" {
589
+ output.push_str(node.data.as_deref().unwrap_or(""));
590
+ } else {
591
+ stack.extend(node.children.iter().rev().copied());
592
+ }
593
+ }
594
+ }
595
+ }
596
+ output
597
+ }
598
+ pub(crate) fn set_text(&mut self, ids: &[u32], value: &str) {
599
+ for id in ids {
600
+ if self
601
+ .node(*id)
602
+ .is_some_and(|node| node.is_element() || node.kind == "root")
603
+ {
604
+ self.set_children(*id, &[]);
605
+ if !value.is_empty() {
606
+ let mut text = DomNode::new("text");
607
+ text.data = Some(value.into());
608
+ let child = self.push(text);
609
+ self.set_children(*id, &[child]);
610
+ }
611
+ }
612
+ }
613
+ }
614
+ pub(crate) fn inner_html(&self, id: u32) -> String {
615
+ self.outer_html(
616
+ self.node(id)
617
+ .map(|node| node.children.as_slice())
618
+ .unwrap_or(&[]),
619
+ )
620
+ }
621
+ pub(crate) fn inner_html_mut(&mut self, id: u32) -> String {
622
+ if !self.xml_mode() && self.options.get("_useHtmlParser2") != Some(&Value::Bool(true)) {
623
+ if let Some(node) = self.node(id) {
624
+ let mut children = node.children.clone();
625
+ let mut index = 0;
626
+ while index < children.len() {
627
+ if let Some(root) = self
628
+ .node(children[index])
629
+ .filter(|node| node.kind == "root")
630
+ {
631
+ let contents = root.children.clone();
632
+ children.remove(index);
633
+ children.insert_many(index, contents);
634
+ }
635
+ index += 1;
636
+ }
637
+ self.nodes[id as usize].children = children;
638
+ self.touch(id);
639
+ }
640
+ }
641
+ if self.xml_mode() || self.options.get("_useHtmlParser2") != Some(&Value::Bool(true)) {
642
+ return self.inner_html(id);
643
+ }
644
+ let children = self
645
+ .node(id)
646
+ .map(|node| node.children.clone())
647
+ .unwrap_or_default();
648
+ self.serialize_mut(&children, &self.options.clone())
649
+ }
650
+ pub(crate) fn outer_html(&self, ids: &[u32]) -> String {
651
+ self.serialize(ids, &self.options)
652
+ }
653
+ pub(crate) fn serialize_mut(&mut self, ids: &[u32], options: &Value) -> String {
654
+ let legacy = options.get("legacySerializer") == Some(&Value::Bool(true));
655
+ if !legacy
656
+ && !xml_mode(options)
657
+ && options.get("_useHtmlParser2") == Some(&Value::Bool(true))
658
+ {
659
+ let mut stack: Vec<(u32, bool)> = ids.iter().rev().map(|id| (*id, false)).collect();
660
+ let mut budget = self.nodes.len().saturating_mul(8).saturating_add(1024);
661
+ while let Some((id, is_foreign)) = stack.pop() {
662
+ if budget == 0 {
663
+ break;
664
+ }
665
+ budget -= 1;
666
+ let Some(node) = self.node(id) else {
667
+ continue;
668
+ };
669
+ let name = node.name.as_deref().unwrap_or("");
670
+ let corrected = is_foreign
671
+ .then(|| foreign_element_name(name))
672
+ .filter(|corrected| *corrected != name)
673
+ .map(str::to_owned);
674
+ let has_foreign_content = node.is_element()
675
+ && ((is_foreign && !is_foreign_integration_child(self, node))
676
+ || matches!(name, "svg" | "math"));
677
+ let children_are_foreign = if node.kind == "root" {
678
+ is_foreign
679
+ } else {
680
+ has_foreign_content
681
+ };
682
+ stack.extend(
683
+ node.children
684
+ .iter()
685
+ .rev()
686
+ .map(|id| (*id, children_are_foreign)),
687
+ );
688
+ if let Some(name) = corrected {
689
+ self.nodes[id as usize].name = Some(name);
690
+ self.name_index = None;
691
+ self.touch(id);
692
+ }
693
+ }
694
+ }
695
+ self.serialize(ids, options)
696
+ }
697
+ pub(crate) fn serialize(&self, ids: &[u32], options: &Value) -> String {
698
+ let mut output = String::new();
699
+ let xml = xml_mode(options);
700
+ let is_htmlparser2 = options.get("_useHtmlParser2") == Some(&Value::Bool(true));
701
+ // dom-serializer 0.1.x (Cheerio 0.22.0): no foreign-name corrections,
702
+ // no foreign-content escaping rules, svg rendered in XML mode.
703
+ let legacy = options.get("legacySerializer") == Some(&Value::Bool(true));
704
+ // Cheerio serializes HTML with parse5, which always escapes; only the
705
+ // htmlparser2 serializer leaves entities alone when asked to.
706
+ let is_parse5 = !xml && !is_htmlparser2;
707
+ // 0.1.x encodes only when `decodeEntities` is truthy — an absent flag
708
+ // (as on the bare module's `cheerio.xml()`) leaves text raw.
709
+ let encode = if legacy {
710
+ options
711
+ .get("decodeEntities")
712
+ .and_then(Value::as_bool)
713
+ .unwrap_or(false)
714
+ } else {
715
+ is_parse5
716
+ || options
717
+ .get("encodeEntities")
718
+ .or_else(|| options.get("decodeEntities"))
719
+ != Some(&Value::Bool(false))
720
+ };
721
+ let is_utf8 = options.get("encodeEntities").and_then(Value::as_str) == Some("utf8");
722
+ let mut stack: Vec<(u32, bool, bool)> =
723
+ ids.iter().rev().map(|id| (*id, false, false)).collect();
724
+ let mut budget = self.nodes.len().saturating_mul(8).saturating_add(1024);
725
+ while let Some((id, close, is_foreign)) = stack.pop() {
726
+ if budget == 0 {
727
+ break;
728
+ }
729
+ budget -= 1;
730
+ let Some(node) = self.node(id) else {
731
+ continue;
732
+ };
733
+ if close {
734
+ output.push_str("</");
735
+ let name = node.name.as_deref().unwrap_or("");
736
+ output.push_str(if is_foreign {
737
+ foreign_element_name(name)
738
+ } else {
739
+ name
740
+ });
741
+ output.push('>');
742
+ continue;
743
+ }
744
+ match node.kind.as_ref() {
745
+ "root" => stack.extend(
746
+ node.children
747
+ .iter()
748
+ .rev()
749
+ .map(|id| (*id, false, is_foreign)),
750
+ ),
751
+ "text" => {
752
+ let raw = if legacy {
753
+ node.parent
754
+ .and_then(|id| self.node(id))
755
+ .is_some_and(|parent| {
756
+ matches!(
757
+ parent.name.as_deref(),
758
+ Some(
759
+ "script"
760
+ | "style"
761
+ | "xmp"
762
+ | "iframe"
763
+ | "noembed"
764
+ | "noframes"
765
+ | "plaintext"
766
+ | "noscript"
767
+ )
768
+ )
769
+ })
770
+ } else {
771
+ !xml && !is_foreign
772
+ && node
773
+ .parent
774
+ .and_then(|id| self.node(id))
775
+ .is_some_and(|parent| {
776
+ matches!(
777
+ parent.name.as_deref(),
778
+ Some(
779
+ "script"
780
+ | "style"
781
+ | "xmp"
782
+ | "iframe"
783
+ | "noembed"
784
+ | "noframes"
785
+ | "plaintext"
786
+ | "noscript"
787
+ )
788
+ ) && (!is_parse5
789
+ || parent.name.as_deref() != Some("noscript")
790
+ || options.get("scriptingEnabled")
791
+ != Some(&Value::Bool(false)))
792
+ })
793
+ };
794
+ if raw || !encode {
795
+ output.push_str(node.data.as_deref().unwrap_or(""));
796
+ } else if legacy {
797
+ legacy_escape(node.data.as_deref().unwrap_or(""), &mut output);
798
+ } else {
799
+ escape(
800
+ node.data.as_deref().unwrap_or(""),
801
+ false,
802
+ xml || (is_htmlparser2 && (is_foreign || !is_utf8)),
803
+ is_utf8 && !xml && !is_foreign,
804
+ &mut output,
805
+ );
806
+ }
807
+ }
808
+ "comment" => {
809
+ output.push_str("<!--");
810
+ output.push_str(node.data.as_deref().unwrap_or(""));
811
+ output.push_str("-->");
812
+ }
813
+ "cdata" => {
814
+ output.push_str("<![CDATA[");
815
+ output.push_str(&self.text(&node.children));
816
+ output.push_str("]]>");
817
+ }
818
+ "directive" | "doctype" => {
819
+ output.push('<');
820
+ if is_parse5 && node.name.as_deref() == Some("!doctype") {
821
+ output.push_str("!DOCTYPE ");
822
+ output.push_str(
823
+ node.extras
824
+ .get("x-name")
825
+ .and_then(Value::as_str)
826
+ .unwrap_or("html"),
827
+ );
828
+ } else {
829
+ output.push_str(node.data.as_deref().unwrap_or(""));
830
+ }
831
+ output.push('>');
832
+ }
833
+ _ if node.is_element() => {
834
+ if legacy {
835
+ // dom-serializer 0.1.x rules: no foreign-content
836
+ // handling; an svg element (and its subtree) renders
837
+ // in XML mode; void elements render their children
838
+ // without a closing tag, as the original did.
839
+ let name = node.name.as_deref().unwrap_or("");
840
+ let in_svg = is_foreign;
841
+ let effective_xml = xml || in_svg || name == "svg";
842
+ output.push('<');
843
+ output.push_str(name);
844
+ let attributes = super::js_property_order(
845
+ node.attribs
846
+ .iter()
847
+ .map(|(name, value)| (name.as_str(), value)),
848
+ );
849
+ for (attr_name, value) in attributes {
850
+ let value = value
851
+ .as_str()
852
+ .map(str::to_owned)
853
+ .unwrap_or_else(|| value.to_string());
854
+ output.push(' ');
855
+ output.push_str(attr_name);
856
+ if effective_xml || !value.is_empty() {
857
+ output.push_str("=\"");
858
+ if encode {
859
+ legacy_escape(&value, &mut output);
860
+ } else {
861
+ output.push_str(&value);
862
+ }
863
+ output.push('"');
864
+ }
865
+ }
866
+ if effective_xml && node.children.is_empty() {
867
+ output.push_str("/>");
868
+ continue;
869
+ }
870
+ output.push('>');
871
+ let single = html_parser_void(name);
872
+ if !single || effective_xml {
873
+ stack.push((id, true, in_svg));
874
+ }
875
+ stack.extend(
876
+ node.children
877
+ .iter()
878
+ .rev()
879
+ .map(|child| (*child, false, in_svg || name == "svg")),
880
+ );
881
+ continue;
882
+ }
883
+ let stored_name = node.name.as_deref().unwrap_or("");
884
+ let name = if is_foreign {
885
+ foreign_element_name(stored_name)
886
+ } else {
887
+ stored_name
888
+ };
889
+ let is_integration_child =
890
+ is_foreign && is_foreign_integration_child(self, node);
891
+ let has_foreign_content = is_htmlparser2
892
+ && !xml
893
+ && ((is_foreign && !is_integration_child)
894
+ || matches!(name, "svg" | "math"));
895
+ output.push('<');
896
+ output.push_str(name);
897
+ // parse5 qualifies foreign attributes; XML and htmlparser2
898
+ // rendering write the stored attribute names unchanged.
899
+ let qualifiers = is_parse5.then_some((
900
+ node.attribs_namespace.as_deref(),
901
+ node.attribs_prefix.as_deref(),
902
+ ));
903
+ let attributes = super::js_property_order(
904
+ node.attribs
905
+ .iter()
906
+ .map(|(name, value)| (name.as_str(), value)),
907
+ );
908
+ for (name, value) in attributes {
909
+ output.push(' ');
910
+ match qualifiers {
911
+ Some((namespaces, prefixes)) => super::push_attribute_name(
912
+ &mut output,
913
+ name,
914
+ namespaces
915
+ .and_then(|map| map.get(name))
916
+ .and_then(Value::as_str),
917
+ prefixes
918
+ .and_then(|map| map.get(name))
919
+ .and_then(Value::as_str),
920
+ ),
921
+ None => output.push_str(if has_foreign_content {
922
+ foreign_attribute_name(name)
923
+ } else {
924
+ name
925
+ }),
926
+ }
927
+ let value = value
928
+ .as_str()
929
+ .map(str::to_owned)
930
+ .unwrap_or_else(|| value.to_string());
931
+ if !xml
932
+ && !has_foreign_content
933
+ && is_htmlparser2
934
+ && options.get("emptyAttrs") != Some(&Value::Bool(true))
935
+ && value.is_empty()
936
+ {
937
+ continue;
938
+ }
939
+ output.push_str("=\"");
940
+ if encode {
941
+ escape(
942
+ &value,
943
+ true,
944
+ xml || (is_htmlparser2 && (has_foreign_content || !is_utf8)),
945
+ is_utf8 && !xml && !has_foreign_content,
946
+ &mut output,
947
+ );
948
+ } else {
949
+ output.push_str(&value.replace('"', "&quot;"));
950
+ }
951
+ output.push('"');
952
+ }
953
+ let is_void = !xml
954
+ && !has_foreign_content
955
+ && (if is_parse5 {
956
+ node.namespace.as_deref() == Some(super::HTML_NS)
957
+ && super::void_name(name)
958
+ } else {
959
+ html_parser_void(name)
960
+ });
961
+ if (xml
962
+ || has_foreign_content
963
+ || (is_htmlparser2
964
+ && is_void
965
+ && options.get("selfClosingTags") == Some(&Value::Bool(true))))
966
+ && node.children.is_empty()
967
+ && options.get("selfClosingTags") != Some(&Value::Bool(false))
968
+ {
969
+ if !xml && !has_foreign_content {
970
+ output.push(' ');
971
+ }
972
+ output.push_str("/>");
973
+ continue;
974
+ }
975
+ output.push('>');
976
+ if is_void && (is_parse5 || node.children.is_empty()) {
977
+ continue;
978
+ }
979
+ if !is_void {
980
+ stack.push((id, true, is_foreign));
981
+ }
982
+ if is_parse5 && name == "template" {
983
+ if let Some(contents) = node.children.first().and_then(|id| self.node(*id))
984
+ {
985
+ stack.extend(
986
+ contents.children.iter().rev().map(|id| (*id, false, false)),
987
+ );
988
+ }
989
+ } else {
990
+ stack.extend(
991
+ node.children
992
+ .iter()
993
+ .rev()
994
+ .map(|id| (*id, false, has_foreign_content)),
995
+ );
996
+ }
997
+ }
998
+ _ => {}
999
+ }
1000
+ }
1001
+ output
1002
+ }
1003
+ pub(crate) fn clone_ids(&mut self, ids: &[u32], deep: bool) -> Vec<u32> {
1004
+ ids.iter()
1005
+ .filter_map(|id| self.clone_branch(*id, deep))
1006
+ .collect()
1007
+ }
1008
+ fn clone_branch(&mut self, root: u32, deep: bool) -> Option<u32> {
1009
+ let mut node = self.node(root)?.clone();
1010
+ if node.is_element() {
1011
+ node.extras.remove("data");
1012
+ }
1013
+ let source_children = node.children.clone();
1014
+ node.children.clear();
1015
+ node.parent = None;
1016
+ node.prev = None;
1017
+ node.next = None;
1018
+ let new_root = self.push(node);
1019
+ if deep {
1020
+ let mut queue = vec![(new_root, source_children)];
1021
+ while let Some((parent, children)) = queue.pop() {
1022
+ for child in children {
1023
+ if let Some(node) = self.node(child) {
1024
+ let mut copy = node.clone();
1025
+ if copy.is_element() {
1026
+ copy.extras.remove("data");
1027
+ }
1028
+ let child_children = copy.children.clone();
1029
+ copy.children.clear();
1030
+ copy.parent = None;
1031
+ copy.prev = None;
1032
+ copy.next = None;
1033
+ let id = self.push(copy);
1034
+ self.nodes[parent as usize].children.push(id);
1035
+ queue.push((id, child_children));
1036
+ }
1037
+ }
1038
+ self.relink(parent);
1039
+ }
1040
+ }
1041
+ Some(new_root)
1042
+ }
1043
+ pub(crate) fn import(&mut self, records: &[DomNode], roots: &[u32]) -> Vec<u32> {
1044
+ self.import_internal(records, roots, true)
1045
+ }
1046
+ fn import_internal(
1047
+ &mut self,
1048
+ records: &[DomNode],
1049
+ roots: &[u32],
1050
+ detach_roots: bool,
1051
+ ) -> Vec<u32> {
1052
+ self.nodes.reserve(records.len());
1053
+ let mut mapping = HashMap::new();
1054
+ for record in records {
1055
+ let mut node = record.clone();
1056
+ node.children.clear();
1057
+ node.parent = None;
1058
+ node.prev = None;
1059
+ node.next = None;
1060
+ let id = self.push(node);
1061
+ mapping.insert(record.id, id);
1062
+ }
1063
+ for record in records {
1064
+ if let Some(id) = mapping.get(&record.id) {
1065
+ self.nodes[*id as usize].children = record
1066
+ .children
1067
+ .iter()
1068
+ .filter_map(|child| mapping.get(child).copied())
1069
+ .collect();
1070
+ self.relink(*id);
1071
+ }
1072
+ }
1073
+ let roots: Vec<_> = roots
1074
+ .iter()
1075
+ .filter_map(|root| mapping.get(root).copied())
1076
+ .collect();
1077
+ if detach_roots {
1078
+ self.detach_many(&roots);
1079
+ }
1080
+ roots
1081
+ }
1082
+ pub(crate) fn create_fragment(&mut self, html: &str, context: Option<u32>) -> Result<Vec<u32>> {
1083
+ let parsed = self.parse_fragment(html, context)?;
1084
+ let roots = parsed.nodes[0].children.clone();
1085
+ Ok(self.import_internal(&parsed.nodes, &roots, false))
1086
+ }
1087
+ /// Parses `html` as the children of `context`; only the context's name
1088
+ /// and namespace affect the result.
1089
+ fn parse_fragment(&self, html: &str, context: Option<u32>) -> Result<DomArena> {
1090
+ let (context_name, namespace) = self.fragment_context(context);
1091
+ let mut options = self.options.clone();
1092
+ if let Some(namespace) = namespace {
1093
+ options["__contextNamespace"] = Value::String(namespace);
1094
+ }
1095
+ let document =
1096
+ super::NativeDocument::parse_options(html, false, options, context_name.as_deref());
1097
+ document.ensure_arena()?;
1098
+ let parsed = document.arena.borrow_mut().take().unwrap();
1099
+ Ok(parsed)
1100
+ }
1101
+ fn fragment_context(&self, context: Option<u32>) -> (Option<String>, Option<String>) {
1102
+ let node = context.and_then(|id| self.node(id));
1103
+ (
1104
+ node.and_then(|node| node.name.clone()),
1105
+ node.and_then(|node| node.namespace.as_deref().map(str::to_owned)),
1106
+ )
1107
+ }
1108
+ pub(crate) fn set_html(&mut self, ids: &[u32], html: &str) -> Result<()> {
1109
+ // Each target receives its own copy; targets of the same element type
1110
+ // share one parse, since the result depends only on that context.
1111
+ let mut parsed: HashMap<(Option<String>, Option<String>), DomArena> = HashMap::new();
1112
+ for id in ids {
1113
+ let key = self.fragment_context(Some(*id));
1114
+ if !parsed.contains_key(&key) {
1115
+ let fragment = self.parse_fragment(html, Some(*id))?;
1116
+ parsed.insert(key.clone(), fragment);
1117
+ }
1118
+ let fragment = &parsed[&key];
1119
+ let roots = fragment.nodes[0].children.clone();
1120
+ let children = self.import_internal(&fragment.nodes, &roots, false);
1121
+ self.set_children(*id, &children);
1122
+ }
1123
+ Ok(())
1124
+ }
1125
+ pub(crate) fn insert(&mut self, targets: &[u32], ids: &[u32], position: &str) -> Vec<u32> {
1126
+ let mut inserted = Vec::new();
1127
+ for (index, target) in targets.iter().enumerate() {
1128
+ // As Cheerio, only nodes that can hold children are targets.
1129
+ if !self.node(*target).is_some_and(|node| {
1130
+ node.is_element() || matches!(node.kind.as_ref(), "root" | "cdata")
1131
+ }) {
1132
+ continue;
1133
+ }
1134
+ if matches!(position, "append" | "prepend")
1135
+ && !self
1136
+ .node(*target)
1137
+ .is_some_and(|node| node.is_element() || node.kind == "root")
1138
+ {
1139
+ continue;
1140
+ }
1141
+ let ids = if index + 1 == targets.len() {
1142
+ ids.to_vec()
1143
+ } else {
1144
+ self.clone_ids(ids, true)
1145
+ };
1146
+ let (parent, mut offset) = if matches!(position, "append" | "prepend") {
1147
+ (
1148
+ *target,
1149
+ if position == "append" {
1150
+ self.nodes[*target as usize].children.len()
1151
+ } else {
1152
+ 0
1153
+ },
1154
+ )
1155
+ } else {
1156
+ let Some(parent) = self.nodes[*target as usize].parent else {
1157
+ continue;
1158
+ };
1159
+ let at = self.nodes[parent as usize]
1160
+ .children
1161
+ .iter()
1162
+ .position(|id| id == target)
1163
+ .unwrap_or(0);
1164
+ (parent, at + usize::from(position == "after"))
1165
+ };
1166
+ let valid: Vec<_> = ids
1167
+ .iter()
1168
+ .copied()
1169
+ .filter(|id| *id != parent && self.node(*id).is_some())
1170
+ .collect();
1171
+ let removed: HashSet<_> = valid.iter().copied().collect();
1172
+ offset -= self.nodes[parent as usize]
1173
+ .children
1174
+ .iter()
1175
+ .take(offset)
1176
+ .filter(|id| removed.contains(id))
1177
+ .count();
1178
+ self.detach_many(&valid);
1179
+ let mut seen = HashSet::new();
1180
+ let mut moved: Vec<_> = valid
1181
+ .iter()
1182
+ .rev()
1183
+ .copied()
1184
+ .filter(|id| seen.insert(*id))
1185
+ .collect();
1186
+ moved.reverse();
1187
+ let offset = offset.min(self.nodes[parent as usize].children.len());
1188
+ self.nodes[parent as usize]
1189
+ .children
1190
+ .insert_many(offset, moved);
1191
+ inserted.extend(valid);
1192
+ self.relink(parent);
1193
+ if position == "replace" && !ids.contains(target) {
1194
+ self.detach(*target);
1195
+ }
1196
+ }
1197
+ inserted
1198
+ }
1199
+ pub(crate) fn traverse(&self, ids: &[u32], kind: &str) -> Vec<u32> {
1200
+ let mut result = Vec::new();
1201
+ for id in ids {
1202
+ let Some(node) = self.node(*id) else {
1203
+ continue;
1204
+ };
1205
+ match kind {
1206
+ "children" => result.extend(
1207
+ node.children
1208
+ .iter()
1209
+ .copied()
1210
+ .filter(|id| self.node(*id).is_some_and(DomNode::is_element)),
1211
+ ),
1212
+ "contents" => result.extend(node.children.iter().copied()),
1213
+ "parent" => result.extend(
1214
+ node.parent
1215
+ .filter(|id| self.node(*id).is_some_and(DomNode::is_element)),
1216
+ ),
1217
+ "parents" | "ancestors" => {
1218
+ // Like Cheerio, stop at the first document node. A template's
1219
+ // contents live in a fragment, so they never report the
1220
+ // template or its ancestors as their own.
1221
+ let mut parent = node.parent;
1222
+ let mut seen = HashSet::new();
1223
+ while let Some(id) = parent {
1224
+ if !seen.insert(id) {
1225
+ break;
1226
+ }
1227
+ let Some(ancestor) = self.node(id) else {
1228
+ break;
1229
+ };
1230
+ if ancestor.kind == "root" {
1231
+ break;
1232
+ }
1233
+ if ancestor.is_element() {
1234
+ result.push(id);
1235
+ }
1236
+ parent = ancestor.parent;
1237
+ }
1238
+ }
1239
+ "next" | "prev" | "nextAll" | "prevAll" => {
1240
+ let forward = kind.starts_with("next");
1241
+ let mut next = if forward { node.next } else { node.prev };
1242
+ let mut seen = HashSet::new();
1243
+ while let Some(id) = next {
1244
+ if !seen.insert(id) {
1245
+ break;
1246
+ }
1247
+ if self.node(id).is_some_and(DomNode::is_element) {
1248
+ result.push(id);
1249
+ if kind == "next" || kind == "prev" {
1250
+ break;
1251
+ }
1252
+ }
1253
+ next = self
1254
+ .node(id)
1255
+ .and_then(|node| if forward { node.next } else { node.prev });
1256
+ }
1257
+ }
1258
+ "siblings" => {
1259
+ if let Some(parent) = node.parent.and_then(|parent| self.node(parent)) {
1260
+ result.extend(parent.children.iter().copied().filter(|other| {
1261
+ other != id && self.node(*other).is_some_and(DomNode::is_element)
1262
+ }));
1263
+ }
1264
+ }
1265
+ "descendants" => {
1266
+ let mut stack: Vec<_> = node.children.iter().rev().copied().collect();
1267
+ while let Some(id) = stack.pop() {
1268
+ if let Some(node) = self.node(id) {
1269
+ if node.is_element() {
1270
+ result.push(id);
1271
+ }
1272
+ stack.extend(node.children.iter().rev().copied());
1273
+ }
1274
+ }
1275
+ }
1276
+ _ => {}
1277
+ }
1278
+ }
1279
+ result
1280
+ }
1281
+ pub(crate) fn set_node(&mut self, id: u32, field: &str, value: &Value) -> Result<()> {
1282
+ if self.node(id).is_none() {
1283
+ return Ok(());
1284
+ }
1285
+ if field == "children" {
1286
+ self.set_children(id, &value_ids(value));
1287
+ return Ok(());
1288
+ }
1289
+ let node = &mut self.nodes[id as usize];
1290
+ match field {
1291
+ "name" | "tagName" => node.name = value.as_str().map(str::to_owned),
1292
+ "data" | "nodeValue" => node.data = value.as_str().map(str::to_owned),
1293
+ "type" => node.kind = node_kind(value.as_str().unwrap_or("tag")),
1294
+ "attribs" => node.attribs = value.as_object().cloned().unwrap_or_default().into(),
1295
+ "parent" => node.parent = value.as_u64().map(|id| id as u32),
1296
+ "prev" => node.prev = value.as_u64().map(|id| id as u32),
1297
+ "next" => node.next = value.as_u64().map(|id| id as u32),
1298
+ "namespace" => node.namespace = value.as_str().map(namespace_name),
1299
+ "attribsNamespace" | "x-attribsNamespace" => {
1300
+ node.attribs_namespace = value.as_object().cloned().map(Box::new)
1301
+ }
1302
+ "attribsPrefix" | "x-attribsPrefix" => {
1303
+ node.attribs_prefix = value.as_object().cloned().map(Box::new)
1304
+ }
1305
+ _ => {
1306
+ if value.is_null() {
1307
+ node.extras.remove(field);
1308
+ } else {
1309
+ node.extras.insert(field.into(), value.clone());
1310
+ }
1311
+ }
1312
+ }
1313
+ Ok(())
1314
+ }
1315
+ }
1316
+
1317
+ impl super::selector::SelectDom for DomArena {
1318
+ fn kind(&self, id: u32) -> &str {
1319
+ self.node(id).map_or("", |node| node.kind.as_ref())
1320
+ }
1321
+ fn name(&self, id: u32) -> Option<&str> {
1322
+ self.node(id)?.name.as_deref()
1323
+ }
1324
+ fn attr(&self, id: u32, name: &str) -> Option<&str> {
1325
+ DomArena::attr(self, id, name)
1326
+ }
1327
+ fn parent(&self, id: u32) -> Option<u32> {
1328
+ self.node(id)?.parent
1329
+ }
1330
+ fn children(&self, id: u32) -> &[u32] {
1331
+ self.node(id).map_or(&[], |node| node.children.as_slice())
1332
+ }
1333
+ fn text(&self, id: u32) -> String {
1334
+ DomArena::text(self, &[id])
1335
+ }
1336
+ fn xml_mode(&self) -> bool {
1337
+ DomArena::xml_mode(self)
1338
+ }
1339
+ fn lower_case_tags(&self) -> bool {
1340
+ self.options
1341
+ .get("lowerCaseTags")
1342
+ .and_then(Value::as_bool)
1343
+ .unwrap_or(!self.xml_mode())
1344
+ }
1345
+ fn lower_case_attribute_names(&self) -> bool {
1346
+ self.options
1347
+ .get("lowerCaseAttributeNames")
1348
+ .and_then(Value::as_bool)
1349
+ .unwrap_or(!self.xml_mode())
1350
+ }
1351
+ fn custom_pseudo(&self, id: u32, name: &str, arg: Option<&str>) -> Option<bool> {
1352
+ let key = format!("{}({})", name, arg.unwrap_or(""));
1353
+ self.options
1354
+ .get("__pseudoMatches")?
1355
+ .get(&key)?
1356
+ .as_array()
1357
+ .map(|ids| ids.iter().any(|value| value.as_u64() == Some(id as u64)))
1358
+ }
1359
+ fn pseudo_alias(&self, name: &str) -> Option<&str> {
1360
+ self.options.get("pseudos")?.get(name)?.as_str()
1361
+ }
1362
+ fn elements_named(&self, lowercase_name: &str) -> Option<&[u32]> {
1363
+ let index = self.name_index.as_ref()?;
1364
+ Some(index.get(lowercase_name).map_or(&[], Vec::as_slice))
1365
+ }
1366
+ fn is_id_order_document_order(&self) -> bool {
1367
+ self.name_index.is_some()
1368
+ }
1369
+ }
1370
+
1371
+ pub(crate) fn value_ids(value: &Value) -> Vec<u32> {
1372
+ value
1373
+ .as_array()
1374
+ .map(|ids| {
1375
+ ids.iter()
1376
+ .filter_map(|id| id.as_u64().map(|id| id as u32))
1377
+ .collect()
1378
+ })
1379
+ .unwrap_or_default()
1380
+ }
1381
+ pub(crate) fn xml_mode(options: &Value) -> bool {
1382
+ options
1383
+ .get("xmlMode")
1384
+ .and_then(Value::as_bool)
1385
+ .unwrap_or_else(|| {
1386
+ options
1387
+ .get("xml")
1388
+ .is_some_and(|xml| xml.is_object() || xml == &Value::Bool(true))
1389
+ })
1390
+ }
1391
+ pub(crate) fn normalized_options(mut options: Value) -> Value {
1392
+ if !options.is_object() {
1393
+ options = json!({});
1394
+ }
1395
+ if let Some(xml) = options.get("xml").and_then(Value::as_object).cloned() {
1396
+ options["xmlMode"] = Value::Bool(true);
1397
+ options["_useHtmlParser2"] = Value::Bool(true);
1398
+ for (key, value) in xml {
1399
+ options[&key] = value;
1400
+ }
1401
+ } else if options.get("xml") == Some(&Value::Bool(true)) {
1402
+ options["xmlMode"] = Value::Bool(true);
1403
+ options["_useHtmlParser2"] = Value::Bool(true);
1404
+ }
1405
+ options
1406
+ }
1407
+ fn is_foreign_integration_child(arena: &DomArena, node: &DomNode) -> bool {
1408
+ node.parent
1409
+ .and_then(|id| arena.node(id))
1410
+ .and_then(|parent| parent.name.as_deref())
1411
+ .is_some_and(|name| {
1412
+ matches!(
1413
+ foreign_element_name(name),
1414
+ "mi" | "mo"
1415
+ | "mn"
1416
+ | "ms"
1417
+ | "mtext"
1418
+ | "annotation-xml"
1419
+ | "foreignObject"
1420
+ | "desc"
1421
+ | "title"
1422
+ )
1423
+ })
1424
+ }
1425
+ fn foreign_element_name(name: &str) -> &str {
1426
+ match name {
1427
+ "altglyph" => "altGlyph",
1428
+ "altglyphdef" => "altGlyphDef",
1429
+ "altglyphitem" => "altGlyphItem",
1430
+ "animatecolor" => "animateColor",
1431
+ "animatemotion" => "animateMotion",
1432
+ "animatetransform" => "animateTransform",
1433
+ "clippath" => "clipPath",
1434
+ "feblend" => "feBlend",
1435
+ "fecolormatrix" => "feColorMatrix",
1436
+ "fecomponenttransfer" => "feComponentTransfer",
1437
+ "fecomposite" => "feComposite",
1438
+ "feconvolvematrix" => "feConvolveMatrix",
1439
+ "fediffuselighting" => "feDiffuseLighting",
1440
+ "fedisplacementmap" => "feDisplacementMap",
1441
+ "fedistantlight" => "feDistantLight",
1442
+ "fedropshadow" => "feDropShadow",
1443
+ "feflood" => "feFlood",
1444
+ "fefunca" => "feFuncA",
1445
+ "fefuncb" => "feFuncB",
1446
+ "fefuncg" => "feFuncG",
1447
+ "fefuncr" => "feFuncR",
1448
+ "fegaussianblur" => "feGaussianBlur",
1449
+ "feimage" => "feImage",
1450
+ "femerge" => "feMerge",
1451
+ "femergenode" => "feMergeNode",
1452
+ "femorphology" => "feMorphology",
1453
+ "feoffset" => "feOffset",
1454
+ "fepointlight" => "fePointLight",
1455
+ "fespecularlighting" => "feSpecularLighting",
1456
+ "fespotlight" => "feSpotLight",
1457
+ "fetile" => "feTile",
1458
+ "feturbulence" => "feTurbulence",
1459
+ "foreignobject" => "foreignObject",
1460
+ "glyphref" => "glyphRef",
1461
+ "lineargradient" => "linearGradient",
1462
+ "radialgradient" => "radialGradient",
1463
+ "textpath" => "textPath",
1464
+ _ => name,
1465
+ }
1466
+ }
1467
+ fn foreign_attribute_name(name: &str) -> &str {
1468
+ match name {
1469
+ "definitionurl" => "definitionURL",
1470
+ "attributename" => "attributeName",
1471
+ "attributetype" => "attributeType",
1472
+ "basefrequency" => "baseFrequency",
1473
+ "baseprofile" => "baseProfile",
1474
+ "calcmode" => "calcMode",
1475
+ "clippathunits" => "clipPathUnits",
1476
+ "diffuseconstant" => "diffuseConstant",
1477
+ "edgemode" => "edgeMode",
1478
+ "filterunits" => "filterUnits",
1479
+ "glyphref" => "glyphRef",
1480
+ "gradienttransform" => "gradientTransform",
1481
+ "gradientunits" => "gradientUnits",
1482
+ "kernelmatrix" => "kernelMatrix",
1483
+ "kernelunitlength" => "kernelUnitLength",
1484
+ "keypoints" => "keyPoints",
1485
+ "keysplines" => "keySplines",
1486
+ "keytimes" => "keyTimes",
1487
+ "lengthadjust" => "lengthAdjust",
1488
+ "limitingconeangle" => "limitingConeAngle",
1489
+ "markerheight" => "markerHeight",
1490
+ "markerunits" => "markerUnits",
1491
+ "markerwidth" => "markerWidth",
1492
+ "maskcontentunits" => "maskContentUnits",
1493
+ "maskunits" => "maskUnits",
1494
+ "numoctaves" => "numOctaves",
1495
+ "pathlength" => "pathLength",
1496
+ "patterncontentunits" => "patternContentUnits",
1497
+ "patterntransform" => "patternTransform",
1498
+ "patternunits" => "patternUnits",
1499
+ "pointsatx" => "pointsAtX",
1500
+ "pointsaty" => "pointsAtY",
1501
+ "pointsatz" => "pointsAtZ",
1502
+ "preservealpha" => "preserveAlpha",
1503
+ "preserveaspectratio" => "preserveAspectRatio",
1504
+ "primitiveunits" => "primitiveUnits",
1505
+ "refx" => "refX",
1506
+ "refy" => "refY",
1507
+ "repeatcount" => "repeatCount",
1508
+ "repeatdur" => "repeatDur",
1509
+ "requiredextensions" => "requiredExtensions",
1510
+ "requiredfeatures" => "requiredFeatures",
1511
+ "specularconstant" => "specularConstant",
1512
+ "specularexponent" => "specularExponent",
1513
+ "spreadmethod" => "spreadMethod",
1514
+ "startoffset" => "startOffset",
1515
+ "stddeviation" => "stdDeviation",
1516
+ "stitchtiles" => "stitchTiles",
1517
+ "surfacescale" => "surfaceScale",
1518
+ "systemlanguage" => "systemLanguage",
1519
+ "tablevalues" => "tableValues",
1520
+ "targetx" => "targetX",
1521
+ "targety" => "targetY",
1522
+ "textlength" => "textLength",
1523
+ "viewbox" => "viewBox",
1524
+ "viewtarget" => "viewTarget",
1525
+ "xchannelselector" => "xChannelSelector",
1526
+ "ychannelselector" => "yChannelSelector",
1527
+ "zoomandpan" => "zoomAndPan",
1528
+ _ => name,
1529
+ }
1530
+ }
1531
+ /// entities 1.1 `encodeXML`, as dom-serializer 0.1.x applies it: the five
1532
+ /// named XML entities, then every non-ASCII scalar as an uppercase hex
1533
+ /// reference. Astral scalars encode as single combined code points, matching
1534
+ /// the original surrogate-pair replacer.
1535
+ fn legacy_escape(value: &str, output: &mut String) {
1536
+ use std::fmt::Write;
1537
+ for ch in value.chars() {
1538
+ match ch {
1539
+ '&' => output.push_str("&amp;"),
1540
+ '\'' => output.push_str("&apos;"),
1541
+ '>' => output.push_str("&gt;"),
1542
+ '<' => output.push_str("&lt;"),
1543
+ '"' => output.push_str("&quot;"),
1544
+ ch if ch > '\u{7f}' => {
1545
+ let _ = write!(output, "&#x{:X};", ch as u32);
1546
+ }
1547
+ ch => output.push(ch),
1548
+ }
1549
+ }
1550
+ }
1551
+
1552
+ fn escape(value: &str, attribute: bool, xml: bool, utf8: bool, output: &mut String) {
1553
+ if xml && !utf8 && crate::codec::has_encoding(value) {
1554
+ use std::fmt::Write;
1555
+ let units = crate::codec::to_units(value);
1556
+ let mut index = 0;
1557
+ while index < units.len() {
1558
+ let unit = units[index];
1559
+ let named = match unit {
1560
+ 34 => Some("&quot;"),
1561
+ 38 => Some("&amp;"),
1562
+ 39 => Some("&apos;"),
1563
+ 60 => Some("&lt;"),
1564
+ 62 => Some("&gt;"),
1565
+ _ => None,
1566
+ };
1567
+ if let Some(named) = named {
1568
+ output.push_str(named);
1569
+ index += 1;
1570
+ continue;
1571
+ }
1572
+ if unit >= 0x80 || unit == 0x24 {
1573
+ let high = (0xd800..=0xdbff).contains(&unit);
1574
+ let code = if high
1575
+ && units
1576
+ .get(index + 1)
1577
+ .is_some_and(|unit| (0xdc00..=0xdfff).contains(unit))
1578
+ {
1579
+ 0x10000 + ((unit as u32 - 0xd800) << 10) + (units[index + 1] as u32 - 0xdc00)
1580
+ } else {
1581
+ unit as u32
1582
+ };
1583
+ let _ = write!(output, "&#x{code:x};");
1584
+ // entities.encodeXML advances over a following code unit for
1585
+ // every high surrogate, including a lone high surrogate.
1586
+ index += if high { 2 } else { 1 };
1587
+ } else {
1588
+ output.push(char::from_u32(unit as u32).unwrap());
1589
+ index += 1;
1590
+ }
1591
+ }
1592
+ return;
1593
+ }
1594
+ for ch in value.chars() {
1595
+ match ch {
1596
+ '&' => output.push_str("&amp;"),
1597
+ '"' if attribute || xml => output.push_str("&quot;"),
1598
+ '\'' if xml => output.push_str("&apos;"),
1599
+ '<' if !attribute || xml => output.push_str("&lt;"),
1600
+ '>' if !attribute || xml => output.push_str("&gt;"),
1601
+ '\u{a0}' if !xml => output.push_str("&nbsp;"),
1602
+ ch if xml && !utf8 && (ch > '\u{7f}' || ch == '$') => {
1603
+ use std::fmt::Write;
1604
+ let _ = write!(output, "&#x{:x};", ch as u32);
1605
+ }
1606
+ ch => output.push(ch),
1607
+ }
1608
+ }
1609
+ }
1610
+
1611
+ pub(crate) fn parse_xml(source: &str, options: Value) -> DomArena {
1612
+ crate::tokenizer::parse_markup(source, options)
1613
+ }
1614
+
1615
+ /// Incremental htmlparser2/XML input. The complete input is tokenized once, so
1616
+ /// tags and entities split across chunks parse exactly as one string does.
1617
+ pub(crate) struct XmlStream {
1618
+ pub arena: DomArena,
1619
+ pending: String,
1620
+ }
1621
+ impl XmlStream {
1622
+ pub(crate) fn new(options: Value) -> Self {
1623
+ Self {
1624
+ arena: DomArena::from_records(vec![DomNode::new("root")], options),
1625
+ pending: String::new(),
1626
+ }
1627
+ }
1628
+ pub(crate) fn feed(&mut self, chunk: &str, finish: bool) {
1629
+ self.pending.push_str(chunk);
1630
+ if finish {
1631
+ let options = self.arena.options.clone();
1632
+ self.arena = parse_xml(&std::mem::take(&mut self.pending), options);
1633
+ }
1634
+ }
1635
+ }
1636
+ pub(crate) fn append_parsed(
1637
+ arena: &mut DomArena,
1638
+ parent: u32,
1639
+ mut node: DomNode,
1640
+ start: usize,
1641
+ end: usize,
1642
+ ) -> u32 {
1643
+ let (start_indices, end_indices) = *arena.parse_indices.get_or_insert_with(|| {
1644
+ (
1645
+ arena.options.get("withStartIndices") == Some(&Value::Bool(true)),
1646
+ arena.options.get("withEndIndices") == Some(&Value::Bool(true)),
1647
+ )
1648
+ });
1649
+ if node.kind == "text" {
1650
+ if let Some(previous) = arena.nodes[parent as usize]
1651
+ .children
1652
+ .last()
1653
+ .copied()
1654
+ .filter(|id| arena.nodes[*id as usize].kind == "text")
1655
+ {
1656
+ arena.nodes[previous as usize]
1657
+ .data
1658
+ .get_or_insert_with(String::new)
1659
+ .push_str(node.data.as_deref().unwrap_or(""));
1660
+ if end_indices {
1661
+ arena.nodes[previous as usize]
1662
+ .extras
1663
+ .insert("endIndex".into(), json!(end));
1664
+ }
1665
+ return previous;
1666
+ }
1667
+ }
1668
+ if start_indices {
1669
+ node.extras.insert("startIndex".into(), json!(start));
1670
+ }
1671
+ if end_indices {
1672
+ node.extras.insert("endIndex".into(), json!(end));
1673
+ }
1674
+ let previous = arena.nodes[parent as usize].children.last().copied();
1675
+ node.parent = Some(parent);
1676
+ node.prev = previous;
1677
+ let id = arena.push(node);
1678
+ if let Some(previous) = previous {
1679
+ arena.nodes[previous as usize].next = Some(id);
1680
+ }
1681
+ arena.nodes[parent as usize].children.push(id);
1682
+ id
1683
+ }
1684
+
1685
+ /// Appends a fresh node of `kind` to `parent` and returns its id. The record
1686
+ /// is built in the arena itself: moving a whole record through the callers
1687
+ /// copied it several times per node.
1688
+ pub(crate) fn append_parsed_new(
1689
+ arena: &mut DomArena,
1690
+ parent: u32,
1691
+ kind: &'static str,
1692
+ start: usize,
1693
+ end: usize,
1694
+ ) -> u32 {
1695
+ let (start_indices, end_indices) = parse_index_flags(arena);
1696
+ let previous = arena.nodes[parent as usize].children.last().copied();
1697
+ let id = arena.push(DomNode::new(kind));
1698
+ let node = &mut arena.nodes[id as usize];
1699
+ node.parent = Some(parent);
1700
+ node.prev = previous;
1701
+ if start_indices {
1702
+ node.extras.insert("startIndex".into(), json!(start));
1703
+ }
1704
+ if end_indices {
1705
+ node.extras.insert("endIndex".into(), json!(end));
1706
+ }
1707
+ if let Some(previous) = previous {
1708
+ arena.nodes[previous as usize].next = Some(id);
1709
+ }
1710
+ arena.nodes[parent as usize].children.push(id);
1711
+ id
1712
+ }
1713
+
1714
+ /// Whether parsing records start and end indices, read once per parse.
1715
+ fn parse_index_flags(arena: &mut DomArena) -> (bool, bool) {
1716
+ *arena.parse_indices.get_or_insert_with(|| {
1717
+ (
1718
+ arena.options.get("withStartIndices") == Some(&Value::Bool(true)),
1719
+ arena.options.get("withEndIndices") == Some(&Value::Bool(true)),
1720
+ )
1721
+ })
1722
+ }
1723
+
1724
+ /// Appends parsed text to `parent`, merging it into a preceding text node.
1725
+ pub(crate) fn append_parsed_text(
1726
+ arena: &mut DomArena,
1727
+ parent: u32,
1728
+ data: String,
1729
+ start: usize,
1730
+ end: usize,
1731
+ ) -> u32 {
1732
+ let previous_text = arena.nodes[parent as usize]
1733
+ .children
1734
+ .last()
1735
+ .copied()
1736
+ .filter(|id| arena.nodes[*id as usize].kind == "text");
1737
+ if let Some(previous) = previous_text {
1738
+ let (_, end_indices) = parse_index_flags(arena);
1739
+ let node = &mut arena.nodes[previous as usize];
1740
+ node.data.get_or_insert_with(String::new).push_str(&data);
1741
+ if end_indices {
1742
+ node.extras.insert("endIndex".into(), json!(end));
1743
+ }
1744
+ return previous;
1745
+ }
1746
+ let id = append_parsed_new(arena, parent, "text", start, end);
1747
+ arena.nodes[id as usize].data = Some(data);
1748
+ id
1749
+ }
1750
+
1751
+ pub(crate) fn html_parser_void(name: &str) -> bool {
1752
+ (super::void_name(name) && name != "bgsound") || matches!(name, "command" | "isindex")
1753
+ }
1754
+ pub(crate) fn implied_close(name: &str, open: &str) -> bool {
1755
+ match name {
1756
+ "tr" => matches!(open, "tr" | "th" | "td"),
1757
+ "th" => open == "th",
1758
+ "td" => matches!(open, "thead" | "th" | "td"),
1759
+ "body" => matches!(open, "head" | "link" | "script"),
1760
+ "li" => open == "li",
1761
+ "option" => open == "option",
1762
+ "optgroup" => matches!(open, "option" | "optgroup"),
1763
+ "select" | "input" | "output" | "button" | "datalist" | "textarea" => matches!(
1764
+ open,
1765
+ "input" | "option" | "optgroup" | "select" | "button" | "datalist" | "textarea"
1766
+ ),
1767
+ "dd" | "dt" => matches!(open, "dd" | "dt"),
1768
+ "rt" | "rp" => matches!(open, "rt" | "rp"),
1769
+ "tbody" | "tfoot" => matches!(open, "thead" | "tbody"),
1770
+ "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "address" | "article" | "aside"
1771
+ | "blockquote" | "details" | "div" | "dl" | "fieldset" | "figcaption" | "figure"
1772
+ | "footer" | "form" | "header" | "hr" | "main" | "nav" | "ol" | "pre" | "section"
1773
+ | "table" | "ul" => open == "p",
1774
+ _ => false,
1775
+ }
1776
+ }
1777
+ pub(crate) fn decode_entities_mode(
1778
+ source: &str,
1779
+ xml: bool,
1780
+ attribute: bool,
1781
+ codec: bool,
1782
+ ) -> String {
1783
+ let scalar_string = |scalar: char| {
1784
+ if codec {
1785
+ crate::codec::encode_scalar(scalar)
1786
+ } else {
1787
+ scalar.to_string()
1788
+ }
1789
+ };
1790
+ let bytes = source.as_bytes();
1791
+ let mut output = String::with_capacity(source.len());
1792
+ let mut cursor = 0;
1793
+ while let Some(relative) = source[cursor..].find('&') {
1794
+ let amp = cursor + relative;
1795
+ output.push_str(&source[cursor..amp]);
1796
+ let mut end = amp + 1;
1797
+ let mut decoded = None;
1798
+ if bytes.get(end) == Some(&b'#') {
1799
+ end += 1;
1800
+ let hexadecimal = matches!(bytes.get(end), Some(b'x' | b'X'));
1801
+ if hexadecimal {
1802
+ end += 1;
1803
+ }
1804
+ let digits = end;
1805
+ let mut number = 0u32;
1806
+ while let Some(digit) = bytes
1807
+ .get(end)
1808
+ .and_then(|value| (*value as char).to_digit(if hexadecimal { 16 } else { 10 }))
1809
+ {
1810
+ number = number
1811
+ .saturating_mul(if hexadecimal { 16 } else { 10 })
1812
+ .saturating_add(digit);
1813
+ end += 1;
1814
+ }
1815
+ let semicolon = bytes.get(end) == Some(&b';');
1816
+ if digits != end && (!xml || semicolon) {
1817
+ if semicolon {
1818
+ end += 1;
1819
+ }
1820
+ let scalar = match number {
1821
+ 0 | 0xd800..=0xdfff | 0x110000..=u32::MAX => '\u{fffd}',
1822
+ 0x80..=0x9f => html5ever::data::C1_REPLACEMENTS[(number - 0x80) as usize]
1823
+ .unwrap_or(char::from_u32(number).unwrap()),
1824
+ _ => char::from_u32(number).unwrap(),
1825
+ };
1826
+ decoded = Some(scalar_string(scalar));
1827
+ }
1828
+ } else {
1829
+ while bytes.get(end).is_some_and(u8::is_ascii_alphanumeric) {
1830
+ end += 1;
1831
+ }
1832
+ if bytes.get(end) == Some(&b';') {
1833
+ end += 1;
1834
+ }
1835
+ if xml {
1836
+ let scalar = match &source[amp + 1..end] {
1837
+ "amp;" => Some('&'),
1838
+ "lt;" => Some('<'),
1839
+ "gt;" => Some('>'),
1840
+ "quot;" => Some('"'),
1841
+ "apos;" => Some('\''),
1842
+ _ => None,
1843
+ };
1844
+ decoded = scalar.map(scalar_string);
1845
+ } else {
1846
+ for candidate in (amp + 2..=end).rev() {
1847
+ if let Some(&(first, second)) =
1848
+ html5ever::data::NAMED_ENTITIES.get(&source[amp + 1..candidate])
1849
+ {
1850
+ if first == 0 {
1851
+ continue;
1852
+ }
1853
+ if bytes[candidate - 1] != b';'
1854
+ && attribute
1855
+ && bytes
1856
+ .get(candidate)
1857
+ .is_some_and(|next| next.is_ascii_alphanumeric() || *next == b'=')
1858
+ {
1859
+ break;
1860
+ }
1861
+ let mut value = scalar_string(char::from_u32(first).unwrap());
1862
+ if second != 0 {
1863
+ value.push_str(&scalar_string(char::from_u32(second).unwrap()));
1864
+ }
1865
+ decoded = Some(value);
1866
+ end = candidate;
1867
+ break;
1868
+ }
1869
+ }
1870
+ }
1871
+ }
1872
+ if let Some(value) = decoded {
1873
+ output.push_str(&value);
1874
+ cursor = end;
1875
+ } else {
1876
+ output.push('&');
1877
+ cursor = amp + 1;
1878
+ }
1879
+ }
1880
+ output.push_str(&source[cursor..]);
1881
+ output
1882
+ }
1883
+
1884
+ pub(crate) fn primitive(arena: &mut DomArena, command: &str, args: &Value) -> Result<Value> {
1885
+ let ids = value_ids(&args["ids"]);
1886
+ let id = args["id"].as_u64().unwrap_or(0) as u32;
1887
+ Ok(match command {
1888
+ "node" => arena
1889
+ .node(id)
1890
+ .map(|node| serde_json::to_value(node).unwrap())
1891
+ .unwrap_or(Value::Null),
1892
+ "createNode" => {
1893
+ let mut fields = args.clone();
1894
+ if let Some(fields) = fields.as_object_mut() {
1895
+ fields.remove("options");
1896
+ }
1897
+ let mut node: DomNode = serde_json::from_value(fields)
1898
+ .map_err(|error| Error::new(Status::InvalidArg, error.to_string()))?;
1899
+ node.children.clear();
1900
+ node.parent = None;
1901
+ node.prev = None;
1902
+ node.next = None;
1903
+ json!(arena.push(node))
1904
+ }
1905
+ "setNode" => {
1906
+ arena.set_node(id, args["field"].as_str().unwrap_or(""), &args["value"])?;
1907
+ Value::Null
1908
+ }
1909
+ "setAttrs" => {
1910
+ // Batched single-attribute writes for one selection: one boundary
1911
+ // crossing instead of one per element.
1912
+ if let Some(writes) = args.get("writes").and_then(Value::as_array) {
1913
+ for write in writes {
1914
+ let id = write
1915
+ .get("id")
1916
+ .and_then(Value::as_u64)
1917
+ .unwrap_or(u32::MAX as u64) as u32;
1918
+ if let Some(node) = arena
1919
+ .node_mut(id)
1920
+ .filter(|node| node.is_element() || node.kind == "root")
1921
+ {
1922
+ if let Some(attrs) = write.get("attrs").and_then(Value::as_array) {
1923
+ for attr in attrs {
1924
+ let name = attr.get("name").and_then(Value::as_str).unwrap_or("");
1925
+ if name.is_empty() {
1926
+ continue;
1927
+ }
1928
+ match attr.get("value") {
1929
+ Some(Value::Null) | None => {
1930
+ node.attribs.shift_remove(name);
1931
+ }
1932
+ Some(value) => {
1933
+ node.attribs.insert(name.to_string(), value.clone());
1934
+ }
1935
+ }
1936
+ }
1937
+ }
1938
+ }
1939
+ }
1940
+ }
1941
+ Value::Null
1942
+ }
1943
+ "attrs" => {
1944
+ if let Some(value) = args.get("value") {
1945
+ arena.set_node(id, "attribs", value)?;
1946
+ Value::Null
1947
+ } else {
1948
+ Value::Object(
1949
+ arena
1950
+ .node(id)
1951
+ .map(|node| node.attribs.to_map())
1952
+ .unwrap_or_default(),
1953
+ )
1954
+ }
1955
+ }
1956
+ "attr" => {
1957
+ let name = args["name"].as_str().unwrap_or("");
1958
+ if let Some(value) = args.get("value") {
1959
+ let value = value
1960
+ .as_str()
1961
+ .map(str::to_owned)
1962
+ .or_else(|| (!value.is_null()).then(|| value.to_string()));
1963
+ arena.set_attr(&ids, name, value.as_deref());
1964
+ Value::Null
1965
+ } else {
1966
+ ids.first()
1967
+ .and_then(|id| arena.attr(*id, name))
1968
+ .map(|value| json!(value))
1969
+ .unwrap_or(Value::Null)
1970
+ }
1971
+ }
1972
+ "text" => {
1973
+ if let Some(value) = args.get("value") {
1974
+ arena.set_text(&ids, value.as_str().unwrap_or(""));
1975
+ Value::Null
1976
+ } else {
1977
+ json!(arena.text(&ids))
1978
+ }
1979
+ }
1980
+ "html" => {
1981
+ if let Some(value) = args.get("value") {
1982
+ arena.set_html(&ids, value.as_str().unwrap_or(""))?;
1983
+ Value::Null
1984
+ } else {
1985
+ ids.first()
1986
+ .map(|id| json!(arena.inner_html_mut(*id)))
1987
+ .unwrap_or(Value::Null)
1988
+ }
1989
+ }
1990
+ "outerHtml" | "render" => {
1991
+ let mut options = arena.options.clone();
1992
+ if let Some(overrides) = args.get("options").and_then(Value::as_object) {
1993
+ for (key, value) in overrides {
1994
+ options[key] = value.clone();
1995
+ }
1996
+ }
1997
+ json!(arena.serialize_mut(&ids, &normalized_options(options)))
1998
+ }
1999
+ "traverse" => json!(arena.traverse(&ids, args["kind"].as_str().unwrap_or("children"))),
2000
+ "select" | "matches" => {
2001
+ let previous = arena
2002
+ .options
2003
+ .as_object_mut()
2004
+ .and_then(|options| options.remove("__pseudoMatches"));
2005
+ if let Some(matches) = args.get("pseudoMatches") {
2006
+ arena.options["__pseudoMatches"] = matches.clone();
2007
+ }
2008
+ let result = if command == "select" {
2009
+ super::selector::select(
2010
+ arena,
2011
+ args["selector"].as_str().unwrap_or(""),
2012
+ args.get("contexts").map(value_ids).as_deref(),
2013
+ )
2014
+ } else {
2015
+ super::selector::filter(arena, args["selector"].as_str().unwrap_or(""), &ids)
2016
+ };
2017
+ arena
2018
+ .options
2019
+ .as_object_mut()
2020
+ .unwrap()
2021
+ .remove("__pseudoMatches");
2022
+ if let Some(previous) = previous {
2023
+ arena.options["__pseudoMatches"] = previous;
2024
+ }
2025
+ json!(result?)
2026
+ }
2027
+ "create" => json!(arena.create_fragment(
2028
+ args["html"].as_str().unwrap_or(""),
2029
+ args["contextId"].as_u64().map(|id| id as u32)
2030
+ )?),
2031
+ "import" => {
2032
+ let records: Vec<DomNode> = serde_json::from_value(args["nodes"].clone())
2033
+ .map_err(|error| Error::new(Status::InvalidArg, error.to_string()))?;
2034
+ json!(arena.import(&records, &value_ids(&args["roots"])))
2035
+ }
2036
+ "clone" => json!(arena.clone_ids(&ids, args["deep"].as_bool().unwrap_or(true))),
2037
+ "insert" => json!(arena.insert(
2038
+ &value_ids(&args["targetIds"]),
2039
+ &value_ids(&args["nodeIds"]),
2040
+ args["position"].as_str().unwrap_or("append")
2041
+ )),
2042
+ "remove" => {
2043
+ if args["keepChildren"].as_bool() == Some(true) {
2044
+ for id in &ids {
2045
+ let children = arena
2046
+ .node(*id)
2047
+ .map(|node| node.children.clone())
2048
+ .unwrap_or_default();
2049
+ arena.insert(&[*id], &children, "before");
2050
+ arena.detach(*id);
2051
+ }
2052
+ } else {
2053
+ arena.detach_many(&ids);
2054
+ }
2055
+ Value::Null
2056
+ }
2057
+ "uniqueSort" => json!(crate::document_order::unique_sort(&*arena, &ids)),
2058
+ "contains" => {
2059
+ let parent = args
2060
+ .get("container")
2061
+ .or_else(|| args.get("parent"))
2062
+ .and_then(Value::as_u64)
2063
+ .unwrap_or(0) as u32;
2064
+ let mut node = args
2065
+ .get("contained")
2066
+ .or_else(|| args.get("child"))
2067
+ .and_then(Value::as_u64)
2068
+ .map(|id| id as u32);
2069
+ let mut found = false;
2070
+ let mut seen = HashSet::new();
2071
+ while let Some(id) = node {
2072
+ if !seen.insert(id) {
2073
+ break;
2074
+ }
2075
+ node = arena.node(id).and_then(|node| node.parent);
2076
+ if node == Some(parent) {
2077
+ found = true;
2078
+ break;
2079
+ }
2080
+ }
2081
+ json!(found)
2082
+ }
2083
+ _ => {
2084
+ return Err(Error::new(
2085
+ Status::InvalidArg,
2086
+ format!("Unknown native DOM command {command}"),
2087
+ ))
2088
+ }
2089
+ })
2090
+ }
2091
+
2092
+ #[cfg(test)]
2093
+ mod child_id_tests {
2094
+ use super::DomNode;
2095
+
2096
+ #[test]
2097
+ fn serde_preserves_empty_inline_and_spilled_child_arrays() {
2098
+ for ids in [&[][..], &[1, 2][..], &[1, 2, 3, 4][..]] {
2099
+ let mut node = DomNode::new("root");
2100
+ node.children.extend_from_slice(ids);
2101
+ let encoded = serde_json::to_value(&node).unwrap();
2102
+ assert_eq!(encoded["children"], serde_json::json!(ids));
2103
+ let decoded: DomNode = serde_json::from_value(encoded).unwrap();
2104
+ assert_eq!(decoded.children.as_slice(), ids);
2105
+ }
2106
+ let node: DomNode = serde_json::from_value(serde_json::json!({})).unwrap();
2107
+ assert!(node.children.is_empty());
2108
+ }
2109
+ }