@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/router.ts ADDED
@@ -0,0 +1,1129 @@
1
+ import { packageDirectory, requireNative, type NativeDocument, type NativeNodeRecord } from './native.js';
2
+ import { hasParserHooks, parseNativeDocument } from './hooks.js';
3
+ import type { CheerioOptions } from './types.js';
4
+ import { NodeSnapshot, plainRecord, type NativeSnapshot } from './snapshot.js';
5
+ import { attributeAssign, type AttributeObject } from './attribute-object.js';
6
+
7
+ interface NativeMemoryStats { live: number; slots: number; retained: number; reclaimed: number; immutableNodes: number; externalBytes: number }
8
+ interface PinnedCollection extends NativeMemoryStats { free: Uint32Array }
9
+ interface ManagedNativeDocument extends NativeDocument {
10
+ setAttribute?(ids: number[], name: string, value: string | null): void;
11
+ addClass?(ids: number[], name: string): void;
12
+ insertHtml?(targetIds: number[], html: string, position: string): number[];
13
+ removeNodes?(ids: number[]): void;
14
+ slotCount?(): number;
15
+ routingIndex?(): number;
16
+ detachedSlots?(root: number): Uint32Array;
17
+ render?(ids: number[], optionsJson?: string): string;
18
+ snapshot?(): NativeSnapshot;
19
+ takeTouched?(): Uint32Array | null;
20
+ collectPinned?(pins: Uint32Array, keepBelow?: number): PinnedCollection;
21
+ collectGarbage?(): NativeMemoryStats;
22
+ isCollectionDue?(): boolean;
23
+ }
24
+
25
+ /**
26
+ * A node id is `state.base + local`, where `local` indexes the node in its
27
+ * native arena. Ids from different documents never collide, so every routed
28
+ * document shares one id space without a lookup table per node.
29
+ */
30
+ const STRIDE = 2 ** 32;
31
+ /** Ids must stay exact doubles, which bounds how many documents may be alive at once. */
32
+ const maximumDocuments = 2 ** 21;
33
+ /** A document's root is its first slot; collections keep it and everything attached to it. */
34
+ const rootSlots = 1;
35
+
36
+ /**
37
+ * Ids held by a JavaScript owner. Collection keeps them; moves rewrite them in
38
+ * place. The finalization registry holds only the token, which references
39
+ * nothing: its cleanup runs only once the event loop turns, and anything it
40
+ * held would keep documents of a synchronous loop alive until then.
41
+ */
42
+ export interface Lease { ids: number[]; token: LeaseToken; states: DocumentState[] }
43
+ interface LeaseToken { isReleased: boolean }
44
+
45
+ /**
46
+ * JavaScript `.data()` storage for one node; moves carry it to the node's new
47
+ * arena. A collection that frees the node releases it, so data objects still
48
+ * held no longer write to whatever node reuses the slot.
49
+ */
50
+ export interface DataEntry { state: DocumentState; local: number; data?: object; isReleased?: boolean }
51
+
52
+ /** Bookkeeping for one native document. */
53
+ export interface DocumentState {
54
+ readonly raw: ManagedNativeDocument;
55
+ readonly base: number;
56
+ /** The id space the state's base belongs to: another copy of the package numbers its documents separately. */
57
+ readonly space: object;
58
+ readonly options: CheerioOptions;
59
+ rootLocal: number | undefined;
60
+ routed: RoutedDocument | undefined;
61
+ generation: number;
62
+ records: (NativeNodeRecord | null | undefined)[];
63
+ bulk: NodeSnapshot | number;
64
+ snapshotSize: number;
65
+ /** Nodes whose snapshot entry is outdated by a targeted write. */
66
+ stale: Set<number>;
67
+ /**
68
+ * Node objects for slots that existed at parse time, until a collection
69
+ * finds their nodes detached; an array read is far cheaper than a map
70
+ * lookup.
71
+ */
72
+ views: (object | undefined)[];
73
+ /** Node objects for slots created later, until a collection finds their nodes detached. */
74
+ looseViews: Map<number, object>;
75
+ /** Size of `looseViews` at which a collection is scheduled. */
76
+ looseViewLimit: number;
77
+ /** Node objects for detached nodes, kept only while something else holds them. */
78
+ weakViews: Map<number, WeakRef<object>>;
79
+ /** Slots that existed when the document was parsed. */
80
+ baseline: number;
81
+ /** Later collections to run while weakened node objects may still become unreachable. */
82
+ collectionRetries: number;
83
+ /** Whether a collection was due but the document left the pending list; its next use schedules it again. */
84
+ isCollectionEvicted: boolean;
85
+ /** Whether the native document holds a snapshot built while parsing, valid until the first write. */
86
+ hasPreparedSnapshot: boolean;
87
+ leases: Set<Lease>;
88
+ /** Lease count at which released leases are swept. */
89
+ leaseSweepSize: number;
90
+ data: Map<number, DataEntry>;
91
+ /**
92
+ * Whether the id table resolves this document. Only ids that reach another
93
+ * document need it, and the `WeakRef` it takes keeps the document alive
94
+ * until the current job ends.
95
+ */
96
+ isExposed: boolean;
97
+ /**
98
+ * Documents whose ids this document's selections or leases may hold. A
99
+ * document's index is reused once it is collected, so holders keep it.
100
+ */
101
+ /** Some node object holds a child array that must follow structural writes. */
102
+ hasChildLists: boolean;
103
+ /** A tree adapter's nodes not yet returned to the caller, by slot. */
104
+ adapterNodes?: (object | undefined)[];
105
+ }
106
+
107
+ /** Fields on node objects; registered symbols so ESM and CJS copies share nodes. */
108
+ export const VIEW_STATE = Symbol.for('cheerox.node.state');
109
+ export const VIEW_LOCAL = Symbol.for('cheerox.node.local');
110
+ export const VIEW_ATTRIBUTES = Symbol.for('cheerox.node.attributes');
111
+ /** Points at the node itself, so a spread copy of a node is not mistaken for it. */
112
+ export const VIEW_SELF = Symbol.for('cheerox.node.self');
113
+ // Internals are own properties under symbols: reads stay plain property
114
+ // loads, which prototype accessors are not on selections of many documents'
115
+ // classes, and selections enumerate like Cheerio's. Registered symbols let
116
+ // the ESM and CommonJS builds read each other's selections.
117
+ export const DOCUMENT: unique symbol = Symbol.for('cheerox.selection.document');
118
+ export const API: unique symbol = Symbol.for('cheerox.selection.api');
119
+ export const IDS: unique symbol = Symbol.for('cheerox.selection.ids');
120
+ export const VALUES: unique symbol = Symbol.for('cheerox.selection.values');
121
+ export const LEASE: unique symbol = Symbol.for('cheerox.selection.lease');
122
+ export const IS_PLAIN: unique symbol = Symbol.for('cheerox.selection.is-plain');
123
+ /** A node object's materialized `children` array, refilled when the node's children change. */
124
+ export const VIEW_CHILD_TARGET = Symbol.for('cheerox.node.child-target');
125
+
126
+ interface Registry {
127
+ space: object;
128
+ /** Writes to any document, so callers can tell whether values they read earlier may be stale. */
129
+ writes: number;
130
+ states: (WeakRef<DocumentState> | undefined)[];
131
+ pending: Set<DocumentState>;
132
+ isScheduled: boolean;
133
+ leaseFinalizer: FinalizationRegistry<LeaseToken>;
134
+ }
135
+ // Each installed copy of the package loads its own addon, which numbers its
136
+ // documents independently, so only entry points of one copy share ids.
137
+ const registryKey = Symbol.for(`cheerox.native-documents.v5:${packageDirectory()}`);
138
+ /** A native document's state lives on the document itself, so they share one lifetime. */
139
+ const stateKey = Symbol.for('cheerox.native-documents.state');
140
+ const globals = globalThis as typeof globalThis & { [key: symbol]: Registry | undefined };
141
+ const registry: Registry = globals[registryKey] ??= (() => {
142
+ const created: Registry = {
143
+ space: {},
144
+ writes: 0,
145
+ states: [],
146
+ pending: new Set(),
147
+ isScheduled: false,
148
+ leaseFinalizer: new FinalizationRegistry((token) => { token.isReleased = true; }),
149
+ };
150
+ return created;
151
+ })();
152
+
153
+ /** The states owning `ids`, resolved through `document`. */
154
+ function statesOf(document: NativeDocument, ids: readonly number[]): DocumentState[] {
155
+ const states: DocumentState[] = [];
156
+ let previous: DocumentState | undefined;
157
+ for (const id of ids) {
158
+ // Selections may hold holes after direct index writes.
159
+ if (id === undefined) continue;
160
+ if (previous && id >= previous.base && id < previous.base + STRIDE) continue;
161
+ const state = stateIn(document, id);
162
+ if (!states.includes(state)) states.push(state);
163
+ previous = state;
164
+ }
165
+ return states;
166
+ }
167
+
168
+ /**
169
+ * Collects once a structural write leaves the arena grown by half with nodes
170
+ * removed; collecting sooner costs more than the garbage it would free.
171
+ */
172
+ function scheduleCollectionIfDue(state: DocumentState): void {
173
+ if (state.raw.isCollectionDue?.()) scheduleCollection(state);
174
+ }
175
+
176
+ /**
177
+ * Collections run on a later turn of the event loop: no library call is then
178
+ * between native writes holding ids of nodes it has just detached, and node
179
+ * objects weakened on an earlier turn may have been reclaimed.
180
+ */
181
+ function scheduleCollection(state: DocumentState): void {
182
+ registry.pending.add(state);
183
+ // Pending documents are held strongly until the event loop turns; in a
184
+ // synchronous loop only the latest few stay pinned. Holding the others
185
+ // weakly would pin them too: a WeakRef keeps its target until the
186
+ // synchronous job ends. An evicted document is scheduled again on its next
187
+ // use; one never used again is either collected whole or idle.
188
+ if (registry.pending.size > maximumPendingCollections) {
189
+ const evicted = registry.pending.values().next().value!;
190
+ registry.pending.delete(evicted);
191
+ evicted.isCollectionEvicted = true;
192
+ }
193
+ if (registry.isScheduled) return;
194
+ registry.isScheduled = true;
195
+ setImmediate(() => {
196
+ registry.isScheduled = false;
197
+ const states = [...registry.pending];
198
+ registry.pending.clear();
199
+ for (const pending of states) collectState(pending);
200
+ }).unref();
201
+ }
202
+
203
+ const maximumPendingCollections = 4;
204
+
205
+ /** Increases with every write to any document. */
206
+ export function writeCount(): number {
207
+ return registry.writes;
208
+ }
209
+
210
+ /**
211
+ * The state of a native document, created on first use. The addon hands out
212
+ * routing indexes and takes one back when its document is finalized, which
213
+ * happens during garbage collection, so indexes recycle even within a
214
+ * synchronous loop.
215
+ */
216
+ export function stateFor(raw: NativeDocument, options: CheerioOptions = {}): DocumentState {
217
+ const holder = raw as unknown as { [stateKey]?: DocumentState };
218
+ const existing = holder[stateKey];
219
+ if (existing) return existing;
220
+ const index = (raw as ManagedNativeDocument).routingIndex!();
221
+ if (index >= maximumDocuments) throw new RangeError('Too many documents are alive at once.');
222
+ const baseline = (raw as ManagedNativeDocument).slotCount?.() ?? 0;
223
+ const state: DocumentState = {
224
+ raw: raw as ManagedNativeDocument, base: index * STRIDE, space: registry.space, options, rootLocal: undefined, routed: undefined,
225
+ // Sized up front: node objects are cached out of order, and regrowing a holey array is costly.
226
+ generation: 0, records: [], bulk: 0, snapshotSize: 0, stale: new Set(), views: new Array(baseline), looseViews: new Map(), looseViewLimit: minimumLooseViewLimit, weakViews: new Map(), baseline,
227
+ leases: new Set(), leaseSweepSize: 64, data: new Map(), isExposed: false, hasChildLists: false, collectionRetries: 0, isCollectionEvicted: false, hasPreparedSnapshot: false,
228
+ };
229
+ holder[stateKey] = state;
230
+ return state;
231
+ }
232
+
233
+ /** Lets ids of `state` be resolved from documents other than its own. */
234
+ function exposeState(state: DocumentState): void {
235
+ if (state.isExposed) return;
236
+ state.isExposed = true;
237
+ registry.states[state.base / STRIDE] = new WeakRef(state);
238
+ }
239
+
240
+ /**
241
+ * Called before ids of `state` enter operations or selections of `document`.
242
+ * Leases keep the documents of the ids a selection holds; node objects keep
243
+ * their own.
244
+ */
245
+ export function exposeTo(document: NativeDocument, state: DocumentState): void {
246
+ if ((document as Partial<RoutedDocument>).state === state) return;
247
+ exposeState(state);
248
+ }
249
+
250
+ /** Called before a selection's ids enter operations of `document`. */
251
+ export function exposeDocumentTo(document: NativeDocument, source: NativeDocument | undefined): void {
252
+ const state = (source as Partial<RoutedDocument> | undefined)?.state;
253
+ if (state) exposeTo(document, state);
254
+ }
255
+
256
+ /** The node object cached for a slot, if any. */
257
+ export function cachedView(state: DocumentState, local: number): object | undefined {
258
+ const view = local < state.baseline ? state.views[local] : state.looseViews.get(local);
259
+ return view ?? (state.weakViews.size ? state.weakViews.get(local)?.deref() : undefined);
260
+ }
261
+
262
+ /** Created nodes held as objects only become collectable through a collection. */
263
+ const minimumLooseViewLimit = 1024;
264
+
265
+ export function cacheView(state: DocumentState, local: number, view: object): void {
266
+ if (local < state.baseline) { state.views[local] = view; return; }
267
+ state.looseViews.set(local, view);
268
+ if (state.looseViews.size >= state.looseViewLimit) {
269
+ state.looseViewLimit = state.looseViews.size * 2;
270
+ scheduleCollection(state);
271
+ }
272
+ }
273
+
274
+ function uncacheView(state: DocumentState, local: number): object | undefined {
275
+ const view = cachedView(state, local);
276
+ if (local < state.baseline) state.views[local] = undefined;
277
+ state.looseViews.delete(local);
278
+ state.weakViews.delete(local);
279
+ return view;
280
+ }
281
+
282
+ /** A collection drops released slots at the arena's end; later nodes reuse their indexes. */
283
+ function releaseSlotsFrom(state: DocumentState, end: number): void {
284
+ for (const local of state.data.keys()) if (local >= end) releaseSlot(state, local);
285
+ for (const local of state.weakViews.keys()) if (local >= end) state.weakViews.delete(local);
286
+ if (state.adapterNodes && state.adapterNodes.length > end) {
287
+ for (let local = end; local < state.adapterNodes.length; local++) releaseAdapterNode(state, local);
288
+ state.adapterNodes.length = end;
289
+ }
290
+ }
291
+
292
+ /** Forgets everything bound to a slot a collection freed. */
293
+ function releaseSlot(state: DocumentState, local: number): void {
294
+ uncacheView(state, local);
295
+ const entry = state.data.get(local);
296
+ if (entry) { entry.isReleased = true; state.data.delete(local); }
297
+ releaseAdapterNode(state, local);
298
+ }
299
+
300
+ /** Hands a freed slot's tree adapter object back to the caller: passed in again, it is imported like any other node. */
301
+ function releaseAdapterNode(state: DocumentState, local: number): void {
302
+ const adapterNode = state.adapterNodes?.[local] as Record<symbol, unknown> | undefined;
303
+ if (!adapterNode) return;
304
+ adapterNode[VIEW_SELF] = undefined;
305
+ state.adapterNodes![local] = undefined;
306
+ }
307
+
308
+ function hasViews(state: DocumentState): boolean {
309
+ return state.views.length > 0 || state.looseViews.size > 0 || state.weakViews.size > 0;
310
+ }
311
+
312
+ function forEachView(state: DocumentState, visit: (view: object, local: number) => void): void {
313
+ state.views.forEach((view, local) => { if (view) visit(view, local); });
314
+ for (const [local, view] of state.looseViews) visit(view, local);
315
+ for (const [local, reference] of state.weakViews) { const view = reference.deref(); if (view) visit(view, local); }
316
+ }
317
+
318
+ /**
319
+ * Node objects of detached nodes stay cached only while something else holds
320
+ * them, so a later collection can reclaim their nodes. The `WeakRef`s are
321
+ * taken during a collection rather than on removal: taking one keeps its
322
+ * target, and so its document, alive until the current job ends. Returns
323
+ * whether any node object was weakened.
324
+ */
325
+ function weakenDetachedViews(state: DocumentState): boolean {
326
+ if (!state.raw.detachedSlots) return false;
327
+ let isWeakened = false;
328
+ for (const local of state.raw.detachedSlots(state.rootLocal ??= state.raw.rootId())) {
329
+ const view = local < state.baseline ? state.views[local] : state.looseViews.get(local);
330
+ if (!view) continue;
331
+ if (local < state.baseline) state.views[local] = undefined;
332
+ else state.looseViews.delete(local);
333
+ state.weakViews.set(local, new WeakRef(view));
334
+ isWeakened = true;
335
+ }
336
+ return isWeakened;
337
+ }
338
+
339
+ /** The state owning `id` of a document whose ids have reached other documents. */
340
+ function exposedStateOf(id: number): DocumentState {
341
+ const state = registry.states[Math.floor(id / STRIDE)]?.deref();
342
+ if (!state || !(id >= 0)) throw new RangeError(`Unknown native node handle ${id}`);
343
+ return state;
344
+ }
345
+
346
+ /** The state owning `id`, resolved without the weak table when `document` owns it. */
347
+ export function stateIn(document: NativeDocument, id: number): DocumentState {
348
+ const own = (document as Partial<RoutedDocument>).state;
349
+ if (own === undefined || id < own.base || id >= own.base + STRIDE) return exposedStateOf(id);
350
+ if (own.isCollectionEvicted) resumeCollection(document);
351
+ return own;
352
+ }
353
+
354
+ /** Schedules again a collection that left the pending list before it ran. */
355
+ export function resumeCollection(document: NativeDocument): void {
356
+ const state = (document as Partial<RoutedDocument>).state;
357
+ if (!state?.isCollectionEvicted) return;
358
+ state.isCollectionEvicted = false;
359
+ scheduleCollection(state);
360
+ }
361
+
362
+ /** The node's record for the current generation, with ids local to `state`. */
363
+ export function recordAt(state: DocumentState, local: number): NativeNodeRecord | null {
364
+ const cached = state.records[local];
365
+ if (cached !== undefined) return cached;
366
+ const record = readRecord(state, local);
367
+ state.records[local] = record;
368
+ return record;
369
+ }
370
+
371
+ const minimumReadsBeforeSnapshot = 64;
372
+
373
+ /**
374
+ * Once individual reads in a generation cost about as much as copying every
375
+ * record, take one snapshot and decode the rest locally. A snapshot costs
376
+ * about two reads plus one read per hundred nodes, and a document read once
377
+ * is usually read again, so an unchanged document of under a hundred nodes
378
+ * takes one on its first read. Mutations start a new generation.
379
+ */
380
+ function readRecord(state: DocumentState, local: number): NativeNodeRecord | null {
381
+ const bulk = state.bulk;
382
+ if (bulk instanceof NodeSnapshot) {
383
+ const record = state.stale.size && state.stale.has(local) ? undefined : bulk.record(local);
384
+ if (record !== undefined) return record;
385
+ } else if (state.raw.snapshot) {
386
+ const reads = bulk + 1;
387
+ const size = Math.max(state.snapshotSize, state.baseline);
388
+ // An unchanged small document is read throughout; after a write, often only a few nodes are.
389
+ const firstSnapshotRead = state.generation === 0 ? size / 100 : 1 + size / 100;
390
+ if (reads >= Math.min(minimumReadsBeforeSnapshot, firstSnapshotRead)) {
391
+ const snapshot = new NodeSnapshot(takePreparedSnapshot(state, true) ?? state.raw.snapshot());
392
+ state.snapshotSize = snapshot.size;
393
+ state.bulk = snapshot;
394
+ const record = snapshot.record(local);
395
+ if (record !== undefined) return record;
396
+ } else state.bulk = reads;
397
+ }
398
+ return rawOperation(state.raw, 'node', { id: local });
399
+ }
400
+
401
+ /**
402
+ * Lets a routed document nothing has read or changed yet use the snapshot
403
+ * its native document built while parsing, when its reads first need one.
404
+ */
405
+ export function usePreparedSnapshot(document: NativeDocument): void {
406
+ if (!(document instanceof RoutedDocument)) return;
407
+ const state = document.state;
408
+ state.hasPreparedSnapshot = state.generation === 0 && state.bulk === 0;
409
+ }
410
+
411
+ function takePreparedSnapshot(state: DocumentState, isWanted: boolean): NativeSnapshot | undefined {
412
+ if (!state.hasPreparedSnapshot) return undefined;
413
+ state.hasPreparedSnapshot = false;
414
+ return state.raw.takePreparedSnapshot?.(isWanted) ?? undefined;
415
+ }
416
+
417
+ /** Start a full-tree walk from one compact record snapshot instead of a series of individual node reads. */
418
+ export function prepareWalkSnapshot(state: DocumentState): void {
419
+ if (state.generation !== 0 || state.bulk instanceof NodeSnapshot || !state.raw.snapshot || state.adapterNodes) return;
420
+ const snapshot = new NodeSnapshot(takePreparedSnapshot(state, true) ?? state.raw.snapshot());
421
+ state.snapshotSize = snapshot.size;
422
+ state.bulk = snapshot;
423
+ }
424
+
425
+ /** Prepare one compact snapshot before materializing a large selection from an unchanged document. */
426
+ export function prepareBulkViews(document: NativeDocument, ids: readonly number[]): void {
427
+ if (ids.length < 64 || !(document instanceof RoutedDocument)) return;
428
+ const state = document.state;
429
+ if (state.generation !== 0 || state.bulk instanceof NodeSnapshot || !state.raw.snapshot || state.adapterNodes) return;
430
+ // Avoid copying the whole tree for repeated IDs or already materialized
431
+ // views. Either case can satisfy toArray without many native record reads.
432
+ let unseen = 0;
433
+ let previous = -1;
434
+ for (const id of ids) {
435
+ const local = id - state.base;
436
+ if (local < 0 || local >= state.baseline) return;
437
+ if (unseen < 64 && !state.views[local] && (!state.weakViews.size || !cachedView(state, local))) {
438
+ // Document-ordered IDs are the common case. Other orders use the
439
+ // regular lazy path rather than allocating a set for this heuristic.
440
+ if (local <= previous) return;
441
+ previous = local;
442
+ unseen++;
443
+ }
444
+ }
445
+ if (unseen < 64) return;
446
+ const snapshot = new NodeSnapshot(takePreparedSnapshot(state, true) ?? state.raw.snapshot());
447
+ state.snapshotSize = snapshot.size;
448
+ state.bulk = snapshot;
449
+ }
450
+
451
+ /** The current snapshot when it holds `local` exactly, so its fields can be read without a record. */
452
+ export function plainSnapshot(state: DocumentState, local: number): NodeSnapshot | undefined {
453
+ const bulk = state.bulk;
454
+ return bulk instanceof NodeSnapshot && !(state.stale.size && state.stale.has(local)) && bulk.isPlain(local) ? bulk : undefined;
455
+ }
456
+
457
+ /**
458
+ * The current snapshot when it holds `local`'s type, name, links and
459
+ * children. Those are kept for every node, also one whose large text or
460
+ * attributes must be read individually.
461
+ */
462
+ export function structureSnapshot(state: DocumentState, local: number): NodeSnapshot | undefined {
463
+ const bulk = state.bulk;
464
+ return bulk instanceof NodeSnapshot && !(state.stale.size && state.stale.has(local)) && bulk.isPresent(local) ? bulk : undefined;
465
+ }
466
+
467
+ /** Nodes a JavaScript `text()` reads before leaving larger subtrees to the native engine. */
468
+ const snapshotTextBudget = 256;
469
+
470
+ /**
471
+ * The text of a small subtree read from the snapshot, as the native `text`
472
+ * concatenates it, or `undefined` to ask the native engine. Text too large
473
+ * for the snapshot is read once per snapshot, so repeated reads do not copy
474
+ * it out of the native tree again.
475
+ */
476
+ function textFromSnapshot(state: DocumentState, local: number): string | undefined {
477
+ let text = '';
478
+ const stack = [local];
479
+ for (let visited = 0; stack.length; visited++) {
480
+ const node = stack.pop()!;
481
+ const snapshot = structureSnapshot(state, node);
482
+ if (!snapshot || visited === snapshotTextBudget) return undefined;
483
+ if (snapshot.isTextAt(node)) {
484
+ text += snapshot.dataOf(node) ?? largeText(state, snapshot, node);
485
+ continue;
486
+ }
487
+ for (let index = snapshot.childCount(node) - 1; index >= 0; index--) stack.push(snapshot.childAt(node, index));
488
+ }
489
+ return text;
490
+ }
491
+
492
+ function largeText(state: DocumentState, snapshot: NodeSnapshot, local: number): string {
493
+ let text = snapshot.largeTexts.get(local);
494
+ if (text === undefined) snapshot.largeTexts.set(local, text = state.raw.text([local]));
495
+ return text;
496
+ }
497
+
498
+ /** A string attribute of an element, read like the native `attr` lookup. */
499
+ export function attributeAt(state: DocumentState, local: number, name: string): string | undefined {
500
+ const snapshot = plainSnapshot(state, local);
501
+ if (snapshot) return snapshot.attributeValue(local, name);
502
+ const attributes = recordAt(state, local)?.attribs as Record<string, unknown> | undefined;
503
+ const value = attributes && Object.hasOwn(attributes, name) ? attributes[name] : undefined;
504
+ return typeof value === 'string' ? value : undefined;
505
+ }
506
+
507
+ /** Starts a new generation: cached records may no longer match the arena. */
508
+ export function invalidate(state: DocumentState): void {
509
+ takePreparedSnapshot(state, false);
510
+ state.generation++;
511
+ state.records = [];
512
+ state.bulk = 0;
513
+ state.stale.clear();
514
+ }
515
+
516
+ function refreshSerializedNodes(state: DocumentState, options: CheerioOptions): void {
517
+ if (!options._useHtmlParser2 || options.xmlMode) return;
518
+ const touched = state.raw.takeTouched?.();
519
+ if (touched === null) invalidate(state);
520
+ else if (touched?.length) invalidateNodes(state, touched);
521
+ }
522
+
523
+ /** Discards the records of nodes a write changed without touching the tree's shape. */
524
+ function invalidateNodes(state: DocumentState, locals: Iterable<number>): void {
525
+ takePreparedSnapshot(state, false);
526
+ const isSnapshot = state.bulk instanceof NodeSnapshot;
527
+ const { records } = state;
528
+ for (const local of locals) {
529
+ // Writing past the end would grow the cache with holes, which V8 turns
530
+ // into a slow dictionary for far indexes.
531
+ if (records[local] !== undefined) records[local] = undefined;
532
+ if (isSnapshot) state.stale.add(local);
533
+ }
534
+ }
535
+
536
+ /** Keeps the ids of `document` that `owner` holds alive, and rewrites them when their nodes move. */
537
+ export function leaseNodes(document: NativeDocument, owner: object, ids: number[]): Lease {
538
+ const token: LeaseToken = { isReleased: false };
539
+ const states = statesOf(document, ids);
540
+ const lease: Lease = { ids, token, states };
541
+ for (const state of states) addLease(state, lease);
542
+ registry.leaseFinalizer.register(owner, token);
543
+ return lease;
544
+ }
545
+
546
+ /** Points a lease at a replacement id list. */
547
+ export function updateLease(document: NativeDocument, lease: Lease, ids: number[]): void {
548
+ lease.ids = ids;
549
+ lease.states = statesOf(document, ids);
550
+ for (const state of lease.states) addLease(state, lease);
551
+ }
552
+
553
+ function addLease(state: DocumentState, lease: Lease): void {
554
+ state.leases.add(lease);
555
+ if (state.leases.size < state.leaseSweepSize) return;
556
+ for (const held of state.leases) if (held.token.isReleased) state.leases.delete(held);
557
+ state.leaseSweepSize = state.leases.size * 2 + 64;
558
+ }
559
+
560
+ /** Weakened node objects become unreachable only after a later garbage collection. */
561
+ const collectionRetries = 3;
562
+
563
+ /** Reclaims removed nodes that no JavaScript owner references. */
564
+ export function collectState(state: DocumentState): NativeMemoryStats | undefined {
565
+ registry.pending.delete(state);
566
+ state.isCollectionEvicted = false;
567
+ if (!state.raw.collectPinned) return state.raw.collectGarbage?.();
568
+ if (weakenDetachedViews(state)) state.collectionRetries = collectionRetries;
569
+ const pins: number[] = [];
570
+ const { base } = state;
571
+ const end = base + STRIDE;
572
+ for (const lease of state.leases) {
573
+ if (lease.token.isReleased) { state.leases.delete(lease); continue; }
574
+ for (const id of lease.ids) if (id >= base && id < end) pins.push(id - base);
575
+ }
576
+ state.views.forEach((view, local) => { if (view) pins.push(local); });
577
+ for (const local of state.looseViews.keys()) pins.push(local);
578
+ for (const [local, reference] of state.weakViews) {
579
+ if (reference.deref()) pins.push(local);
580
+ else state.weakViews.delete(local);
581
+ }
582
+ const { free, ...stats } = state.raw.collectPinned(Uint32Array.from(pins), rootSlots);
583
+ invalidate(state);
584
+ for (const local of free) releaseSlot(state, local);
585
+ releaseSlotsFrom(state, stats.slots);
586
+ state.looseViewLimit = Math.max(minimumLooseViewLimit, state.looseViews.size * 2);
587
+ if (state.collectionRetries > 0 && state.weakViews.size > 0) {
588
+ state.collectionRetries--;
589
+ scheduleCollection(state);
590
+ }
591
+ return stats;
592
+ }
593
+
594
+ function rawOperation<T = any>(document: NativeDocument, command: string, args: any): T {
595
+ const result = document.op(command, JSON.stringify(args));
596
+ return result === '' || result === undefined ? undefined as T : JSON.parse(result);
597
+ }
598
+
599
+ /** Converts a record's local links to ids. */
600
+ function globalRecord(state: DocumentState, record: NativeNodeRecord | null): NativeNodeRecord | null {
601
+ if (!record) return null;
602
+ const { base } = state;
603
+ const link = (local: number | null | undefined): number | null => local == null ? null : base + local;
604
+ return { ...plainRecord(record), id: base + record.id, children: (record.children ?? []).map((child) => base + child), parent: link(record.parent), prev: link(record.prev), next: link(record.next) } as NativeNodeRecord;
605
+ }
606
+
607
+ const parentTypes = new Set(['root', 'tag', 'script', 'style', 'cdata']);
608
+ const pointerFields = new Set(['parent', 'parentNode', 'prev', 'previousSibling', 'next', 'nextSibling']);
609
+ const idResultCommands = new Set(['select', 'matches', 'uniqueSort', 'traverse', 'clone']);
610
+ const scratchCommands = new Set(['select', 'matches', 'uniqueSort', 'serializeArray', 'serialize', 'extractPlan']);
611
+ const writeCommands = new Set(['create', 'createNode', 'setNode', 'setAttrs', 'import', 'insert', 'clone', 'remove', 'removeAttr', 'removeData', 'addClass', 'removeClass', 'toggleClass']);
612
+ const attributeFields = new Set(['attribs', 'x-attribsNamespace', 'x-attribsPrefix']);
613
+ const targetedAttributeWrites = new Set(['attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'css']);
614
+ /** Writes that only change the records of their own ids. */
615
+ const recordOnlyWrites = new Set([...targetedAttributeWrites, 'data', 'removeData', 'setAttrs']);
616
+ const structuralWrites = new Set(['create', 'createNode', 'import', 'insert', 'clone', 'remove', 'html', 'text', 'data', 'removeData']);
617
+
618
+ /**
619
+ * Routes commands for ids from any document to the arena that owns them.
620
+ * Native adoption moves nodes between arenas; `moveInto` rewrites the ids that
621
+ * live owners hold so node identities survive the move.
622
+ */
623
+ export class RoutedDocument implements NativeDocument {
624
+ readonly nodeSpace = registry.space;
625
+ readonly options: CheerioOptions;
626
+ readonly state: DocumentState;
627
+ get raw(): ManagedNativeDocument { return this.state.raw; }
628
+
629
+ constructor(document: NativeDocument, options: CheerioOptions = {}) {
630
+ this.options = options;
631
+ this.state = stateFor(document, options);
632
+ }
633
+
634
+ /**
635
+ * Sets (or with `null` removes) an attribute, as the `attr` command does,
636
+ * through a typed native call. Attribute objects already handed out are
637
+ * updated in place instead of being read back.
638
+ */
639
+ setAttribute(ids: number[], name: string, value: string | null): void {
640
+ const own = this.state;
641
+ if (ids.length === 1 && own.raw.setAttribute) {
642
+ const id = ids[0];
643
+ if (id >= own.base && id < own.base + STRIDE) {
644
+ registry.writes++;
645
+ const local = id - own.base;
646
+ invalidateNodes(own, [local]);
647
+ own.raw.setAttribute([local], name, value);
648
+ const attributes = (cachedView(own, local) as Record<symbol, AttributeObject | undefined> | undefined)?.[VIEW_ATTRIBUTES];
649
+ if (attributes) attributeAssign(attributes, name, value);
650
+ return;
651
+ }
652
+ }
653
+ registry.writes++;
654
+ for (const { state, locals } of this.groups(ids)) {
655
+ if (!state.raw.setAttribute) { this.call(state, 'attr', { ids: locals, name, value }); continue; }
656
+ invalidateNodes(state, locals);
657
+ state.raw.setAttribute(locals, name, value);
658
+ for (const local of locals) {
659
+ const attributes = (cachedView(state, local) as Record<symbol, AttributeObject | undefined> | undefined)?.[VIEW_ATTRIBUTES];
660
+ if (attributes) attributeAssign(attributes, name, value);
661
+ }
662
+ }
663
+ }
664
+
665
+ addClass(ids: number[], name: string): void {
666
+ const own = this.state;
667
+ if (ids.length === 1 && own.raw.addClass) {
668
+ const id = ids[0];
669
+ if (id >= own.base && id < own.base + STRIDE) {
670
+ registry.writes++;
671
+ const local = id - own.base;
672
+ invalidateNodes(own, [local]);
673
+ own.raw.addClass([local], name);
674
+ const attributes = (cachedView(own, local) as Record<symbol, AttributeObject | undefined> | undefined)?.[VIEW_ATTRIBUTES];
675
+ if (attributes) attributeAssign(attributes, 'class', own.raw.attr(local, 'class') ?? null);
676
+ return;
677
+ }
678
+ }
679
+ registry.writes++;
680
+ for (const { state, locals } of this.groups(ids)) {
681
+ if (!state.raw.addClass) { this.call(state, 'addClass', { ids: locals, name }); continue; }
682
+ invalidateNodes(state, locals);
683
+ state.raw.addClass(locals, name);
684
+ for (const local of locals) {
685
+ const attributes = (cachedView(state, local) as Record<symbol, AttributeObject | undefined> | undefined)?.[VIEW_ATTRIBUTES];
686
+ if (attributes) attributeAssign(attributes, 'class', state.raw.attr(local, 'class') ?? null);
687
+ }
688
+ }
689
+ }
690
+
691
+ retainNode(id: number): void { this.owner(id); }
692
+ collectGarbage(): NativeMemoryStats | undefined { return collectState(this.state); }
693
+ retainNodeData(id: number, data: object): void { dataEntry(this.owner(id), id).data = data; }
694
+ nodeData(id: number): object | undefined { const state = this.owner(id); return state.data.get(id - state.base)?.data; }
695
+ nodeDataOperation(id: number): (command: string, args: any) => any {
696
+ const entry = dataEntry(this.owner(id), id);
697
+ const options = this.options;
698
+ // Resolve the entry's current arena on each call: the node may have moved.
699
+ return (command, args) => entry.isReleased ? undefined : routedFor(entry.state).operate(command, { ...args, ids: [entry.state.base + entry.local], options });
700
+ }
701
+ localNodeId(local: number): number { return this.state.base + local; }
702
+ rootId(): number { return this.state.base + (this.state.rootLocal ??= this.raw.rootId()); }
703
+ isOwnNode(id: number): boolean { return id >= this.state.base && id < this.state.base + STRIDE; }
704
+ private owner(id: number): DocumentState { return stateIn(this, id); }
705
+
706
+ private globals(state: DocumentState, locals: number[]): number[] {
707
+ const { base } = state;
708
+ return locals.map((local) => base + local);
709
+ }
710
+
711
+ private groups(ids: number[]): { state: DocumentState; locals: number[] }[] {
712
+ const groups: { state: DocumentState; locals: number[] }[] = [];
713
+ const own = this.state;
714
+ let last: { state: DocumentState; locals: number[] } | undefined;
715
+ for (const id of ids) {
716
+ const state = id >= own.base && id < own.base + STRIDE ? own : exposedStateOf(id);
717
+ if (last?.state === state) last.locals.push(id - state.base);
718
+ else groups.push(last = { state, locals: [id - state.base] });
719
+ }
720
+ return groups;
721
+ }
722
+
723
+ private call<T = any>(state: DocumentState, command: string, args: any): T {
724
+ if (command === 'extractPlan' && JSON.stringify(args.plan).includes('innerHTML')) invalidate(state);
725
+ const isWrite = Object.hasOwn(args, 'value') || writeCommands.has(command);
726
+ const recordOnlyWrite = recordOnlyWrites.has(command) || command === 'setNode' && attributeFields.has(args.field);
727
+ if (isWrite) {
728
+ registry.writes++;
729
+ const changed = recordOnlyWrites.has(command) ? args.ids ?? [] : command === 'setNode' && attributeFields.has(args.field) ? [args.id] : undefined;
730
+ if (changed) invalidateNodes(state, changed);
731
+ else invalidate(state);
732
+ }
733
+ const result = rawOperation(state.raw, command, { ...args, options: args.options ?? this.options });
734
+ const hasSerializedHtml = command === 'render' || command === 'outerHtml' || (command === 'html' && !isWrite) || (command === 'prop' && (args.name === 'innerHTML' || args.name === 'outerHTML'));
735
+ if (hasSerializedHtml) refreshSerializedNodes(state, args.options ?? this.options);
736
+ if (isWrite) {
737
+ refreshWrittenAttributes(state, command, args);
738
+ if (!recordOnlyWrite) { refreshChildLists(state); scheduleCollectionIfDue(state); }
739
+ }
740
+ return result;
741
+ }
742
+
743
+ /** Moves or copies nodes into `target`; returns their local ids there. */
744
+ private moveInto(target: DocumentState, ids: number[], isCopy = false): number[] {
745
+ if (!isCopy) {
746
+ for (const group of this.groups(ids)) {
747
+ if (group.state === target) continue;
748
+ if (!target.raw.adopt) throw new Error('The native addon does not support cross-document adoption. Rebuild the Rust addon.');
749
+ const adopted: { mapping: [number, number][] } = JSON.parse(target.raw.adopt(group.state.raw, group.locals, true));
750
+ rehome(group.state, target, adopted.mapping, ids);
751
+ refreshChildLists(group.state);
752
+ refreshChildLists(target);
753
+ scheduleCollectionIfDue(group.state);
754
+ }
755
+ return ids.map((id) => id - target.base);
756
+ }
757
+ const result: number[] = [];
758
+ for (const group of this.groups(ids)) {
759
+ if (group.state === target) {
760
+ result.push(...this.call<number[]>(target, 'clone', { ids: group.locals, deep: true }));
761
+ continue;
762
+ }
763
+ if (!target.raw.adopt) throw new Error('The native addon does not support cross-document adoption. Rebuild the Rust addon.');
764
+ invalidate(target);
765
+ const adopted: { roots: number[] } = JSON.parse(target.raw.adopt(group.state.raw, group.locals, false));
766
+ result.push(...adopted.roots);
767
+ }
768
+ return result;
769
+ }
770
+
771
+ private scratch(command: string, args: any, ids: number[]): any {
772
+ const states = [...new Set(ids.map((id) => this.owner(id)))];
773
+ const scratch = new (requireNative().NativeDocument)('', false, JSON.stringify(args.options ?? this.options));
774
+ const toScratch = new Map<number, number>();
775
+ const fromScratch = new Map<number, number>();
776
+ for (const state of states) {
777
+ const roots = state.raw.forestRoots?.() ?? (JSON.parse(state.raw.exportTree()) as NativeNodeRecord[]).filter((record) => record.parent == null).map((record) => record.id);
778
+ if (!scratch.adopt) throw new Error('The native addon does not support native document copies.');
779
+ const copied: { mapping: [number, number][] } = JSON.parse(scratch.adopt(state.raw, roots, false));
780
+ for (const [local, copy] of copied.mapping) {
781
+ const global = state.base + local;
782
+ toScratch.set(global, copy); fromScratch.set(copy, global);
783
+ }
784
+ }
785
+ const translated = { ...args };
786
+ for (const key of ['ids', 'contexts']) if (Array.isArray(args[key])) translated[key] = args[key].map((id: number) => toScratch.get(id)).filter((id: number | undefined) => id !== undefined);
787
+ if (args.pseudoMatches) translated.pseudoMatches = Object.fromEntries(Object.entries(args.pseudoMatches).map(([key, values]) => [key, (values as number[]).map((id) => toScratch.get(id)).filter((id) => id !== undefined)]));
788
+ const result = rawOperation(scratch, command, { ...translated, options: translated.options ?? this.options });
789
+ return ['select', 'matches', 'uniqueSort'].includes(command) ? (result as number[]).map((id) => fromScratch.get(id)!).filter((id) => id !== undefined) : result;
790
+ }
791
+
792
+ private isMixed(groups: { state: DocumentState }[]): boolean {
793
+ return groups.length > 1 && groups.some((group) => group.state !== groups[0].state);
794
+ }
795
+
796
+ select(selector: string, contexts?: number[]): number[] {
797
+ const ids = contexts ?? [this.rootId()];
798
+ if (!ids.length) return this.call(this.state, 'select', { selector, contexts: [] });
799
+ if (ids.length === 1) {
800
+ const own = this.state;
801
+ const id = ids[0];
802
+ if (id >= own.base && id < own.base + STRIDE) {
803
+ const found = own.raw.select(selector, [id - own.base]);
804
+ return this.globals(own, found);
805
+ }
806
+ }
807
+ const groups = this.groups(ids);
808
+ if (this.isMixed(groups)) return this.scratch('select', { selector, contexts: ids }, ids);
809
+ const group = groups[0];
810
+ const found = group.state === this.state ? group.state.raw.select(selector, group.locals) : this.call<number[]>(group.state, 'select', { selector, contexts: group.locals });
811
+ return this.globals(group.state, found);
812
+ }
813
+ text(ids: number[]): string {
814
+ if (ids.length === 1) {
815
+ const state = this.owner(ids[0]);
816
+ const text = textFromSnapshot(state, ids[0] - state.base);
817
+ if (text !== undefined) return text;
818
+ }
819
+ return this.groups(ids).map((group) => group.state.raw.text(group.locals)).join('');
820
+ }
821
+ innerHtml(id: number): string {
822
+ const state = this.owner(id);
823
+ const local = id - state.base;
824
+ // Serializing template content splices its fragment into the element.
825
+ const isSplicing = recordAt(state, local)?.children?.some((child) => recordAt(state, child)?.type === 'root') ?? false;
826
+ if (isSplicing) invalidate(state);
827
+ const html = state === this.state ? state.raw.innerHtml(local) : this.call<string>(state, 'html', { ids: [local] });
828
+ if (state === this.state) refreshSerializedNodes(state, state.options);
829
+ if (isSplicing && state.hasChildLists && childRefresher) forEachView(state, childRefresher);
830
+ return html;
831
+ }
832
+ outerHtml(ids: number[]): string {
833
+ return this.groups(ids).map((group) => {
834
+ if (group.state !== this.state) return this.call<string>(group.state, 'render', { ids: group.locals });
835
+ const html = group.state.raw.outerHtml(group.locals);
836
+ refreshSerializedNodes(group.state, group.state.options);
837
+ return html;
838
+ }).join('');
839
+ }
840
+ attr(id: number, name: string): string | undefined { const state = this.owner(id); return this.call(state, 'attr', { ids: [id - state.base], name }) ?? undefined; }
841
+ tagName(id: number): string | undefined { const state = this.owner(id); return recordAt(state, id - state.base)?.name; }
842
+ exportTree(): string {
843
+ if (this.raw.exportTreeWithOffset) return this.raw.exportTreeWithOffset(this.state.base);
844
+ return JSON.stringify((JSON.parse(this.raw.exportTree()) as NativeNodeRecord[]).map((record) => globalRecord(this.state, record)));
845
+ }
846
+ create(html: string, contextId?: number): number[] { return this.operate('create', { html, contextId }); }
847
+
848
+ insertHtml(targetIds: number[], html: string, position: string): number[] | undefined {
849
+ const groups = this.groups(targetIds);
850
+ if (groups.length !== 1) return undefined;
851
+ const { state, locals } = groups[0];
852
+ const insertHtml = state.raw.insertHtml;
853
+ if (!insertHtml) return undefined;
854
+ registry.writes++;
855
+ invalidate(state);
856
+ const inserted = insertHtml.call(state.raw, locals, html, position);
857
+ if (state.hasChildLists) refreshChildLists(state);
858
+ scheduleCollectionIfDue(state);
859
+ return this.globals(state, inserted);
860
+ }
861
+
862
+ remove(ids: number[]): void {
863
+ registry.writes++;
864
+ for (const { state, locals } of this.groups(ids)) {
865
+ if (!state.raw.removeNodes) { this.call(state, 'remove', { ids: locals }); continue; }
866
+ invalidate(state);
867
+ state.raw.removeNodes(locals);
868
+ if (state.hasChildLists) refreshChildLists(state);
869
+ scheduleCollectionIfDue(state);
870
+ }
871
+ }
872
+
873
+ op(command: string, json: string): string { return JSON.stringify(this.operate(command, JSON.parse(json)) ?? null); }
874
+
875
+ operate(command: string, args: any): any {
876
+ const options = args.options ?? this.options;
877
+ const hasValue = Object.hasOwn(args, 'value');
878
+ if (command === 'node') { const state = this.owner(args.id); return globalRecord(state, recordAt(state, args.id - state.base)); }
879
+ if (command === 'createNode') return this.state.base + this.call<number>(this.state, command, args);
880
+ if (command === 'import') return this.globals(this.state, this.call(this.state, command, args));
881
+ if (command === 'create') {
882
+ const context = args.contextId == null ? undefined : this.owner(args.contextId);
883
+ const state = context ?? this.state;
884
+ const contextLocal = context ? args.contextId - context.base : undefined;
885
+ if (hasParserHooks(options)) {
886
+ const contextRecord = context ? recordAt(context, contextLocal!) : undefined;
887
+ const children = parsedChildren(args.html, { ...options, ...(contextRecord ? { __contextName: contextRecord.name, __contextNamespace: contextRecord.namespace } : {}) });
888
+ return this.globals(state, this.moveInto(state, children));
889
+ }
890
+ return this.globals(state, this.call(state, command, { ...args, contextId: contextLocal }));
891
+ }
892
+ if (command === 'setNode' || command === 'prop' && hasValue && (args.name === 'children' || args.name === 'childNodes' || pointerFields.has(args.name))) {
893
+ const field = command === 'setNode' ? args.field : args.name;
894
+ let result = null;
895
+ for (const id of command === 'setNode' ? [args.id] : args.ids ?? []) {
896
+ let state = this.owner(id);
897
+ let nodeId = id;
898
+ let value = args.value;
899
+ if (field === 'children' || field === 'childNodes') value = this.moveInto(state, value ?? []);
900
+ else if (pointerFields.has(field) && value != null) {
901
+ const pointer = this.owner(value);
902
+ if (pointer !== state) { const moved = [id]; this.moveInto(pointer, moved); nodeId = moved[0]; state = pointer; }
903
+ value = args.value - pointer.base;
904
+ }
905
+ const local = nodeId - state.base;
906
+ result = this.call(state, command, command === 'setNode' ? { ...args, id: local, value } : { ...args, ids: [local], value });
907
+ }
908
+ return result;
909
+ }
910
+ if (command === 'setAttrs') {
911
+ // Batched attribute writes: one native call per document group.
912
+ const groups = this.groups((args.writes ?? []).map((write: { id: number }) => write.id));
913
+ for (const group of groups) {
914
+ const byId = new Map<number, Array<{ name: string; value?: unknown }>>();
915
+ for (const write of args.writes ?? []) {
916
+ const state = this.owner(write.id);
917
+ if (state !== group.state) continue;
918
+ const local = write.id - state.base;
919
+ const list = byId.get(local) ?? [];
920
+ list.push({ name: write.name, value: write.value });
921
+ byId.set(local, list);
922
+ }
923
+ const writes = [...byId.entries()].map(([id, attrs]) => ({ id, attrs }));
924
+ this.call(group.state, command, { ids: [...byId.keys()], writes });
925
+ }
926
+ return null;
927
+ }
928
+ if (command === 'insert') {
929
+ const targets: number[] = args.targetIds ?? [];
930
+ const nodes: number[] = args.nodeIds ?? [];
931
+ const sameDocument = targets.length > 0 && this.groups([...targets, ...nodes]);
932
+ if (sameDocument && sameDocument.length === 1) {
933
+ // One native call clones for every target but the last, as the loop below does per target.
934
+ const { state } = sameDocument[0];
935
+ const inserted = this.call<number[]>(state, command, { ...args, targetIds: targets.map((id) => id - state.base), nodeIds: nodes.map((id) => id - state.base) });
936
+ return this.globals(state, inserted);
937
+ }
938
+ const result: number[] = [];
939
+ const isBesideTarget = args.position === 'before' || args.position === 'after';
940
+ for (let index = 0; index < targets.length; index++) {
941
+ const target = this.owner(targets[index]);
942
+ const targetLocal = targets[index] - target.base;
943
+ // As the native insert, skip targets that cannot receive nodes before
944
+ // moving any there: the nodes would leave their document for nothing.
945
+ const record = recordAt(target, targetLocal);
946
+ if (!record || !parentTypes.has(record.type) || (isBesideTarget && record.parent == null)) continue;
947
+ const local = this.moveInto(target, nodes, index + 1 < targets.length);
948
+ const inserted = this.call<number[]>(target, command, { ...args, targetIds: [targetLocal], nodeIds: local });
949
+ result.push(...this.globals(target, inserted));
950
+ }
951
+ return result;
952
+ }
953
+ if (command === 'html' && hasValue && hasParserHooks(options)) {
954
+ let result = null;
955
+ for (const id of args.ids ?? []) {
956
+ const state = this.owner(id);
957
+ const local = id - state.base;
958
+ const record = recordAt(state, local);
959
+ if (!record || !parentTypes.has(record.type)) continue;
960
+ const children = parsedChildren(String(args.value), { ...options, __contextName: record.name, __contextNamespace: record.namespace });
961
+ result = this.call(state, 'setNode', { id: local, field: 'children', value: this.moveInto(state, children), options });
962
+ }
963
+ return result;
964
+ }
965
+ if (command === 'contains') {
966
+ const container = args.container ?? args.parent;
967
+ const contained = args.contained ?? args.child;
968
+ const parent = this.owner(container);
969
+ const isSameDocument = contained >= parent.base && contained < parent.base + STRIDE;
970
+ return isSameDocument && this.call(parent, command, { container: container - parent.base, contained: contained - parent.base });
971
+ }
972
+ const ids: number[] = command === 'select' ? args.contexts ?? [this.rootId()] : args.ids ?? [];
973
+ const groups = this.groups(ids);
974
+ // Nodes owned by different documents compare equal in domutils' sort.
975
+ if (command === 'uniqueSort' && ids.length === 2 && groups.length === 2 && groups[0].state !== groups[1].state) return ids.slice();
976
+ // Positional filters operate on the input selection, so they need only the
977
+ // first or last matching element rather than copies of every source tree.
978
+ if (command === 'matches' && this.isMixed(groups) && !options.pseudos && !args.pseudoMatches && (args.selector === ':first' || args.selector === ':last')) {
979
+ const ordered = args.selector === ':first' ? groups : [...groups].reverse();
980
+ for (const group of ordered) {
981
+ const matches = this.call<number[]>(group.state, 'matches', { selector: '*', ids: group.locals, options });
982
+ if (matches.length) return [group.state.base + (args.selector === ':first' ? matches[0] : matches[matches.length - 1])];
983
+ }
984
+ return [];
985
+ }
986
+ if (this.isMixed(groups) && scratchCommands.has(command)) return this.scratch(command, { ...args, options }, ids) ?? null;
987
+ if (command === 'extractPlan') { const group = groups[0]; return this.call(group?.state ?? this.state, command, { ...args, options, ids: group?.locals ?? [] }) ?? null; }
988
+ if (idResultCommands.has(command)) {
989
+ const isSelect = command === 'select';
990
+ if (!groups.length && (isSelect || command === 'matches')) return this.call(this.state, command, { ...args, options, ids: [], ...(isSelect ? { contexts: [] } : {}) });
991
+ const result: number[] = [];
992
+ for (const group of groups) {
993
+ const pseudoMatches = args.pseudoMatches ? Object.fromEntries(Object.entries(args.pseudoMatches as Record<string, number[]>).map(([key, values]) => [key, values.filter((id) => id >= group.state.base && id < group.state.base + STRIDE).map((id) => id - group.state.base)])) : undefined;
994
+ const values = this.call<number[]>(group.state, command, { ...args, options, ids: group.locals, ...(isSelect ? { contexts: group.locals } : {}), ...(pseudoMatches ? { pseudoMatches } : {}) });
995
+ result.push(...this.globals(group.state, values));
996
+ }
997
+ return result;
998
+ }
999
+ if (command === 'render' && !hasValue) {
1000
+ const optionsJson = JSON.stringify(options);
1001
+ return groups.map((group) => group.state.raw.render ? group.state.raw.render(group.locals, optionsJson) : this.call<string>(group.state, command, { ...args, options, ids: group.locals })).join('');
1002
+ }
1003
+ if ((command === 'outerHtml' || command === 'text') && !hasValue) return groups.map((group) => this.call<string>(group.state, command, { ...args, options, ids: group.locals })).join('');
1004
+ if (command === 'hasClass') return groups.some((group) => this.call<boolean>(group.state, command, { ...args, options, ids: group.locals }));
1005
+ if (command === 'serializeArray' || command === 'serialize') return groups.length ? this.call(groups[0].state, command, { ...args, options, ids: groups[0].locals }) : command === 'serializeArray' ? [] : '';
1006
+ if (command === 'html') for (const group of groups) invalidate(group.state);
1007
+ const isWrite = hasValue || writeCommands.has(command);
1008
+ let result = null;
1009
+ for (const group of isWrite ? groups : groups.slice(0, 1)) result = this.call(group.state, command, { ...args, options, ids: group.locals });
1010
+ return result ?? null;
1011
+ }
1012
+ }
1013
+
1014
+ /** Parses `html` into a document of its own, whose children the caller then moves. */
1015
+ function parsedChildren(html: string, options: CheerioOptions): number[] {
1016
+ const parsed = parseNativeDocument(html, options, false) as RoutedDocument;
1017
+ exposeState(parsed.state);
1018
+ return (parsed.operate('node', { id: parsed.rootId() }) as NativeNodeRecord).children;
1019
+ }
1020
+
1021
+ function dataEntry(state: DocumentState, id: number): DataEntry {
1022
+ const local = id - state.base;
1023
+ let entry = state.data.get(local);
1024
+ if (!entry) state.data.set(local, entry = { state, local });
1025
+ return entry;
1026
+ }
1027
+
1028
+ /**
1029
+ * Moves the bookkeeping of adopted nodes to their new arena. Live owners'
1030
+ * id lists, node objects and data follow the nodes; `ids` is updated too.
1031
+ */
1032
+ function rehome(source: DocumentState, target: DocumentState, mapping: [number, number][], ids: number[]): void {
1033
+ registry.writes++;
1034
+ invalidate(source); invalidate(target);
1035
+ // Owners of the moved ids, including selections of the source's API, now hold ids of the target.
1036
+ exposeState(target);
1037
+ const moved = new Map<number, number>();
1038
+ for (const [oldLocal, newLocal] of mapping) {
1039
+ moved.set(source.base + oldLocal, target.base + newLocal);
1040
+ const node = uncacheView(source, oldLocal) as Record<symbol, unknown> | undefined;
1041
+ if (node) {
1042
+ node[VIEW_STATE] = target; node[VIEW_LOCAL] = newLocal; cacheView(target, newLocal, node);
1043
+ if (node[VIEW_CHILD_TARGET]) target.hasChildLists = true;
1044
+ }
1045
+ const entry = source.data.get(oldLocal);
1046
+ if (entry) { source.data.delete(oldLocal); entry.state = target; entry.local = newLocal; target.data.set(newLocal, entry); }
1047
+ const adapterNode = source.adapterNodes?.[oldLocal] as Record<symbol, unknown> | undefined;
1048
+ if (adapterNode) {
1049
+ source.adapterNodes![oldLocal] = undefined;
1050
+ (target.adapterNodes ??= [])[newLocal] = adapterNode;
1051
+ adapterNode[VIEW_STATE] = target; adapterNode[VIEW_LOCAL] = newLocal;
1052
+ }
1053
+ }
1054
+ const rewrite = (list: number[]): boolean => {
1055
+ let isTouched = false;
1056
+ for (let index = 0; index < list.length; index++) {
1057
+ const next = moved.get(list[index]);
1058
+ if (next !== undefined) { list[index] = next; isTouched = true; }
1059
+ }
1060
+ return isTouched;
1061
+ };
1062
+ // Leases first: `ids` may be a lease's own list, which must still hold the
1063
+ // moved ids for the lease to be found.
1064
+ for (const lease of [...source.leases]) {
1065
+ if (!rewrite(lease.ids)) continue;
1066
+ target.leases.add(lease);
1067
+ if (!lease.states.includes(target)) lease.states.push(target);
1068
+ if (!lease.ids.some((id) => id >= source.base && id < source.base + STRIDE)) {
1069
+ source.leases.delete(lease);
1070
+ lease.states = lease.states.filter((state) => state !== source);
1071
+ }
1072
+ }
1073
+ rewrite(ids);
1074
+ }
1075
+
1076
+ /** Keeps attribute objects that callers hold in step with native writes. */
1077
+ function refreshWrittenAttributes(state: DocumentState, command: string, args: any): void {
1078
+ if (!hasViews(state)) return;
1079
+ let locals: number[] | undefined;
1080
+ if (command === 'setAttrs') {
1081
+ locals = (args.writes ?? []).map((write: { id: number }) => write.id);
1082
+ } else if (targetedAttributeWrites.has(command)) locals = args.ids ?? [];
1083
+ else if (command === 'setNode') { if (!attributeFields.has(args.field)) return; locals = [args.id]; }
1084
+ else if (structuralWrites.has(command)) return;
1085
+ const refresh = (view: object | undefined): void => { if (view && (view as Record<symbol, unknown>)[VIEW_ATTRIBUTES]) attributeRefresher?.(view); };
1086
+ if (locals) for (const local of locals) refresh(cachedView(state, local));
1087
+ else forEachView(state, refresh);
1088
+ }
1089
+
1090
+ let attributeRefresher: ((view: object) => void) | undefined;
1091
+ let childRefresher: ((view: object) => void) | undefined;
1092
+
1093
+ /** Registers how node objects re-read their attributes and children after a native write. */
1094
+ export function onViewRefresh(attributes: (view: object) => void, children: (view: object) => void): void {
1095
+ attributeRefresher = attributes;
1096
+ childRefresher = children;
1097
+ }
1098
+
1099
+ /** Refills the child arrays of parents whose children a native write changed. */
1100
+ function refreshChildLists(state: DocumentState): void {
1101
+ if (!state.hasChildLists || !childRefresher) return;
1102
+ const touched = state.raw.takeTouched?.();
1103
+ if (touched === undefined) return;
1104
+ if (touched === null) { forEachView(state, childRefresher); return; }
1105
+ for (const local of touched) { const view = cachedView(state, local); if (view) childRefresher(view); }
1106
+ }
1107
+
1108
+ export function routeDocument(document: NativeDocument, options: CheerioOptions = {}): NativeDocument {
1109
+ return document.nodeSpace === registry.space ? document : new RoutedDocument(document, options);
1110
+ }
1111
+
1112
+ /** The unanchored routed document node objects of `state` use. */
1113
+ export function routedFor(state: DocumentState): RoutedDocument {
1114
+ return state.routed ??= new RoutedDocument(state.raw, state.options);
1115
+ }
1116
+
1117
+ export function sameNodeSpace(first: NativeDocument, second: NativeDocument): boolean {
1118
+ return first === second || !!first.nodeSpace && first.nodeSpace === second.nodeSpace;
1119
+ }
1120
+
1121
+ /** Whether ids of `state` belong to this copy of the package; nodes of another copy are foreign objects here. */
1122
+ export function isLocalState(state: DocumentState): boolean {
1123
+ return state.space === registry.space;
1124
+ }
1125
+
1126
+ /** Whether `document` routes ids through this registry. */
1127
+ export function isRouted(document: NativeDocument): boolean {
1128
+ return document.nodeSpace === registry.space;
1129
+ }