@dvaji/cheerox 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/CONTRIBUTING.md +74 -0
  2. package/Cargo.lock +1094 -0
  3. package/Cargo.toml +46 -0
  4. package/LICENSE +21 -0
  5. package/README.md +121 -2
  6. package/RELEASING.md +114 -0
  7. package/THIRD_PARTY_NOTICES.md +7579 -0
  8. package/build.rs +3 -0
  9. package/cheerox.darwin-arm64.node +0 -0
  10. package/cheerox.darwin-x64.node +0 -0
  11. package/cheerox.linux-arm64-gnu.node +0 -0
  12. package/cheerox.linux-arm64-musl.node +0 -0
  13. package/cheerox.linux-x64-gnu.node +0 -0
  14. package/cheerox.linux-x64-musl.node +0 -0
  15. package/cheerox.win32-arm64-msvc.node +0 -0
  16. package/cheerox.win32-x64-msvc.node +0 -0
  17. package/dist/cheerio-compat-BS--qPzw.mjs +1648 -0
  18. package/dist/cheerio-compat-BS--qPzw.mjs.map +1 -0
  19. package/dist/cheerio-compat-DRLPzBdX.d.mts +88 -0
  20. package/dist/cheerio-compat-DRsINTwV.d.cts +88 -0
  21. package/dist/cheerio-compat-DRsINTwV.d.ts +88 -0
  22. package/dist/cheerio-compat-DSwBAJ1s.cjs +1719 -0
  23. package/dist/cheerio-compat-DSwBAJ1s.cjs.map +1 -0
  24. package/dist/cheerio-compat.cjs +18 -0
  25. package/dist/cheerio-compat.d.cts +2 -0
  26. package/dist/cheerio-compat.d.mts +2 -0
  27. package/dist/cheerio-compat.d.ts +2 -0
  28. package/dist/cheerio-compat.mjs +1 -0
  29. package/dist/index.cjs +13 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +28 -0
  32. package/dist/index.d.mts +6 -0
  33. package/dist/index.d.ts +28 -0
  34. package/dist/index.mjs +53 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/legacy-parse.cjs +5 -0
  37. package/dist/legacy-parse.d.mts +8 -0
  38. package/dist/legacy-parse.d.ts +7 -0
  39. package/dist/legacy-parse.mjs +1 -0
  40. package/dist/modern-B7hyW4cI.d.cts +102 -0
  41. package/dist/modern-B7hyW4cI.d.ts +102 -0
  42. package/dist/modern-CHQGP0Yt.cjs +2858 -0
  43. package/dist/modern-CHQGP0Yt.cjs.map +1 -0
  44. package/dist/modern-CJvSD_y5.d.mts +102 -0
  45. package/dist/modern-CvXcTn82.mjs +2769 -0
  46. package/dist/modern-CvXcTn82.mjs.map +1 -0
  47. package/dist/modern.cjs +19 -0
  48. package/dist/modern.d.cts +3 -0
  49. package/dist/modern.d.mts +3 -0
  50. package/dist/modern.d.ts +3 -0
  51. package/dist/modern.mjs +3 -0
  52. package/dist/nodes-jbWWhssj.cjs +4210 -0
  53. package/dist/nodes-jbWWhssj.cjs.map +1 -0
  54. package/dist/nodes-sYxb5qyZ.mjs +3803 -0
  55. package/dist/nodes-sYxb5qyZ.mjs.map +1 -0
  56. package/dist/slim.cjs +16 -0
  57. package/dist/slim.cjs.map +1 -0
  58. package/dist/slim.d.cts +6 -0
  59. package/dist/slim.d.mts +6 -0
  60. package/dist/slim.d.ts +6 -0
  61. package/dist/slim.mjs +12 -0
  62. package/dist/slim.mjs.map +1 -0
  63. package/dist/types-CA01Zg3r.d.cts +526 -0
  64. package/dist/types-CA01Zg3r.d.mts +526 -0
  65. package/dist/types-CA01Zg3r.d.ts +526 -0
  66. package/dist/utils.cjs +31 -0
  67. package/dist/utils.cjs.map +1 -0
  68. package/dist/utils.d.cts +8 -0
  69. package/dist/utils.d.mts +8 -0
  70. package/dist/utils.d.ts +8 -0
  71. package/dist/utils.mjs +25 -0
  72. package/dist/utils.mjs.map +1 -0
  73. package/native/src/arena.rs +2109 -0
  74. package/native/src/attributes.rs +946 -0
  75. package/native/src/codec.rs +298 -0
  76. package/native/src/diagnostics.rs +1249 -0
  77. package/native/src/document_order.rs +711 -0
  78. package/native/src/extraction.rs +321 -0
  79. package/native/src/gc.rs +175 -0
  80. package/native/src/hook_sink.rs +801 -0
  81. package/native/src/hook_stream.rs +513 -0
  82. package/native/src/id_hash.rs +42 -0
  83. package/native/src/immutable.rs +333 -0
  84. package/native/src/lib.rs +4119 -0
  85. package/native/src/location.rs +392 -0
  86. package/native/src/markup_tokenizer.rs +668 -0
  87. package/native/src/runtime.rs +368 -0
  88. package/native/src/selector.rs +1596 -0
  89. package/native/src/sink.rs +274 -0
  90. package/native/src/snapshot.rs +672 -0
  91. package/native/src/stream.rs +334 -0
  92. package/native/src/tokenizer.rs +581 -0
  93. package/native/src/tracker.rs +232 -0
  94. package/native/vendor/README.md +26 -0
  95. package/native/vendor/html5ever-0.35.0/.cargo_vcs_info.json +6 -0
  96. package/native/vendor/html5ever-0.35.0/Cargo.lock +828 -0
  97. package/native/vendor/html5ever-0.35.0/Cargo.toml +85 -0
  98. package/native/vendor/html5ever-0.35.0/LICENSE-APACHE +201 -0
  99. package/native/vendor/html5ever-0.35.0/LICENSE-MIT +25 -0
  100. package/native/vendor/html5ever-0.35.0/README.md +60 -0
  101. package/native/vendor/html5ever-0.35.0/benches/html5ever.rs +86 -0
  102. package/native/vendor/html5ever-0.35.0/data/bench/lipsum-zh.html +19 -0
  103. package/native/vendor/html5ever-0.35.0/data/bench/lipsum.html +40 -0
  104. package/native/vendor/html5ever-0.35.0/data/bench/medium-fragment.html +24 -0
  105. package/native/vendor/html5ever-0.35.0/data/bench/small-fragment.html +7 -0
  106. package/native/vendor/html5ever-0.35.0/data/bench/strong.html +1 -0
  107. package/native/vendor/html5ever-0.35.0/data/bench/tiny-fragment.html +1 -0
  108. package/native/vendor/html5ever-0.35.0/examples/arena.rs +356 -0
  109. package/native/vendor/html5ever-0.35.0/examples/capi/tokenize.c +74 -0
  110. package/native/vendor/html5ever-0.35.0/examples/noop-tokenize.rs +47 -0
  111. package/native/vendor/html5ever-0.35.0/examples/noop-tree-builder.rs +132 -0
  112. package/native/vendor/html5ever-0.35.0/examples/print-tree-actions.rs +185 -0
  113. package/native/vendor/html5ever-0.35.0/examples/tokenize.rs +111 -0
  114. package/native/vendor/html5ever-0.35.0/src/driver.rs +148 -0
  115. package/native/vendor/html5ever-0.35.0/src/lib.rs +30 -0
  116. package/native/vendor/html5ever-0.35.0/src/macros.rs +34 -0
  117. package/native/vendor/html5ever-0.35.0/src/serialize/mod.rs +255 -0
  118. package/native/vendor/html5ever-0.35.0/src/tokenizer/char_ref/mod.rs +530 -0
  119. package/native/vendor/html5ever-0.35.0/src/tokenizer/interface.rs +99 -0
  120. package/native/vendor/html5ever-0.35.0/src/tokenizer/mod.rs +2628 -0
  121. package/native/vendor/html5ever-0.35.0/src/tokenizer/states.rs +97 -0
  122. package/native/vendor/html5ever-0.35.0/src/tree_builder/data.rs +170 -0
  123. package/native/vendor/html5ever-0.35.0/src/tree_builder/mod.rs +1848 -0
  124. package/native/vendor/html5ever-0.35.0/src/tree_builder/rules.rs +1494 -0
  125. package/native/vendor/html5ever-0.35.0/src/tree_builder/tag_sets.rs +114 -0
  126. package/native/vendor/html5ever-0.35.0/src/tree_builder/types.rs +91 -0
  127. package/native/vendor/html5ever-0.35.0/src/util/str.rs +52 -0
  128. package/native/vendor/html5gum-0.8.4/Cargo.lock +1006 -0
  129. package/native/vendor/html5gum-0.8.4/Cargo.toml +109 -0
  130. package/native/vendor/html5gum-0.8.4/LICENSE +19 -0
  131. package/native/vendor/html5gum-0.8.4/README.md +110 -0
  132. package/native/vendor/html5gum-0.8.4/benches/files/0050.html +2131 -0
  133. package/native/vendor/html5gum-0.8.4/benches/files/6D30.html +1004 -0
  134. package/native/vendor/html5gum-0.8.4/benches/files.rs +32 -0
  135. package/native/vendor/html5gum-0.8.4/benches/patterns.rs +31 -0
  136. package/native/vendor/html5gum-0.8.4/src/arrayvec.rs +29 -0
  137. package/native/vendor/html5gum-0.8.4/src/char_validator.rs +134 -0
  138. package/native/vendor/html5gum-0.8.4/src/emitters/callback.rs +676 -0
  139. package/native/vendor/html5gum-0.8.4/src/emitters/default.rs +207 -0
  140. package/native/vendor/html5gum-0.8.4/src/emitters/emitter.rs +344 -0
  141. package/native/vendor/html5gum-0.8.4/src/emitters/html5ever.rs +306 -0
  142. package/native/vendor/html5gum-0.8.4/src/emitters/mod.rs +25 -0
  143. package/native/vendor/html5gum-0.8.4/src/entities.rs +3342 -0
  144. package/native/vendor/html5gum-0.8.4/src/error.rs +96 -0
  145. package/native/vendor/html5gum-0.8.4/src/htmlstring.rs +130 -0
  146. package/native/vendor/html5gum-0.8.4/src/lib.rs +66 -0
  147. package/native/vendor/html5gum-0.8.4/src/machine.rs +2136 -0
  148. package/native/vendor/html5gum-0.8.4/src/machine_helper.rs +277 -0
  149. package/native/vendor/html5gum-0.8.4/src/read_helper.rs +244 -0
  150. package/native/vendor/html5gum-0.8.4/src/reader.rs +440 -0
  151. package/native/vendor/html5gum-0.8.4/src/span.rs +98 -0
  152. package/native/vendor/html5gum-0.8.4/src/state.rs +16 -0
  153. package/native/vendor/html5gum-0.8.4/src/testutils.rs +71 -0
  154. package/native/vendor/html5gum-0.8.4/src/tokenizer.rs +189 -0
  155. package/native/vendor/html5gum-0.8.4/src/utils.rs +88 -0
  156. package/native/vendor/markup5ever-0.35.0/.cargo_vcs_info.json +6 -0
  157. package/native/vendor/markup5ever-0.35.0/Cargo.toml +45 -0
  158. package/native/vendor/markup5ever-0.35.0/LICENSE-APACHE +201 -0
  159. package/native/vendor/markup5ever-0.35.0/LICENSE-MIT +25 -0
  160. package/native/vendor/markup5ever-0.35.0/interface/mod.rs +422 -0
  161. package/native/vendor/markup5ever-0.35.0/interface/tree_builder.rs +280 -0
  162. package/native/vendor/markup5ever-0.35.0/lib.rs +59 -0
  163. package/native/vendor/markup5ever-0.35.0/serialize.rs +77 -0
  164. package/native/vendor/markup5ever-0.35.0/util/buffer_queue.rs +333 -0
  165. package/native/vendor/markup5ever-0.35.0/util/smallcharset.rs +88 -0
  166. package/package.json +167 -4
  167. package/scripts/check-native.mjs +15 -0
  168. package/scripts/check-release.mjs +234 -0
  169. package/scripts/fix-declarations.mjs +39 -0
  170. package/scripts/generate-notices.mjs +188 -0
  171. package/scripts/notices/README.md +13 -0
  172. package/scripts/notices/cheerio-MIT.txt +21 -0
  173. package/scripts/notices/html5ever-AUTHORS.txt +20 -0
  174. package/scripts/notices/html5ever-COPYRIGHT.txt +8 -0
  175. package/scripts/notices/html5ever-LICENSE-APACHE.txt +201 -0
  176. package/scripts/notices/html5ever-LICENSE-MIT.txt +25 -0
  177. package/scripts/notices/htmlparser2-MIT.txt +18 -0
  178. package/scripts/notices/napi-rs-MIT.txt +43 -0
  179. package/scripts/notices/neon-MIT.txt +19 -0
  180. package/scripts/notices/runtime-01c266bced4a434da005.txt +3 -0
  181. package/scripts/notices/runtime-0a54e647fe54104658b5.txt +14 -0
  182. package/scripts/notices/runtime-0b74dfa0bcee5c420c6b.txt +25 -0
  183. package/scripts/notices/runtime-0d542e0c8804e39aa7f3.txt +177 -0
  184. package/scripts/notices/runtime-0f96a83840e146e43c0e.txt +21 -0
  185. package/scripts/notices/runtime-123a331b5dbf04c30097.txt +25 -0
  186. package/scripts/notices/runtime-172020dbfd5b53a226df.txt +34 -0
  187. package/scripts/notices/runtime-209fbbe0ad52d9235e37.txt +26 -0
  188. package/scripts/notices/runtime-23f18e03dc49df91622f.txt +23 -0
  189. package/scripts/notices/runtime-268872b9816f90fd8e85.txt +220 -0
  190. package/scripts/notices/runtime-35242e7a83f69875e6ed.txt +176 -0
  191. package/scripts/notices/runtime-378f5840b258e2779c39.txt +25 -0
  192. package/scripts/notices/runtime-4108245a1f2df9d4e94d.txt +25 -0
  193. package/scripts/notices/runtime-4455bf75a91154108304.txt +21 -0
  194. package/scripts/notices/runtime-553fffcd9b1cb158bc3e.txt +13 -0
  195. package/scripts/notices/runtime-62c7a1e35f56406896d7.txt +176 -0
  196. package/scripts/notices/runtime-6485b8ed310d3f0340bf.txt +25 -0
  197. package/scripts/notices/runtime-69fef7b0f322a6555415.txt +201 -0
  198. package/scripts/notices/runtime-6df43f6f4b5d4587f3d8.txt +187 -0
  199. package/scripts/notices/runtime-799e9ca9d179295ef372.txt +24 -0
  200. package/scripts/notices/runtime-7b63ecd5f1902af1b637.txt +25 -0
  201. package/scripts/notices/runtime-7bc7d5de2a0b793d4e1a.txt +21 -0
  202. package/scripts/notices/runtime-7e12e5df4bae12cb2158.txt +24 -0
  203. package/scripts/notices/runtime-861399f8c21c042b1105.txt +12 -0
  204. package/scripts/notices/runtime-8ada45cd9f843acf64e4.txt +201 -0
  205. package/scripts/notices/runtime-90eb64f0279b0d9432ac.txt +12 -0
  206. package/scripts/notices/runtime-a60eea817514531668d7.txt +201 -0
  207. package/scripts/notices/runtime-a7c936ff1ed8fa340172.txt +25 -0
  208. package/scripts/notices/runtime-ab6eec6caf0fa5775e41.txt +275 -0
  209. package/scripts/notices/runtime-b1181a40b2a7b25cf66f.txt +19 -0
  210. package/scripts/notices/runtime-b71bd43a069ca0641a9e.txt +25 -0
  211. package/scripts/notices/runtime-c16f8dcf1a368b83be78.txt +201 -0
  212. package/scripts/notices/runtime-c2cfccb812fe482101a8.txt +21 -0
  213. package/scripts/notices/runtime-e99d88d232bf57d70f0f.txt +25 -0
  214. package/scripts/notices/runtime-f32fb3b417a194167cfa.txt +9 -0
  215. package/scripts/notices/runtime-f5062c9a188d81dfe66b.txt +39 -0
  216. package/scripts/notices/runtime-f9070a832833fa7488fd.txt +4 -0
  217. package/scripts/notices/runtime-fab3dd6bdab226f1c086.txt +373 -0
  218. package/scripts/notices/runtime-fba3318d0c600380177e.txt +62 -0
  219. package/scripts/notices/runtime-ff8f68cb076caf8cefe7.txt +25 -0
  220. package/scripts/notices/runtime-ff92bed461f50338dd70.txt +74 -0
  221. package/scripts/notices/runtime.json +1632 -0
  222. package/scripts/notices/sources.json +561 -0
  223. package/scripts/notices/xray-MIT.txt +21 -0
  224. package/src/attribute-object.ts +71 -0
  225. package/src/attributes.ts +308 -0
  226. package/src/cheerio-compat/css.ts +58 -0
  227. package/src/cheerio-compat/render.ts +106 -0
  228. package/src/cheerio-compat/selectors.ts +51 -0
  229. package/src/cheerio-compat/types.ts +52 -0
  230. package/src/cheerio-compat.ts +2055 -0
  231. package/src/codec.ts +96 -0
  232. package/src/dom.ts +87 -0
  233. package/src/extract-plan.ts +97 -0
  234. package/src/extract.ts +322 -0
  235. package/src/hooks.ts +369 -0
  236. package/src/index.ts +48 -0
  237. package/src/io.ts +491 -0
  238. package/src/match.ts +207 -0
  239. package/src/modern.ts +259 -0
  240. package/src/native.ts +149 -0
  241. package/src/nodes.ts +831 -0
  242. package/src/parse.ts +53 -0
  243. package/src/parser-types.ts +157 -0
  244. package/src/router.ts +1129 -0
  245. package/src/selection.ts +682 -0
  246. package/src/slim.ts +12 -0
  247. package/src/snapshot.ts +291 -0
  248. package/src/transport.ts +113 -0
  249. package/src/types.ts +186 -0
  250. package/src/utils.ts +29 -0
  251. package/src/workers.ts +21 -0
  252. package/tsconfig.json +15 -0
  253. package/tsdown.config.mjs +17 -0
