@dvaji/cheerox 0.0.0-stage → 0.1.2

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 (268) hide show
  1. package/CONTRIBUTING.md +74 -0
  2. package/Cargo.lock +1091 -0
  3. package/Cargo.toml +47 -0
  4. package/LICENSE +21 -0
  5. package/README.md +121 -2
  6. package/RELEASING.md +114 -0
  7. package/THIRD_PARTY_NOTICES.md +7581 -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-BKkfJEAr.mjs +1648 -0
  18. package/dist/cheerio-compat-BKkfJEAr.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-DcnYK9OB.cjs +1719 -0
  23. package/dist/cheerio-compat-DcnYK9OB.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 +4120 -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 +35 -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/native/vendor/scraper-0.24.0/Cargo.toml +52 -0
  167. package/native/vendor/scraper-0.24.0/LICENSE +15 -0
  168. package/native/vendor/scraper-0.24.0/src/element_ref/element.rs +212 -0
  169. package/native/vendor/scraper-0.24.0/src/element_ref/mod.rs +236 -0
  170. package/native/vendor/scraper-0.24.0/src/element_ref/serializable.rs +15 -0
  171. package/native/vendor/scraper-0.24.0/src/error/utils.rs +91 -0
  172. package/native/vendor/scraper-0.24.0/src/error.rs +118 -0
  173. package/native/vendor/scraper-0.24.0/src/html/mod.rs +270 -0
  174. package/native/vendor/scraper-0.24.0/src/html/serializable.rs +27 -0
  175. package/native/vendor/scraper-0.24.0/src/html/tree_sink.rs +285 -0
  176. package/native/vendor/scraper-0.24.0/src/lib.rs +180 -0
  177. package/native/vendor/scraper-0.24.0/src/node/serializable.rs +52 -0
  178. package/native/vendor/scraper-0.24.0/src/node.rs +465 -0
  179. package/native/vendor/scraper-0.24.0/src/selectable.rs +70 -0
  180. package/native/vendor/scraper-0.24.0/src/selector.rs +290 -0
  181. package/package.json +167 -4
  182. package/scripts/check-native.mjs +15 -0
  183. package/scripts/check-release.mjs +234 -0
  184. package/scripts/fix-declarations.mjs +39 -0
  185. package/scripts/generate-notices.mjs +194 -0
  186. package/scripts/notices/README.md +13 -0
  187. package/scripts/notices/cheerio-MIT.txt +21 -0
  188. package/scripts/notices/html5ever-AUTHORS.txt +20 -0
  189. package/scripts/notices/html5ever-COPYRIGHT.txt +8 -0
  190. package/scripts/notices/html5ever-LICENSE-APACHE.txt +201 -0
  191. package/scripts/notices/html5ever-LICENSE-MIT.txt +25 -0
  192. package/scripts/notices/htmlparser2-MIT.txt +18 -0
  193. package/scripts/notices/napi-rs-MIT.txt +43 -0
  194. package/scripts/notices/neon-MIT.txt +19 -0
  195. package/scripts/notices/runtime-01c266bced4a434da005.txt +3 -0
  196. package/scripts/notices/runtime-0a54e647fe54104658b5.txt +14 -0
  197. package/scripts/notices/runtime-0b74dfa0bcee5c420c6b.txt +25 -0
  198. package/scripts/notices/runtime-0d542e0c8804e39aa7f3.txt +177 -0
  199. package/scripts/notices/runtime-0f96a83840e146e43c0e.txt +21 -0
  200. package/scripts/notices/runtime-123a331b5dbf04c30097.txt +25 -0
  201. package/scripts/notices/runtime-172020dbfd5b53a226df.txt +34 -0
  202. package/scripts/notices/runtime-209fbbe0ad52d9235e37.txt +26 -0
  203. package/scripts/notices/runtime-23f18e03dc49df91622f.txt +23 -0
  204. package/scripts/notices/runtime-268872b9816f90fd8e85.txt +220 -0
  205. package/scripts/notices/runtime-35242e7a83f69875e6ed.txt +176 -0
  206. package/scripts/notices/runtime-378f5840b258e2779c39.txt +25 -0
  207. package/scripts/notices/runtime-4108245a1f2df9d4e94d.txt +25 -0
  208. package/scripts/notices/runtime-4455bf75a91154108304.txt +21 -0
  209. package/scripts/notices/runtime-553fffcd9b1cb158bc3e.txt +13 -0
  210. package/scripts/notices/runtime-62c7a1e35f56406896d7.txt +176 -0
  211. package/scripts/notices/runtime-6485b8ed310d3f0340bf.txt +25 -0
  212. package/scripts/notices/runtime-69fef7b0f322a6555415.txt +201 -0
  213. package/scripts/notices/runtime-6df43f6f4b5d4587f3d8.txt +187 -0
  214. package/scripts/notices/runtime-799e9ca9d179295ef372.txt +24 -0
  215. package/scripts/notices/runtime-7b63ecd5f1902af1b637.txt +25 -0
  216. package/scripts/notices/runtime-7bc7d5de2a0b793d4e1a.txt +21 -0
  217. package/scripts/notices/runtime-7e12e5df4bae12cb2158.txt +24 -0
  218. package/scripts/notices/runtime-861399f8c21c042b1105.txt +12 -0
  219. package/scripts/notices/runtime-8ada45cd9f843acf64e4.txt +201 -0
  220. package/scripts/notices/runtime-90eb64f0279b0d9432ac.txt +12 -0
  221. package/scripts/notices/runtime-a60eea817514531668d7.txt +201 -0
  222. package/scripts/notices/runtime-a7c936ff1ed8fa340172.txt +25 -0
  223. package/scripts/notices/runtime-ab6eec6caf0fa5775e41.txt +275 -0
  224. package/scripts/notices/runtime-b1181a40b2a7b25cf66f.txt +19 -0
  225. package/scripts/notices/runtime-b71bd43a069ca0641a9e.txt +25 -0
  226. package/scripts/notices/runtime-c16f8dcf1a368b83be78.txt +201 -0
  227. package/scripts/notices/runtime-c2cfccb812fe482101a8.txt +21 -0
  228. package/scripts/notices/runtime-e99d88d232bf57d70f0f.txt +25 -0
  229. package/scripts/notices/runtime-f32fb3b417a194167cfa.txt +9 -0
  230. package/scripts/notices/runtime-f5062c9a188d81dfe66b.txt +39 -0
  231. package/scripts/notices/runtime-f9070a832833fa7488fd.txt +4 -0
  232. package/scripts/notices/runtime-fab3dd6bdab226f1c086.txt +373 -0
  233. package/scripts/notices/runtime-fba3318d0c600380177e.txt +62 -0
  234. package/scripts/notices/runtime-ff8f68cb076caf8cefe7.txt +25 -0
  235. package/scripts/notices/runtime-ff92bed461f50338dd70.txt +74 -0
  236. package/scripts/notices/runtime.json +1632 -0
  237. package/scripts/notices/sources.json +561 -0
  238. package/scripts/notices/xray-MIT.txt +21 -0
  239. package/src/attribute-object.ts +71 -0
  240. package/src/attributes.ts +308 -0
  241. package/src/cheerio-compat/css.ts +58 -0
  242. package/src/cheerio-compat/render.ts +106 -0
  243. package/src/cheerio-compat/selectors.ts +51 -0
  244. package/src/cheerio-compat/types.ts +52 -0
  245. package/src/cheerio-compat.ts +2055 -0
  246. package/src/codec.ts +96 -0
  247. package/src/dom.ts +87 -0
  248. package/src/extract-plan.ts +97 -0
  249. package/src/extract.ts +322 -0
  250. package/src/hooks.ts +369 -0
  251. package/src/index.ts +48 -0
  252. package/src/io.ts +491 -0
  253. package/src/match.ts +207 -0
  254. package/src/modern.ts +259 -0
  255. package/src/native.ts +149 -0
  256. package/src/nodes.ts +831 -0
  257. package/src/parse.ts +53 -0
  258. package/src/parser-types.ts +157 -0
  259. package/src/router.ts +1129 -0
  260. package/src/selection.ts +682 -0
  261. package/src/slim.ts +12 -0
  262. package/src/snapshot.ts +291 -0
  263. package/src/transport.ts +113 -0
  264. package/src/types.ts +186 -0
  265. package/src/utils.ts +29 -0
  266. package/src/workers.ts +21 -0
  267. package/tsconfig.json +15 -0
  268. package/tsdown.config.mjs +17 -0
@@ -0,0 +1,4210 @@
1
+ let node_module = require("node:module");
2
+ let node_fs = require("node:fs");
3
+ let node_path = require("node:path");
4
+ let node_url = require("node:url");
5
+ // src/codec.ts
6
+ /**
7
+ * Node strings use UTF-16, including unpaired surrogates. Rust strings use
8
+ * Unicode scalar values. Reserve a small private-use alphabet on this private
9
+ * boundary so neither representation loses a code unit.
10
+ */
11
+ const reserved = /[\ud800-\ue800]/;
12
+ const encoded = /[\ue000-\ue800]/;
13
+ const escapeUnit = 59392;
14
+ const isWellFormed = String.prototype.isWellFormed;
15
+ function encodeString(value) {
16
+ if (!encoded.test(value) && (isWellFormed ? isWellFormed.call(value) : !reserved.test(value))) return value;
17
+ const parts = [];
18
+ let start = 0;
19
+ for (let index = 0; index < value.length; index++) {
20
+ const unit = value.charCodeAt(index);
21
+ if (unit >= 55296 && unit <= 56319) {
22
+ const next = value.charCodeAt(index + 1);
23
+ if (next >= 56320 && next <= 57343) {
24
+ index++;
25
+ continue;
26
+ }
27
+ }
28
+ let replacement;
29
+ if (unit >= 55296 && unit <= 57343) replacement = String.fromCharCode(57344 + unit - 55296);
30
+ else if (unit >= 57344 && unit <= escapeUnit) replacement = "" + value[index];
31
+ if (replacement !== void 0) {
32
+ parts.push(value.slice(start, index), replacement);
33
+ start = index + 1;
34
+ }
35
+ }
36
+ return start === 0 ? value : parts.join("") + value.slice(start);
37
+ }
38
+ function decodeString(value) {
39
+ if (!encoded.test(value)) return value;
40
+ const parts = [];
41
+ let start = 0;
42
+ for (let index = 0; index < value.length; index++) {
43
+ const unit = value.charCodeAt(index);
44
+ if (unit < 57344 || unit > escapeUnit) continue;
45
+ const next = value.charCodeAt(index + 1);
46
+ if (unit === escapeUnit) {
47
+ if (next < 57344 || next > escapeUnit || Number.isNaN(next)) continue;
48
+ parts.push(value.slice(start, index), value[++index]);
49
+ } else parts.push(value.slice(start, index), String.fromCharCode(55296 + unit - 57344));
50
+ start = index + 1;
51
+ }
52
+ return start === 0 ? value : parts.join("") + value.slice(start);
53
+ }
54
+ const encodeJsonCandidate = /[\ud800-\ue800]|\\u(?:d[89a-f][\da-f]{2}|e[0-8][\da-f]{2})/i;
55
+ const escapedJsonCandidate = /\\u(?:d[89a-f][\da-f]{2}|e[0-8][\da-f]{2})/i;
56
+ const decodeJsonCandidate = /[\ue000-\ue800]|\\ue[0-8][\da-f]{2}/i;
57
+ function encodeJson(value) {
58
+ if (!encodeJsonCandidate.test(value)) return value;
59
+ if (isWellFormed?.call(value) && !encoded.test(value) && !escapedJsonCandidate.test(value)) return value;
60
+ return mapJsonStrings(value, encodeString, encodeJsonCandidate);
61
+ }
62
+ function decodeJson(value) {
63
+ return decodeJsonCandidate.test(value) ? mapJsonStrings(value, decodeString, decodeJsonCandidate) : value;
64
+ }
65
+ /**
66
+ * Replaces every string token of the JSON text `json` with `transform` of its
67
+ * value, in one left-to-right pass. A regular expression scanning for tokens
68
+ * retries from every quote of an unterminated token, which is quadratic.
69
+ */
70
+ function mapJsonStrings(json, transform, candidate) {
71
+ const parts = [];
72
+ let copied = 0;
73
+ let quote = json.indexOf("\"");
74
+ while (quote !== -1) {
75
+ let end = quote + 1;
76
+ while (end < json.length && json.charCodeAt(end) !== 34) end += json.charCodeAt(end) === 92 ? 2 : 1;
77
+ if (end >= json.length) break;
78
+ const token = json.slice(quote, end + 1);
79
+ if (candidate.test(token)) {
80
+ parts.push(json.slice(copied, quote), JSON.stringify(transform(JSON.parse(token))));
81
+ copied = end + 1;
82
+ }
83
+ quote = json.indexOf("\"", end + 1);
84
+ }
85
+ return copied === 0 ? json : parts.join("") + json.slice(copied);
86
+ }
87
+ /** Private parser protocol flag, appended without deserializing large options. */
88
+ function encodeOptions(value) {
89
+ if (value === void 0) return "{\"__utf16Codec\":true}";
90
+ const json = encodeJson(value);
91
+ if (!json.trimStart().startsWith("{")) return "{\"__utf16Codec\":true}";
92
+ const end = json.lastIndexOf("}");
93
+ const prefix = json.slice(0, end);
94
+ return prefix + (prefix.trimEnd().endsWith("{") ? "" : ",") + "\"__utf16Codec\":true" + json.slice(end);
95
+ }
96
+ // src/transport.ts
97
+ const registryKey$1 = Symbol.for("cheerox.native-transport.v2");
98
+ const globals$1 = globalThis;
99
+ const registry$1 = globals$1[registryKey$1] ??= { userErrors: /* @__PURE__ */ new WeakSet() };
100
+ const transportedKey = Symbol.for("cheerox.native-transport.prototype");
101
+ const jsonMethods = /* @__PURE__ */ new Set([
102
+ "op",
103
+ "node",
104
+ "exportTree",
105
+ "exportTreeWithOffset",
106
+ "parserDiagnostics",
107
+ "adopt"
108
+ ]);
109
+ /** String arguments each document method takes, by position, and how to encode them. */
110
+ const argumentEncoders = {
111
+ op: (args) => {
112
+ args[1] = encodeJson(args[1]);
113
+ },
114
+ create: (args) => {
115
+ args[0] = encodeString(args[0]);
116
+ if (typeof args[2] === "string") args[2] = encodeOptions(args[2]);
117
+ },
118
+ select: (args) => {
119
+ args[0] = encodeString(args[0]);
120
+ },
121
+ matches: (args) => {
122
+ args[0] = encodeString(args[0]);
123
+ },
124
+ attr: (args) => {
125
+ args[1] = encodeString(args[1]);
126
+ },
127
+ setAttribute: (args) => {
128
+ args[1] = encodeString(args[1]);
129
+ if (typeof args[2] === "string") args[2] = encodeString(args[2]);
130
+ },
131
+ render: (args) => {
132
+ if (typeof args[1] === "string") args[1] = encodeJson(args[1]);
133
+ }
134
+ };
135
+ /** Keep the codec at the private addon boundary, including callback RPC. */
136
+ function wrapNativeBinding(binding) {
137
+ const raw = binding;
138
+ const { userErrors } = registry$1;
139
+ const restoreError = (error) => {
140
+ if (error instanceof Error && !userErrors.has(error)) {
141
+ const message = decodeString(error.message);
142
+ if (message !== error.message) {
143
+ const stack = error.stack;
144
+ error.message = message;
145
+ if (stack) error.stack = decodeString(stack);
146
+ }
147
+ }
148
+ throw error;
149
+ };
150
+ const invoke = (call) => {
151
+ try {
152
+ const result = call();
153
+ return result instanceof Promise ? result.catch(restoreError) : result;
154
+ } catch (error) {
155
+ return restoreError(error);
156
+ }
157
+ };
158
+ const wrapBridge = (bridge) => (request) => {
159
+ try {
160
+ return encodeJson(bridge(decodeJson(request)));
161
+ } catch (error) {
162
+ if (error !== null && (typeof error === "object" || typeof error === "function")) userErrors.add(error);
163
+ throw error;
164
+ }
165
+ };
166
+ const transportMethod = (name, method) => {
167
+ const encodeArguments = argumentEncoders[name];
168
+ const decode = jsonMethods.has(name) ? decodeJson : decodeString;
169
+ const isOperation = name === "op";
170
+ return function transported(...args) {
171
+ try {
172
+ if (encodeArguments) encodeArguments(args);
173
+ const result = method.apply(this, args);
174
+ if (typeof result !== "string") return result;
175
+ if (isOperation && args[0] === "serialize" && result.startsWith("{")) {
176
+ const error = JSON.parse(result).__nativeError;
177
+ if (error?.name === "URIError") throw new URIError(error.message);
178
+ }
179
+ return decode(result);
180
+ } catch (error) {
181
+ return restoreError(error);
182
+ }
183
+ };
184
+ };
185
+ const prototype = raw.NativeDocument.prototype;
186
+ if (!Object.hasOwn(prototype, transportedKey)) {
187
+ for (const name of Object.getOwnPropertyNames(prototype)) {
188
+ const method = prototype[name];
189
+ if (name !== "constructor" && typeof method === "function") prototype[name] = transportMethod(name, method);
190
+ }
191
+ Object.defineProperty(prototype, transportedKey, { value: true });
192
+ }
193
+ const wrapStream = (stream) => {
194
+ let carry = "";
195
+ return {
196
+ async write(chunk) {
197
+ let source = carry + chunk;
198
+ carry = "";
199
+ const last = source.charCodeAt(source.length - 1);
200
+ if (last >= 55296 && last <= 56319) {
201
+ carry = source.slice(-1);
202
+ source = source.slice(0, -1);
203
+ }
204
+ if (source) await invoke(() => stream.write(encodeString(source)));
205
+ },
206
+ async finish() {
207
+ if (carry) {
208
+ const final = carry;
209
+ carry = "";
210
+ await invoke(() => stream.write(encodeString(final)));
211
+ }
212
+ return invoke(() => stream.finish());
213
+ },
214
+ abort() {
215
+ carry = "";
216
+ return invoke(() => stream.abort());
217
+ }
218
+ };
219
+ };
220
+ const wrapConstructor = (Constructor, argumentsFor, wrap) => new Proxy(Constructor, { construct(target, args) {
221
+ return wrap(invoke(() => Reflect.construct(target, argumentsFor(args))));
222
+ } });
223
+ const wrapped = { ...raw };
224
+ const Document = raw.NativeDocument;
225
+ wrapped.NativeDocument = function NativeDocument(html, isDocument, options) {
226
+ try {
227
+ return new Document(encodeString(html), isDocument, encodeOptions(options));
228
+ } catch (error) {
229
+ return restoreError(error);
230
+ }
231
+ };
232
+ if (raw.NativeStream) wrapped.NativeStream = wrapConstructor(raw.NativeStream, ([options, isDocument, bridge]) => [
233
+ encodeOptions(options),
234
+ isDocument,
235
+ bridge && wrapBridge(bridge)
236
+ ], wrapStream);
237
+ if (raw.NativeHookStream) wrapped.NativeHookStream = wrapConstructor(raw.NativeHookStream, ([isDocument, options, bridge]) => [
238
+ isDocument,
239
+ encodeOptions(options),
240
+ wrapBridge(bridge)
241
+ ], wrapStream);
242
+ if (raw.parseWithTreeAdapter) wrapped.parseWithTreeAdapter = (source, isDocument, options, bridge) => invoke(() => raw.parseWithTreeAdapter(encodeString(source), isDocument, encodeOptions(options), wrapBridge(bridge)));
243
+ if (raw.parseAsync) wrapped.parseAsync = (source, isDocument, options) => invoke(() => raw.parseAsync(encodeString(source), isDocument, encodeOptions(options)));
244
+ if (raw.parseManyAsync) wrapped.parseManyAsync = (sources, isDocument, threads, options, plans) => invoke(() => raw.parseManyAsync(sources.map(encodeString), isDocument, threads, encodeOptions(options), plans === void 0 ? void 0 : encodeJson(plans)));
245
+ if (raw.extractPlanManyAsync) wrapped.extractPlanManyAsync = async (sources, plan, threads, options) => decodeJson(await invoke(() => raw.extractPlanManyAsync(sources.map(encodeString), encodeJson(plan), threads, encodeOptions(options))));
246
+ if (raw.extractManyAsync) wrapped.extractManyAsync = async (sources, queries, threads, isDocument, options) => decodeJson(await invoke(() => raw.extractManyAsync(sources.map(encodeString), queries.map((query) => ({
247
+ ...query,
248
+ key: encodeString(query.key),
249
+ selector: encodeString(query.selector),
250
+ ...query.attr === void 0 ? {} : { attr: encodeString(query.attr) }
251
+ })), threads, isDocument, encodeOptions(options))));
252
+ return wrapped;
253
+ }
254
+ // src/native.ts
255
+ let cached;
256
+ let attempted = false;
257
+ let bindingError;
258
+ /**
259
+ * The directory of this bundle, shared by the package's CommonJS and ESM
260
+ * entry points and distinct for every installed copy of the package.
261
+ */
262
+ function packageDirectory() {
263
+ return typeof __dirname === "string" ? __dirname : (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
264
+ }
265
+ /** Resolve the native addon bundled with the npm package. */
266
+ function nativeBinding() {
267
+ if (attempted) return cached;
268
+ attempted = true;
269
+ const moduleDirectory = packageDirectory();
270
+ const require$1 = (0, node_module.createRequire)((0, node_path.join)(moduleDirectory, "cheerox-loader.cjs"));
271
+ const directories = [moduleDirectory, (0, node_path.dirname)(moduleDirectory)];
272
+ const libc = process.platform === "linux" ? (process.report?.getReport())?.header?.glibcVersionRuntime ? "gnu" : "musl" : void 0;
273
+ const names = [`cheerox.${`${process.platform}-${process.arch}${libc ? `-${libc}` : process.platform === "win32" ? "-msvc" : ""}`}.node`, "cheerox.node"];
274
+ const candidates = [...new Set(directories.flatMap((directory) => names.map((name) => (0, node_path.join)(directory, name))))];
275
+ for (const candidate of candidates) {
276
+ if (!(0, node_fs.existsSync)(candidate)) continue;
277
+ try {
278
+ const loaded = require$1(candidate);
279
+ if (typeof loaded.NativeDocument === "function") {
280
+ cached = wrapNativeBinding(loaded);
281
+ return cached;
282
+ }
283
+ } catch (error) {
284
+ bindingError ??= error;
285
+ }
286
+ }
287
+ }
288
+ function requireNative() {
289
+ const binding = nativeBinding();
290
+ if (binding) return binding;
291
+ throw new Error("Cheerox could not load its Rust native binding. Reinstall cheerox for this platform or run \"npm run build:native\" from a source checkout.", { cause: bindingError });
292
+ }
293
+ /** Useful for installation diagnostics and benchmarks that require native code. */
294
+ function nativeStatus() {
295
+ const available = !!nativeBinding();
296
+ return available ? { available } : {
297
+ available,
298
+ error: String(bindingError ?? "Native binding not found")
299
+ };
300
+ }
301
+ // src/attribute-object.ts
302
+ const ATTR_META = Symbol.for("cheerox.attribs.meta");
303
+ const accessorPairs = /* @__PURE__ */ new Map();
304
+ /** One shared accessor pair per attribute name; `this` is the attribute object. */
305
+ function accessorPairFor(key) {
306
+ let pair = accessorPairs.get(key);
307
+ if (pair === void 0) {
308
+ pair = {
309
+ get() {
310
+ return this[ATTR_META].values[key];
311
+ },
312
+ set(value) {
313
+ const meta = this[ATTR_META];
314
+ meta.write?.(meta.view, this, key, value);
315
+ },
316
+ enumerable: true,
317
+ configurable: true
318
+ };
319
+ accessorPairs.set(key, pair);
320
+ }
321
+ return pair;
322
+ }
323
+ /** Defines a shared accessor for `key` when the object has none yet. */
324
+ function defineAttributeAccessor(attributes, key) {
325
+ if (!Object.hasOwn(attributes, key)) Object.defineProperty(attributes, key, accessorPairFor(key));
326
+ }
327
+ /**
328
+ * Defines an attribute key with its stored value. `__proto__` must stay a
329
+ * plain data property on both layers: an accessor there would shadow the
330
+ * prototype's setter, reflection expects a value descriptor, and assigning
331
+ * `values.__proto__` would mutate the store's prototype instead of setting a
332
+ * key.
333
+ */
334
+ function defineAttributeKey(attributes, key, value) {
335
+ const values = attributes[ATTR_META].values;
336
+ if (key === "__proto__") {
337
+ Object.defineProperty(attributes, key, {
338
+ value,
339
+ writable: true,
340
+ enumerable: true,
341
+ configurable: true
342
+ });
343
+ Object.defineProperty(values, key, {
344
+ value,
345
+ writable: true,
346
+ enumerable: true,
347
+ configurable: true
348
+ });
349
+ } else {
350
+ defineAttributeAccessor(attributes, key);
351
+ values[key] = value;
352
+ }
353
+ }
354
+ /** Attaches the metadata that accessor setters need to reach the record. */
355
+ function setAttributeMeta(attributes, meta) {
356
+ Object.defineProperty(attributes, ATTR_META, {
357
+ value: meta,
358
+ enumerable: false,
359
+ writable: true,
360
+ configurable: true
361
+ });
362
+ }
363
+ /** Assigns or removes an attribute from the outside (the router's fast native paths). */
364
+ function attributeAssign(attributes, name, value) {
365
+ const meta = attributes[ATTR_META];
366
+ if (!meta) return;
367
+ if (value === null) {
368
+ delete attributes[name];
369
+ delete meta.values[name];
370
+ } else defineAttributeKey(attributes, name, value);
371
+ meta.generation = -1;
372
+ }
373
+ // src/snapshot.ts
374
+ const HEADER = 5;
375
+ const STRIDE$1 = 15;
376
+ const ABSENT = 4294967295;
377
+ const HAS_START_INDEX = 1;
378
+ const HAS_END_INDEX = 2;
379
+ const HAS_NAMESPACE = 4;
380
+ const EMPTY_ATTRIBUTE_MAPS = 8;
381
+ const OPAQUE = 16;
382
+ const RELEASED = 32;
383
+ const noChildren = Object.freeze([]);
384
+ const noAttributes = Object.freeze({});
385
+ /**
386
+ * A record read from a snapshot. It stores only its position; fields decode
387
+ * on read, and strings and lists are kept once decoded. Every instance has
388
+ * the same fields, so reads stay monomorphic. Absent fields read `undefined`.
389
+ */
390
+ var SnapshotRecord = class {
391
+ snapshot;
392
+ id;
393
+ base;
394
+ decodedData;
395
+ decodedAttributes;
396
+ decodedChildren;
397
+ constructor(snapshot, id, base) {
398
+ this.snapshot = snapshot;
399
+ this.id = id;
400
+ this.base = base;
401
+ this.decodedData = void 0;
402
+ this.decodedAttributes = void 0;
403
+ this.decodedChildren = void 0;
404
+ }
405
+ get type() {
406
+ return this.snapshot.name(this.snapshot.nodes[this.base]);
407
+ }
408
+ get name() {
409
+ const name = this.snapshot.nodes[this.base + 6];
410
+ return name ? this.snapshot.name(name - 1) : void 0;
411
+ }
412
+ get data() {
413
+ if (this.decodedData !== void 0) return this.decodedData;
414
+ const data = this.snapshot.nodes[this.base + 7];
415
+ return data ? this.decodedData = this.snapshot.string(data - 1) : void 0;
416
+ }
417
+ get parent() {
418
+ const parent = this.snapshot.nodes[this.base + 1];
419
+ return parent ? parent - 1 : null;
420
+ }
421
+ get prev() {
422
+ const prev = this.snapshot.nodes[this.base + 2];
423
+ return prev ? prev - 1 : null;
424
+ }
425
+ get next() {
426
+ const next = this.snapshot.nodes[this.base + 3];
427
+ return next ? next - 1 : null;
428
+ }
429
+ get startIndex() {
430
+ return this.index(HAS_START_INDEX, 11);
431
+ }
432
+ get endIndex() {
433
+ return this.index(HAS_END_INDEX, 12);
434
+ }
435
+ get namespace() {
436
+ const nodes = this.snapshot.nodes;
437
+ return nodes[this.base + 10] & HAS_NAMESPACE ? this.snapshot.name(nodes[this.base + 13]) : void 0;
438
+ }
439
+ get attribsNamespace() {
440
+ return this.snapshot.nodes[this.base + 10] & EMPTY_ATTRIBUTE_MAPS ? {} : void 0;
441
+ }
442
+ get attribsPrefix() {
443
+ return this.snapshot.nodes[this.base + 10] & EMPTY_ATTRIBUTE_MAPS ? {} : void 0;
444
+ }
445
+ get attribs() {
446
+ return this.decodedAttributes ??= this.snapshot.attributesOf(this.id);
447
+ }
448
+ get children() {
449
+ return this.decodedChildren ??= this.snapshot.childrenOf(this.id);
450
+ }
451
+ index(flag, offset) {
452
+ const nodes = this.snapshot.nodes;
453
+ if (!(nodes[this.base + 10] & flag)) return void 0;
454
+ const value = nodes[this.base + offset];
455
+ return value === ABSENT ? null : value;
456
+ }
457
+ };
458
+ /** Snapshot records extended with fields stored as JSON, which are rare. */
459
+ const recordFields = [
460
+ "type",
461
+ "name",
462
+ "data",
463
+ "parent",
464
+ "prev",
465
+ "next",
466
+ "startIndex",
467
+ "endIndex",
468
+ "namespace",
469
+ "attribsNamespace",
470
+ "attribsPrefix",
471
+ "attribs",
472
+ "children"
473
+ ];
474
+ /** A plain copy of a record, for callers that spread or serialize it. */
475
+ function plainRecord(record) {
476
+ if (!(record instanceof SnapshotRecord)) return record;
477
+ const copy = { id: record.id };
478
+ for (const field of recordFields) {
479
+ const value = record[field];
480
+ if (value !== void 0) copy[field] = value;
481
+ }
482
+ for (const key of Object.keys(record)) if (!key.startsWith("decoded") && key !== "snapshot" && key !== "base" && key !== "id") copy[key] = record[key];
483
+ return copy;
484
+ }
485
+ /** Decodes node records from a snapshot on demand, exactly as `node()` returns them. */
486
+ var NodeSnapshot = class {
487
+ size;
488
+ nodes;
489
+ children;
490
+ attributes;
491
+ strings;
492
+ text;
493
+ isEncoded;
494
+ names = [];
495
+ /** Per interned type: 1 for element types, 2 for root, 3 for text, 0 otherwise. */
496
+ typeKinds = [];
497
+ /** Node object constructors by interned type, resolved once per snapshot. */
498
+ viewConstructors = void 0;
499
+ /** Text nodes too large for the arrays, read individually while this snapshot is current. */
500
+ largeTexts = /* @__PURE__ */ new Map();
501
+ constructor(raw) {
502
+ const { data } = raw;
503
+ const childrenStart = HEADER + data[0];
504
+ const attributesStart = childrenStart + data[1];
505
+ const stringsStart = attributesStart + data[2];
506
+ this.text = raw.text;
507
+ this.isEncoded = data[4] === 1;
508
+ this.nodes = data.subarray(HEADER, childrenStart);
509
+ this.children = data.subarray(childrenStart, attributesStart);
510
+ this.attributes = data.subarray(attributesStart, stringsStart);
511
+ this.strings = data.subarray(stringsStart, stringsStart + data[3]);
512
+ this.size = this.nodes.length / STRIDE$1;
513
+ }
514
+ /** The record, `null` for a released node, or `undefined` when it must be read individually. */
515
+ record(local) {
516
+ if (local >= this.size) return void 0;
517
+ const base = local * STRIDE$1;
518
+ const flags = this.nodes[base + 10];
519
+ if (flags & RELEASED) return null;
520
+ if (flags & OPAQUE) return void 0;
521
+ const record = new SnapshotRecord(this, local, base);
522
+ const extras = this.nodes[base + 14];
523
+ if (extras) {
524
+ const fields = JSON.parse(this.string(extras - 1));
525
+ for (const key of Object.keys(fields)) Object.defineProperty(record, key, {
526
+ value: fields[key],
527
+ writable: true,
528
+ enumerable: true,
529
+ configurable: true
530
+ });
531
+ }
532
+ return record;
533
+ }
534
+ /** Whether a node's fields all live in the arrays, so callers may read them without a record. */
535
+ isPlain(local) {
536
+ if (local >= this.size) return false;
537
+ const base = local * STRIDE$1;
538
+ return (this.nodes[base + 10] & 48) === 0 && this.nodes[base + 14] === 0;
539
+ }
540
+ typeOf(local) {
541
+ return this.name(this.nodes[local * STRIDE$1]);
542
+ }
543
+ nameOf(local) {
544
+ const name = this.nodes[local * STRIDE$1 + 6];
545
+ return name ? this.name(name - 1) : void 0;
546
+ }
547
+ dataOf(local) {
548
+ const data = this.nodes[local * STRIDE$1 + 7];
549
+ return data ? this.string(data - 1) : void 0;
550
+ }
551
+ /** The parent, previous or next sibling (`offset` 1, 2 or 3), or `null`. */
552
+ linkOf(local, offset) {
553
+ const link = this.nodes[local * STRIDE$1 + offset];
554
+ return link ? link - 1 : null;
555
+ }
556
+ namespaceOf(local) {
557
+ const base = local * STRIDE$1;
558
+ return this.nodes[base + 10] & HAS_NAMESPACE ? this.name(this.nodes[base + 13]) : void 0;
559
+ }
560
+ /** A node's attributes as parse5 attribute objects; plain nodes have no namespaced ones. */
561
+ attributeObjects(local) {
562
+ const base = local * STRIDE$1;
563
+ const count = this.nodes[base + 9];
564
+ const first = this.nodes[base + 8];
565
+ const attributes = this.attributes;
566
+ const result = new Array(count);
567
+ for (let index = 0; index < count; index++) {
568
+ const pair = (first + index) * 2;
569
+ result[index] = {
570
+ name: this.name(attributes[pair]),
571
+ value: this.string(attributes[pair + 1])
572
+ };
573
+ }
574
+ return result;
575
+ }
576
+ /** Copies a node's attributes onto `target`, in order. */
577
+ /** Copies a node's attributes as the shared accessors of `attributes`, in record order. */
578
+ copyAttributes(local, attributes) {
579
+ const base = local * STRIDE$1;
580
+ const count = this.nodes[base + 9];
581
+ const first = this.nodes[base + 8];
582
+ const attributes_ = this.attributes;
583
+ for (let index = 0; index < count; index++) {
584
+ const pair = (first + index) * 2;
585
+ defineAttributeKey(attributes, this.name(attributes_[pair]), this.string(attributes_[pair + 1]));
586
+ }
587
+ }
588
+ /** The flat child id list; a node's children start at `childStart(local)`. */
589
+ get childIds() {
590
+ return this.children;
591
+ }
592
+ childStart(local) {
593
+ return this.nodes[local * STRIDE$1 + 4];
594
+ }
595
+ /** Whether a node is an element: a tag, script or style. */
596
+ isElementAt(local) {
597
+ return this.typeKind(local) === 1;
598
+ }
599
+ isRootAt(local) {
600
+ return this.typeKind(local) === 2;
601
+ }
602
+ isTextAt(local) {
603
+ return this.typeKind(local) === 3;
604
+ }
605
+ /** Whether a node's record adds fields stored as JSON, such as source locations. */
606
+ hasExtraFields(local) {
607
+ return this.nodes[local * STRIDE$1 + 14] !== 0;
608
+ }
609
+ /** Whether the slot holds a node, rather than one a collection released. */
610
+ isPresent(local) {
611
+ return local < this.size && (this.nodes[local * STRIDE$1 + 10] & RELEASED) === 0;
612
+ }
613
+ typeKind(local) {
614
+ const reference = this.nodes[local * STRIDE$1];
615
+ let kind = this.typeKinds[reference];
616
+ if (kind === void 0) {
617
+ const type = this.name(reference);
618
+ kind = this.typeKinds[reference] = type === "tag" || type === "script" || type === "style" ? 1 : type === "root" ? 2 : type === "text" ? 3 : 0;
619
+ }
620
+ return kind;
621
+ }
622
+ /** The interned reference of a node's type, comparable across nodes of this snapshot. */
623
+ typeReference(local) {
624
+ return this.nodes[local * STRIDE$1];
625
+ }
626
+ /** Child ids without materializing the record. */
627
+ childCount(local) {
628
+ return this.nodes[local * STRIDE$1 + 5];
629
+ }
630
+ childAt(local, index) {
631
+ return this.children[this.nodes[local * STRIDE$1 + 4] + index];
632
+ }
633
+ childrenOf(local) {
634
+ const base = local * STRIDE$1;
635
+ const count = this.nodes[base + 5];
636
+ if (count === 0) return noChildren;
637
+ const first = this.nodes[base + 4];
638
+ return Array.from(this.children.subarray(first, first + count));
639
+ }
640
+ attributesOf(local) {
641
+ const base = local * STRIDE$1;
642
+ const count = this.nodes[base + 9];
643
+ if (count === 0) return noAttributes;
644
+ const first = this.nodes[base + 8];
645
+ const attributes = this.attributes;
646
+ const result = {};
647
+ for (let index = 0; index < count; index++) {
648
+ const pair = (first + index) * 2;
649
+ const name = this.name(attributes[pair]);
650
+ const value = this.string(attributes[pair + 1]);
651
+ if (name === "__proto__") Object.defineProperty(result, name, {
652
+ value,
653
+ writable: true,
654
+ enumerable: true,
655
+ configurable: true
656
+ });
657
+ else result[name] = value;
658
+ }
659
+ return result;
660
+ }
661
+ /** One attribute's value, without decoding the rest. */
662
+ attributeValue(local, name) {
663
+ const base = local * STRIDE$1;
664
+ const count = this.nodes[base + 9];
665
+ const first = this.nodes[base + 8];
666
+ const attributes = this.attributes;
667
+ for (let index = count - 1; index >= 0; index--) {
668
+ const pair = (first + index) * 2;
669
+ if (this.name(attributes[pair]) === name) return this.string(attributes[pair + 1]);
670
+ }
671
+ }
672
+ string(reference) {
673
+ const strings = this.strings;
674
+ const value = this.text.slice(strings[reference * 2], strings[reference * 2 + 1]);
675
+ return this.isEncoded ? decodeString(value) : value;
676
+ }
677
+ /** Names repeat across nodes, so each decodes once. */
678
+ name(reference) {
679
+ return this.names[reference] ??= this.string(reference);
680
+ }
681
+ };
682
+ // src/hooks.ts
683
+ const tokenCallbacks = [
684
+ "onattribdata",
685
+ "onattribentity",
686
+ "onattribend",
687
+ "onattribname",
688
+ "oncdata",
689
+ "onclosetag",
690
+ "oncomment",
691
+ "ondeclaration",
692
+ "onend",
693
+ "onopentagend",
694
+ "onopentagname",
695
+ "onprocessinginstruction",
696
+ "onselfclosingtag",
697
+ "ontext",
698
+ "ontextentity"
699
+ ];
700
+ function createTokenizerSession(options) {
701
+ const events = [];
702
+ const callbacks = Object.fromEntries(tokenCallbacks.map((name) => [name, (...args) => {
703
+ if (name === "ontextentity" || name === "onattribentity") {
704
+ const codePoint = +args[0];
705
+ (0, String.fromCodePoint)(codePoint);
706
+ args[0] = codePoint;
707
+ }
708
+ events.push([name, ...args]);
709
+ }]));
710
+ const Constructor = options.Tokenizer;
711
+ const tokenizer = new Constructor(options, callbacks);
712
+ return {
713
+ write(chunk) {
714
+ if (tokenizer.running) tokenizer.write(chunk);
715
+ },
716
+ end() {
717
+ tokenizer.end();
718
+ const result = cleanParserOptions(options);
719
+ result.__tokenEvents = events;
720
+ return result;
721
+ }
722
+ };
723
+ }
724
+ function cleanParserOptions(options) {
725
+ const result = { ...options };
726
+ delete result.Tokenizer;
727
+ delete result.treeAdapter;
728
+ delete result.onParseError;
729
+ delete result.__tokenEvents;
730
+ if (!options._useHtmlParser2 && options.onParseError) {
731
+ result.__collectParseErrors = true;
732
+ result.sourceCodeLocationInfo = true;
733
+ }
734
+ return result;
735
+ }
736
+ /** User tokenizers run on JavaScript; their actual events are consumed by Rust. */
737
+ function parserOptions(source, options) {
738
+ if (options._useHtmlParser2 && options.Tokenizer) {
739
+ const session = createTokenizerSession(options);
740
+ session.write(source);
741
+ return session.end();
742
+ }
743
+ return cleanParserOptions(options);
744
+ }
745
+ function deliverParseErrors(document, options) {
746
+ if (options._useHtmlParser2 || !options.onParseError) return;
747
+ const diagnostics = document.parserDiagnostics?.();
748
+ const errors = typeof diagnostics === "string" ? JSON.parse(diagnostics) : diagnostics ?? [];
749
+ for (const error of errors) options.onParseError(error);
750
+ }
751
+ function hasParserHooks(options) {
752
+ return !!(options._useHtmlParser2 ? options.Tokenizer : options.treeAdapter || options.onParseError);
753
+ }
754
+ /** A live tree adapter bridge. Every tree-builder decision consults the user's adapter. */
755
+ function treeAdapterBridge(adapter, options) {
756
+ const deliveredErrors = /* @__PURE__ */ new Set();
757
+ const nodes = [];
758
+ const ids = /* @__PURE__ */ new WeakMap();
759
+ const identify = (node) => {
760
+ if (node == null) return null;
761
+ if (typeof node !== "object") throw new TypeError("treeAdapter methods must return DOM node objects");
762
+ let id = ids.get(node);
763
+ if (id === void 0) {
764
+ id = nodes.length;
765
+ ids.set(node, id);
766
+ nodes.push(node);
767
+ }
768
+ return id;
769
+ };
770
+ const nodeArgs = {
771
+ appendChild: [0, 1],
772
+ insertBefore: [
773
+ 0,
774
+ 1,
775
+ 2
776
+ ],
777
+ setTemplateContent: [0, 1],
778
+ getTemplateContent: [0],
779
+ setDocumentType: [0],
780
+ setDocumentMode: [0],
781
+ getDocumentMode: [0],
782
+ detachNode: [0],
783
+ insertText: [0],
784
+ insertTextBefore: [0, 2],
785
+ adoptAttributes: [0],
786
+ getFirstChild: [0],
787
+ getChildNodes: [0],
788
+ getParentNode: [0],
789
+ getAttrList: [0],
790
+ getTagName: [0],
791
+ getNamespaceURI: [0],
792
+ getTextNodeContent: [0],
793
+ getCommentNodeContent: [0],
794
+ getDocumentTypeNodeName: [0],
795
+ getDocumentTypeNodePublicId: [0],
796
+ getDocumentTypeNodeSystemId: [0],
797
+ isTextNode: [0],
798
+ isCommentNode: [0],
799
+ isElementNode: [0],
800
+ isDocumentTypeNode: [0],
801
+ setNodeSourceCodeLocation: [0],
802
+ getNodeSourceCodeLocation: [0],
803
+ updateNodeSourceCodeLocation: [0],
804
+ onItemPop: [0, 1],
805
+ onItemPush: [0]
806
+ };
807
+ const nodeReturns = /* @__PURE__ */ new Set([
808
+ "createDocument",
809
+ "createDocumentFragment",
810
+ "createElement",
811
+ "createCommentNode",
812
+ "createTextNode",
813
+ "getTemplateContent",
814
+ "getFirstChild",
815
+ "getParentNode"
816
+ ]);
817
+ const invoke = (method, args) => {
818
+ const fn = adapter[method];
819
+ if (typeof fn !== "function") {
820
+ if (method === "onItemPop" || method === "onItemPush") return void 0;
821
+ throw new TypeError(`treeAdapter.${method} must be a function`);
822
+ }
823
+ return Reflect.apply(fn, adapter, args);
824
+ };
825
+ const snapshot = () => {
826
+ const records = [];
827
+ for (let id = 0; id < nodes.length; id++) {
828
+ const node = nodes[id];
829
+ const element = invoke("isElementNode", [node]);
830
+ const text = invoke("isTextNode", [node]);
831
+ const comment = invoke("isCommentNode", [node]);
832
+ const doctype = invoke("isDocumentTypeNode", [node]);
833
+ const name = element ? invoke("getTagName", [node]) : doctype ? "!doctype" : node.name;
834
+ const type = element ? name === "script" || name === "style" ? name : "tag" : text ? "text" : comment ? "comment" : doctype ? "directive" : node.type ?? "root";
835
+ const children = element || type === "root" || type === "cdata" ? invoke("getChildNodes", [node]) ?? [] : [];
836
+ const record = {
837
+ id,
838
+ type,
839
+ children: Array.from(children, identify),
840
+ parent: identify(invoke("getParentNode", [node]))
841
+ };
842
+ if (name !== void 0) record.name = name;
843
+ if (element) {
844
+ record.namespace = invoke("getNamespaceURI", [node]);
845
+ record.attribs = Object.create(null);
846
+ record.attribsNamespace = Object.create(null);
847
+ record.attribsPrefix = Object.create(null);
848
+ for (const attr of invoke("getAttrList", [node])) {
849
+ Object.defineProperty(record.attribs, attr.name, {
850
+ value: attr.value,
851
+ enumerable: true,
852
+ configurable: true,
853
+ writable: true
854
+ });
855
+ record.attribsNamespace[attr.name] = attr.namespace;
856
+ record.attribsPrefix[attr.name] = attr.prefix;
857
+ }
858
+ } else if (text || comment) record.data = invoke(text ? "getTextNodeContent" : "getCommentNodeContent", [node]);
859
+ else if (doctype) {
860
+ record.data = node.data;
861
+ for (const [field, method] of [
862
+ ["x-name", "getDocumentTypeNodeName"],
863
+ ["x-publicId", "getDocumentTypeNodePublicId"],
864
+ ["x-systemId", "getDocumentTypeNodeSystemId"]
865
+ ]) record[field] = invoke(method, [node]);
866
+ }
867
+ if (type === "root" && node["x-mode"] !== void 0) record["x-mode"] = invoke("getDocumentMode", [node]);
868
+ for (const field of [
869
+ "startIndex",
870
+ "endIndex",
871
+ "sourceCodeLocation"
872
+ ]) if (node[field] !== void 0) record[field] = node[field];
873
+ records.push(record);
874
+ }
875
+ return records;
876
+ };
877
+ const bridge = (request) => {
878
+ const { method, args = [] } = JSON.parse(request);
879
+ if (method === "__parseError") {
880
+ deliveredErrors.add(JSON.stringify(args[0]));
881
+ options.onParseError?.(args[0]);
882
+ return "null";
883
+ }
884
+ if (method === "__snapshot") return JSON.stringify(snapshot());
885
+ if (method === "__locations") {
886
+ for (const entry of args[0]) invoke("setNodeSourceCodeLocation", [nodes[entry.id], hydrateLocation(entry.location)]);
887
+ return "null";
888
+ }
889
+ const values = args.slice();
890
+ if (method === "setNodeSourceCodeLocation" || method === "updateNodeSourceCodeLocation") hydrateLocation(values[1]);
891
+ for (const index of nodeArgs[method] ?? []) values[index] = values[index] == null ? null : nodes[values[index]];
892
+ const result = invoke(method, values);
893
+ return JSON.stringify(method === "getChildNodes" ? Array.from(result ?? [], identify) : nodeReturns.has(method) ? identify(result) : result ?? null);
894
+ };
895
+ return {
896
+ bridge,
897
+ nodes,
898
+ deliveredErrors
899
+ };
900
+ }
901
+ function bindAdapterDocument(document, options, adapter) {
902
+ if (options.onParseError) {
903
+ const errors = document.parserDiagnostics?.();
904
+ for (const error of errors ? JSON.parse(errors) : []) if (!adapter.deliveredErrors.has(JSON.stringify(error))) options.onParseError(error);
905
+ }
906
+ const routed = routeDocument(document, options);
907
+ const globalId = routed.localNodeId.bind(routed);
908
+ for (let id = 0; id < adapter.nodes.length; id++) getNode(routed, globalId(id), adapter.nodes[id]);
909
+ return routed;
910
+ }
911
+ function createTreeAdapterSession(options, isDocument) {
912
+ const binding = requireNative();
913
+ if (!binding.NativeHookStream) throw new Error("This native addon does not support streaming treeAdapter hooks; rebuild the Rust addon.");
914
+ const adapter = treeAdapterBridge(options.treeAdapter, options);
915
+ let hasFailure = false;
916
+ let failure;
917
+ let aborted = false;
918
+ const bridge = (request) => {
919
+ if (hasFailure || aborted) return "{\"__cheeroxHookError\":true}";
920
+ try {
921
+ return adapter.bridge(request);
922
+ } catch (error) {
923
+ hasFailure = true;
924
+ failure = error;
925
+ return "{\"__cheeroxHookError\":true}";
926
+ }
927
+ };
928
+ const parser = new binding.NativeHookStream(isDocument, JSON.stringify(cleanParserOptions(options)), bridge);
929
+ const restoreFailure = (error) => {
930
+ if (hasFailure) throw failure;
931
+ throw error;
932
+ };
933
+ return {
934
+ async write(chunk) {
935
+ try {
936
+ await parser.write(chunk);
937
+ if (hasFailure) throw failure;
938
+ } catch (error) {
939
+ restoreFailure(error);
940
+ }
941
+ },
942
+ async end() {
943
+ try {
944
+ const document = await parser.finish();
945
+ if (hasFailure) throw failure;
946
+ return bindAdapterDocument(document, options, adapter);
947
+ } catch (error) {
948
+ return restoreFailure(error);
949
+ }
950
+ },
951
+ abort() {
952
+ aborted = true;
953
+ parser.abort();
954
+ }
955
+ };
956
+ }
957
+ function parseNativeDocument(source, options, isDocument) {
958
+ const binding = requireNative();
959
+ const nativeOptions = parserOptions(source, options);
960
+ if (!options._useHtmlParser2 && options.treeAdapter && canReplay(options)) {
961
+ const document = routeDocument(new binding.NativeDocument(source, isDocument, JSON.stringify(nativeOptions)), options);
962
+ const nodes = replayIntoAdapter(document, options.treeAdapter, isDocument);
963
+ if (nodes) {
964
+ attachParsedNodes(document.state, nodes);
965
+ return document;
966
+ }
967
+ }
968
+ if (!options._useHtmlParser2 && options.treeAdapter) {
969
+ const parse = binding.parseWithTreeAdapter;
970
+ if (!parse) throw new Error("This native addon does not support treeAdapter hooks; rebuild the Rust addon.");
971
+ const adapter = treeAdapterBridge(options.treeAdapter, options);
972
+ return bindAdapterDocument(parse(source, isDocument, JSON.stringify(nativeOptions), adapter.bridge), options, adapter);
973
+ }
974
+ const document = new binding.NativeDocument(source, isDocument, JSON.stringify(nativeOptions));
975
+ deliverParseErrors(document, options);
976
+ return routeDocument(document, options);
977
+ }
978
+ /** Error-only streams keep the Rust DOM and deliver diagnostics during writes. */
979
+ function createDiagnosticSession(options, isDocument = true) {
980
+ const binding = requireNative();
981
+ if (!binding.NativeStream) throw new Error("This native addon does not support incremental parser diagnostics; rebuild the Rust addon.");
982
+ let hasFailure = false;
983
+ let failure;
984
+ let aborted = false;
985
+ const bridge = (request) => {
986
+ if (hasFailure || aborted) return "{\"__cheeroxHookError\":true}";
987
+ try {
988
+ const { method, args } = JSON.parse(request);
989
+ if (method === "__parseError") options.onParseError?.(args[0]);
990
+ return "null";
991
+ } catch (error) {
992
+ hasFailure = true;
993
+ failure = error;
994
+ return "{\"__cheeroxHookError\":true}";
995
+ }
996
+ };
997
+ const parser = new binding.NativeStream(JSON.stringify(cleanParserOptions(options)), isDocument, bridge);
998
+ const restoreFailure = (error) => {
999
+ if (hasFailure) throw failure;
1000
+ throw error;
1001
+ };
1002
+ return {
1003
+ async write(chunk) {
1004
+ try {
1005
+ await parser.write(chunk);
1006
+ if (hasFailure) throw failure;
1007
+ } catch (error) {
1008
+ restoreFailure(error);
1009
+ }
1010
+ },
1011
+ async end() {
1012
+ try {
1013
+ const document = await parser.finish();
1014
+ if (hasFailure) throw failure;
1015
+ return routeDocument(document, options);
1016
+ } catch (error) {
1017
+ return restoreFailure(error);
1018
+ }
1019
+ },
1020
+ abort() {
1021
+ aborted = true;
1022
+ parser.abort();
1023
+ }
1024
+ };
1025
+ }
1026
+ /**
1027
+ * Whether an adapter can be given the finished tree instead of every parser
1028
+ * step: it observes neither the open-element stack nor source locations, and
1029
+ * no parse-error callback can change it while parsing.
1030
+ */
1031
+ function canReplay(options) {
1032
+ const adapter = options.treeAdapter;
1033
+ return !options.onParseError && !options.sourceCodeLocationInfo && adapter.onItemPush === void 0 && adapter.onItemPop === void 0;
1034
+ }
1035
+ /**
1036
+ * Builds the adapter's tree from a native parse by calling its construction
1037
+ * methods in document order, then checks every node against the parse. An
1038
+ * adapter whose nodes differ from what it was given (renamed elements,
1039
+ * rewritten text, filtered children) could have steered parsing differently,
1040
+ * so it returns `undefined` and the caller runs the parser with the adapter
1041
+ * live instead.
1042
+ */
1043
+ function replayIntoAdapter(document, adapter, isDocument) {
1044
+ const state = document.state;
1045
+ const root = document.rootId() - state.base;
1046
+ const size = state.baseline;
1047
+ const nodes = new Array(size);
1048
+ for (let local = 0; local < Math.min(size, 65); local++) recordAt(state, local);
1049
+ for (let local = 0; local < size; local++) {
1050
+ const snapshot = plainSnapshot(state, local);
1051
+ const record = snapshot ? void 0 : recordAt(state, local);
1052
+ if (!snapshot && !record) continue;
1053
+ const type = snapshot ? snapshot.typeOf(local) : record.type;
1054
+ if (local === root) {
1055
+ nodes[local] = isDocument ? adapter.createDocument() : adapter.createDocumentFragment();
1056
+ const mode = record?.["x-mode"];
1057
+ if (isDocument && mode !== void 0) adapter.setDocumentMode(nodes[local], mode);
1058
+ continue;
1059
+ }
1060
+ const parentLocal = snapshot ? snapshot.linkOf(local, 1) : record.parent;
1061
+ const parent = parentLocal == null ? void 0 : nodes[parentLocal];
1062
+ if (parent === void 0) return void 0;
1063
+ switch (type) {
1064
+ case "tag":
1065
+ case "script":
1066
+ case "style": {
1067
+ const element = snapshot ? adapter.createElement(snapshot.nameOf(local), snapshot.namespaceOf(local), snapshot.attributeObjects(local)) : adapter.createElement(record.name, record.namespace, attributeList(record));
1068
+ adapter.appendChild(parent, element);
1069
+ nodes[local] = element;
1070
+ break;
1071
+ }
1072
+ case "root": {
1073
+ const content = adapter.createDocumentFragment();
1074
+ adapter.setTemplateContent(parent, content);
1075
+ nodes[local] = content;
1076
+ break;
1077
+ }
1078
+ case "text": {
1079
+ adapter.insertText(parent, (snapshot ? snapshot.dataOf(local) : record.data) ?? "");
1080
+ const children = adapter.getChildNodes(parent);
1081
+ nodes[local] = children[children.length - 1];
1082
+ break;
1083
+ }
1084
+ case "comment": {
1085
+ const comment = adapter.createCommentNode((snapshot ? snapshot.dataOf(local) : record.data) ?? "");
1086
+ adapter.appendChild(parent, comment);
1087
+ nodes[local] = comment;
1088
+ break;
1089
+ }
1090
+ case "directive":
1091
+ if (!record || record.name !== "!doctype" || !isDocument) return void 0;
1092
+ adapter.setDocumentType(parent, record["x-name"] ?? "", record["x-publicId"] ?? "", record["x-systemId"] ?? "");
1093
+ nodes[local] = Array.from(adapter.getChildNodes(parent) ?? []).find((child) => adapter.isDocumentTypeNode(child));
1094
+ break;
1095
+ default: return;
1096
+ }
1097
+ }
1098
+ const changes = differencesFromParse(adapter, nodes, state, root);
1099
+ if (!changes) return void 0;
1100
+ for (const change of changes) operation(document, "setNode", {
1101
+ id: state.base + change.local,
1102
+ field: change.field,
1103
+ value: change.value
1104
+ });
1105
+ return nodes;
1106
+ }
1107
+ function attributeList(record) {
1108
+ const attributes = record.attribs ?? {};
1109
+ return Object.keys(attributes).map((name) => {
1110
+ const namespace = record.attribsNamespace?.[name];
1111
+ const prefix = record.attribsPrefix?.[name];
1112
+ return {
1113
+ name,
1114
+ value: attributes[name],
1115
+ ...namespace === void 0 ? {} : { namespace },
1116
+ ...prefix === void 0 ? {} : { prefix }
1117
+ };
1118
+ });
1119
+ }
1120
+ /**
1121
+ * The attribute and text values in which the adapter's nodes differ from the
1122
+ * parse, or `undefined` when a name, namespace or link differs, since those
1123
+ * could have steered parsing.
1124
+ */
1125
+ function differencesFromParse(adapter, nodes, state, root) {
1126
+ const changes = [];
1127
+ for (let local = 0; local < nodes.length; local++) {
1128
+ const node = nodes[local];
1129
+ const snapshot = plainSnapshot(state, local);
1130
+ const record = snapshot ? void 0 : recordAt(state, local);
1131
+ if (!snapshot && !record) continue;
1132
+ if (!node) return void 0;
1133
+ const type = snapshot ? snapshot.typeOf(local) : record.type;
1134
+ if (local !== root && adapter.getParentNode(node) !== nodes[snapshot ? snapshot.linkOf(local, 1) : record.parent]) return void 0;
1135
+ if (type !== "text" && type !== "comment" && type !== "directive") {
1136
+ const children = adapter.getChildNodes(node) ?? [];
1137
+ const count = snapshot ? snapshot.childCount(local) : record.children.length;
1138
+ if (children.length !== count) return void 0;
1139
+ for (let index = 0; index < count; index++) if (children[index] !== nodes[snapshot ? snapshot.childAt(local, index) : record.children[index]]) return void 0;
1140
+ }
1141
+ if (type === "tag" || type === "script" || type === "style") {
1142
+ const name = snapshot ? snapshot.nameOf(local) : record.name;
1143
+ const namespace = snapshot ? snapshot.namespaceOf(local) : record.namespace;
1144
+ if (!adapter.isElementNode(node) || adapter.getTagName(node) !== name || adapter.getNamespaceURI(node) !== namespace) return void 0;
1145
+ const attributes = adapter.getAttrList(node) ?? [];
1146
+ const expected = snapshot ? snapshot.attributeObjects(local) : attributeList(record);
1147
+ if (!(attributes.length === expected.length && attributes.every((attribute, index) => attribute.name === expected[index].name && attribute.value === expected[index].value))) {
1148
+ const values = Object.create(null);
1149
+ const namespaces = Object.create(null);
1150
+ const prefixes = Object.create(null);
1151
+ for (const attribute of attributes) {
1152
+ values[attribute.name] = attribute.value;
1153
+ if (attribute.namespace !== void 0) namespaces[attribute.name] = attribute.namespace;
1154
+ if (attribute.prefix !== void 0) prefixes[attribute.name] = attribute.prefix;
1155
+ }
1156
+ changes.push({
1157
+ local,
1158
+ field: "attribs",
1159
+ value: values
1160
+ }, {
1161
+ local,
1162
+ field: "attribsNamespace",
1163
+ value: namespaces
1164
+ }, {
1165
+ local,
1166
+ field: "attribsPrefix",
1167
+ value: prefixes
1168
+ });
1169
+ }
1170
+ } else if (type === "text" || type === "comment") {
1171
+ if (type === "text" ? !adapter.isTextNode(node) : !adapter.isCommentNode(node)) return void 0;
1172
+ const data = type === "text" ? adapter.getTextNodeContent(node) : adapter.getCommentNodeContent(node);
1173
+ if (data !== (snapshot ? snapshot.dataOf(local) : record.data)) changes.push({
1174
+ local,
1175
+ field: "data",
1176
+ value: data
1177
+ });
1178
+ }
1179
+ }
1180
+ return changes;
1181
+ }
1182
+ // src/router.ts
1183
+ /**
1184
+ * A node id is `state.base + local`, where `local` indexes the node in its
1185
+ * native arena. Ids from different documents never collide, so every routed
1186
+ * document shares one id space without a lookup table per node.
1187
+ */
1188
+ const STRIDE = 2 ** 32;
1189
+ /** Ids must stay exact doubles, which bounds how many documents may be alive at once. */
1190
+ const maximumDocuments = 2 ** 21;
1191
+ /** A document's root is its first slot; collections keep it and everything attached to it. */
1192
+ const rootSlots = 1;
1193
+ /** Fields on node objects; registered symbols so ESM and CJS copies share nodes. */
1194
+ const VIEW_STATE = Symbol.for("cheerox.node.state");
1195
+ const VIEW_LOCAL = Symbol.for("cheerox.node.local");
1196
+ const VIEW_ATTRIBUTES = Symbol.for("cheerox.node.attributes");
1197
+ /** Points at the node itself, so a spread copy of a node is not mistaken for it. */
1198
+ const VIEW_SELF = Symbol.for("cheerox.node.self");
1199
+ const DOCUMENT = Symbol.for("cheerox.selection.document");
1200
+ const API = Symbol.for("cheerox.selection.api");
1201
+ const IDS = Symbol.for("cheerox.selection.ids");
1202
+ const VALUES = Symbol.for("cheerox.selection.values");
1203
+ const LEASE = Symbol.for("cheerox.selection.lease");
1204
+ const IS_PLAIN = Symbol.for("cheerox.selection.is-plain");
1205
+ /** A node object's materialized `children` array, refilled when the node's children change. */
1206
+ const VIEW_CHILD_TARGET = Symbol.for("cheerox.node.child-target");
1207
+ const registryKey = Symbol.for(`cheerox.native-documents.v5:${packageDirectory()}`);
1208
+ /** A native document's state lives on the document itself, so they share one lifetime. */
1209
+ const stateKey = Symbol.for("cheerox.native-documents.state");
1210
+ const globals = globalThis;
1211
+ const registry = globals[registryKey] ??= (() => {
1212
+ return {
1213
+ space: {},
1214
+ writes: 0,
1215
+ states: [],
1216
+ pending: /* @__PURE__ */ new Set(),
1217
+ isScheduled: false,
1218
+ leaseFinalizer: new FinalizationRegistry((token) => {
1219
+ token.isReleased = true;
1220
+ })
1221
+ };
1222
+ })();
1223
+ /** The states owning `ids`, resolved through `document`. */
1224
+ function statesOf(document, ids) {
1225
+ const states = [];
1226
+ let previous;
1227
+ for (const id of ids) {
1228
+ if (id === void 0) continue;
1229
+ if (previous && id >= previous.base && id < previous.base + STRIDE) continue;
1230
+ const state = stateIn(document, id);
1231
+ if (!states.includes(state)) states.push(state);
1232
+ previous = state;
1233
+ }
1234
+ return states;
1235
+ }
1236
+ /**
1237
+ * Collects once a structural write leaves the arena grown by half with nodes
1238
+ * removed; collecting sooner costs more than the garbage it would free.
1239
+ */
1240
+ function scheduleCollectionIfDue(state) {
1241
+ if (state.raw.isCollectionDue?.()) scheduleCollection(state);
1242
+ }
1243
+ /**
1244
+ * Collections run on a later turn of the event loop: no library call is then
1245
+ * between native writes holding ids of nodes it has just detached, and node
1246
+ * objects weakened on an earlier turn may have been reclaimed.
1247
+ */
1248
+ function scheduleCollection(state) {
1249
+ registry.pending.add(state);
1250
+ if (registry.pending.size > maximumPendingCollections) {
1251
+ const evicted = registry.pending.values().next().value;
1252
+ registry.pending.delete(evicted);
1253
+ evicted.isCollectionEvicted = true;
1254
+ }
1255
+ if (registry.isScheduled) return;
1256
+ registry.isScheduled = true;
1257
+ setImmediate(() => {
1258
+ registry.isScheduled = false;
1259
+ const states = [...registry.pending];
1260
+ registry.pending.clear();
1261
+ for (const pending of states) collectState(pending);
1262
+ }).unref();
1263
+ }
1264
+ const maximumPendingCollections = 4;
1265
+ /** Increases with every write to any document. */
1266
+ function writeCount() {
1267
+ return registry.writes;
1268
+ }
1269
+ /**
1270
+ * The state of a native document, created on first use. The addon hands out
1271
+ * routing indexes and takes one back when its document is finalized, which
1272
+ * happens during garbage collection, so indexes recycle even within a
1273
+ * synchronous loop.
1274
+ */
1275
+ function stateFor(raw, options = {}) {
1276
+ const holder = raw;
1277
+ const existing = holder[stateKey];
1278
+ if (existing) return existing;
1279
+ const index = raw.routingIndex();
1280
+ if (index >= maximumDocuments) throw new RangeError("Too many documents are alive at once.");
1281
+ const baseline = raw.slotCount?.() ?? 0;
1282
+ const state = {
1283
+ raw,
1284
+ base: index * STRIDE,
1285
+ space: registry.space,
1286
+ options,
1287
+ rootLocal: void 0,
1288
+ routed: void 0,
1289
+ generation: 0,
1290
+ records: [],
1291
+ bulk: 0,
1292
+ snapshotSize: 0,
1293
+ stale: /* @__PURE__ */ new Set(),
1294
+ views: new Array(baseline),
1295
+ looseViews: /* @__PURE__ */ new Map(),
1296
+ looseViewLimit: minimumLooseViewLimit,
1297
+ weakViews: /* @__PURE__ */ new Map(),
1298
+ baseline,
1299
+ leases: /* @__PURE__ */ new Set(),
1300
+ leaseSweepSize: 64,
1301
+ data: /* @__PURE__ */ new Map(),
1302
+ isExposed: false,
1303
+ hasChildLists: false,
1304
+ collectionRetries: 0,
1305
+ isCollectionEvicted: false,
1306
+ hasPreparedSnapshot: false
1307
+ };
1308
+ holder[stateKey] = state;
1309
+ return state;
1310
+ }
1311
+ /** Lets ids of `state` be resolved from documents other than its own. */
1312
+ function exposeState(state) {
1313
+ if (state.isExposed) return;
1314
+ state.isExposed = true;
1315
+ registry.states[state.base / STRIDE] = new WeakRef(state);
1316
+ }
1317
+ /**
1318
+ * Called before ids of `state` enter operations or selections of `document`.
1319
+ * Leases keep the documents of the ids a selection holds; node objects keep
1320
+ * their own.
1321
+ */
1322
+ function exposeTo(document, state) {
1323
+ if (document.state === state) return;
1324
+ exposeState(state);
1325
+ }
1326
+ /** Called before a selection's ids enter operations of `document`. */
1327
+ function exposeDocumentTo(document, source) {
1328
+ const state = source?.state;
1329
+ if (state) exposeTo(document, state);
1330
+ }
1331
+ /** The node object cached for a slot, if any. */
1332
+ function cachedView(state, local) {
1333
+ return (local < state.baseline ? state.views[local] : state.looseViews.get(local)) ?? (state.weakViews.size ? state.weakViews.get(local)?.deref() : void 0);
1334
+ }
1335
+ /** Created nodes held as objects only become collectable through a collection. */
1336
+ const minimumLooseViewLimit = 1024;
1337
+ function cacheView(state, local, view) {
1338
+ if (local < state.baseline) {
1339
+ state.views[local] = view;
1340
+ return;
1341
+ }
1342
+ state.looseViews.set(local, view);
1343
+ if (state.looseViews.size >= state.looseViewLimit) {
1344
+ state.looseViewLimit = state.looseViews.size * 2;
1345
+ scheduleCollection(state);
1346
+ }
1347
+ }
1348
+ function uncacheView(state, local) {
1349
+ const view = cachedView(state, local);
1350
+ if (local < state.baseline) state.views[local] = void 0;
1351
+ state.looseViews.delete(local);
1352
+ state.weakViews.delete(local);
1353
+ return view;
1354
+ }
1355
+ /** A collection drops released slots at the arena's end; later nodes reuse their indexes. */
1356
+ function releaseSlotsFrom(state, end) {
1357
+ for (const local of state.data.keys()) if (local >= end) releaseSlot(state, local);
1358
+ for (const local of state.weakViews.keys()) if (local >= end) state.weakViews.delete(local);
1359
+ if (state.adapterNodes && state.adapterNodes.length > end) {
1360
+ for (let local = end; local < state.adapterNodes.length; local++) releaseAdapterNode(state, local);
1361
+ state.adapterNodes.length = end;
1362
+ }
1363
+ }
1364
+ /** Forgets everything bound to a slot a collection freed. */
1365
+ function releaseSlot(state, local) {
1366
+ uncacheView(state, local);
1367
+ const entry = state.data.get(local);
1368
+ if (entry) {
1369
+ entry.isReleased = true;
1370
+ state.data.delete(local);
1371
+ }
1372
+ releaseAdapterNode(state, local);
1373
+ }
1374
+ /** Hands a freed slot's tree adapter object back to the caller: passed in again, it is imported like any other node. */
1375
+ function releaseAdapterNode(state, local) {
1376
+ const adapterNode = state.adapterNodes?.[local];
1377
+ if (!adapterNode) return;
1378
+ adapterNode[VIEW_SELF] = void 0;
1379
+ state.adapterNodes[local] = void 0;
1380
+ }
1381
+ function hasViews(state) {
1382
+ return state.views.length > 0 || state.looseViews.size > 0 || state.weakViews.size > 0;
1383
+ }
1384
+ function forEachView(state, visit) {
1385
+ state.views.forEach((view, local) => {
1386
+ if (view) visit(view, local);
1387
+ });
1388
+ for (const [local, view] of state.looseViews) visit(view, local);
1389
+ for (const [local, reference] of state.weakViews) {
1390
+ const view = reference.deref();
1391
+ if (view) visit(view, local);
1392
+ }
1393
+ }
1394
+ /**
1395
+ * Node objects of detached nodes stay cached only while something else holds
1396
+ * them, so a later collection can reclaim their nodes. The `WeakRef`s are
1397
+ * taken during a collection rather than on removal: taking one keeps its
1398
+ * target, and so its document, alive until the current job ends. Returns
1399
+ * whether any node object was weakened.
1400
+ */
1401
+ function weakenDetachedViews(state) {
1402
+ if (!state.raw.detachedSlots) return false;
1403
+ let isWeakened = false;
1404
+ for (const local of state.raw.detachedSlots(state.rootLocal ??= state.raw.rootId())) {
1405
+ const view = local < state.baseline ? state.views[local] : state.looseViews.get(local);
1406
+ if (!view) continue;
1407
+ if (local < state.baseline) state.views[local] = void 0;
1408
+ else state.looseViews.delete(local);
1409
+ state.weakViews.set(local, new WeakRef(view));
1410
+ isWeakened = true;
1411
+ }
1412
+ return isWeakened;
1413
+ }
1414
+ /** The state owning `id` of a document whose ids have reached other documents. */
1415
+ function exposedStateOf(id) {
1416
+ const state = registry.states[Math.floor(id / STRIDE)]?.deref();
1417
+ if (!state || !(id >= 0)) throw new RangeError(`Unknown native node handle ${id}`);
1418
+ return state;
1419
+ }
1420
+ /** The state owning `id`, resolved without the weak table when `document` owns it. */
1421
+ function stateIn(document, id) {
1422
+ const own = document.state;
1423
+ if (own === void 0 || id < own.base || id >= own.base + STRIDE) return exposedStateOf(id);
1424
+ if (own.isCollectionEvicted) resumeCollection(document);
1425
+ return own;
1426
+ }
1427
+ /** Schedules again a collection that left the pending list before it ran. */
1428
+ function resumeCollection(document) {
1429
+ const state = document.state;
1430
+ if (!state?.isCollectionEvicted) return;
1431
+ state.isCollectionEvicted = false;
1432
+ scheduleCollection(state);
1433
+ }
1434
+ /** The node's record for the current generation, with ids local to `state`. */
1435
+ function recordAt(state, local) {
1436
+ const cached = state.records[local];
1437
+ if (cached !== void 0) return cached;
1438
+ const record = readRecord(state, local);
1439
+ state.records[local] = record;
1440
+ return record;
1441
+ }
1442
+ const minimumReadsBeforeSnapshot = 64;
1443
+ /**
1444
+ * Once individual reads in a generation cost about as much as copying every
1445
+ * record, take one snapshot and decode the rest locally. A snapshot costs
1446
+ * about two reads plus one read per hundred nodes, and a document read once
1447
+ * is usually read again, so an unchanged document of under a hundred nodes
1448
+ * takes one on its first read. Mutations start a new generation.
1449
+ */
1450
+ function readRecord(state, local) {
1451
+ const bulk = state.bulk;
1452
+ if (bulk instanceof NodeSnapshot) {
1453
+ const record = state.stale.size && state.stale.has(local) ? void 0 : bulk.record(local);
1454
+ if (record !== void 0) return record;
1455
+ } else if (state.raw.snapshot) {
1456
+ const reads = bulk + 1;
1457
+ const size = Math.max(state.snapshotSize, state.baseline);
1458
+ const firstSnapshotRead = state.generation === 0 ? size / 100 : 1 + size / 100;
1459
+ if (reads >= Math.min(minimumReadsBeforeSnapshot, firstSnapshotRead)) {
1460
+ const snapshot = new NodeSnapshot(takePreparedSnapshot(state, true) ?? state.raw.snapshot());
1461
+ state.snapshotSize = snapshot.size;
1462
+ state.bulk = snapshot;
1463
+ const record = snapshot.record(local);
1464
+ if (record !== void 0) return record;
1465
+ } else state.bulk = reads;
1466
+ }
1467
+ return rawOperation(state.raw, "node", { id: local });
1468
+ }
1469
+ /**
1470
+ * Lets a routed document nothing has read or changed yet use the snapshot
1471
+ * its native document built while parsing, when its reads first need one.
1472
+ */
1473
+ function usePreparedSnapshot(document) {
1474
+ if (!(document instanceof RoutedDocument)) return;
1475
+ const state = document.state;
1476
+ state.hasPreparedSnapshot = state.generation === 0 && state.bulk === 0;
1477
+ }
1478
+ function takePreparedSnapshot(state, isWanted) {
1479
+ if (!state.hasPreparedSnapshot) return void 0;
1480
+ state.hasPreparedSnapshot = false;
1481
+ return state.raw.takePreparedSnapshot?.(isWanted) ?? void 0;
1482
+ }
1483
+ /** Start a full-tree walk from one compact record snapshot instead of a series of individual node reads. */
1484
+ function prepareWalkSnapshot(state) {
1485
+ if (state.generation !== 0 || state.bulk instanceof NodeSnapshot || !state.raw.snapshot || state.adapterNodes) return;
1486
+ const snapshot = new NodeSnapshot(takePreparedSnapshot(state, true) ?? state.raw.snapshot());
1487
+ state.snapshotSize = snapshot.size;
1488
+ state.bulk = snapshot;
1489
+ }
1490
+ /** Prepare one compact snapshot before materializing a large selection from an unchanged document. */
1491
+ function prepareBulkViews(document, ids) {
1492
+ if (ids.length < 64 || !(document instanceof RoutedDocument)) return;
1493
+ const state = document.state;
1494
+ if (state.generation !== 0 || state.bulk instanceof NodeSnapshot || !state.raw.snapshot || state.adapterNodes) return;
1495
+ let unseen = 0;
1496
+ let previous = -1;
1497
+ for (const id of ids) {
1498
+ const local = id - state.base;
1499
+ if (local < 0 || local >= state.baseline) return;
1500
+ if (unseen < 64 && !state.views[local] && (!state.weakViews.size || !cachedView(state, local))) {
1501
+ if (local <= previous) return;
1502
+ previous = local;
1503
+ unseen++;
1504
+ }
1505
+ }
1506
+ if (unseen < 64) return;
1507
+ const snapshot = new NodeSnapshot(takePreparedSnapshot(state, true) ?? state.raw.snapshot());
1508
+ state.snapshotSize = snapshot.size;
1509
+ state.bulk = snapshot;
1510
+ }
1511
+ /** The current snapshot when it holds `local` exactly, so its fields can be read without a record. */
1512
+ function plainSnapshot(state, local) {
1513
+ const bulk = state.bulk;
1514
+ return bulk instanceof NodeSnapshot && !(state.stale.size && state.stale.has(local)) && bulk.isPlain(local) ? bulk : void 0;
1515
+ }
1516
+ /**
1517
+ * The current snapshot when it holds `local`'s type, name, links and
1518
+ * children. Those are kept for every node, also one whose large text or
1519
+ * attributes must be read individually.
1520
+ */
1521
+ function structureSnapshot(state, local) {
1522
+ const bulk = state.bulk;
1523
+ return bulk instanceof NodeSnapshot && !(state.stale.size && state.stale.has(local)) && bulk.isPresent(local) ? bulk : void 0;
1524
+ }
1525
+ /** Nodes a JavaScript `text()` reads before leaving larger subtrees to the native engine. */
1526
+ const snapshotTextBudget = 256;
1527
+ /**
1528
+ * The text of a small subtree read from the snapshot, as the native `text`
1529
+ * concatenates it, or `undefined` to ask the native engine. Text too large
1530
+ * for the snapshot is read once per snapshot, so repeated reads do not copy
1531
+ * it out of the native tree again.
1532
+ */
1533
+ function textFromSnapshot(state, local) {
1534
+ let text = "";
1535
+ const stack = [local];
1536
+ for (let visited = 0; stack.length; visited++) {
1537
+ const node = stack.pop();
1538
+ const snapshot = structureSnapshot(state, node);
1539
+ if (!snapshot || visited === snapshotTextBudget) return void 0;
1540
+ if (snapshot.isTextAt(node)) {
1541
+ text += snapshot.dataOf(node) ?? largeText(state, snapshot, node);
1542
+ continue;
1543
+ }
1544
+ for (let index = snapshot.childCount(node) - 1; index >= 0; index--) stack.push(snapshot.childAt(node, index));
1545
+ }
1546
+ return text;
1547
+ }
1548
+ function largeText(state, snapshot, local) {
1549
+ let text = snapshot.largeTexts.get(local);
1550
+ if (text === void 0) snapshot.largeTexts.set(local, text = state.raw.text([local]));
1551
+ return text;
1552
+ }
1553
+ /** A string attribute of an element, read like the native `attr` lookup. */
1554
+ function attributeAt(state, local, name) {
1555
+ const snapshot = plainSnapshot(state, local);
1556
+ if (snapshot) return snapshot.attributeValue(local, name);
1557
+ const attributes = recordAt(state, local)?.attribs;
1558
+ const value = attributes && Object.hasOwn(attributes, name) ? attributes[name] : void 0;
1559
+ return typeof value === "string" ? value : void 0;
1560
+ }
1561
+ /** Starts a new generation: cached records may no longer match the arena. */
1562
+ function invalidate(state) {
1563
+ takePreparedSnapshot(state, false);
1564
+ state.generation++;
1565
+ state.records = [];
1566
+ state.bulk = 0;
1567
+ state.stale.clear();
1568
+ }
1569
+ function refreshSerializedNodes(state, options) {
1570
+ if (!options._useHtmlParser2 || options.xmlMode) return;
1571
+ const touched = state.raw.takeTouched?.();
1572
+ if (touched === null) invalidate(state);
1573
+ else if (touched?.length) invalidateNodes(state, touched);
1574
+ }
1575
+ /** Discards the records of nodes a write changed without touching the tree's shape. */
1576
+ function invalidateNodes(state, locals) {
1577
+ takePreparedSnapshot(state, false);
1578
+ const isSnapshot = state.bulk instanceof NodeSnapshot;
1579
+ const { records } = state;
1580
+ for (const local of locals) {
1581
+ if (records[local] !== void 0) records[local] = void 0;
1582
+ if (isSnapshot) state.stale.add(local);
1583
+ }
1584
+ }
1585
+ /** Keeps the ids of `document` that `owner` holds alive, and rewrites them when their nodes move. */
1586
+ function leaseNodes(document, owner, ids) {
1587
+ const token = { isReleased: false };
1588
+ const states = statesOf(document, ids);
1589
+ const lease = {
1590
+ ids,
1591
+ token,
1592
+ states
1593
+ };
1594
+ for (const state of states) addLease(state, lease);
1595
+ registry.leaseFinalizer.register(owner, token);
1596
+ return lease;
1597
+ }
1598
+ /** Points a lease at a replacement id list. */
1599
+ function updateLease(document, lease, ids) {
1600
+ lease.ids = ids;
1601
+ lease.states = statesOf(document, ids);
1602
+ for (const state of lease.states) addLease(state, lease);
1603
+ }
1604
+ function addLease(state, lease) {
1605
+ state.leases.add(lease);
1606
+ if (state.leases.size < state.leaseSweepSize) return;
1607
+ for (const held of state.leases) if (held.token.isReleased) state.leases.delete(held);
1608
+ state.leaseSweepSize = state.leases.size * 2 + 64;
1609
+ }
1610
+ /** Weakened node objects become unreachable only after a later garbage collection. */
1611
+ const collectionRetries = 3;
1612
+ /** Reclaims removed nodes that no JavaScript owner references. */
1613
+ function collectState(state) {
1614
+ registry.pending.delete(state);
1615
+ state.isCollectionEvicted = false;
1616
+ if (!state.raw.collectPinned) return state.raw.collectGarbage?.();
1617
+ if (weakenDetachedViews(state)) state.collectionRetries = collectionRetries;
1618
+ const pins = [];
1619
+ const { base } = state;
1620
+ const end = base + STRIDE;
1621
+ for (const lease of state.leases) {
1622
+ if (lease.token.isReleased) {
1623
+ state.leases.delete(lease);
1624
+ continue;
1625
+ }
1626
+ for (const id of lease.ids) if (id >= base && id < end) pins.push(id - base);
1627
+ }
1628
+ state.views.forEach((view, local) => {
1629
+ if (view) pins.push(local);
1630
+ });
1631
+ for (const local of state.looseViews.keys()) pins.push(local);
1632
+ for (const [local, reference] of state.weakViews) if (reference.deref()) pins.push(local);
1633
+ else state.weakViews.delete(local);
1634
+ const { free, ...stats } = state.raw.collectPinned(Uint32Array.from(pins), rootSlots);
1635
+ invalidate(state);
1636
+ for (const local of free) releaseSlot(state, local);
1637
+ releaseSlotsFrom(state, stats.slots);
1638
+ state.looseViewLimit = Math.max(minimumLooseViewLimit, state.looseViews.size * 2);
1639
+ if (state.collectionRetries > 0 && state.weakViews.size > 0) {
1640
+ state.collectionRetries--;
1641
+ scheduleCollection(state);
1642
+ }
1643
+ return stats;
1644
+ }
1645
+ function rawOperation(document, command, args) {
1646
+ const result = document.op(command, JSON.stringify(args));
1647
+ return result === "" || result === void 0 ? void 0 : JSON.parse(result);
1648
+ }
1649
+ /** Converts a record's local links to ids. */
1650
+ function globalRecord(state, record) {
1651
+ if (!record) return null;
1652
+ const { base } = state;
1653
+ const link = (local) => local == null ? null : base + local;
1654
+ return {
1655
+ ...plainRecord(record),
1656
+ id: base + record.id,
1657
+ children: (record.children ?? []).map((child) => base + child),
1658
+ parent: link(record.parent),
1659
+ prev: link(record.prev),
1660
+ next: link(record.next)
1661
+ };
1662
+ }
1663
+ const parentTypes = /* @__PURE__ */ new Set([
1664
+ "root",
1665
+ "tag",
1666
+ "script",
1667
+ "style",
1668
+ "cdata"
1669
+ ]);
1670
+ const pointerFields = /* @__PURE__ */ new Set([
1671
+ "parent",
1672
+ "parentNode",
1673
+ "prev",
1674
+ "previousSibling",
1675
+ "next",
1676
+ "nextSibling"
1677
+ ]);
1678
+ const idResultCommands = /* @__PURE__ */ new Set([
1679
+ "select",
1680
+ "matches",
1681
+ "uniqueSort",
1682
+ "traverse",
1683
+ "clone"
1684
+ ]);
1685
+ const scratchCommands = /* @__PURE__ */ new Set([
1686
+ "select",
1687
+ "matches",
1688
+ "uniqueSort",
1689
+ "serializeArray",
1690
+ "serialize",
1691
+ "extractPlan"
1692
+ ]);
1693
+ const writeCommands = /* @__PURE__ */ new Set([
1694
+ "create",
1695
+ "createNode",
1696
+ "setNode",
1697
+ "setAttrs",
1698
+ "import",
1699
+ "insert",
1700
+ "clone",
1701
+ "remove",
1702
+ "removeAttr",
1703
+ "removeData",
1704
+ "addClass",
1705
+ "removeClass",
1706
+ "toggleClass"
1707
+ ]);
1708
+ const attributeFields = /* @__PURE__ */ new Set([
1709
+ "attribs",
1710
+ "x-attribsNamespace",
1711
+ "x-attribsPrefix"
1712
+ ]);
1713
+ const targetedAttributeWrites = /* @__PURE__ */ new Set([
1714
+ "attr",
1715
+ "removeAttr",
1716
+ "addClass",
1717
+ "removeClass",
1718
+ "toggleClass",
1719
+ "css"
1720
+ ]);
1721
+ /** Writes that only change the records of their own ids. */
1722
+ const recordOnlyWrites = /* @__PURE__ */ new Set([
1723
+ ...targetedAttributeWrites,
1724
+ "data",
1725
+ "removeData",
1726
+ "setAttrs"
1727
+ ]);
1728
+ const structuralWrites = /* @__PURE__ */ new Set([
1729
+ "create",
1730
+ "createNode",
1731
+ "import",
1732
+ "insert",
1733
+ "clone",
1734
+ "remove",
1735
+ "html",
1736
+ "text",
1737
+ "data",
1738
+ "removeData"
1739
+ ]);
1740
+ /**
1741
+ * Routes commands for ids from any document to the arena that owns them.
1742
+ * Native adoption moves nodes between arenas; `moveInto` rewrites the ids that
1743
+ * live owners hold so node identities survive the move.
1744
+ */
1745
+ var RoutedDocument = class {
1746
+ nodeSpace = registry.space;
1747
+ options;
1748
+ state;
1749
+ get raw() {
1750
+ return this.state.raw;
1751
+ }
1752
+ constructor(document, options = {}) {
1753
+ this.options = options;
1754
+ this.state = stateFor(document, options);
1755
+ }
1756
+ /**
1757
+ * Sets (or with `null` removes) an attribute, as the `attr` command does,
1758
+ * through a typed native call. Attribute objects already handed out are
1759
+ * updated in place instead of being read back.
1760
+ */
1761
+ setAttribute(ids, name, value) {
1762
+ const own = this.state;
1763
+ if (ids.length === 1 && own.raw.setAttribute) {
1764
+ const id = ids[0];
1765
+ if (id >= own.base && id < own.base + STRIDE) {
1766
+ registry.writes++;
1767
+ const local = id - own.base;
1768
+ invalidateNodes(own, [local]);
1769
+ own.raw.setAttribute([local], name, value);
1770
+ const attributes = cachedView(own, local)?.[VIEW_ATTRIBUTES];
1771
+ if (attributes) attributeAssign(attributes, name, value);
1772
+ return;
1773
+ }
1774
+ }
1775
+ registry.writes++;
1776
+ for (const { state, locals } of this.groups(ids)) {
1777
+ if (!state.raw.setAttribute) {
1778
+ this.call(state, "attr", {
1779
+ ids: locals,
1780
+ name,
1781
+ value
1782
+ });
1783
+ continue;
1784
+ }
1785
+ invalidateNodes(state, locals);
1786
+ state.raw.setAttribute(locals, name, value);
1787
+ for (const local of locals) {
1788
+ const attributes = cachedView(state, local)?.[VIEW_ATTRIBUTES];
1789
+ if (attributes) attributeAssign(attributes, name, value);
1790
+ }
1791
+ }
1792
+ }
1793
+ addClass(ids, name) {
1794
+ const own = this.state;
1795
+ if (ids.length === 1 && own.raw.addClass) {
1796
+ const id = ids[0];
1797
+ if (id >= own.base && id < own.base + STRIDE) {
1798
+ registry.writes++;
1799
+ const local = id - own.base;
1800
+ invalidateNodes(own, [local]);
1801
+ own.raw.addClass([local], name);
1802
+ const attributes = cachedView(own, local)?.[VIEW_ATTRIBUTES];
1803
+ if (attributes) attributeAssign(attributes, "class", own.raw.attr(local, "class") ?? null);
1804
+ return;
1805
+ }
1806
+ }
1807
+ registry.writes++;
1808
+ for (const { state, locals } of this.groups(ids)) {
1809
+ if (!state.raw.addClass) {
1810
+ this.call(state, "addClass", {
1811
+ ids: locals,
1812
+ name
1813
+ });
1814
+ continue;
1815
+ }
1816
+ invalidateNodes(state, locals);
1817
+ state.raw.addClass(locals, name);
1818
+ for (const local of locals) {
1819
+ const attributes = cachedView(state, local)?.[VIEW_ATTRIBUTES];
1820
+ if (attributes) attributeAssign(attributes, "class", state.raw.attr(local, "class") ?? null);
1821
+ }
1822
+ }
1823
+ }
1824
+ retainNode(id) {
1825
+ this.owner(id);
1826
+ }
1827
+ collectGarbage() {
1828
+ return collectState(this.state);
1829
+ }
1830
+ retainNodeData(id, data) {
1831
+ dataEntry(this.owner(id), id).data = data;
1832
+ }
1833
+ nodeData(id) {
1834
+ const state = this.owner(id);
1835
+ return state.data.get(id - state.base)?.data;
1836
+ }
1837
+ nodeDataOperation(id) {
1838
+ const entry = dataEntry(this.owner(id), id);
1839
+ const options = this.options;
1840
+ return (command, args) => entry.isReleased ? void 0 : routedFor(entry.state).operate(command, {
1841
+ ...args,
1842
+ ids: [entry.state.base + entry.local],
1843
+ options
1844
+ });
1845
+ }
1846
+ localNodeId(local) {
1847
+ return this.state.base + local;
1848
+ }
1849
+ rootId() {
1850
+ return this.state.base + (this.state.rootLocal ??= this.raw.rootId());
1851
+ }
1852
+ isOwnNode(id) {
1853
+ return id >= this.state.base && id < this.state.base + STRIDE;
1854
+ }
1855
+ owner(id) {
1856
+ return stateIn(this, id);
1857
+ }
1858
+ globals(state, locals) {
1859
+ const { base } = state;
1860
+ return locals.map((local) => base + local);
1861
+ }
1862
+ groups(ids) {
1863
+ const groups = [];
1864
+ const own = this.state;
1865
+ let last;
1866
+ for (const id of ids) {
1867
+ const state = id >= own.base && id < own.base + STRIDE ? own : exposedStateOf(id);
1868
+ if (last?.state === state) last.locals.push(id - state.base);
1869
+ else groups.push(last = {
1870
+ state,
1871
+ locals: [id - state.base]
1872
+ });
1873
+ }
1874
+ return groups;
1875
+ }
1876
+ call(state, command, args) {
1877
+ if (command === "extractPlan" && JSON.stringify(args.plan).includes("innerHTML")) invalidate(state);
1878
+ const isWrite = Object.hasOwn(args, "value") || writeCommands.has(command);
1879
+ const recordOnlyWrite = recordOnlyWrites.has(command) || command === "setNode" && attributeFields.has(args.field);
1880
+ if (isWrite) {
1881
+ registry.writes++;
1882
+ const changed = recordOnlyWrites.has(command) ? args.ids ?? [] : command === "setNode" && attributeFields.has(args.field) ? [args.id] : void 0;
1883
+ if (changed) invalidateNodes(state, changed);
1884
+ else invalidate(state);
1885
+ }
1886
+ const result = rawOperation(state.raw, command, {
1887
+ ...args,
1888
+ options: args.options ?? this.options
1889
+ });
1890
+ if (command === "render" || command === "outerHtml" || command === "html" && !isWrite || command === "prop" && (args.name === "innerHTML" || args.name === "outerHTML")) refreshSerializedNodes(state, args.options ?? this.options);
1891
+ if (isWrite) {
1892
+ refreshWrittenAttributes(state, command, args);
1893
+ if (!recordOnlyWrite) {
1894
+ refreshChildLists(state);
1895
+ scheduleCollectionIfDue(state);
1896
+ }
1897
+ }
1898
+ return result;
1899
+ }
1900
+ /** Moves or copies nodes into `target`; returns their local ids there. */
1901
+ moveInto(target, ids, isCopy = false) {
1902
+ if (!isCopy) {
1903
+ for (const group of this.groups(ids)) {
1904
+ if (group.state === target) continue;
1905
+ if (!target.raw.adopt) throw new Error("The native addon does not support cross-document adoption. Rebuild the Rust addon.");
1906
+ const adopted = JSON.parse(target.raw.adopt(group.state.raw, group.locals, true));
1907
+ rehome(group.state, target, adopted.mapping, ids);
1908
+ refreshChildLists(group.state);
1909
+ refreshChildLists(target);
1910
+ scheduleCollectionIfDue(group.state);
1911
+ }
1912
+ return ids.map((id) => id - target.base);
1913
+ }
1914
+ const result = [];
1915
+ for (const group of this.groups(ids)) {
1916
+ if (group.state === target) {
1917
+ result.push(...this.call(target, "clone", {
1918
+ ids: group.locals,
1919
+ deep: true
1920
+ }));
1921
+ continue;
1922
+ }
1923
+ if (!target.raw.adopt) throw new Error("The native addon does not support cross-document adoption. Rebuild the Rust addon.");
1924
+ invalidate(target);
1925
+ const adopted = JSON.parse(target.raw.adopt(group.state.raw, group.locals, false));
1926
+ result.push(...adopted.roots);
1927
+ }
1928
+ return result;
1929
+ }
1930
+ scratch(command, args, ids) {
1931
+ const states = [...new Set(ids.map((id) => this.owner(id)))];
1932
+ const scratch = new (requireNative()).NativeDocument("", false, JSON.stringify(args.options ?? this.options));
1933
+ const toScratch = /* @__PURE__ */ new Map();
1934
+ const fromScratch = /* @__PURE__ */ new Map();
1935
+ for (const state of states) {
1936
+ const roots = state.raw.forestRoots?.() ?? JSON.parse(state.raw.exportTree()).filter((record) => record.parent == null).map((record) => record.id);
1937
+ if (!scratch.adopt) throw new Error("The native addon does not support native document copies.");
1938
+ const copied = JSON.parse(scratch.adopt(state.raw, roots, false));
1939
+ for (const [local, copy] of copied.mapping) {
1940
+ const global = state.base + local;
1941
+ toScratch.set(global, copy);
1942
+ fromScratch.set(copy, global);
1943
+ }
1944
+ }
1945
+ const translated = { ...args };
1946
+ for (const key of ["ids", "contexts"]) if (Array.isArray(args[key])) translated[key] = args[key].map((id) => toScratch.get(id)).filter((id) => id !== void 0);
1947
+ if (args.pseudoMatches) translated.pseudoMatches = Object.fromEntries(Object.entries(args.pseudoMatches).map(([key, values]) => [key, values.map((id) => toScratch.get(id)).filter((id) => id !== void 0)]));
1948
+ const result = rawOperation(scratch, command, {
1949
+ ...translated,
1950
+ options: translated.options ?? this.options
1951
+ });
1952
+ return [
1953
+ "select",
1954
+ "matches",
1955
+ "uniqueSort"
1956
+ ].includes(command) ? result.map((id) => fromScratch.get(id)).filter((id) => id !== void 0) : result;
1957
+ }
1958
+ isMixed(groups) {
1959
+ return groups.length > 1 && groups.some((group) => group.state !== groups[0].state);
1960
+ }
1961
+ select(selector, contexts) {
1962
+ const ids = contexts ?? [this.rootId()];
1963
+ if (!ids.length) return this.call(this.state, "select", {
1964
+ selector,
1965
+ contexts: []
1966
+ });
1967
+ if (ids.length === 1) {
1968
+ const own = this.state;
1969
+ const id = ids[0];
1970
+ if (id >= own.base && id < own.base + STRIDE) {
1971
+ const found = own.raw.select(selector, [id - own.base]);
1972
+ return this.globals(own, found);
1973
+ }
1974
+ }
1975
+ const groups = this.groups(ids);
1976
+ if (this.isMixed(groups)) return this.scratch("select", {
1977
+ selector,
1978
+ contexts: ids
1979
+ }, ids);
1980
+ const group = groups[0];
1981
+ const found = group.state === this.state ? group.state.raw.select(selector, group.locals) : this.call(group.state, "select", {
1982
+ selector,
1983
+ contexts: group.locals
1984
+ });
1985
+ return this.globals(group.state, found);
1986
+ }
1987
+ text(ids) {
1988
+ if (ids.length === 1) {
1989
+ const state = this.owner(ids[0]);
1990
+ const text = textFromSnapshot(state, ids[0] - state.base);
1991
+ if (text !== void 0) return text;
1992
+ }
1993
+ return this.groups(ids).map((group) => group.state.raw.text(group.locals)).join("");
1994
+ }
1995
+ innerHtml(id) {
1996
+ const state = this.owner(id);
1997
+ const local = id - state.base;
1998
+ const isSplicing = recordAt(state, local)?.children?.some((child) => recordAt(state, child)?.type === "root") ?? false;
1999
+ if (isSplicing) invalidate(state);
2000
+ const html = state === this.state ? state.raw.innerHtml(local) : this.call(state, "html", { ids: [local] });
2001
+ if (state === this.state) refreshSerializedNodes(state, state.options);
2002
+ if (isSplicing && state.hasChildLists && childRefresher) forEachView(state, childRefresher);
2003
+ return html;
2004
+ }
2005
+ outerHtml(ids) {
2006
+ return this.groups(ids).map((group) => {
2007
+ if (group.state !== this.state) return this.call(group.state, "render", { ids: group.locals });
2008
+ const html = group.state.raw.outerHtml(group.locals);
2009
+ refreshSerializedNodes(group.state, group.state.options);
2010
+ return html;
2011
+ }).join("");
2012
+ }
2013
+ attr(id, name) {
2014
+ const state = this.owner(id);
2015
+ return this.call(state, "attr", {
2016
+ ids: [id - state.base],
2017
+ name
2018
+ }) ?? void 0;
2019
+ }
2020
+ tagName(id) {
2021
+ const state = this.owner(id);
2022
+ return recordAt(state, id - state.base)?.name;
2023
+ }
2024
+ exportTree() {
2025
+ if (this.raw.exportTreeWithOffset) return this.raw.exportTreeWithOffset(this.state.base);
2026
+ return JSON.stringify(JSON.parse(this.raw.exportTree()).map((record) => globalRecord(this.state, record)));
2027
+ }
2028
+ create(html, contextId) {
2029
+ return this.operate("create", {
2030
+ html,
2031
+ contextId
2032
+ });
2033
+ }
2034
+ insertHtml(targetIds, html, position) {
2035
+ const groups = this.groups(targetIds);
2036
+ if (groups.length !== 1) return void 0;
2037
+ const { state, locals } = groups[0];
2038
+ const insertHtml = state.raw.insertHtml;
2039
+ if (!insertHtml) return void 0;
2040
+ registry.writes++;
2041
+ invalidate(state);
2042
+ const inserted = insertHtml.call(state.raw, locals, html, position);
2043
+ if (state.hasChildLists) refreshChildLists(state);
2044
+ scheduleCollectionIfDue(state);
2045
+ return this.globals(state, inserted);
2046
+ }
2047
+ remove(ids) {
2048
+ registry.writes++;
2049
+ for (const { state, locals } of this.groups(ids)) {
2050
+ if (!state.raw.removeNodes) {
2051
+ this.call(state, "remove", { ids: locals });
2052
+ continue;
2053
+ }
2054
+ invalidate(state);
2055
+ state.raw.removeNodes(locals);
2056
+ if (state.hasChildLists) refreshChildLists(state);
2057
+ scheduleCollectionIfDue(state);
2058
+ }
2059
+ }
2060
+ op(command, json) {
2061
+ return JSON.stringify(this.operate(command, JSON.parse(json)) ?? null);
2062
+ }
2063
+ operate(command, args) {
2064
+ const options = args.options ?? this.options;
2065
+ const hasValue = Object.hasOwn(args, "value");
2066
+ if (command === "node") {
2067
+ const state = this.owner(args.id);
2068
+ return globalRecord(state, recordAt(state, args.id - state.base));
2069
+ }
2070
+ if (command === "createNode") return this.state.base + this.call(this.state, command, args);
2071
+ if (command === "import") return this.globals(this.state, this.call(this.state, command, args));
2072
+ if (command === "create") {
2073
+ const context = args.contextId == null ? void 0 : this.owner(args.contextId);
2074
+ const state = context ?? this.state;
2075
+ const contextLocal = context ? args.contextId - context.base : void 0;
2076
+ if (hasParserHooks(options)) {
2077
+ const contextRecord = context ? recordAt(context, contextLocal) : void 0;
2078
+ const children = parsedChildren(args.html, {
2079
+ ...options,
2080
+ ...contextRecord ? {
2081
+ __contextName: contextRecord.name,
2082
+ __contextNamespace: contextRecord.namespace
2083
+ } : {}
2084
+ });
2085
+ return this.globals(state, this.moveInto(state, children));
2086
+ }
2087
+ return this.globals(state, this.call(state, command, {
2088
+ ...args,
2089
+ contextId: contextLocal
2090
+ }));
2091
+ }
2092
+ if (command === "setNode" || command === "prop" && hasValue && (args.name === "children" || args.name === "childNodes" || pointerFields.has(args.name))) {
2093
+ const field = command === "setNode" ? args.field : args.name;
2094
+ let result = null;
2095
+ for (const id of command === "setNode" ? [args.id] : args.ids ?? []) {
2096
+ let state = this.owner(id);
2097
+ let nodeId = id;
2098
+ let value = args.value;
2099
+ if (field === "children" || field === "childNodes") value = this.moveInto(state, value ?? []);
2100
+ else if (pointerFields.has(field) && value != null) {
2101
+ const pointer = this.owner(value);
2102
+ if (pointer !== state) {
2103
+ const moved = [id];
2104
+ this.moveInto(pointer, moved);
2105
+ nodeId = moved[0];
2106
+ state = pointer;
2107
+ }
2108
+ value = args.value - pointer.base;
2109
+ }
2110
+ const local = nodeId - state.base;
2111
+ result = this.call(state, command, command === "setNode" ? {
2112
+ ...args,
2113
+ id: local,
2114
+ value
2115
+ } : {
2116
+ ...args,
2117
+ ids: [local],
2118
+ value
2119
+ });
2120
+ }
2121
+ return result;
2122
+ }
2123
+ if (command === "setAttrs") {
2124
+ const groups = this.groups((args.writes ?? []).map((write) => write.id));
2125
+ for (const group of groups) {
2126
+ const byId = /* @__PURE__ */ new Map();
2127
+ for (const write of args.writes ?? []) {
2128
+ const state = this.owner(write.id);
2129
+ if (state !== group.state) continue;
2130
+ const local = write.id - state.base;
2131
+ const list = byId.get(local) ?? [];
2132
+ list.push({
2133
+ name: write.name,
2134
+ value: write.value
2135
+ });
2136
+ byId.set(local, list);
2137
+ }
2138
+ const writes = [...byId.entries()].map(([id, attrs]) => ({
2139
+ id,
2140
+ attrs
2141
+ }));
2142
+ this.call(group.state, command, {
2143
+ ids: [...byId.keys()],
2144
+ writes
2145
+ });
2146
+ }
2147
+ return null;
2148
+ }
2149
+ if (command === "insert") {
2150
+ const targets = args.targetIds ?? [];
2151
+ const nodes = args.nodeIds ?? [];
2152
+ const sameDocument = targets.length > 0 && this.groups([...targets, ...nodes]);
2153
+ if (sameDocument && sameDocument.length === 1) {
2154
+ const { state } = sameDocument[0];
2155
+ const inserted = this.call(state, command, {
2156
+ ...args,
2157
+ targetIds: targets.map((id) => id - state.base),
2158
+ nodeIds: nodes.map((id) => id - state.base)
2159
+ });
2160
+ return this.globals(state, inserted);
2161
+ }
2162
+ const result = [];
2163
+ const isBesideTarget = args.position === "before" || args.position === "after";
2164
+ for (let index = 0; index < targets.length; index++) {
2165
+ const target = this.owner(targets[index]);
2166
+ const targetLocal = targets[index] - target.base;
2167
+ const record = recordAt(target, targetLocal);
2168
+ if (!record || !parentTypes.has(record.type) || isBesideTarget && record.parent == null) continue;
2169
+ const local = this.moveInto(target, nodes, index + 1 < targets.length);
2170
+ const inserted = this.call(target, command, {
2171
+ ...args,
2172
+ targetIds: [targetLocal],
2173
+ nodeIds: local
2174
+ });
2175
+ result.push(...this.globals(target, inserted));
2176
+ }
2177
+ return result;
2178
+ }
2179
+ if (command === "html" && hasValue && hasParserHooks(options)) {
2180
+ let result = null;
2181
+ for (const id of args.ids ?? []) {
2182
+ const state = this.owner(id);
2183
+ const local = id - state.base;
2184
+ const record = recordAt(state, local);
2185
+ if (!record || !parentTypes.has(record.type)) continue;
2186
+ const children = parsedChildren(String(args.value), {
2187
+ ...options,
2188
+ __contextName: record.name,
2189
+ __contextNamespace: record.namespace
2190
+ });
2191
+ result = this.call(state, "setNode", {
2192
+ id: local,
2193
+ field: "children",
2194
+ value: this.moveInto(state, children),
2195
+ options
2196
+ });
2197
+ }
2198
+ return result;
2199
+ }
2200
+ if (command === "contains") {
2201
+ const container = args.container ?? args.parent;
2202
+ const contained = args.contained ?? args.child;
2203
+ const parent = this.owner(container);
2204
+ return contained >= parent.base && contained < parent.base + STRIDE && this.call(parent, command, {
2205
+ container: container - parent.base,
2206
+ contained: contained - parent.base
2207
+ });
2208
+ }
2209
+ const ids = command === "select" ? args.contexts ?? [this.rootId()] : args.ids ?? [];
2210
+ const groups = this.groups(ids);
2211
+ if (command === "uniqueSort" && ids.length === 2 && groups.length === 2 && groups[0].state !== groups[1].state) return ids.slice();
2212
+ if (command === "matches" && this.isMixed(groups) && !options.pseudos && !args.pseudoMatches && (args.selector === ":first" || args.selector === ":last")) {
2213
+ const ordered = args.selector === ":first" ? groups : [...groups].reverse();
2214
+ for (const group of ordered) {
2215
+ const matches = this.call(group.state, "matches", {
2216
+ selector: "*",
2217
+ ids: group.locals,
2218
+ options
2219
+ });
2220
+ if (matches.length) return [group.state.base + (args.selector === ":first" ? matches[0] : matches[matches.length - 1])];
2221
+ }
2222
+ return [];
2223
+ }
2224
+ if (this.isMixed(groups) && scratchCommands.has(command)) return this.scratch(command, {
2225
+ ...args,
2226
+ options
2227
+ }, ids) ?? null;
2228
+ if (command === "extractPlan") {
2229
+ const group = groups[0];
2230
+ return this.call(group?.state ?? this.state, command, {
2231
+ ...args,
2232
+ options,
2233
+ ids: group?.locals ?? []
2234
+ }) ?? null;
2235
+ }
2236
+ if (idResultCommands.has(command)) {
2237
+ const isSelect = command === "select";
2238
+ if (!groups.length && (isSelect || command === "matches")) return this.call(this.state, command, {
2239
+ ...args,
2240
+ options,
2241
+ ids: [],
2242
+ ...isSelect ? { contexts: [] } : {}
2243
+ });
2244
+ const result = [];
2245
+ for (const group of groups) {
2246
+ const pseudoMatches = args.pseudoMatches ? Object.fromEntries(Object.entries(args.pseudoMatches).map(([key, values]) => [key, values.filter((id) => id >= group.state.base && id < group.state.base + STRIDE).map((id) => id - group.state.base)])) : void 0;
2247
+ const values = this.call(group.state, command, {
2248
+ ...args,
2249
+ options,
2250
+ ids: group.locals,
2251
+ ...isSelect ? { contexts: group.locals } : {},
2252
+ ...pseudoMatches ? { pseudoMatches } : {}
2253
+ });
2254
+ result.push(...this.globals(group.state, values));
2255
+ }
2256
+ return result;
2257
+ }
2258
+ if (command === "render" && !hasValue) {
2259
+ const optionsJson = JSON.stringify(options);
2260
+ return groups.map((group) => group.state.raw.render ? group.state.raw.render(group.locals, optionsJson) : this.call(group.state, command, {
2261
+ ...args,
2262
+ options,
2263
+ ids: group.locals
2264
+ })).join("");
2265
+ }
2266
+ if ((command === "outerHtml" || command === "text") && !hasValue) return groups.map((group) => this.call(group.state, command, {
2267
+ ...args,
2268
+ options,
2269
+ ids: group.locals
2270
+ })).join("");
2271
+ if (command === "hasClass") return groups.some((group) => this.call(group.state, command, {
2272
+ ...args,
2273
+ options,
2274
+ ids: group.locals
2275
+ }));
2276
+ if (command === "serializeArray" || command === "serialize") return groups.length ? this.call(groups[0].state, command, {
2277
+ ...args,
2278
+ options,
2279
+ ids: groups[0].locals
2280
+ }) : command === "serializeArray" ? [] : "";
2281
+ if (command === "html") for (const group of groups) invalidate(group.state);
2282
+ const isWrite = hasValue || writeCommands.has(command);
2283
+ let result = null;
2284
+ for (const group of isWrite ? groups : groups.slice(0, 1)) result = this.call(group.state, command, {
2285
+ ...args,
2286
+ options,
2287
+ ids: group.locals
2288
+ });
2289
+ return result ?? null;
2290
+ }
2291
+ };
2292
+ /** Parses `html` into a document of its own, whose children the caller then moves. */
2293
+ function parsedChildren(html, options) {
2294
+ const parsed = parseNativeDocument(html, options, false);
2295
+ exposeState(parsed.state);
2296
+ return parsed.operate("node", { id: parsed.rootId() }).children;
2297
+ }
2298
+ function dataEntry(state, id) {
2299
+ const local = id - state.base;
2300
+ let entry = state.data.get(local);
2301
+ if (!entry) state.data.set(local, entry = {
2302
+ state,
2303
+ local
2304
+ });
2305
+ return entry;
2306
+ }
2307
+ /**
2308
+ * Moves the bookkeeping of adopted nodes to their new arena. Live owners'
2309
+ * id lists, node objects and data follow the nodes; `ids` is updated too.
2310
+ */
2311
+ function rehome(source, target, mapping, ids) {
2312
+ registry.writes++;
2313
+ invalidate(source);
2314
+ invalidate(target);
2315
+ exposeState(target);
2316
+ const moved = /* @__PURE__ */ new Map();
2317
+ for (const [oldLocal, newLocal] of mapping) {
2318
+ moved.set(source.base + oldLocal, target.base + newLocal);
2319
+ const node = uncacheView(source, oldLocal);
2320
+ if (node) {
2321
+ node[VIEW_STATE] = target;
2322
+ node[VIEW_LOCAL] = newLocal;
2323
+ cacheView(target, newLocal, node);
2324
+ if (node[VIEW_CHILD_TARGET]) target.hasChildLists = true;
2325
+ }
2326
+ const entry = source.data.get(oldLocal);
2327
+ if (entry) {
2328
+ source.data.delete(oldLocal);
2329
+ entry.state = target;
2330
+ entry.local = newLocal;
2331
+ target.data.set(newLocal, entry);
2332
+ }
2333
+ const adapterNode = source.adapterNodes?.[oldLocal];
2334
+ if (adapterNode) {
2335
+ source.adapterNodes[oldLocal] = void 0;
2336
+ (target.adapterNodes ??= [])[newLocal] = adapterNode;
2337
+ adapterNode[VIEW_STATE] = target;
2338
+ adapterNode[VIEW_LOCAL] = newLocal;
2339
+ }
2340
+ }
2341
+ const rewrite = (list) => {
2342
+ let isTouched = false;
2343
+ for (let index = 0; index < list.length; index++) {
2344
+ const next = moved.get(list[index]);
2345
+ if (next !== void 0) {
2346
+ list[index] = next;
2347
+ isTouched = true;
2348
+ }
2349
+ }
2350
+ return isTouched;
2351
+ };
2352
+ for (const lease of [...source.leases]) {
2353
+ if (!rewrite(lease.ids)) continue;
2354
+ target.leases.add(lease);
2355
+ if (!lease.states.includes(target)) lease.states.push(target);
2356
+ if (!lease.ids.some((id) => id >= source.base && id < source.base + STRIDE)) {
2357
+ source.leases.delete(lease);
2358
+ lease.states = lease.states.filter((state) => state !== source);
2359
+ }
2360
+ }
2361
+ rewrite(ids);
2362
+ }
2363
+ /** Keeps attribute objects that callers hold in step with native writes. */
2364
+ function refreshWrittenAttributes(state, command, args) {
2365
+ if (!hasViews(state)) return;
2366
+ let locals;
2367
+ if (command === "setAttrs") locals = (args.writes ?? []).map((write) => write.id);
2368
+ else if (targetedAttributeWrites.has(command)) locals = args.ids ?? [];
2369
+ else if (command === "setNode") {
2370
+ if (!attributeFields.has(args.field)) return;
2371
+ locals = [args.id];
2372
+ } else if (structuralWrites.has(command)) return;
2373
+ const refresh = (view) => {
2374
+ if (view && view[VIEW_ATTRIBUTES]) attributeRefresher?.(view);
2375
+ };
2376
+ if (locals) for (const local of locals) refresh(cachedView(state, local));
2377
+ else forEachView(state, refresh);
2378
+ }
2379
+ let attributeRefresher;
2380
+ let childRefresher;
2381
+ /** Registers how node objects re-read their attributes and children after a native write. */
2382
+ function onViewRefresh(attributes, children) {
2383
+ attributeRefresher = attributes;
2384
+ childRefresher = children;
2385
+ }
2386
+ /** Refills the child arrays of parents whose children a native write changed. */
2387
+ function refreshChildLists(state) {
2388
+ if (!state.hasChildLists || !childRefresher) return;
2389
+ const touched = state.raw.takeTouched?.();
2390
+ if (touched === void 0) return;
2391
+ if (touched === null) {
2392
+ forEachView(state, childRefresher);
2393
+ return;
2394
+ }
2395
+ for (const local of touched) {
2396
+ const view = cachedView(state, local);
2397
+ if (view) childRefresher(view);
2398
+ }
2399
+ }
2400
+ function routeDocument(document, options = {}) {
2401
+ return document.nodeSpace === registry.space ? document : new RoutedDocument(document, options);
2402
+ }
2403
+ /** The unanchored routed document node objects of `state` use. */
2404
+ function routedFor(state) {
2405
+ return state.routed ??= new RoutedDocument(state.raw, state.options);
2406
+ }
2407
+ function sameNodeSpace(first, second) {
2408
+ return first === second || !!first.nodeSpace && first.nodeSpace === second.nodeSpace;
2409
+ }
2410
+ /** Whether ids of `state` belong to this copy of the package; nodes of another copy are foreign objects here. */
2411
+ function isLocalState(state) {
2412
+ return state.space === registry.space;
2413
+ }
2414
+ /** Whether `document` routes ids through this registry. */
2415
+ function isRouted(document) {
2416
+ return document.nodeSpace === registry.space;
2417
+ }
2418
+ // src/dom.ts
2419
+ const ElementType = Object.freeze({
2420
+ Root: "root",
2421
+ Text: "text",
2422
+ Directive: "directive",
2423
+ Comment: "comment",
2424
+ Script: "script",
2425
+ Style: "style",
2426
+ Tag: "tag",
2427
+ CDATA: "cdata",
2428
+ Doctype: "doctype"
2429
+ });
2430
+ function initialize(node, type, fields, children = []) {
2431
+ const document = routeDocument(new (requireNative()).NativeDocument("", false));
2432
+ const id = operation(document, "createNode", {
2433
+ type,
2434
+ ...fields
2435
+ });
2436
+ if (children.length) operation(document, "setNode", {
2437
+ id,
2438
+ field: "children",
2439
+ value: importNodes(document, children)
2440
+ });
2441
+ return getNode(document, id, node);
2442
+ }
2443
+ /** DOM constructors backed by native storage, also shared across ESM/CJS views. */
2444
+ var Node = class {
2445
+ static [Symbol.hasInstance](value) {
2446
+ if (!nodeBinding(value)) return Function.prototype[Symbol.hasInstance].call(this, value);
2447
+ const type = value.type;
2448
+ switch (this.name) {
2449
+ case "Node": return true;
2450
+ case "DataNode": return [
2451
+ "text",
2452
+ "comment",
2453
+ "directive"
2454
+ ].includes(type);
2455
+ case "NodeWithChildren": return [
2456
+ "root",
2457
+ "tag",
2458
+ "script",
2459
+ "style",
2460
+ "cdata"
2461
+ ].includes(type);
2462
+ case "Element": return [
2463
+ "tag",
2464
+ "script",
2465
+ "style"
2466
+ ].includes(type);
2467
+ case "Document": return type === "root";
2468
+ case "CDATA": return type === "cdata";
2469
+ case "Text": return type === "text";
2470
+ case "Comment": return type === "comment";
2471
+ case "ProcessingInstruction": return type === "directive";
2472
+ default: return Function.prototype[Symbol.hasInstance].call(this, value);
2473
+ }
2474
+ }
2475
+ };
2476
+ var DataNode = class extends Node {};
2477
+ var NodeWithChildren = class extends Node {};
2478
+ var Text = class extends DataNode {
2479
+ constructor(data) {
2480
+ super();
2481
+ return initialize(this, "text", { data });
2482
+ }
2483
+ };
2484
+ var Comment = class extends DataNode {
2485
+ constructor(data) {
2486
+ super();
2487
+ return initialize(this, "comment", { data });
2488
+ }
2489
+ };
2490
+ var ProcessingInstruction = class extends DataNode {
2491
+ constructor(name, data) {
2492
+ super();
2493
+ return initialize(this, "directive", {
2494
+ name,
2495
+ data
2496
+ });
2497
+ }
2498
+ };
2499
+ var Document = class extends NodeWithChildren {
2500
+ constructor(children) {
2501
+ super();
2502
+ return initialize(this, "root", {}, children);
2503
+ }
2504
+ };
2505
+ var CDATA = class extends NodeWithChildren {
2506
+ constructor(children) {
2507
+ super();
2508
+ return initialize(this, "cdata", {}, children);
2509
+ }
2510
+ };
2511
+ var Element = class extends NodeWithChildren {
2512
+ constructor(name, attribs, children = [], type) {
2513
+ super();
2514
+ return initialize(this, type ?? (name === "script" || name === "style" ? name : "tag"), {
2515
+ name,
2516
+ attribs
2517
+ }, children);
2518
+ }
2519
+ };
2520
+ /** @internal */
2521
+ function nodePrototype(type) {
2522
+ return ({
2523
+ root: Document,
2524
+ text: Text,
2525
+ comment: Comment,
2526
+ directive: ProcessingInstruction,
2527
+ cdata: CDATA,
2528
+ tag: Element,
2529
+ script: Element,
2530
+ style: Element
2531
+ }[type] ?? Node).prototype;
2532
+ }
2533
+ const isTag = (node) => [
2534
+ "tag",
2535
+ "script",
2536
+ "style"
2537
+ ].includes(node.type);
2538
+ const isText = (node) => node.type === "text";
2539
+ const isComment = (node) => node.type === "comment";
2540
+ const isDirective = (node) => node.type === "directive";
2541
+ const isDocument = (node) => node.type === "root";
2542
+ const isCDATA = (node) => node.type === "cdata";
2543
+ const hasChildren = (node) => "children" in node;
2544
+ Object.defineProperties(Node.prototype, {
2545
+ cloneNode: {
2546
+ configurable: true,
2547
+ writable: true,
2548
+ value: cloneNode
2549
+ },
2550
+ parentNode: {
2551
+ configurable: true,
2552
+ get() {
2553
+ return this.parent;
2554
+ },
2555
+ set(value) {
2556
+ this.parent = value;
2557
+ }
2558
+ },
2559
+ previousSibling: {
2560
+ configurable: true,
2561
+ get() {
2562
+ return this.prev;
2563
+ },
2564
+ set(value) {
2565
+ this.prev = value;
2566
+ }
2567
+ },
2568
+ nextSibling: {
2569
+ configurable: true,
2570
+ get() {
2571
+ return this.next;
2572
+ },
2573
+ set(value) {
2574
+ this.next = value;
2575
+ }
2576
+ },
2577
+ nodeType: {
2578
+ configurable: true,
2579
+ get() {
2580
+ return {
2581
+ root: 9,
2582
+ text: 3,
2583
+ comment: 8,
2584
+ cdata: 4
2585
+ }[this.type] ?? 1;
2586
+ }
2587
+ }
2588
+ });
2589
+ Object.defineProperty(DataNode.prototype, "nodeValue", {
2590
+ configurable: true,
2591
+ get() {
2592
+ return this.data;
2593
+ },
2594
+ set(value) {
2595
+ this.data = value;
2596
+ }
2597
+ });
2598
+ Object.defineProperties(NodeWithChildren.prototype, {
2599
+ childNodes: {
2600
+ configurable: true,
2601
+ get() {
2602
+ return this.children;
2603
+ },
2604
+ set(value) {
2605
+ this.children = value;
2606
+ }
2607
+ },
2608
+ firstChild: {
2609
+ configurable: true,
2610
+ get() {
2611
+ return this.children[0] ?? null;
2612
+ }
2613
+ },
2614
+ lastChild: {
2615
+ configurable: true,
2616
+ get() {
2617
+ return this.children[this.children.length - 1] ?? null;
2618
+ }
2619
+ }
2620
+ });
2621
+ Object.defineProperties(Element.prototype, {
2622
+ tagName: {
2623
+ configurable: true,
2624
+ get() {
2625
+ return this.name;
2626
+ },
2627
+ set(value) {
2628
+ this.name = value;
2629
+ }
2630
+ },
2631
+ attributes: {
2632
+ configurable: true,
2633
+ get() {
2634
+ return Object.keys(this.attribs).map((name) => ({
2635
+ name,
2636
+ value: this.attribs[name],
2637
+ namespace: this["x-attribsNamespace"]?.[name],
2638
+ prefix: this["x-attribsPrefix"]?.[name]
2639
+ }));
2640
+ }
2641
+ }
2642
+ });
2643
+ // src/nodes.ts
2644
+ const VIEW_CHILDREN = Symbol.for("cheerox.node.children");
2645
+ const emptyRecord = Object.freeze({
2646
+ id: -1,
2647
+ type: "released",
2648
+ children: []
2649
+ });
2650
+ function operation(document, command, args = {}) {
2651
+ const direct = document.operate;
2652
+ if (direct) return direct.call(document, command, args);
2653
+ const value = document.op(command, JSON.stringify(args));
2654
+ return value === void 0 || value === "" ? void 0 : JSON.parse(value);
2655
+ }
2656
+ /** The id of a native node object, without allocating a binding. */
2657
+ function viewId(node) {
2658
+ const view = node;
2659
+ const state = view?.[VIEW_STATE];
2660
+ return state !== void 0 && view[VIEW_SELF] === view && isLocalState(state) ? state.base + view[VIEW_LOCAL] : void 0;
2661
+ }
2662
+ /** Whether `node` is a node object of a native document, of this or another copy of the package. */
2663
+ function isNativeNode(node) {
2664
+ const view = node;
2665
+ return view?.[VIEW_STATE] !== void 0 && view[VIEW_SELF] === view;
2666
+ }
2667
+ /** The id of a native node object, made resolvable by `document`'s operations. */
2668
+ function viewIdIn(document, node) {
2669
+ const id = viewId(node);
2670
+ if (id !== void 0) exposeTo(document, node[VIEW_STATE]);
2671
+ return id;
2672
+ }
2673
+ function nodeBinding(node) {
2674
+ const id = node && typeof node === "object" ? viewId(node) : void 0;
2675
+ return id === void 0 ? void 0 : {
2676
+ document: routedFor(node[VIEW_STATE]),
2677
+ id
2678
+ };
2679
+ }
2680
+ function hasMaterializedChildren(node) {
2681
+ return !!node?.[VIEW_CHILD_TARGET];
2682
+ }
2683
+ function hasMaterializedAttributes(node) {
2684
+ return !!node?.[VIEW_ATTRIBUTES];
2685
+ }
2686
+ function nodeId(node, document) {
2687
+ const id = node && typeof node === "object" ? viewId(node) : void 0;
2688
+ return id !== void 0 && (!document || isRouted(document)) ? id : void 0;
2689
+ }
2690
+ /** Recreate parse5's null-prototype attribute maps and shared start-tag map. */
2691
+ function hydrateLocation(location) {
2692
+ if (!location || typeof location !== "object") return location;
2693
+ const value = location;
2694
+ if (value.attrs && typeof value.attrs === "object") Object.setPrototypeOf(value.attrs, null);
2695
+ if (value.startTag?.attrs && typeof value.startTag.attrs === "object") {
2696
+ Object.setPrototypeOf(value.startTag.attrs, null);
2697
+ if (value.attrs && JSON.stringify(value.attrs) === JSON.stringify(value.startTag.attrs)) value.startTag.attrs = value.attrs;
2698
+ }
2699
+ return location;
2700
+ }
2701
+ /** The node's record; its links are ids local to the node's document. */
2702
+ function nodeRecord(document, id) {
2703
+ if (!isRouted(document)) return operation(document, "node", { id });
2704
+ const state = stateIn(document, id);
2705
+ return recordAt(state, id - state.base);
2706
+ }
2707
+ const isElementType = (type) => type === "tag" || type === "script" || type === "style";
2708
+ /** Mirrors the native `traverse` operation over cached records; `undefined` defers to it. */
2709
+ function traverseRecords(document, ids, kind) {
2710
+ if (!isRouted(document)) return void 0;
2711
+ const result = [];
2712
+ for (const id of ids) {
2713
+ const state = stateIn(document, id);
2714
+ const { base } = state;
2715
+ const snapshot = state.bulk instanceof NodeSnapshot ? state.bulk : void 0;
2716
+ if (snapshot?.isPresent(id - base) && traverseSnapshot(snapshot, base, id - base, kind, result)) continue;
2717
+ const node = recordAt(state, id - base);
2718
+ if (!node) continue;
2719
+ const isElement = (local) => isElementType(recordAt(state, local)?.type);
2720
+ if (kind === "children") {
2721
+ for (const child of node.children ?? []) if (isElement(child)) result.push(base + child);
2722
+ } else if (kind === "contents") for (const child of node.children ?? []) result.push(base + child);
2723
+ else if (kind === "parent") {
2724
+ if (node.parent != null && isElement(node.parent)) result.push(base + node.parent);
2725
+ } else if (kind === "parents" || kind === "ancestors") {
2726
+ const seen = /* @__PURE__ */ new Set();
2727
+ for (let parent = node.parent; parent != null && !seen.has(parent);) {
2728
+ seen.add(parent);
2729
+ const ancestor = recordAt(state, parent);
2730
+ if (!ancestor || ancestor.type === "root") break;
2731
+ if (isElementType(ancestor.type)) result.push(base + parent);
2732
+ parent = ancestor.parent;
2733
+ }
2734
+ } else if (kind === "next" || kind === "prev" || kind === "nextAll" || kind === "prevAll") {
2735
+ const isForward = kind === "next" || kind === "nextAll";
2736
+ const isSingle = kind === "next" || kind === "prev";
2737
+ const seen = /* @__PURE__ */ new Set();
2738
+ for (let sibling = isForward ? node.next : node.prev; sibling != null && !seen.has(sibling);) {
2739
+ seen.add(sibling);
2740
+ const record = recordAt(state, sibling);
2741
+ if (!record) break;
2742
+ if (isElementType(record.type)) {
2743
+ result.push(base + sibling);
2744
+ if (isSingle) break;
2745
+ }
2746
+ sibling = isForward ? record.next : record.prev;
2747
+ }
2748
+ } else if (kind === "siblings") {
2749
+ const parent = node.parent == null ? null : recordAt(state, node.parent);
2750
+ const local = id - base;
2751
+ for (const other of parent?.children ?? []) if (other !== local && isElement(other)) result.push(base + other);
2752
+ } else return void 0;
2753
+ }
2754
+ return result;
2755
+ }
2756
+ /** `traverseRecords` for one node of a current snapshot; false for kinds it leaves to records. */
2757
+ function traverseSnapshot(snapshot, base, local, kind, result) {
2758
+ const pushChildren = (parent, isElementsOnly, except) => {
2759
+ const count = snapshot.childCount(parent);
2760
+ for (let index = 0; index < count; index++) {
2761
+ const child = snapshot.childAt(parent, index);
2762
+ if (child !== except && (!isElementsOnly || snapshot.isElementAt(child))) result.push(base + child);
2763
+ }
2764
+ };
2765
+ switch (kind) {
2766
+ case "children":
2767
+ pushChildren(local, true, -1);
2768
+ return true;
2769
+ case "contents":
2770
+ pushChildren(local, false, -1);
2771
+ return true;
2772
+ case "siblings": {
2773
+ const parent = snapshot.linkOf(local, 1);
2774
+ if (parent !== null && snapshot.isPresent(parent)) pushChildren(parent, true, local);
2775
+ return true;
2776
+ }
2777
+ case "parent": {
2778
+ const parent = snapshot.linkOf(local, 1);
2779
+ if (parent !== null && snapshot.isPresent(parent) && snapshot.isElementAt(parent)) result.push(base + parent);
2780
+ return true;
2781
+ }
2782
+ case "parents":
2783
+ case "ancestors": {
2784
+ let parent = snapshot.linkOf(local, 1);
2785
+ for (let steps = 0; parent !== null && steps < snapshot.size && snapshot.isPresent(parent) && !snapshot.isRootAt(parent); steps++) {
2786
+ if (snapshot.isElementAt(parent)) result.push(base + parent);
2787
+ parent = snapshot.linkOf(parent, 1);
2788
+ }
2789
+ return true;
2790
+ }
2791
+ case "next":
2792
+ case "prev":
2793
+ case "nextAll":
2794
+ case "prevAll": {
2795
+ const offset = kind === "next" || kind === "nextAll" ? 3 : 2;
2796
+ const isSingle = kind === "next" || kind === "prev";
2797
+ let sibling = snapshot.linkOf(local, offset);
2798
+ for (let steps = 0; sibling !== null && steps < snapshot.size && snapshot.isPresent(sibling); steps++) {
2799
+ if (snapshot.isElementAt(sibling)) {
2800
+ result.push(base + sibling);
2801
+ if (isSingle) break;
2802
+ }
2803
+ sibling = snapshot.linkOf(sibling, offset);
2804
+ }
2805
+ return true;
2806
+ }
2807
+ default: return false;
2808
+ }
2809
+ }
2810
+ /** The node object for an arena slot, created on first use and then shared. */
2811
+ function viewAt(state, local, knownType) {
2812
+ const existing = state.views[local] ?? cachedView(state, local);
2813
+ if (existing) {
2814
+ applyPendingRoot(state, local, existing);
2815
+ return existing;
2816
+ }
2817
+ const parsed = state.adapterNodes?.[local];
2818
+ if (parsed) {
2819
+ state.adapterNodes[local] = void 0;
2820
+ const view = adoptObject(state, local, parsed);
2821
+ applyPendingRoot(state, local, view);
2822
+ return view;
2823
+ }
2824
+ const snapshot = knownType ? void 0 : structureSnapshot(state, local);
2825
+ let constructor;
2826
+ if (knownType && !state.options.sourceCodeLocationInfo) constructor = viewConstructor(state, knownType, false);
2827
+ else if (snapshot && !snapshot.hasExtraFields(local)) constructor = viewConstructor(state, snapshot.typeOf(local), false);
2828
+ else {
2829
+ const record = recordAt(state, local);
2830
+ if (!record) return void 0;
2831
+ constructor = viewConstructor(state, record.type, record.sourceCodeLocation !== void 0);
2832
+ }
2833
+ const view = constructor(state, local);
2834
+ cacheView(state, local, view);
2835
+ applyPendingRoot(state, local, view);
2836
+ return view;
2837
+ }
2838
+ /** A document root's node object, built without reading its record: its type is known. */
2839
+ function rootNode(document, id) {
2840
+ if (!isRouted(document)) throw new TypeError("Native nodes require a routed document");
2841
+ const state = stateIn(document, id);
2842
+ const local = id - state.base;
2843
+ const existing = cachedView(state, local);
2844
+ if (existing) {
2845
+ applyPendingRoot(state, local, existing);
2846
+ return existing;
2847
+ }
2848
+ if (state.adapterNodes?.[local] || state.options.sourceCodeLocationInfo) return viewAt(state, local);
2849
+ const view = viewConstructor(state, "root", false)(state, local);
2850
+ cacheView(state, local, view);
2851
+ applyPendingRoot(state, local, view);
2852
+ return view;
2853
+ }
2854
+ /** Stable DOM node identities; each property reads or updates the Rust arena. */
2855
+ function getNode(document, id, original, knownType) {
2856
+ if (!isRouted(document)) throw new TypeError("Native nodes require a routed document");
2857
+ const state = stateIn(document, id);
2858
+ const local = id - state.base;
2859
+ if (original === void 0) return viewAt(state, local, knownType);
2860
+ const view = adoptObject(state, local, original);
2861
+ applyPendingRoot(state, local, view);
2862
+ return view;
2863
+ }
2864
+ function getNodesOfType(document, ids, type) {
2865
+ if (!ids.length) return [];
2866
+ const state = stateIn(document, ids[0]);
2867
+ if (state.options.sourceCodeLocationInfo || state.adapterNodes) return ids.map((id) => getNode(document, id));
2868
+ const constructor = viewConstructor(state, type, false);
2869
+ const result = new Array(ids.length);
2870
+ for (let index = 0; index < ids.length; index++) {
2871
+ const id = ids[index];
2872
+ if (stateIn(document, id) !== state) {
2873
+ result[index] = getNode(document, id);
2874
+ continue;
2875
+ }
2876
+ const local = id - state.base;
2877
+ let view = state.views[local];
2878
+ if (!view && (local >= state.baseline || state.weakViews.size)) view = cachedView(state, local);
2879
+ if (!view) {
2880
+ view = constructor(state, local);
2881
+ cacheView(state, local, view);
2882
+ }
2883
+ if (state._pendingRoots) applyPendingRoot(state, local, view);
2884
+ result[index] = view;
2885
+ }
2886
+ return result;
2887
+ }
2888
+ function viewRecord(view) {
2889
+ const state = view[VIEW_STATE];
2890
+ const local = view[VIEW_LOCAL];
2891
+ return state.records[local] ?? recordAt(state, local) ?? emptyRecord;
2892
+ }
2893
+ function linkedView(view, local) {
2894
+ return local == null ? null : viewAt(view[VIEW_STATE], local) ?? null;
2895
+ }
2896
+ function setField(view, field, value) {
2897
+ const state = view[VIEW_STATE];
2898
+ operation(routedFor(state), "setNode", {
2899
+ id: state.base + view[VIEW_LOCAL],
2900
+ field,
2901
+ value
2902
+ });
2903
+ }
2904
+ function setPointer(view, field, value) {
2905
+ setField(view, field, value == null ? null : importNodes(routedFor(view[VIEW_STATE]), [value])[0]);
2906
+ }
2907
+ function attributesOf(view) {
2908
+ const state = view[VIEW_STATE];
2909
+ let attributes = view[VIEW_ATTRIBUTES];
2910
+ if (!attributes) view[VIEW_ATTRIBUTES] = attributes = createAttributes(view, state.options._useHtmlParser2 === false ? null : Object.prototype);
2911
+ const meta = attributes[ATTR_META];
2912
+ if (meta.generation !== state.generation || meta.state !== state) syncAttributes(view, attributes);
2913
+ return attributes;
2914
+ }
2915
+ /** Pushes a direct attribute write through to the node's native record (shared; no per-object closure). */
2916
+ function writeAttributeThrough(view, attributes, key, value) {
2917
+ const owner = view;
2918
+ setField(owner, "attribs", {
2919
+ ...viewRecord(owner).attribs,
2920
+ [key]: String(value)
2921
+ });
2922
+ attributes[ATTR_META].values[key] = String(value);
2923
+ }
2924
+ function createAttributes(view, prototype) {
2925
+ const attributes = Object.create(prototype);
2926
+ setAttributeMeta(attributes, {
2927
+ view,
2928
+ generation: -1,
2929
+ state: view[VIEW_STATE],
2930
+ values: {},
2931
+ write: writeAttributeThrough
2932
+ });
2933
+ return attributes;
2934
+ }
2935
+ /** Copies the record's attributes into the shared accessors, preserving key order. */
2936
+ function syncAttributes(view, attributes) {
2937
+ const meta = attributes[ATTR_META];
2938
+ const state = view[VIEW_STATE];
2939
+ const local = view[VIEW_LOCAL];
2940
+ if (meta.generation === -1) {
2941
+ const snapshot = plainSnapshot(state, local);
2942
+ if (snapshot) {
2943
+ snapshot.copyAttributes(local, attributes);
2944
+ meta.generation = state.generation;
2945
+ return;
2946
+ }
2947
+ }
2948
+ const values = viewRecord(view).attribs ?? {};
2949
+ const nextKeys = Object.keys(values);
2950
+ const currentKeys = Object.keys(attributes);
2951
+ let isSameOrder = currentKeys.length === nextKeys.length;
2952
+ for (let index = 0; isSameOrder && index < nextKeys.length; index++) isSameOrder = currentKeys[index] === nextKeys[index];
2953
+ const stored = meta.values;
2954
+ if (!isSameOrder) {
2955
+ for (const key of currentKeys) {
2956
+ delete attributes[key];
2957
+ delete stored[key];
2958
+ }
2959
+ for (const key of nextKeys) defineAttributeKey(attributes, key, values[key]);
2960
+ } else for (const key of nextKeys) {
2961
+ if (key === "__proto__") {
2962
+ defineAttributeKey(attributes, key, values[key]);
2963
+ continue;
2964
+ }
2965
+ if (stored[key] !== values[key]) stored[key] = values[key];
2966
+ }
2967
+ meta.generation = state.generation;
2968
+ meta.state = state;
2969
+ }
2970
+ /** Re-reads attributes for a node whose attributes a native command changed. */
2971
+ function refreshAttributes(view) {
2972
+ const attributes = view[VIEW_ATTRIBUTES];
2973
+ if (attributes) syncAttributes(view, attributes);
2974
+ }
2975
+ onViewRefresh(refreshAttributes, fillChildren);
2976
+ /** Namespace and prefix maps are rare; they read the record on every access. */
2977
+ function attributeMap(view, field) {
2978
+ const read = () => viewRecord(view)[field] ?? {};
2979
+ const target = Object.create(view[VIEW_STATE].options._useHtmlParser2 === false ? null : Object.prototype);
2980
+ const viewField = `x-${field}`;
2981
+ return new Proxy(target, {
2982
+ get(_target, key) {
2983
+ if (typeof key === "symbol") return Reflect.get(target, key);
2984
+ const values = read();
2985
+ return Object.hasOwn(values, key) ? values[key] : Reflect.get(target, key);
2986
+ },
2987
+ set(_target, key, value) {
2988
+ setField(view, viewField, {
2989
+ ...read(),
2990
+ [key]: String(value)
2991
+ });
2992
+ return true;
2993
+ },
2994
+ deleteProperty(_target, key) {
2995
+ const values = { ...read() };
2996
+ delete values[key];
2997
+ setField(view, viewField, values);
2998
+ return true;
2999
+ },
3000
+ ownKeys() {
3001
+ return Reflect.ownKeys(read());
3002
+ },
3003
+ has(_target, key) {
3004
+ return Object.hasOwn(read(), key) || key in target;
3005
+ },
3006
+ getOwnPropertyDescriptor(_target, key) {
3007
+ const values = read();
3008
+ return Object.hasOwn(values, key) ? {
3009
+ value: values[key],
3010
+ writable: true,
3011
+ enumerable: true,
3012
+ configurable: true
3013
+ } : void 0;
3014
+ },
3015
+ defineProperty(_target, key, descriptor) {
3016
+ setField(view, viewField, {
3017
+ ...read(),
3018
+ [key]: String(descriptor.value)
3019
+ });
3020
+ return true;
3021
+ }
3022
+ });
3023
+ }
3024
+ /**
3025
+ * A node's children: a real array of node objects, so reads cost what
3026
+ * Cheerio's do. Its mutating methods write the whole list to Rust once, and
3027
+ * the router refills the array in place whenever Rust reports the parent
3028
+ * changed. Assigning an index or `length` directly changes only this array.
3029
+ * `constructor` is `Array`, so arrays derived from it are plain.
3030
+ */
3031
+ var ChildArray = class ChildArray extends Array {
3032
+ #view;
3033
+ constructor(view) {
3034
+ super();
3035
+ this.#view = view;
3036
+ }
3037
+ static viewOf(list) {
3038
+ return list instanceof ChildArray ? list.#view : void 0;
3039
+ }
3040
+ };
3041
+ Object.defineProperty(ChildArray.prototype, "constructor", {
3042
+ configurable: true,
3043
+ writable: true,
3044
+ value: Array
3045
+ });
3046
+ for (const method of [
3047
+ "push",
3048
+ "pop",
3049
+ "shift",
3050
+ "unshift",
3051
+ "splice",
3052
+ "sort",
3053
+ "reverse",
3054
+ "copyWithin",
3055
+ "fill"
3056
+ ]) Object.defineProperty(ChildArray.prototype, method, {
3057
+ configurable: true,
3058
+ writable: true,
3059
+ value(...args) {
3060
+ const view = ChildArray.viewOf(this);
3061
+ if (!view) return Reflect.apply(Array.prototype[method], this, args);
3062
+ const values = Array.from(this);
3063
+ const result = Reflect.apply(Array.prototype[method], values, args);
3064
+ saveChildren(view, values);
3065
+ return result === values ? this : result;
3066
+ }
3067
+ });
3068
+ function saveChildren(view, values) {
3069
+ setField(view, "children", importNodes(routedFor(view[VIEW_STATE]), values));
3070
+ }
3071
+ function childList(view) {
3072
+ const existing = view[VIEW_CHILDREN];
3073
+ if (existing) return existing;
3074
+ const state = view[VIEW_STATE];
3075
+ if (state.baseline > 4096 && state.rootLocal !== void 0 && view[VIEW_LOCAL] === state.rootLocal + 1) prepareWalkSnapshot(state);
3076
+ if (!state.hasChildLists) {
3077
+ state.hasChildLists = true;
3078
+ state.raw.takeTouched?.();
3079
+ }
3080
+ const list = new ChildArray(view);
3081
+ view[VIEW_CHILD_TARGET] = list;
3082
+ view[VIEW_CHILDREN] = list;
3083
+ fillChildren(view);
3084
+ return list;
3085
+ }
3086
+ /** Rebuilds a materialized child array from the node's current record. */
3087
+ function fillChildren(view) {
3088
+ const target = view[VIEW_CHILD_TARGET];
3089
+ if (!target) return;
3090
+ const state = view[VIEW_STATE];
3091
+ const local = view[VIEW_LOCAL];
3092
+ const snapshot = structureSnapshot(state, local);
3093
+ if (snapshot && state.stale.size === 0) {
3094
+ fillFromSnapshot(state, snapshot, local, target);
3095
+ return;
3096
+ }
3097
+ const locals = viewRecord(view).children ?? [];
3098
+ for (let index = 0; index < locals.length; index++) target[index] = viewAt(state, locals[index]);
3099
+ truncate(target, locals.length);
3100
+ }
3101
+ /**
3102
+ * Children are written in order and the length is trimmed afterwards:
3103
+ * presetting the length of a fresh array makes it holey and costs more than
3104
+ * filling it.
3105
+ */
3106
+ function truncate(target, length) {
3107
+ if (target.length !== length) target.length = length;
3108
+ }
3109
+ /**
3110
+ * The common case of a walk: a node's children read straight from the
3111
+ * snapshot arrays and cached strongly, with each type's constructor resolved
3112
+ * once per snapshot instead of once per node.
3113
+ */
3114
+ function fillFromSnapshot(state, snapshot, local, target) {
3115
+ const count = snapshot.childCount(local);
3116
+ const first = snapshot.childStart(local);
3117
+ const childIds = snapshot.childIds;
3118
+ const views = state.views;
3119
+ const isStrong = !state.adapterNodes;
3120
+ const hasWeakViews = state.weakViews.size > 0;
3121
+ const hasPendingRoots = !!state._pendingRoots;
3122
+ const constructors = snapshotConstructors(state, snapshot);
3123
+ for (let index = 0; index < count; index++) {
3124
+ const child = childIds[first + index];
3125
+ let node = views[child] ?? (hasWeakViews ? cachedView(state, child) : void 0);
3126
+ if (node === void 0) {
3127
+ const constructor = isStrong && child < state.baseline && snapshot.isPlain(child) ? constructors(snapshot.typeReference(child)) : void 0;
3128
+ if (constructor) views[child] = node = constructor(state, child);
3129
+ else node = viewAt(state, child);
3130
+ }
3131
+ if (hasPendingRoots) applyPendingRoot(state, child, node);
3132
+ target[index] = node;
3133
+ }
3134
+ truncate(target, count);
3135
+ }
3136
+ function snapshotConstructors(state, snapshot) {
3137
+ let lookup = snapshot.viewConstructors;
3138
+ if (!lookup) {
3139
+ const byReference = [];
3140
+ lookup = (reference) => byReference[reference] ??= viewConstructor(state, snapshot.name(reference), false);
3141
+ snapshot.viewConstructors = lookup;
3142
+ }
3143
+ return lookup;
3144
+ }
3145
+ const recordField = (field, fallback) => ({
3146
+ get() {
3147
+ return viewRecord(this)[field] ?? fallback;
3148
+ },
3149
+ set(value) {
3150
+ setField(this, field, value);
3151
+ }
3152
+ });
3153
+ /** Fields read straight from the snapshot when it holds the node, without building a record. */
3154
+ const snapshotField = (field) => ({
3155
+ get() {
3156
+ const state = this[VIEW_STATE];
3157
+ const local = this[VIEW_LOCAL];
3158
+ const snapshot = field === "data" ? plainSnapshot(state, local) : structureSnapshot(state, local);
3159
+ if (snapshot) return field === "type" ? snapshot.typeOf(local) : field === "name" ? snapshot.nameOf(local) : snapshot.dataOf(local);
3160
+ return viewRecord(this)[field];
3161
+ },
3162
+ set(value) {
3163
+ setField(this, field, value);
3164
+ }
3165
+ });
3166
+ const linkOffsets = {
3167
+ parent: 1,
3168
+ prev: 2,
3169
+ next: 3
3170
+ };
3171
+ const pointerField = (field) => ({
3172
+ get() {
3173
+ const state = this[VIEW_STATE];
3174
+ const local = this[VIEW_LOCAL];
3175
+ const snapshot = structureSnapshot(state, local);
3176
+ return linkedView(this, snapshot ? snapshot.linkOf(local, linkOffsets[field]) : viewRecord(this)[field]);
3177
+ },
3178
+ set(value) {
3179
+ setPointer(this, field, value);
3180
+ }
3181
+ });
3182
+ const nodeAccessors = {
3183
+ type: snapshotField("type"),
3184
+ parent: pointerField("parent"),
3185
+ prev: pointerField("prev"),
3186
+ next: pointerField("next"),
3187
+ startIndex: recordField("startIndex", null),
3188
+ endIndex: recordField("endIndex", null)
3189
+ };
3190
+ /** Present only on nodes parsed with location info, as in Cheerio. */
3191
+ const locationAccessor = {
3192
+ get() {
3193
+ return hydrateLocation(viewRecord(this).sourceCodeLocation);
3194
+ },
3195
+ set(value) {
3196
+ setField(this, "sourceCodeLocation", value);
3197
+ }
3198
+ };
3199
+ const childAccessors = { children: {
3200
+ get() {
3201
+ return childList(this);
3202
+ },
3203
+ set(value) {
3204
+ setField(this, "children", importNodes(routedFor(this[VIEW_STATE]), value));
3205
+ }
3206
+ } };
3207
+ const elementAccessors = {
3208
+ name: snapshotField("name"),
3209
+ attribs: {
3210
+ get() {
3211
+ return attributesOf(this);
3212
+ },
3213
+ set(value) {
3214
+ setField(this, "attribs", value);
3215
+ }
3216
+ },
3217
+ namespace: recordField("namespace"),
3218
+ prefix: recordField("prefix"),
3219
+ "x-attribsNamespace": {
3220
+ get() {
3221
+ return viewRecord(this).attribsNamespace !== void 0 ? attributeMap(this, "attribsNamespace") : void 0;
3222
+ },
3223
+ set(value) {
3224
+ setField(this, "x-attribsNamespace", value);
3225
+ }
3226
+ },
3227
+ "x-attribsPrefix": {
3228
+ get() {
3229
+ return viewRecord(this).attribsPrefix !== void 0 ? attributeMap(this, "attribsPrefix") : void 0;
3230
+ },
3231
+ set(value) {
3232
+ setField(this, "x-attribsPrefix", value);
3233
+ }
3234
+ }
3235
+ };
3236
+ const dataAccessors = { data: snapshotField("data") };
3237
+ const directiveAccessors = {
3238
+ name: recordField("name"),
3239
+ "x-name": recordField("x-name"),
3240
+ "x-publicId": recordField("x-publicId"),
3241
+ "x-systemId": recordField("x-systemId")
3242
+ };
3243
+ const documentAccessors = { "x-mode": recordField("x-mode") };
3244
+ function accessorsFor(type) {
3245
+ switch (type) {
3246
+ case "tag":
3247
+ case "script":
3248
+ case "style": return {
3249
+ ...nodeAccessors,
3250
+ ...childAccessors,
3251
+ ...elementAccessors
3252
+ };
3253
+ case "root": return {
3254
+ ...nodeAccessors,
3255
+ ...childAccessors,
3256
+ ...documentAccessors
3257
+ };
3258
+ case "cdata": return {
3259
+ ...nodeAccessors,
3260
+ ...childAccessors
3261
+ };
3262
+ case "directive": return {
3263
+ ...nodeAccessors,
3264
+ ...dataAccessors,
3265
+ ...directiveAccessors
3266
+ };
3267
+ case "text":
3268
+ case "comment": return {
3269
+ ...nodeAccessors,
3270
+ ...dataAccessors
3271
+ };
3272
+ default: return {
3273
+ ...nodeAccessors,
3274
+ ...childAccessors,
3275
+ ...dataAccessors,
3276
+ name: recordField("name")
3277
+ };
3278
+ }
3279
+ }
3280
+ const viewConstructors = /* @__PURE__ */ new Map();
3281
+ const plainConstructors = Object.create(null);
3282
+ /**
3283
+ * Legacy (Cheerio 0.22.0) node-shape rules, enabled per document through the
3284
+ * `_legacyDom` option:
3285
+ * - a top-level node's `parent` reads as null; its document root is exposed
3286
+ * through the separate `root` field instead;
3287
+ * - every node carries a writable `root` field, stored on the JavaScript side
3288
+ * exactly like the plain-object field of the original library;
3289
+ * - the synthetic root keeps its `name` of "root" and an `attribs` object.
3290
+ */
3291
+ const rootReferences = /* @__PURE__ */ new WeakMap();
3292
+ function applyPendingRoot(state, local, view) {
3293
+ const pending = state._pendingRoots;
3294
+ if (pending === void 0) return;
3295
+ if (pending.has(local)) {
3296
+ rootReferences.set(view, pending.get(local));
3297
+ pending.delete(local);
3298
+ if (pending.size === 0) state._pendingRoots = void 0;
3299
+ }
3300
+ }
3301
+ function setRootIfCached(document, id, root) {
3302
+ const state = stateIn(document, id);
3303
+ const local = id - state.base;
3304
+ const view = cachedView(state, local);
3305
+ if (view) {
3306
+ rootReferences.set(view, root);
3307
+ return;
3308
+ }
3309
+ let pending = state._pendingRoots;
3310
+ if (!pending) state._pendingRoots = pending = /* @__PURE__ */ new Map();
3311
+ pending.set(local, root);
3312
+ }
3313
+ const legacyParentAccessor = {
3314
+ get() {
3315
+ const state = this[VIEW_STATE];
3316
+ const local = this[VIEW_LOCAL];
3317
+ const snapshot = structureSnapshot(state, local);
3318
+ const parentLocal = snapshot ? snapshot.linkOf(local, 1) : viewRecord(this).parent;
3319
+ if (parentLocal == null) return null;
3320
+ if (parentLocal === state.rootLocal) return null;
3321
+ return linkedView(this, parentLocal);
3322
+ },
3323
+ set(value) {
3324
+ setPointer(this, "parent", value);
3325
+ }
3326
+ };
3327
+ const legacyRootAccessor = {
3328
+ get() {
3329
+ return rootReferences.get(this);
3330
+ },
3331
+ set(value) {
3332
+ rootReferences.set(this, value);
3333
+ }
3334
+ };
3335
+ function legacyAccessors(type) {
3336
+ const accessors = {
3337
+ parent: legacyParentAccessor,
3338
+ root: legacyRootAccessor
3339
+ };
3340
+ if (type === "root") accessors.name = {
3341
+ get: () => "root",
3342
+ set(value) {
3343
+ setField(this, "name", value);
3344
+ }
3345
+ };
3346
+ accessors.tagName = {
3347
+ get() {
3348
+ return this.name || null;
3349
+ },
3350
+ set(value) {
3351
+ this.name = value;
3352
+ }
3353
+ };
3354
+ accessors.nodeValue = {
3355
+ get() {
3356
+ return this.data || null;
3357
+ },
3358
+ set(value) {
3359
+ this.data = value;
3360
+ }
3361
+ };
3362
+ return accessors;
3363
+ }
3364
+ /**
3365
+ * The own fields of a 0.22.0 node object, per node kind. Legacy views define
3366
+ * these as own enumerable accessor properties so that enumeration
3367
+ * (`Object.keys(node)`) and deep-equality checks behave like they do on the
3368
+ * original plain-object nodes.
3369
+ */
3370
+ const legacyOwnFields = {
3371
+ root: [
3372
+ "type",
3373
+ "name",
3374
+ "attribs",
3375
+ "children",
3376
+ "parent",
3377
+ "prev",
3378
+ "next"
3379
+ ],
3380
+ tag: [
3381
+ "type",
3382
+ "name",
3383
+ "attribs",
3384
+ "children",
3385
+ "parent",
3386
+ "prev",
3387
+ "next"
3388
+ ],
3389
+ script: [
3390
+ "type",
3391
+ "name",
3392
+ "attribs",
3393
+ "children",
3394
+ "parent",
3395
+ "prev",
3396
+ "next"
3397
+ ],
3398
+ style: [
3399
+ "type",
3400
+ "name",
3401
+ "attribs",
3402
+ "children",
3403
+ "parent",
3404
+ "prev",
3405
+ "next"
3406
+ ],
3407
+ cdata: [
3408
+ "type",
3409
+ "children",
3410
+ "parent",
3411
+ "prev",
3412
+ "next"
3413
+ ],
3414
+ directive: [
3415
+ "type",
3416
+ "name",
3417
+ "data",
3418
+ "parent",
3419
+ "prev",
3420
+ "next"
3421
+ ],
3422
+ text: [
3423
+ "type",
3424
+ "data",
3425
+ "parent",
3426
+ "prev",
3427
+ "next"
3428
+ ],
3429
+ comment: [
3430
+ "type",
3431
+ "data",
3432
+ "parent",
3433
+ "prev",
3434
+ "next"
3435
+ ]
3436
+ };
3437
+ /** One constructor per node shape so node objects share a hidden class and prototype. */
3438
+ function viewConstructor(state, type, hasLocation) {
3439
+ const legacy = state.options._legacyDom === true;
3440
+ const suffix = hasLocation ? ":location" : "";
3441
+ const key = legacy ? `${type}${suffix}:legacy` : `${type}${suffix}`;
3442
+ if (!hasLocation && !legacy) {
3443
+ const plain = plainConstructors[type];
3444
+ if (plain) return plain;
3445
+ }
3446
+ let constructor = viewConstructors.get(key);
3447
+ if (constructor) return constructor;
3448
+ const prototype = Object.create(nodePrototype(type));
3449
+ let accessors = hasLocation ? {
3450
+ ...accessorsFor(type),
3451
+ sourceCodeLocation: locationAccessor
3452
+ } : accessorsFor(type);
3453
+ if (legacy) accessors = {
3454
+ ...accessors,
3455
+ ...legacyAccessors(type),
3456
+ ...type === "root" ? { attribs: elementAccessors.attribs } : {}
3457
+ };
3458
+ const childrenDescriptor = "children" in accessors ? {
3459
+ ...childAccessors.children,
3460
+ configurable: true,
3461
+ enumerable: true
3462
+ } : void 0;
3463
+ for (const [field, accessor] of Object.entries(accessors)) Object.defineProperty(prototype, field, {
3464
+ ...accessor,
3465
+ configurable: true,
3466
+ enumerable: false
3467
+ });
3468
+ const ownDescriptors = {};
3469
+ if (childrenDescriptor) ownDescriptors.children = childrenDescriptor;
3470
+ if (legacy) {
3471
+ const fields = legacyOwnFields[type];
3472
+ if (fields) for (const field of fields) {
3473
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, field);
3474
+ if (descriptor && (descriptor.get || descriptor.set)) ownDescriptors[field] = {
3475
+ get: descriptor.get,
3476
+ set: descriptor.set,
3477
+ configurable: true,
3478
+ enumerable: true
3479
+ };
3480
+ }
3481
+ }
3482
+ const createView = legacy ? () => Object.create(prototype, ownDescriptors) : childrenDescriptor ? () => Object.defineProperty(Object.create(prototype), "children", childrenDescriptor) : () => Object.create(prototype);
3483
+ constructor = function(state, local) {
3484
+ const view = createView();
3485
+ view[VIEW_STATE] = state;
3486
+ view[VIEW_LOCAL] = local;
3487
+ view[VIEW_SELF] = view;
3488
+ view[VIEW_ATTRIBUTES] = void 0;
3489
+ view[VIEW_CHILD_TARGET] = void 0;
3490
+ view[VIEW_CHILDREN] = void 0;
3491
+ return view;
3492
+ };
3493
+ Object.defineProperty(prototype, inspectSymbol, {
3494
+ configurable: true,
3495
+ writable: true,
3496
+ value: inspectNode
3497
+ });
3498
+ constructor.prototype = prototype;
3499
+ viewConstructors.set(key, constructor);
3500
+ if (!hasLocation && !legacy) plainConstructors[type] = constructor;
3501
+ return constructor;
3502
+ }
3503
+ const inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
3504
+ const inspectedFields = [
3505
+ "type",
3506
+ "name",
3507
+ "data",
3508
+ "attribs",
3509
+ "namespace",
3510
+ "startIndex",
3511
+ "endIndex"
3512
+ ];
3513
+ /** Console output shows the node's fields instead of its native bookkeeping. */
3514
+ function inspectNode(depth, options, inspect) {
3515
+ const fields = {};
3516
+ for (const field of inspectedFields) if (field in this && this[field] != null) fields[field] = field === "attribs" ? { ...this.attribs } : this[field];
3517
+ if ("children" in this) fields.children = `[${this.children.length} nodes]`;
3518
+ const name = Object.getPrototypeOf(Object.getPrototypeOf(this))?.constructor?.name ?? "Node";
3519
+ return depth < 0 ? `[${name}]` : `${name} ${inspect(fields, {
3520
+ ...options,
3521
+ depth: 1
3522
+ })}`;
3523
+ }
3524
+ const adoptedAliases = {
3525
+ parentNode: {
3526
+ configurable: true,
3527
+ enumerable: false,
3528
+ get() {
3529
+ return this.parent;
3530
+ },
3531
+ set(value) {
3532
+ this.parent = value;
3533
+ }
3534
+ },
3535
+ previousSibling: {
3536
+ configurable: true,
3537
+ enumerable: false,
3538
+ get() {
3539
+ return this.prev;
3540
+ },
3541
+ set(value) {
3542
+ this.prev = value;
3543
+ }
3544
+ },
3545
+ nextSibling: {
3546
+ configurable: true,
3547
+ enumerable: false,
3548
+ get() {
3549
+ return this.next;
3550
+ },
3551
+ set(value) {
3552
+ this.next = value;
3553
+ }
3554
+ },
3555
+ nodeType: {
3556
+ configurable: true,
3557
+ enumerable: false,
3558
+ get() {
3559
+ return {
3560
+ root: 9,
3561
+ text: 3,
3562
+ comment: 8,
3563
+ cdata: 4
3564
+ }[viewRecord(this).type] ?? 1;
3565
+ }
3566
+ },
3567
+ cloneNode: {
3568
+ configurable: true,
3569
+ enumerable: false,
3570
+ writable: true,
3571
+ value: cloneNode
3572
+ }
3573
+ };
3574
+ const adoptedChildAliases = {
3575
+ childNodes: {
3576
+ configurable: true,
3577
+ enumerable: false,
3578
+ get() {
3579
+ return this.children;
3580
+ },
3581
+ set(value) {
3582
+ this.children = value;
3583
+ }
3584
+ },
3585
+ firstChild: {
3586
+ configurable: true,
3587
+ enumerable: false,
3588
+ get() {
3589
+ return this.children[0] ?? null;
3590
+ }
3591
+ },
3592
+ lastChild: {
3593
+ configurable: true,
3594
+ enumerable: false,
3595
+ get() {
3596
+ return this.children[this.children.length - 1] ?? null;
3597
+ }
3598
+ }
3599
+ };
3600
+ const adoptedElementAliases = {
3601
+ tagName: {
3602
+ configurable: true,
3603
+ enumerable: false,
3604
+ get() {
3605
+ return this.name;
3606
+ },
3607
+ set(value) {
3608
+ this.name = value;
3609
+ }
3610
+ },
3611
+ attributes: {
3612
+ configurable: true,
3613
+ enumerable: false,
3614
+ get() {
3615
+ const attributes = this.attribs;
3616
+ const record = viewRecord(this);
3617
+ return Object.keys(attributes).map((name) => ({
3618
+ name,
3619
+ value: attributes[name],
3620
+ namespace: record.attribsNamespace?.[name],
3621
+ prefix: record.attribsPrefix?.[name]
3622
+ }));
3623
+ }
3624
+ }
3625
+ };
3626
+ const adoptedDataAliases = { nodeValue: {
3627
+ configurable: true,
3628
+ enumerable: false,
3629
+ get() {
3630
+ return this.data;
3631
+ },
3632
+ set(value) {
3633
+ this.data = value;
3634
+ }
3635
+ } };
3636
+ const adoptedFields = /* @__PURE__ */ new Map();
3637
+ const optionalAdoptedKeys = [
3638
+ "name",
3639
+ "data",
3640
+ "namespace",
3641
+ "prefix",
3642
+ "sourceCodeLocation",
3643
+ "x-name",
3644
+ "x-publicId",
3645
+ "x-systemId",
3646
+ "x-mode",
3647
+ "x-attribsNamespace",
3648
+ "x-attribsPrefix"
3649
+ ];
3650
+ const optionalAdoptedFields = new Set(optionalAdoptedKeys);
3651
+ const adoptedShapes = /* @__PURE__ */ new Map();
3652
+ /**
3653
+ * Binds an object created outside the arena (a DOM constructor or a parser
3654
+ * hook's node) to its native node, keeping the caller's object identity.
3655
+ */
3656
+ function adoptObject(state, local, original) {
3657
+ const record = recordAt(state, local);
3658
+ if (!record) return void 0;
3659
+ const view = original;
3660
+ const attributesPrototype = original.attribs && typeof original.attribs === "object" ? Object.getPrototypeOf(original.attribs) : void 0;
3661
+ view[VIEW_STATE] = state;
3662
+ view[VIEW_LOCAL] = local;
3663
+ view[VIEW_SELF] = view;
3664
+ view[VIEW_ATTRIBUTES] = void 0;
3665
+ view[VIEW_CHILD_TARGET] = void 0;
3666
+ view[VIEW_CHILDREN] = void 0;
3667
+ let fields = adoptedFields.get(record.type);
3668
+ if (!fields) {
3669
+ fields = {};
3670
+ for (const [key, accessor] of Object.entries({
3671
+ ...accessorsFor(record.type),
3672
+ sourceCodeLocation: locationAccessor
3673
+ })) fields[key] = {
3674
+ ...accessor,
3675
+ configurable: true,
3676
+ enumerable: true
3677
+ };
3678
+ adoptedFields.set(record.type, fields);
3679
+ }
3680
+ let shape = record.type;
3681
+ for (const key of optionalAdoptedKeys) {
3682
+ if (!(key in fields)) continue;
3683
+ shape += record[key === "x-attribsNamespace" ? "attribsNamespace" : key === "x-attribsPrefix" ? "attribsPrefix" : key] !== void 0 || Object.hasOwn(original, key) ? "1" : "0";
3684
+ }
3685
+ let descriptors = adoptedShapes.get(shape);
3686
+ if (!descriptors) {
3687
+ const present = {};
3688
+ for (const key in fields) {
3689
+ const field = key === "x-attribsNamespace" ? "attribsNamespace" : key === "x-attribsPrefix" ? "attribsPrefix" : key;
3690
+ if (optionalAdoptedFields.has(key) && record[field] === void 0 && !Object.hasOwn(original, key)) continue;
3691
+ present[key] = fields[key];
3692
+ }
3693
+ const isParent = "children" in present;
3694
+ const isData = record.type === "text" || record.type === "comment" || record.type === "directive";
3695
+ descriptors = {
3696
+ ...present,
3697
+ ...adoptedAliases,
3698
+ ...isParent ? adoptedChildAliases : {},
3699
+ ...isElementType(record.type) ? adoptedElementAliases : {},
3700
+ ...isData ? adoptedDataAliases : {}
3701
+ };
3702
+ adoptedShapes.set(shape, descriptors);
3703
+ }
3704
+ const isElement = isElementType(record.type);
3705
+ try {
3706
+ Object.defineProperties(view, descriptors);
3707
+ } catch {}
3708
+ if (isElement && attributesPrototype !== void 0) view[VIEW_ATTRIBUTES] = createAttributes(view, attributesPrototype);
3709
+ cacheView(state, local, view);
3710
+ return view;
3711
+ }
3712
+ /**
3713
+ * Registers a tree adapter's nodes for the document's slots. Each node can be
3714
+ * passed back to the API at once; its fields become live when first returned.
3715
+ */
3716
+ function attachParsedNodes(state, nodes) {
3717
+ state.adapterNodes = nodes;
3718
+ for (let local = 0; local < nodes.length; local++) {
3719
+ const node = nodes[local];
3720
+ if (!node) continue;
3721
+ node[VIEW_STATE] = state;
3722
+ node[VIEW_LOCAL] = local;
3723
+ node[VIEW_SELF] = node;
3724
+ }
3725
+ }
3726
+ /** Clone through the receiver's current native owner, including borrowed calls. */
3727
+ function cloneNode(recursive = false) {
3728
+ const binding = nodeBinding(this);
3729
+ if (!binding) throw new TypeError("cloneNode requires a native DOM node receiver");
3730
+ return getNode(binding.document, operation(binding.document, "clone", {
3731
+ ids: [binding.id],
3732
+ deep: recursive
3733
+ })[0]);
3734
+ }
3735
+ function childIds(document, id) {
3736
+ const state = stateIn(document, id);
3737
+ return (recordAt(state, id - state.base)?.children ?? []).map((child) => state.base + child);
3738
+ }
3739
+ /** Import external DOM nodes once and keep their object identities as handles. */
3740
+ function importNodes(document, input) {
3741
+ if (input == null || input === false) return [];
3742
+ const values = Array.isArray(input) || typeof input === "object" && "length" in input && !("type" in input) ? Array.from(input) : [input];
3743
+ const result = [];
3744
+ for (const node of values) {
3745
+ if (node == null) continue;
3746
+ const existing = node && typeof node === "object" ? viewIdIn(document, node) : void 0;
3747
+ if (existing !== void 0) {
3748
+ result.push(existing);
3749
+ continue;
3750
+ }
3751
+ if (typeof node !== "object" || typeof node.type !== "string") continue;
3752
+ const records = [];
3753
+ const originals = /* @__PURE__ */ new Map();
3754
+ const visit = (value, parent) => {
3755
+ const id = records.length;
3756
+ const record = {
3757
+ id,
3758
+ type: value.type,
3759
+ children: [],
3760
+ ...parent === void 0 ? {} : { parent }
3761
+ };
3762
+ records.push(record);
3763
+ originals.set(id, value);
3764
+ for (const field of [
3765
+ "name",
3766
+ "data",
3767
+ "namespace",
3768
+ "prefix",
3769
+ "startIndex",
3770
+ "endIndex",
3771
+ "sourceCodeLocation",
3772
+ "x-name",
3773
+ "x-publicId",
3774
+ "x-systemId",
3775
+ "x-mode"
3776
+ ]) if (value[field] !== void 0) record[field] = value[field];
3777
+ if (value.attribs) record.attribs = { ...value.attribs };
3778
+ if (value["x-attribsNamespace"]) record.attribsNamespace = { ...value["x-attribsNamespace"] };
3779
+ if (value["x-attribsPrefix"]) record.attribsPrefix = { ...value["x-attribsPrefix"] };
3780
+ record.children = (value.children ?? []).map((child) => visit(child, id));
3781
+ return id;
3782
+ };
3783
+ const root = visit(node);
3784
+ const imported = operation(document, "import", {
3785
+ nodes: records,
3786
+ roots: [root]
3787
+ });
3788
+ if (!imported.length) continue;
3789
+ const adopt = (oldId, newId) => {
3790
+ const source = originals.get(oldId);
3791
+ const oldChildren = records[oldId].children;
3792
+ const newChildren = childIds(document, newId);
3793
+ getNode(document, newId, isNativeNode(source) ? void 0 : source);
3794
+ for (let i = 0; i < oldChildren.length; i++) if (newChildren[i] !== void 0) adopt(oldChildren[i], newChildren[i]);
3795
+ };
3796
+ adopt(root, imported[0]);
3797
+ result.push(imported[0]);
3798
+ }
3799
+ return result;
3800
+ }
3801
+ Object.defineProperty(exports, "API", {
3802
+ enumerable: true,
3803
+ get: function() {
3804
+ return API;
3805
+ }
3806
+ });
3807
+ Object.defineProperty(exports, "CDATA", {
3808
+ enumerable: true,
3809
+ get: function() {
3810
+ return CDATA;
3811
+ }
3812
+ });
3813
+ Object.defineProperty(exports, "Comment", {
3814
+ enumerable: true,
3815
+ get: function() {
3816
+ return Comment;
3817
+ }
3818
+ });
3819
+ Object.defineProperty(exports, "DOCUMENT", {
3820
+ enumerable: true,
3821
+ get: function() {
3822
+ return DOCUMENT;
3823
+ }
3824
+ });
3825
+ Object.defineProperty(exports, "DataNode", {
3826
+ enumerable: true,
3827
+ get: function() {
3828
+ return DataNode;
3829
+ }
3830
+ });
3831
+ Object.defineProperty(exports, "Document", {
3832
+ enumerable: true,
3833
+ get: function() {
3834
+ return Document;
3835
+ }
3836
+ });
3837
+ Object.defineProperty(exports, "Element", {
3838
+ enumerable: true,
3839
+ get: function() {
3840
+ return Element;
3841
+ }
3842
+ });
3843
+ Object.defineProperty(exports, "ElementType", {
3844
+ enumerable: true,
3845
+ get: function() {
3846
+ return ElementType;
3847
+ }
3848
+ });
3849
+ Object.defineProperty(exports, "IDS", {
3850
+ enumerable: true,
3851
+ get: function() {
3852
+ return IDS;
3853
+ }
3854
+ });
3855
+ Object.defineProperty(exports, "IS_PLAIN", {
3856
+ enumerable: true,
3857
+ get: function() {
3858
+ return IS_PLAIN;
3859
+ }
3860
+ });
3861
+ Object.defineProperty(exports, "LEASE", {
3862
+ enumerable: true,
3863
+ get: function() {
3864
+ return LEASE;
3865
+ }
3866
+ });
3867
+ Object.defineProperty(exports, "Node", {
3868
+ enumerable: true,
3869
+ get: function() {
3870
+ return Node;
3871
+ }
3872
+ });
3873
+ Object.defineProperty(exports, "NodeSnapshot", {
3874
+ enumerable: true,
3875
+ get: function() {
3876
+ return NodeSnapshot;
3877
+ }
3878
+ });
3879
+ Object.defineProperty(exports, "NodeWithChildren", {
3880
+ enumerable: true,
3881
+ get: function() {
3882
+ return NodeWithChildren;
3883
+ }
3884
+ });
3885
+ Object.defineProperty(exports, "ProcessingInstruction", {
3886
+ enumerable: true,
3887
+ get: function() {
3888
+ return ProcessingInstruction;
3889
+ }
3890
+ });
3891
+ Object.defineProperty(exports, "Text", {
3892
+ enumerable: true,
3893
+ get: function() {
3894
+ return Text;
3895
+ }
3896
+ });
3897
+ Object.defineProperty(exports, "VALUES", {
3898
+ enumerable: true,
3899
+ get: function() {
3900
+ return VALUES;
3901
+ }
3902
+ });
3903
+ Object.defineProperty(exports, "VIEW_LOCAL", {
3904
+ enumerable: true,
3905
+ get: function() {
3906
+ return VIEW_LOCAL;
3907
+ }
3908
+ });
3909
+ Object.defineProperty(exports, "VIEW_SELF", {
3910
+ enumerable: true,
3911
+ get: function() {
3912
+ return VIEW_SELF;
3913
+ }
3914
+ });
3915
+ Object.defineProperty(exports, "VIEW_STATE", {
3916
+ enumerable: true,
3917
+ get: function() {
3918
+ return VIEW_STATE;
3919
+ }
3920
+ });
3921
+ Object.defineProperty(exports, "attributeAt", {
3922
+ enumerable: true,
3923
+ get: function() {
3924
+ return attributeAt;
3925
+ }
3926
+ });
3927
+ Object.defineProperty(exports, "cleanParserOptions", {
3928
+ enumerable: true,
3929
+ get: function() {
3930
+ return cleanParserOptions;
3931
+ }
3932
+ });
3933
+ Object.defineProperty(exports, "createDiagnosticSession", {
3934
+ enumerable: true,
3935
+ get: function() {
3936
+ return createDiagnosticSession;
3937
+ }
3938
+ });
3939
+ Object.defineProperty(exports, "createTokenizerSession", {
3940
+ enumerable: true,
3941
+ get: function() {
3942
+ return createTokenizerSession;
3943
+ }
3944
+ });
3945
+ Object.defineProperty(exports, "createTreeAdapterSession", {
3946
+ enumerable: true,
3947
+ get: function() {
3948
+ return createTreeAdapterSession;
3949
+ }
3950
+ });
3951
+ Object.defineProperty(exports, "decodeJson", {
3952
+ enumerable: true,
3953
+ get: function() {
3954
+ return decodeJson;
3955
+ }
3956
+ });
3957
+ Object.defineProperty(exports, "deliverParseErrors", {
3958
+ enumerable: true,
3959
+ get: function() {
3960
+ return deliverParseErrors;
3961
+ }
3962
+ });
3963
+ Object.defineProperty(exports, "exposeDocumentTo", {
3964
+ enumerable: true,
3965
+ get: function() {
3966
+ return exposeDocumentTo;
3967
+ }
3968
+ });
3969
+ Object.defineProperty(exports, "getNode", {
3970
+ enumerable: true,
3971
+ get: function() {
3972
+ return getNode;
3973
+ }
3974
+ });
3975
+ Object.defineProperty(exports, "getNodesOfType", {
3976
+ enumerable: true,
3977
+ get: function() {
3978
+ return getNodesOfType;
3979
+ }
3980
+ });
3981
+ Object.defineProperty(exports, "hasChildren", {
3982
+ enumerable: true,
3983
+ get: function() {
3984
+ return hasChildren;
3985
+ }
3986
+ });
3987
+ Object.defineProperty(exports, "hasMaterializedAttributes", {
3988
+ enumerable: true,
3989
+ get: function() {
3990
+ return hasMaterializedAttributes;
3991
+ }
3992
+ });
3993
+ Object.defineProperty(exports, "hasMaterializedChildren", {
3994
+ enumerable: true,
3995
+ get: function() {
3996
+ return hasMaterializedChildren;
3997
+ }
3998
+ });
3999
+ Object.defineProperty(exports, "hasParserHooks", {
4000
+ enumerable: true,
4001
+ get: function() {
4002
+ return hasParserHooks;
4003
+ }
4004
+ });
4005
+ Object.defineProperty(exports, "hydrateLocation", {
4006
+ enumerable: true,
4007
+ get: function() {
4008
+ return hydrateLocation;
4009
+ }
4010
+ });
4011
+ Object.defineProperty(exports, "importNodes", {
4012
+ enumerable: true,
4013
+ get: function() {
4014
+ return importNodes;
4015
+ }
4016
+ });
4017
+ Object.defineProperty(exports, "isCDATA", {
4018
+ enumerable: true,
4019
+ get: function() {
4020
+ return isCDATA;
4021
+ }
4022
+ });
4023
+ Object.defineProperty(exports, "isComment", {
4024
+ enumerable: true,
4025
+ get: function() {
4026
+ return isComment;
4027
+ }
4028
+ });
4029
+ Object.defineProperty(exports, "isDirective", {
4030
+ enumerable: true,
4031
+ get: function() {
4032
+ return isDirective;
4033
+ }
4034
+ });
4035
+ Object.defineProperty(exports, "isDocument", {
4036
+ enumerable: true,
4037
+ get: function() {
4038
+ return isDocument;
4039
+ }
4040
+ });
4041
+ Object.defineProperty(exports, "isRouted", {
4042
+ enumerable: true,
4043
+ get: function() {
4044
+ return isRouted;
4045
+ }
4046
+ });
4047
+ Object.defineProperty(exports, "isTag", {
4048
+ enumerable: true,
4049
+ get: function() {
4050
+ return isTag;
4051
+ }
4052
+ });
4053
+ Object.defineProperty(exports, "isText", {
4054
+ enumerable: true,
4055
+ get: function() {
4056
+ return isText;
4057
+ }
4058
+ });
4059
+ Object.defineProperty(exports, "leaseNodes", {
4060
+ enumerable: true,
4061
+ get: function() {
4062
+ return leaseNodes;
4063
+ }
4064
+ });
4065
+ Object.defineProperty(exports, "nativeStatus", {
4066
+ enumerable: true,
4067
+ get: function() {
4068
+ return nativeStatus;
4069
+ }
4070
+ });
4071
+ Object.defineProperty(exports, "nodeBinding", {
4072
+ enumerable: true,
4073
+ get: function() {
4074
+ return nodeBinding;
4075
+ }
4076
+ });
4077
+ Object.defineProperty(exports, "nodeId", {
4078
+ enumerable: true,
4079
+ get: function() {
4080
+ return nodeId;
4081
+ }
4082
+ });
4083
+ Object.defineProperty(exports, "nodeRecord", {
4084
+ enumerable: true,
4085
+ get: function() {
4086
+ return nodeRecord;
4087
+ }
4088
+ });
4089
+ Object.defineProperty(exports, "operation", {
4090
+ enumerable: true,
4091
+ get: function() {
4092
+ return operation;
4093
+ }
4094
+ });
4095
+ Object.defineProperty(exports, "parseNativeDocument", {
4096
+ enumerable: true,
4097
+ get: function() {
4098
+ return parseNativeDocument;
4099
+ }
4100
+ });
4101
+ Object.defineProperty(exports, "parserOptions", {
4102
+ enumerable: true,
4103
+ get: function() {
4104
+ return parserOptions;
4105
+ }
4106
+ });
4107
+ Object.defineProperty(exports, "plainSnapshot", {
4108
+ enumerable: true,
4109
+ get: function() {
4110
+ return plainSnapshot;
4111
+ }
4112
+ });
4113
+ Object.defineProperty(exports, "prepareBulkViews", {
4114
+ enumerable: true,
4115
+ get: function() {
4116
+ return prepareBulkViews;
4117
+ }
4118
+ });
4119
+ Object.defineProperty(exports, "recordAt", {
4120
+ enumerable: true,
4121
+ get: function() {
4122
+ return recordAt;
4123
+ }
4124
+ });
4125
+ Object.defineProperty(exports, "requireNative", {
4126
+ enumerable: true,
4127
+ get: function() {
4128
+ return requireNative;
4129
+ }
4130
+ });
4131
+ Object.defineProperty(exports, "resumeCollection", {
4132
+ enumerable: true,
4133
+ get: function() {
4134
+ return resumeCollection;
4135
+ }
4136
+ });
4137
+ Object.defineProperty(exports, "rootNode", {
4138
+ enumerable: true,
4139
+ get: function() {
4140
+ return rootNode;
4141
+ }
4142
+ });
4143
+ Object.defineProperty(exports, "routeDocument", {
4144
+ enumerable: true,
4145
+ get: function() {
4146
+ return routeDocument;
4147
+ }
4148
+ });
4149
+ Object.defineProperty(exports, "sameNodeSpace", {
4150
+ enumerable: true,
4151
+ get: function() {
4152
+ return sameNodeSpace;
4153
+ }
4154
+ });
4155
+ Object.defineProperty(exports, "setRootIfCached", {
4156
+ enumerable: true,
4157
+ get: function() {
4158
+ return setRootIfCached;
4159
+ }
4160
+ });
4161
+ Object.defineProperty(exports, "stateIn", {
4162
+ enumerable: true,
4163
+ get: function() {
4164
+ return stateIn;
4165
+ }
4166
+ });
4167
+ Object.defineProperty(exports, "structureSnapshot", {
4168
+ enumerable: true,
4169
+ get: function() {
4170
+ return structureSnapshot;
4171
+ }
4172
+ });
4173
+ Object.defineProperty(exports, "traverseRecords", {
4174
+ enumerable: true,
4175
+ get: function() {
4176
+ return traverseRecords;
4177
+ }
4178
+ });
4179
+ Object.defineProperty(exports, "updateLease", {
4180
+ enumerable: true,
4181
+ get: function() {
4182
+ return updateLease;
4183
+ }
4184
+ });
4185
+ Object.defineProperty(exports, "usePreparedSnapshot", {
4186
+ enumerable: true,
4187
+ get: function() {
4188
+ return usePreparedSnapshot;
4189
+ }
4190
+ });
4191
+ Object.defineProperty(exports, "viewId", {
4192
+ enumerable: true,
4193
+ get: function() {
4194
+ return viewId;
4195
+ }
4196
+ });
4197
+ Object.defineProperty(exports, "viewIdIn", {
4198
+ enumerable: true,
4199
+ get: function() {
4200
+ return viewIdIn;
4201
+ }
4202
+ });
4203
+ Object.defineProperty(exports, "writeCount", {
4204
+ enumerable: true,
4205
+ get: function() {
4206
+ return writeCount;
4207
+ }
4208
+ });
4209
+
4210
+ //# sourceMappingURL=nodes-jbWWhssj.cjs.map