package/src/nodes.ts ADDED
@@ -0,0 +1,831 @@
1
+ import type { NativeDocument, NativeNodeRecord } from './native.js';
2
+ import { NodeSnapshot } from './snapshot.js';
3
+ import type { AnyNode } from './types.js';
4
+ import { nodePrototype } from './dom.js';
5
+ import { ATTR_META, attributeAssign, defineAttributeKey, setAttributeMeta, type AttributeMeta, type AttributeObject } from './attribute-object.js';
6
+ import { cachedView, cacheView, exposeTo, isLocalState, isRouted, onViewRefresh, plainSnapshot, prepareWalkSnapshot, recordAt, routedFor, stateIn, structureSnapshot, VIEW_ATTRIBUTES, VIEW_CHILD_TARGET, VIEW_LOCAL, VIEW_SELF, VIEW_STATE, type DocumentState } from './router.js';
7
+
8
+ export interface NodeBinding { document: NativeDocument; id: number }
9
+
10
+ /** A node object: its fields read the native record for the node's current location. */
11
+ interface View { [VIEW_STATE]: DocumentState; [VIEW_LOCAL]: number; [VIEW_SELF]: View; [VIEW_ATTRIBUTES]: AttributeObject | undefined; [VIEW_CHILDREN]: AnyNode[] | undefined; [VIEW_CHILD_TARGET]: AnyNode[] | undefined; [key: string]: any }
12
+
13
+ const VIEW_CHILDREN = Symbol.for('cheerox.node.children');
14
+
15
+ const arrayIndex = /^(?:0|[1-9]\d*)$/;
16
+ const emptyRecord = Object.freeze({ id: -1, type: 'released', children: [] }) as unknown as NativeNodeRecord;
17
+
18
+ export function operation<T = any>(document: NativeDocument, command: string, args: unknown = {}): T {
19
+ const direct = (document as NativeDocument & { operate?(command: string, args: unknown): T }).operate;
20
+ if (direct) return direct.call(document, command, args);
21
+ const value = document.op(command, JSON.stringify(args));
22
+ return (value === undefined || value === '' ? undefined : JSON.parse(value)) as T;
23
+ }
24
+
25
+ /** The id of a native node object, without allocating a binding. */
26
+ export function viewId(node: unknown): number | undefined {
27
+ const view = node as View | null | undefined;
28
+ const state = view?.[VIEW_STATE];
29
+ return state !== undefined && view![VIEW_SELF] === view && isLocalState(state) ? state.base + view![VIEW_LOCAL] : undefined;
30
+ }
31
+
32
+ /** Whether `node` is a node object of a native document, of this or another copy of the package. */
33
+ function isNativeNode(node: unknown): boolean {
34
+ const view = node as View | null | undefined;
35
+ return view?.[VIEW_STATE] !== undefined && view[VIEW_SELF] === view;
36
+ }
37
+
38
+ /** The id of a native node object, made resolvable by `document`'s operations. */
39
+ export function viewIdIn(document: NativeDocument, node: unknown): number | undefined {
40
+ const id = viewId(node);
41
+ if (id !== undefined) exposeTo(document, (node as View)[VIEW_STATE]);
42
+ return id;
43
+ }
44
+
45
+ export function nodeBinding(node: unknown): NodeBinding | undefined {
46
+ const id = node && typeof node === 'object' ? viewId(node) : undefined;
47
+ return id === undefined ? undefined : { document: routedFor((node as View)[VIEW_STATE]), id };
48
+ }
49
+
50
+ export function hasMaterializedChildren(node: unknown): boolean {
51
+ return !!(node as View | null | undefined)?.[VIEW_CHILD_TARGET];
52
+ }
53
+
54
+ export function hasMaterializedAttributes(node: unknown): boolean {
55
+ return !!(node as View | null | undefined)?.[VIEW_ATTRIBUTES];
56
+ }
57
+
58
+ export function nodeId(node: unknown, document?: NativeDocument): number | undefined {
59
+ const id = node && typeof node === 'object' ? viewId(node) : undefined;
60
+ return id !== undefined && (!document || isRouted(document)) ? id : undefined;
61
+ }
62
+
63
+ /** Recreate parse5's null-prototype attribute maps and shared start-tag map. */
64
+ export function hydrateLocation<T>(location: T): T {
65
+ if (!location || typeof location !== 'object') return location;
66
+ const value = location as Record<string, any>;
67
+ if (value.attrs && typeof value.attrs === 'object') Object.setPrototypeOf(value.attrs, null);
68
+ if (value.startTag?.attrs && typeof value.startTag.attrs === 'object') {
69
+ Object.setPrototypeOf(value.startTag.attrs, null);
70
+ if (value.attrs && JSON.stringify(value.attrs) === JSON.stringify(value.startTag.attrs)) value.startTag.attrs = value.attrs;
71
+ }
72
+ return location;
73
+ }
74
+
75
+ /** The node's record; its links are ids local to the node's document. */
76
+ export function nodeRecord(document: NativeDocument, id: number): NativeNodeRecord {
77
+ if (!isRouted(document)) return operation(document, 'node', { id });
78
+ const state = stateIn(document, id);
79
+ return recordAt(state, id - state.base) as NativeNodeRecord;
80
+ }
81
+
82
+ const isElementType = (type: string | undefined): boolean => type === 'tag' || type === 'script' || type === 'style';
83
+
84
+ /** Mirrors the native `traverse` operation over cached records; `undefined` defers to it. */
85
+ export function traverseRecords(document: NativeDocument, ids: number[], kind: string): number[] | undefined {
86
+ if (!isRouted(document)) return undefined;
87
+ const result: number[] = [];
88
+ for (const id of ids) {
89
+ const state = stateIn(document, id);
90
+ const { base } = state;
91
+ // Attribute writes leave a snapshot's links and types current, and other
92
+ // writes discard it, so its arrays answer without records.
93
+ const snapshot = state.bulk instanceof NodeSnapshot ? state.bulk : undefined;
94
+ if (snapshot?.isPresent(id - base) && traverseSnapshot(snapshot, base, id - base, kind, result)) continue;
95
+ const node = recordAt(state, id - base);
96
+ if (!node) continue;
97
+ const isElement = (local: number): boolean => isElementType(recordAt(state, local)?.type);
98
+ if (kind === 'children') {
99
+ for (const child of node.children ?? []) if (isElement(child)) result.push(base + child);
100
+ } else if (kind === 'contents') {
101
+ for (const child of node.children ?? []) result.push(base + child);
102
+ } else if (kind === 'parent') {
103
+ if (node.parent != null && isElement(node.parent)) result.push(base + node.parent);
104
+ } else if (kind === 'parents' || kind === 'ancestors') {
105
+ const seen = new Set<number>();
106
+ for (let parent = node.parent; parent != null && !seen.has(parent);) {
107
+ seen.add(parent);
108
+ const ancestor = recordAt(state, parent);
109
+ if (!ancestor || ancestor.type === 'root') break;
110
+ if (isElementType(ancestor.type)) result.push(base + parent);
111
+ parent = ancestor.parent;
112
+ }
113
+ } else if (kind === 'next' || kind === 'prev' || kind === 'nextAll' || kind === 'prevAll') {
114
+ const isForward = kind === 'next' || kind === 'nextAll';
115
+ const isSingle = kind === 'next' || kind === 'prev';
116
+ const seen = new Set<number>();
117
+ for (let sibling = isForward ? node.next : node.prev; sibling != null && !seen.has(sibling);) {
118
+ seen.add(sibling);
119
+ const record = recordAt(state, sibling);
120
+ if (!record) break;
121
+ if (isElementType(record.type)) {
122
+ result.push(base + sibling);
123
+ if (isSingle) break;
124
+ }
125
+ sibling = isForward ? record.next : record.prev;
126
+ }
127
+ } else if (kind === 'siblings') {
128
+ const parent = node.parent == null ? null : recordAt(state, node.parent);
129
+ const local = id - base;
130
+ for (const other of parent?.children ?? []) if (other !== local && isElement(other)) result.push(base + other);
131
+ } else return undefined;
132
+ }
133
+ return result;
134
+ }
135
+
136
+ /** `traverseRecords` for one node of a current snapshot; false for kinds it leaves to records. */
137
+ function traverseSnapshot(snapshot: NodeSnapshot, base: number, local: number, kind: string, result: number[]): boolean {
138
+ const pushChildren = (parent: number, isElementsOnly: boolean, except: number): void => {
139
+ const count = snapshot.childCount(parent);
140
+ for (let index = 0; index < count; index++) {
141
+ const child = snapshot.childAt(parent, index);
142
+ if (child !== except && (!isElementsOnly || snapshot.isElementAt(child))) result.push(base + child);
143
+ }
144
+ };
145
+ switch (kind) {
146
+ case 'children': pushChildren(local, true, -1); return true;
147
+ case 'contents': pushChildren(local, false, -1); return true;
148
+ case 'siblings': {
149
+ const parent = snapshot.linkOf(local, 1);
150
+ if (parent !== null && snapshot.isPresent(parent)) pushChildren(parent, true, local);
151
+ return true;
152
+ }
153
+ case 'parent': {
154
+ const parent = snapshot.linkOf(local, 1);
155
+ if (parent !== null && snapshot.isPresent(parent) && snapshot.isElementAt(parent)) result.push(base + parent);
156
+ return true;
157
+ }
158
+ case 'parents': case 'ancestors': {
159
+ let parent = snapshot.linkOf(local, 1);
160
+ for (let steps = 0; parent !== null && steps < snapshot.size && snapshot.isPresent(parent) && !snapshot.isRootAt(parent); steps++) {
161
+ if (snapshot.isElementAt(parent)) result.push(base + parent);
162
+ parent = snapshot.linkOf(parent, 1);
163
+ }
164
+ return true;
165
+ }
166
+ case 'next': case 'prev': case 'nextAll': case 'prevAll': {
167
+ const offset = kind === 'next' || kind === 'nextAll' ? 3 : 2;
168
+ const isSingle = kind === 'next' || kind === 'prev';
169
+ let sibling = snapshot.linkOf(local, offset);
170
+ for (let steps = 0; sibling !== null && steps < snapshot.size && snapshot.isPresent(sibling); steps++) {
171
+ if (snapshot.isElementAt(sibling)) {
172
+ result.push(base + sibling);
173
+ if (isSingle) break;
174
+ }
175
+ sibling = snapshot.linkOf(sibling, offset);
176
+ }
177
+ return true;
178
+ }
179
+ default: return false;
180
+ }
181
+ }
182
+
183
+ /** The node object for an arena slot, created on first use and then shared. */
184
+ export function viewAt(state: DocumentState, local: number, knownType?: string): AnyNode | undefined {
185
+ const existing = state.views[local] ?? cachedView(state, local);
186
+ if (existing) { applyPendingRoot(state, local, existing); return existing as AnyNode; }
187
+ const parsed = state.adapterNodes?.[local];
188
+ if (parsed) {
189
+ state.adapterNodes![local] = undefined;
190
+ const view = adoptObject(state, local, parsed);
191
+ applyPendingRoot(state, local, view);
192
+ return view;
193
+ }
194
+ const snapshot = knownType ? undefined : structureSnapshot(state, local);
195
+ let constructor: ViewConstructor;
196
+ if (knownType && !state.options.sourceCodeLocationInfo) constructor = viewConstructor(state, knownType, false);
197
+ else if (snapshot && !snapshot.hasExtraFields(local)) constructor = viewConstructor(state, snapshot.typeOf(local), false);
198
+ else {
199
+ const record = recordAt(state, local);
200
+ if (!record) return undefined;
201
+ constructor = viewConstructor(state, record.type, record.sourceCodeLocation !== undefined);
202
+ }
203
+ const view = constructor(state, local);
204
+ cacheView(state, local, view);
205
+ applyPendingRoot(state, local, view);
206
+ return view as unknown as AnyNode;
207
+ }
208
+
209
+ /** A document root's node object, built without reading its record: its type is known. */
210
+ export function rootNode(document: NativeDocument, id: number): AnyNode {
211
+ if (!isRouted(document)) throw new TypeError('Native nodes require a routed document');
212
+ const state = stateIn(document, id);
213
+ const local = id - state.base;
214
+ const existing = cachedView(state, local);
215
+ if (existing) { applyPendingRoot(state, local, existing); return existing as AnyNode; }
216
+ if (state.adapterNodes?.[local] || state.options.sourceCodeLocationInfo) return viewAt(state, local) as AnyNode;
217
+ const view = (viewConstructor(state, 'root', false))(state, local);
218
+ cacheView(state, local, view);
219
+ applyPendingRoot(state, local, view);
220
+ return view as unknown as AnyNode;
221
+ }
222
+
223
+ /** Stable DOM node identities; each property reads or updates the Rust arena. */
224
+ export function getNode(document: NativeDocument, id: number, original?: any, knownType?: string): AnyNode {
225
+ if (!isRouted(document)) throw new TypeError('Native nodes require a routed document');
226
+ const state = stateIn(document, id);
227
+ const local = id - state.base;
228
+ if (original === undefined) return viewAt(state, local, knownType) as AnyNode;
229
+ const view = adoptObject(state, local, original);
230
+ applyPendingRoot(state, local, view);
231
+ return view;
232
+ }
233
+
234
+ export function getNodesOfType(document: NativeDocument, ids: number[], type: string): AnyNode[] {
235
+ if (!ids.length) return [];
236
+ const state = stateIn(document, ids[0]);
237
+ if (state.options.sourceCodeLocationInfo || state.adapterNodes) return ids.map((id) => getNode(document, id));
238
+ const constructor = viewConstructor(state, type, false);
239
+ const result = new Array<AnyNode>(ids.length);
240
+ for (let index = 0; index < ids.length; index++) {
241
+ const id = ids[index];
242
+ if (stateIn(document, id) !== state) {
243
+ result[index] = getNode(document, id);
244
+ continue;
245
+ }
246
+ const local = id - state.base;
247
+ let view = state.views[local] as AnyNode | undefined;
248
+ if (!view && (local >= state.baseline || state.weakViews.size)) view = cachedView(state, local) as AnyNode | undefined;
249
+ if (!view) {
250
+ view = constructor(state, local) as unknown as AnyNode;
251
+ cacheView(state, local, view);
252
+ }
253
+ if ((state as any)._pendingRoots) applyPendingRoot(state, local, view);
254
+ result[index] = view;
255
+ }
256
+ return result;
257
+ }
258
+
259
+ function viewRecord(view: View): NativeNodeRecord {
260
+ const state = view[VIEW_STATE];
261
+ const local = view[VIEW_LOCAL];
262
+ return state.records[local] ?? recordAt(state, local) ?? emptyRecord;
263
+ }
264
+
265
+ function linkedView(view: View, local: number | null | undefined): AnyNode | null {
266
+ return local == null ? null : viewAt(view[VIEW_STATE], local) ?? null;
267
+ }
268
+
269
+ function setField(view: View, field: string, value: unknown): void {
270
+ const state = view[VIEW_STATE];
271
+ operation(routedFor(state), 'setNode', { id: state.base + view[VIEW_LOCAL], field, value });
272
+ }
273
+
274
+ function setPointer(view: View, field: string, value: unknown): void {
275
+ setField(view, field, value == null ? null : importNodes(routedFor(view[VIEW_STATE]), [value])[0]);
276
+ }
277
+
278
+ function attributesOf(view: View): Record<string, string> {
279
+ const state = view[VIEW_STATE];
280
+ let attributes = view[VIEW_ATTRIBUTES];
281
+ if (!attributes) view[VIEW_ATTRIBUTES] = attributes = createAttributes(view, state.options._useHtmlParser2 === false ? null : Object.prototype);
282
+ const meta = attributes[ATTR_META]!;
283
+ if (meta.generation !== state.generation || meta.state !== state) syncAttributes(view, attributes);
284
+ return attributes;
285
+ }
286
+
287
+ /** Pushes a direct attribute write through to the node's native record (shared; no per-object closure). */
288
+ function writeAttributeThrough(view: unknown, attributes: AttributeObject, key: string, value: unknown): void {
289
+ const owner = view as View;
290
+ setField(owner, 'attribs', { ...viewRecord(owner).attribs, [key]: String(value) });
291
+ (attributes[ATTR_META] as AttributeMeta).values[key] = String(value);
292
+ }
293
+
294
+ function createAttributes(view: View, prototype: object | null): AttributeObject {
295
+ const attributes = Object.create(prototype) as AttributeObject;
296
+ setAttributeMeta(attributes, {
297
+ view,
298
+ generation: -1,
299
+ state: view[VIEW_STATE],
300
+ values: {},
301
+ write: writeAttributeThrough,
302
+ });
303
+ return attributes;
304
+ }
305
+
306
+ /** Copies the record's attributes into the shared accessors, preserving key order. */
307
+ function syncAttributes(view: View, attributes: AttributeObject): void {
308
+ const meta = attributes[ATTR_META]!;
309
+ const state = view[VIEW_STATE];
310
+ const local = view[VIEW_LOCAL];
311
+ if (meta.generation === -1) {
312
+ const snapshot = plainSnapshot(state, local);
313
+ if (snapshot) {
314
+ snapshot.copyAttributes(local, attributes);
315
+ meta.generation = state.generation;
316
+ return;
317
+ }
318
+ }
319
+ const values = viewRecord(view).attribs ?? {};
320
+ const nextKeys = Object.keys(values);
321
+ const currentKeys = Object.keys(attributes);
322
+ let isSameOrder = currentKeys.length === nextKeys.length;
323
+ for (let index = 0; isSameOrder && index < nextKeys.length; index++) isSameOrder = currentKeys[index] === nextKeys[index];
324
+ const stored = meta.values;
325
+ if (!isSameOrder) {
326
+ for (const key of currentKeys) {
327
+ delete attributes[key];
328
+ delete stored[key];
329
+ }
330
+ for (const key of nextKeys) defineAttributeKey(attributes, key, values[key]);
331
+ } else {
332
+ for (const key of nextKeys) {
333
+ // `__proto__` cannot be assigned through the store object: plain
334
+ // assignment would mutate the store's prototype.
335
+ if (key === '__proto__') { defineAttributeKey(attributes, key, values[key]); continue; }
336
+ if (stored[key] !== values[key]) stored[key] = values[key];
337
+ }
338
+ }
339
+ meta.generation = state.generation;
340
+ meta.state = state;
341
+ }
342
+
343
+ /** Re-reads attributes for a node whose attributes a native command changed. */
344
+ function refreshAttributes(view: object): void {
345
+ const attributes = (view as View)[VIEW_ATTRIBUTES];
346
+ if (attributes) syncAttributes(view as View, attributes);
347
+ }
348
+ onViewRefresh(refreshAttributes, fillChildren);
349
+
350
+ /** Namespace and prefix maps are rare; they read the record on every access. */
351
+ function attributeMap(view: View, field: 'attribsNamespace' | 'attribsPrefix'): Record<string, string> {
352
+ const read = (): Record<string, string> => (viewRecord(view) as any)[field] ?? {};
353
+ const target = Object.create(view[VIEW_STATE].options._useHtmlParser2 === false ? null : Object.prototype);
354
+ const viewField = `x-${field}`;
355
+ return new Proxy(target, {
356
+ get(_target, key) {
357
+ if (typeof key === 'symbol') return Reflect.get(target, key);
358
+ const values = read();
359
+ return Object.hasOwn(values, key) ? values[key] : Reflect.get(target, key);
360
+ },
361
+ set(_target, key, value) { setField(view, viewField, { ...read(), [key]: String(value) }); return true; },
362
+ deleteProperty(_target, key) { const values = { ...read() }; delete values[key as string]; setField(view, viewField, values); return true; },
363
+ ownKeys() { return Reflect.ownKeys(read()); },
364
+ has(_target, key) { return Object.hasOwn(read(), key) || key in target; },
365
+ getOwnPropertyDescriptor(_target, key) { const values = read(); return Object.hasOwn(values, key) ? { value: values[key as string], writable: true, enumerable: true, configurable: true } : undefined; },
366
+ defineProperty(_target, key, descriptor) { setField(view, viewField, { ...read(), [key]: String(descriptor.value) }); return true; },
367
+ });
368
+ }
369
+
370
+ /**
371
+ * A node's children: a real array of node objects, so reads cost what
372
+ * Cheerio's do. Its mutating methods write the whole list to Rust once, and
373
+ * the router refills the array in place whenever Rust reports the parent
374
+ * changed. Assigning an index or `length` directly changes only this array.
375
+ * `constructor` is `Array`, so arrays derived from it are plain.
376
+ */
377
+ class ChildArray extends Array<AnyNode> {
378
+ readonly #view: View;
379
+ constructor(view: View) {
380
+ super();
381
+ this.#view = view;
382
+ }
383
+ static viewOf(list: unknown): View | undefined {
384
+ return list instanceof ChildArray ? list.#view : undefined;
385
+ }
386
+ }
387
+ Object.defineProperty(ChildArray.prototype, 'constructor', { configurable: true, writable: true, value: Array });
388
+ for (const method of ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'copyWithin', 'fill'] as const) {
389
+ Object.defineProperty(ChildArray.prototype, method, {
390
+ configurable: true, writable: true,
391
+ value(this: ChildArray, ...args: unknown[]) {
392
+ const view = ChildArray.viewOf(this);
393
+ if (!view) return Reflect.apply((Array.prototype as any)[method], this, args);
394
+ const values = Array.from(this);
395
+ const result = Reflect.apply((Array.prototype as any)[method], values, args);
396
+ saveChildren(view, values);
397
+ return result === values ? this : result;
398
+ },
399
+ });
400
+ }
401
+
402
+ function saveChildren(view: View, values: unknown[]): void {
403
+ setField(view, 'children', importNodes(routedFor(view[VIEW_STATE]), values));
404
+ }
405
+
406
+ function childList(view: View): AnyNode[] {
407
+ const existing = view[VIEW_CHILDREN];
408
+ if (existing) return existing;
409
+ const state = view[VIEW_STATE];
410
+ if (state.baseline > 4096 && state.rootLocal !== undefined && view[VIEW_LOCAL] === state.rootLocal + 1) prepareWalkSnapshot(state);
411
+ if (!state.hasChildLists) { state.hasChildLists = true; state.raw.takeTouched?.(); }
412
+ const list = new ChildArray(view);
413
+ view[VIEW_CHILD_TARGET] = list;
414
+ view[VIEW_CHILDREN] = list;
415
+ fillChildren(view);
416
+ return list;
417
+ }
418
+
419
+ /** Rebuilds a materialized child array from the node's current record. */
420
+ function fillChildren(view: object): void {
421
+ const target = (view as View)[VIEW_CHILD_TARGET];
422
+ if (!target) return;
423
+ const state = (view as View)[VIEW_STATE];
424
+ const local = (view as View)[VIEW_LOCAL];
425
+ const snapshot = structureSnapshot(state, local);
426
+ if (snapshot && state.stale.size === 0) {
427
+ fillFromSnapshot(state, snapshot, local, target);
428
+ return;
429
+ }
430
+ const locals = viewRecord(view as View).children ?? [];
431
+ for (let index = 0; index < locals.length; index++) target[index] = viewAt(state, locals[index])!;
432
+ truncate(target, locals.length);
433
+ }
434
+
435
+ /**
436
+ * Children are written in order and the length is trimmed afterwards:
437
+ * presetting the length of a fresh array makes it holey and costs more than
438
+ * filling it.
439
+ */
440
+ function truncate(target: AnyNode[], length: number): void {
441
+ if (target.length !== length) target.length = length;
442
+ }
443
+
444
+ /**
445
+ * The common case of a walk: a node's children read straight from the
446
+ * snapshot arrays and cached strongly, with each type's constructor resolved
447
+ * once per snapshot instead of once per node.
448
+ */
449
+ function fillFromSnapshot(state: DocumentState, snapshot: NodeSnapshot, local: number, target: AnyNode[]): void {
450
+ const count = snapshot.childCount(local);
451
+ const first = snapshot.childStart(local);
452
+ const childIds = snapshot.childIds;
453
+ const views = state.views;
454
+ const isStrong = !state.adapterNodes;
455
+ const hasWeakViews = state.weakViews.size > 0;
456
+ const hasPendingRoots = !!(state as any)._pendingRoots;
457
+ const constructors = snapshotConstructors(state, snapshot);
458
+ for (let index = 0; index < count; index++) {
459
+ const child = childIds[first + index];
460
+ let node = (views[child] ?? (hasWeakViews ? cachedView(state, child) : undefined)) as AnyNode | undefined;
461
+ if (node === undefined) {
462
+ const constructor = isStrong && child < state.baseline && snapshot.isPlain(child) ? constructors(snapshot.typeReference(child)) : undefined;
463
+ if (constructor) views[child] = node = constructor(state, child) as unknown as AnyNode;
464
+ else node = viewAt(state, child)!;
465
+ }
466
+ if (hasPendingRoots) applyPendingRoot(state, child, node);
467
+ target[index] = node;
468
+ }
469
+ truncate(target, count);
470
+ }
471
+
472
+ function snapshotConstructors(state: DocumentState, snapshot: NodeSnapshot): (reference: number) => ViewConstructor {
473
+ let lookup = snapshot.viewConstructors as ((reference: number) => ViewConstructor) | undefined;
474
+ if (!lookup) {
475
+ const byReference: ViewConstructor[] = [];
476
+ lookup = (reference) => byReference[reference] ??= viewConstructor(state, snapshot.name(reference), false);
477
+ snapshot.viewConstructors = lookup;
478
+ }
479
+ return lookup;
480
+ }
481
+
482
+ type Accessor = { get(this: View): unknown; set(this: View, value: any): void };
483
+ const recordField = (field: string, fallback?: null): Accessor => ({
484
+ get() { return (viewRecord(this) as any)[field] ?? fallback; },
485
+ set(value) { setField(this, field, value); },
486
+ });
487
+ /** Fields read straight from the snapshot when it holds the node, without building a record. */
488
+ const snapshotField = (field: 'type' | 'name' | 'data'): Accessor => ({
489
+ get() {
490
+ const state = this[VIEW_STATE];
491
+ const local = this[VIEW_LOCAL];
492
+ const snapshot = field === 'data' ? plainSnapshot(state, local) : structureSnapshot(state, local);
493
+ if (snapshot) return field === 'type' ? snapshot.typeOf(local) : field === 'name' ? snapshot.nameOf(local) : snapshot.dataOf(local);
494
+ return (viewRecord(this) as any)[field];
495
+ },
496
+ set(value) { setField(this, field, value); },
497
+ });
498
+ const linkOffsets = { parent: 1, prev: 2, next: 3 } as const;
499
+ const pointerField = (field: 'parent' | 'prev' | 'next'): Accessor => ({
500
+ get() {
501
+ const state = this[VIEW_STATE];
502
+ const local = this[VIEW_LOCAL];
503
+ const snapshot = structureSnapshot(state, local);
504
+ return linkedView(this, snapshot ? snapshot.linkOf(local, linkOffsets[field]) : viewRecord(this)[field]);
505
+ },
506
+ set(value) { setPointer(this, field, value); },
507
+ });
508
+ const nodeAccessors: Record<string, Accessor> = {
509
+ type: snapshotField('type'),
510
+ parent: pointerField('parent'),
511
+ prev: pointerField('prev'),
512
+ next: pointerField('next'),
513
+ startIndex: recordField('startIndex', null),
514
+ endIndex: recordField('endIndex', null),
515
+ };
516
+ /** Present only on nodes parsed with location info, as in Cheerio. */
517
+ const locationAccessor: Accessor = { get() { return hydrateLocation(viewRecord(this).sourceCodeLocation); }, set(value) { setField(this, 'sourceCodeLocation', value); } };
518
+ const childAccessors: Record<string, Accessor> = {
519
+ children: { get() { return childList(this); }, set(value) { setField(this, 'children', importNodes(routedFor(this[VIEW_STATE]), value)); } },
520
+ };
521
+ const elementAccessors: Record<string, Accessor> = {
522
+ name: snapshotField('name'),
523
+ attribs: { get() { return attributesOf(this); }, set(value) { setField(this, 'attribs', value); } },
524
+ namespace: recordField('namespace'),
525
+ prefix: recordField('prefix'),
526
+ 'x-attribsNamespace': { get() { return viewRecord(this).attribsNamespace !== undefined ? attributeMap(this, 'attribsNamespace') : undefined; }, set(value) { setField(this, 'x-attribsNamespace', value); } },
527
+ 'x-attribsPrefix': { get() { return viewRecord(this).attribsPrefix !== undefined ? attributeMap(this, 'attribsPrefix') : undefined; }, set(value) { setField(this, 'x-attribsPrefix', value); } },
528
+ };
529
+ const dataAccessors: Record<string, Accessor> = { data: snapshotField('data') };
530
+ const directiveAccessors: Record<string, Accessor> = { name: recordField('name'), 'x-name': recordField('x-name'), 'x-publicId': recordField('x-publicId'), 'x-systemId': recordField('x-systemId') };
531
+ const documentAccessors: Record<string, Accessor> = { 'x-mode': recordField('x-mode') };
532
+
533
+ function accessorsFor(type: string): Record<string, Accessor> {
534
+ switch (type) {
535
+ case 'tag': case 'script': case 'style': return { ...nodeAccessors, ...childAccessors, ...elementAccessors };
536
+ case 'root': return { ...nodeAccessors, ...childAccessors, ...documentAccessors };
537
+ case 'cdata': return { ...nodeAccessors, ...childAccessors };
538
+ case 'directive': return { ...nodeAccessors, ...dataAccessors, ...directiveAccessors };
539
+ case 'text': case 'comment': return { ...nodeAccessors, ...dataAccessors };
540
+ default: return { ...nodeAccessors, ...childAccessors, ...dataAccessors, name: recordField('name') };
541
+ }
542
+ }
543
+
544
+ type ViewConstructor = (state: DocumentState, local: number) => View;
545
+ const viewConstructors = new Map<string, ViewConstructor>();
546
+ const plainConstructors: Record<string, ViewConstructor | undefined> = Object.create(null);
547
+
548
+ /**
549
+ * Legacy (Cheerio 0.22.0) node-shape rules, enabled per document through the
550
+ * `_legacyDom` option:
551
+ * - a top-level node's `parent` reads as null; its document root is exposed
552
+ * through the separate `root` field instead;
553
+ * - every node carries a writable `root` field, stored on the JavaScript side
554
+ * exactly like the plain-object field of the original library;
555
+ * - the synthetic root keeps its `name` of "root" and an `attribs` object.
556
+ */
557
+ const rootReferences = new WeakMap<object, unknown>();
558
+ function applyPendingRoot(state: DocumentState, local: number, view: unknown): void {
559
+ const pending = (state as any)._pendingRoots as Map<number, unknown> | undefined;
560
+ if (pending === undefined) return;
561
+ if (pending.has(local)) {
562
+ rootReferences.set(view as object, pending.get(local));
563
+ pending.delete(local);
564
+ if (pending.size === 0) (state as any)._pendingRoots = undefined;
565
+ }
566
+ }
567
+ export function setRootIfCached(document: NativeDocument, id: number, root: unknown): void {
568
+ const state = stateIn(document, id);
569
+ const local = id - state.base;
570
+ const view = cachedView(state, local);
571
+ if (view) { rootReferences.set(view, root); return; }
572
+ let pending = (state as any)._pendingRoots as Map<number, unknown> | undefined;
573
+ if (!pending) (state as any)._pendingRoots = pending = new Map();
574
+ pending.set(local, root);
575
+ }
576
+ /** Fast path for callers that already resolved state+local (e.g. static adjacent insert). */
577
+ export function setRootIfCachedLocal(state: DocumentState, local: number, root: unknown): void {
578
+ const view = cachedView(state, local);
579
+ if (view) { rootReferences.set(view, root); return; }
580
+ let pending = (state as any)._pendingRoots as Map<number, unknown> | undefined;
581
+ if (!pending) (state as any)._pendingRoots = pending = new Map();
582
+ pending.set(local, root);
583
+ }
584
+ const legacyParentAccessor: Accessor = {
585
+ get() {
586
+ const state = this[VIEW_STATE];
587
+ const local = this[VIEW_LOCAL];
588
+ const snapshot = structureSnapshot(state, local);
589
+ const parentLocal = snapshot ? snapshot.linkOf(local, 1) : viewRecord(this).parent;
590
+ if (parentLocal == null) return null;
591
+ if (parentLocal === state.rootLocal) return null;
592
+ return linkedView(this, parentLocal);
593
+ },
594
+ set(value) { setPointer(this, 'parent', value); },
595
+ };
596
+ const legacyRootAccessor: Accessor = {
597
+ get() { return rootReferences.get(this); },
598
+ set(value) { rootReferences.set(this, value); },
599
+ };
600
+
601
+ function legacyAccessors(type: string): Record<string, Accessor> {
602
+ const accessors: Record<string, Accessor> = { parent: legacyParentAccessor, root: legacyRootAccessor };
603
+ if (type === 'root') accessors.name = { get: () => 'root', set(value) { setField(this, 'name', value); } };
604
+ // domhandler 2.4.2 defines the DOM Lvl 1 aliases on every node prototype.
605
+ accessors.tagName = { get() { return this.name || null; }, set(value) { this.name = value; } };
606
+ accessors.nodeValue = { get() { return this.data || null; }, set(value) { this.data = value; } };
607
+ return accessors;
608
+ }
609
+
610
+ /**
611
+ * The own fields of a 0.22.0 node object, per node kind. Legacy views define
612
+ * these as own enumerable accessor properties so that enumeration
613
+ * (`Object.keys(node)`) and deep-equality checks behave like they do on the
614
+ * original plain-object nodes.
615
+ */
616
+ const legacyOwnFields: Record<string, string[]> = {
617
+ root: ['type', 'name', 'attribs', 'children', 'parent', 'prev', 'next'],
618
+ tag: ['type', 'name', 'attribs', 'children', 'parent', 'prev', 'next'],
619
+ script: ['type', 'name', 'attribs', 'children', 'parent', 'prev', 'next'],
620
+ style: ['type', 'name', 'attribs', 'children', 'parent', 'prev', 'next'],
621
+ cdata: ['type', 'children', 'parent', 'prev', 'next'],
622
+ directive: ['type', 'name', 'data', 'parent', 'prev', 'next'],
623
+ text: ['type', 'data', 'parent', 'prev', 'next'],
624
+ comment: ['type', 'data', 'parent', 'prev', 'next'],
625
+ };
626
+
627
+ /** One constructor per node shape so node objects share a hidden class and prototype. */
628
+ function viewConstructor(state: DocumentState, type: string, hasLocation: boolean): ViewConstructor {
629
+ const legacy = state.options._legacyDom === true;
630
+ const suffix = hasLocation ? ':location' : '';
631
+ const key = legacy ? `${type}${suffix}:legacy` : `${type}${suffix}`;
632
+ if (!hasLocation && !legacy) { const plain = plainConstructors[type]; if (plain) return plain; }
633
+ let constructor = viewConstructors.get(key);
634
+ if (constructor) return constructor;
635
+ const prototype = Object.create(nodePrototype(type));
636
+ let accessors = hasLocation ? { ...accessorsFor(type), sourceCodeLocation: locationAccessor } : accessorsFor(type);
637
+ if (legacy) accessors = { ...accessors, ...legacyAccessors(type), ...(type === 'root' ? { attribs: elementAccessors.attribs } : {}) };
638
+ const childrenDescriptor = 'children' in accessors ? { ...childAccessors.children, configurable: true, enumerable: true } : undefined;
639
+ for (const [field, accessor] of Object.entries(accessors)) Object.defineProperty(prototype, field, { ...accessor, configurable: true, enumerable: false });
640
+ const ownDescriptors: PropertyDescriptorMap = {};
641
+ if (childrenDescriptor) ownDescriptors.children = childrenDescriptor;
642
+ if (legacy) {
643
+ const fields = legacyOwnFields[type];
644
+ if (fields) {
645
+ for (const field of fields) {
646
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, field);
647
+ if (descriptor && (descriptor.get || descriptor.set)) ownDescriptors[field] = { get: descriptor.get, set: descriptor.set, configurable: true, enumerable: true };
648
+ }
649
+ }
650
+ }
651
+ const createView = legacy
652
+ ? () => Object.create(prototype, ownDescriptors) as View
653
+ : childrenDescriptor
654
+ ? () => Object.defineProperty(Object.create(prototype), 'children', childrenDescriptor) as View
655
+ : () => Object.create(prototype) as View;
656
+ constructor = function (state: DocumentState, local: number): View {
657
+ const view = createView();
658
+ view[VIEW_STATE] = state;
659
+ view[VIEW_LOCAL] = local;
660
+ view[VIEW_SELF] = view;
661
+ view[VIEW_ATTRIBUTES] = undefined;
662
+ view[VIEW_CHILD_TARGET] = undefined;
663
+ view[VIEW_CHILDREN] = undefined;
664
+ return view;
665
+ };
666
+ Object.defineProperty(prototype, inspectSymbol, { configurable: true, writable: true, value: inspectNode });
667
+ constructor.prototype = prototype;
668
+ viewConstructors.set(key, constructor);
669
+ if (!hasLocation && !legacy) plainConstructors[type] = constructor;
670
+ return constructor;
671
+ }
672
+
673
+ const inspectSymbol = Symbol.for('nodejs.util.inspect.custom');
674
+ const inspectedFields = ['type', 'name', 'data', 'attribs', 'namespace', 'startIndex', 'endIndex'];
675
+
676
+ /** Console output shows the node's fields instead of its native bookkeeping. */
677
+ function inspectNode(this: View, depth: number, options: object, inspect: (value: unknown, options: object) => string): string {
678
+ const fields: Record<string, unknown> = {};
679
+ for (const field of inspectedFields) if (field in this && this[field] != null) fields[field] = field === 'attribs' ? { ...this.attribs } : this[field];
680
+ if ('children' in this) fields.children = `[${this.children.length} nodes]`;
681
+ const name = Object.getPrototypeOf(Object.getPrototypeOf(this))?.constructor?.name ?? 'Node';
682
+ return depth < 0 ? `[${name}]` : `${name} ${inspect(fields, { ...options, depth: 1 })}`;
683
+ }
684
+
685
+ const adoptedAliases: PropertyDescriptorMap = {
686
+ parentNode: { configurable: true, enumerable: false, get(this: View) { return this.parent; }, set(this: View, value) { this.parent = value; } },
687
+ previousSibling: { configurable: true, enumerable: false, get(this: View) { return this.prev; }, set(this: View, value) { this.prev = value; } },
688
+ nextSibling: { configurable: true, enumerable: false, get(this: View) { return this.next; }, set(this: View, value) { this.next = value; } },
689
+ nodeType: { configurable: true, enumerable: false, get(this: View) { return ({ root: 9, text: 3, comment: 8, cdata: 4 } as Record<string, number>)[viewRecord(this).type] ?? 1; } },
690
+ cloneNode: { configurable: true, enumerable: false, writable: true, value: cloneNode },
691
+ };
692
+ const adoptedChildAliases: PropertyDescriptorMap = {
693
+ childNodes: { configurable: true, enumerable: false, get(this: View) { return this.children; }, set(this: View, value) { this.children = value; } },
694
+ firstChild: { configurable: true, enumerable: false, get(this: View) { return this.children[0] ?? null; } },
695
+ lastChild: { configurable: true, enumerable: false, get(this: View) { return this.children[this.children.length - 1] ?? null; } },
696
+ };
697
+ const adoptedElementAliases: PropertyDescriptorMap = {
698
+ tagName: { configurable: true, enumerable: false, get(this: View) { return this.name; }, set(this: View, value) { this.name = value; } },
699
+ attributes: { configurable: true, enumerable: false, get(this: View) { const attributes = this.attribs; const record = viewRecord(this); return Object.keys(attributes).map((name) => ({ name, value: attributes[name], namespace: record.attribsNamespace?.[name], prefix: record.attribsPrefix?.[name] })); } },
700
+ };
701
+ const adoptedDataAliases: PropertyDescriptorMap = {
702
+ nodeValue: { configurable: true, enumerable: false, get(this: View) { return this.data; }, set(this: View, value) { this.data = value; } },
703
+ };
704
+ const adoptedFields = new Map<string, PropertyDescriptorMap>();
705
+ const optionalAdoptedKeys = ['name', 'data', 'namespace', 'prefix', 'sourceCodeLocation', 'x-name', 'x-publicId', 'x-systemId', 'x-mode', 'x-attribsNamespace', 'x-attribsPrefix'];
706
+ const optionalAdoptedFields = new Set(optionalAdoptedKeys);
707
+ const adoptedShapes = new Map<string, PropertyDescriptorMap>();
708
+
709
+ /**
710
+ * Binds an object created outside the arena (a DOM constructor or a parser
711
+ * hook's node) to its native node, keeping the caller's object identity.
712
+ */
713
+ function adoptObject(state: DocumentState, local: number, original: any): AnyNode {
714
+ const record = recordAt(state, local);
715
+ if (!record) return undefined as unknown as AnyNode;
716
+ const view = original as View;
717
+ const attributesPrototype = original.attribs && typeof original.attribs === 'object' ? Object.getPrototypeOf(original.attribs) : undefined;
718
+ view[VIEW_STATE] = state;
719
+ view[VIEW_LOCAL] = local;
720
+ view[VIEW_SELF] = view;
721
+ view[VIEW_ATTRIBUTES] = undefined;
722
+ view[VIEW_CHILD_TARGET] = undefined;
723
+ view[VIEW_CHILDREN] = undefined;
724
+ let fields = adoptedFields.get(record.type);
725
+ if (!fields) {
726
+ fields = {};
727
+ for (const [key, accessor] of Object.entries({ ...accessorsFor(record.type), sourceCodeLocation: locationAccessor })) fields[key] = { ...accessor, configurable: true, enumerable: true };
728
+ adoptedFields.set(record.type, fields);
729
+ }
730
+ // Which optional fields a node has varies; each combination's full descriptor map is built once.
731
+ let shape = record.type;
732
+ for (const key of optionalAdoptedKeys) {
733
+ if (!(key in fields)) continue;
734
+ const field = key === 'x-attribsNamespace' ? 'attribsNamespace' : key === 'x-attribsPrefix' ? 'attribsPrefix' : key;
735
+ shape += (record as any)[field] !== undefined || Object.hasOwn(original, key) ? '1' : '0';
736
+ }
737
+ let descriptors = adoptedShapes.get(shape);
738
+ if (!descriptors) {
739
+ const present: PropertyDescriptorMap = {};
740
+ for (const key in fields) {
741
+ const field = key === 'x-attribsNamespace' ? 'attribsNamespace' : key === 'x-attribsPrefix' ? 'attribsPrefix' : key;
742
+ if (optionalAdoptedFields.has(key) && (record as any)[field] === undefined && !Object.hasOwn(original, key)) continue;
743
+ present[key] = fields[key];
744
+ }
745
+ const isParent = 'children' in present;
746
+ const isData = record.type === 'text' || record.type === 'comment' || record.type === 'directive';
747
+ descriptors = { ...present, ...adoptedAliases, ...(isParent ? adoptedChildAliases : {}), ...(isElementType(record.type) ? adoptedElementAliases : {}), ...(isData ? adoptedDataAliases : {}) };
748
+ adoptedShapes.set(shape, descriptors);
749
+ }
750
+ const isElement = isElementType(record.type);
751
+ try {
752
+ Object.defineProperties(view, descriptors);
753
+ } catch {
754
+ // Foreign user properties may be non-configurable; those keep their values.
755
+ }
756
+ if (isElement && attributesPrototype !== undefined) view[VIEW_ATTRIBUTES] = createAttributes(view, attributesPrototype);
757
+ cacheView(state, local, view);
758
+ return view as unknown as AnyNode;
759
+ }
760
+
761
+ /**
762
+ * Registers a tree adapter's nodes for the document's slots. Each node can be
763
+ * passed back to the API at once; its fields become live when first returned.
764
+ */
765
+ export function attachParsedNodes(state: DocumentState, nodes: (object | undefined)[]): void {
766
+ state.adapterNodes = nodes;
767
+ for (let local = 0; local < nodes.length; local++) {
768
+ const node = nodes[local] as View | undefined;
769
+ if (!node) continue;
770
+ node[VIEW_STATE] = state;
771
+ node[VIEW_LOCAL] = local;
772
+ node[VIEW_SELF] = node;
773
+ }
774
+ }
775
+
776
+ /** Clone through the receiver's current native owner, including borrowed calls. */
777
+ export function cloneNode<T extends AnyNode>(this: T, recursive = false): T {
778
+ const binding = nodeBinding(this);
779
+ if (!binding) throw new TypeError('cloneNode requires a native DOM node receiver');
780
+ return getNode(binding.document, operation<number[]>(binding.document, 'clone', { ids: [binding.id], deep: recursive })[0]) as T;
781
+ }
782
+
783
+ function childIds(document: NativeDocument, id: number): number[] {
784
+ const state = stateIn(document, id);
785
+ return (recordAt(state, id - state.base)?.children ?? []).map((child) => state.base + child);
786
+ }
787
+
788
+ /** Import external DOM nodes once and keep their object identities as handles. */
789
+ export function importNodes(document: NativeDocument, input: unknown): number[] {
790
+ if (input == null || input === false) return [];
791
+ const values: any[] = Array.isArray(input) || (typeof input === 'object' && 'length' in input && !('type' in input)) ? Array.from(input as ArrayLike<any>) : [input];
792
+ const result: number[] = [];
793
+ for (const node of values) {
794
+ if (node == null) continue;
795
+ const existing = node && typeof node === 'object' ? viewIdIn(document, node) : undefined;
796
+ if (existing !== undefined) { result.push(existing); continue; }
797
+ if (typeof node !== 'object' || typeof node.type !== 'string') continue;
798
+ const records: any[] = [];
799
+ const originals = new Map<number, any>();
800
+ const visit = (value: any, parent?: number): number => {
801
+ const id = records.length;
802
+ const record: any = { id, type: value.type, children: [], ...(parent === undefined ? {} : { parent }) };
803
+ records.push(record); originals.set(id, value);
804
+ for (const field of ['name', 'data', 'namespace', 'prefix', 'startIndex', 'endIndex', 'sourceCodeLocation', 'x-name', 'x-publicId', 'x-systemId', 'x-mode']) if (value[field] !== undefined) record[field] = value[field];
805
+ if (value.attribs) record.attribs = { ...value.attribs };
806
+ if (value['x-attribsNamespace']) record.attribsNamespace = { ...value['x-attribsNamespace'] };
807
+ if (value['x-attribsPrefix']) record.attribsPrefix = { ...value['x-attribsPrefix'] };
808
+ record.children = (value.children ?? []).map((child: any) => visit(child, id));
809
+ return id;
810
+ };
811
+ const root = visit(node);
812
+ const imported = operation<number[]>(document, 'import', { nodes: records, roots: [root] });
813
+ if (!imported.length) continue;
814
+ const adopt = (oldId: number, newId: number): void => {
815
+ const source = originals.get(oldId);
816
+ const oldChildren = records[oldId].children;
817
+ const newChildren = childIds(document, newId);
818
+ // A node already belonging to another Rust document must retain its
819
+ // original document handle. Imported clones receive their own handles.
820
+ getNode(document, newId, isNativeNode(source) ? undefined : source);
821
+ for (let i = 0; i < oldChildren.length; i++) if (newChildren[i] !== undefined) adopt(oldChildren[i], newChildren[i]);
822
+ };
823
+ adopt(root, imported[0]);
824
+ result.push(imported[0]);
825
+ }
826
+ return result;
827
+ }
828
+
829
+ export const isTag = (node: any): boolean => !!node && isElementType(node.type);
830
+ export const isDocument = (node: any): boolean => node?.type === 'root';
831
+ export const hasChildren = (node: any): boolean => !!node && 'children' in node;