/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/extract/dom * * Element tree snapshot over a native DOM ({@link NativeDoc}). * * The native bridge exposes selector queries and per-node reads but no * parent/child navigation. The element tree is rebuilt from three document * queries: `*` (pre-order), `:first-child` and `:last-child`. In pre-order an * element flagged `:first-child` is the first child of the previous element; * any other element is the next sibling of the nearest ancestor-or-self of the * previous element that is not a `:last-child`. Text and attributes are read * lazily through node ids, so nothing is re-parsed. */ import type { NativeDoc } from "../ffi/native-dom.ts"; import { normalizeText } from "./schema.ts"; export interface SnapshotNode { /** Pre-order position in {@link DomSnapshot.nodes}. */ index: number; /** Native node id (valid for `doc.tree` calls). */ id: number; tag: string; attrs: Record; /** Parent position, `-1` for the root element. */ parent: number; children: number[]; depth: number; /** Position of the last descendant (inclusive); `index` for leaves. */ end: number; } /** Elements whose content is never record data. */ export const SKIPPED_TAGS: ReadonlySet = new Set([ "script", "style", "noscript", "template", "head", "meta", "link", "title", "base", "svg", "path", "iframe", "br", "hr", "wbr", ]); /** A class token that looks machine-generated (CSS-in-JS, CSS modules hash). */ export function isHashedToken(token: string): boolean { if (/^(css|sc|jsx|emotion|styled|tw|chakra|mui|e\d+)-[a-z0-9]{4,}$/i.test(token)) return true; if (/^_?[a-z0-9]{5,8}$/i.test(token) && /\d/.test(token) && /[a-z]/i.test(token)) { const letters = token.replace(/[^a-z]/gi, ""); // Hashes mix digits with few vowel-bearing syllables. return !/[aeiou]{1}[a-z]{2,}/i.test(letters) || /\d.*[a-z].*\d/i.test(token); } return /__[a-z0-9]{5,}$/i.test(token) && /\d/.test(token.split("__").pop() ?? ""); } /** Class tokens with CSS-module hash suffixes stripped and hashed tokens removed. */ export function stableClassTokens(className: string | undefined): string[] { if (!className) return []; const out: string[] = []; for (const raw of className.split(/\s+/)) { if (!raw || isHashedToken(raw)) continue; if (!/^[a-z_-][a-z0-9_-]*$/i.test(raw)) continue; out.push(raw); } return out; } export function cssEscapeIdent(value: string): string { return value.replace(/([^a-zA-Z0-9_-])/g, "\\$1").replace(/^(\d)/, "\\3$1 "); } export function cssAttrValue(value: string): string { return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } export class DomSnapshot { readonly doc: NativeDoc; readonly nodes: SnapshotNode[]; readonly #byId = new Map(); readonly #text = new Map(); private constructor(doc: NativeDoc, nodes: SnapshotNode[]) { this.doc = doc; this.nodes = nodes; for (const node of nodes) this.#byId.set(node.id, node.index); } static build(doc: NativeDoc): DomSnapshot { const tree = doc.tree; const ids = tree.selectNodes("*"); const firsts = new Set(tree.selectNodes(":first-child")); const lasts = new Set(tree.selectNodes(":last-child")); const nodes: SnapshotNode[] = []; // Stack of ancestor-or-self positions of the previous element. const stack: number[] = []; for (const id of ids) { const index = nodes.length; let parent = -1; if (index > 0) { if (firsts.has(id)) { parent = stack[stack.length - 1] ?? -1; } else { // The previous element is a leaf: climb past trailing last children, // then replace the sibling we follow. while (stack.length > 0 && lasts.has(nodes[stack[stack.length - 1] as number]?.id ?? -1)) { stack.pop(); } stack.pop(); parent = stack[stack.length - 1] ?? -1; } } const parentNode = parent >= 0 ? nodes[parent] : undefined; const node: SnapshotNode = { index, id, tag: tree.tagName(id), attrs: tree.attributes(id), parent, children: [], depth: parentNode ? parentNode.depth + 1 : 0, end: index, }; parentNode?.children.push(index); nodes.push(node); stack.push(index); } for (let i = nodes.length - 1; i >= 0; i--) { const node = nodes[i] as SnapshotNode; const last = node.children[node.children.length - 1]; if (last !== undefined) node.end = (nodes[last] as SnapshotNode).end; } return new DomSnapshot(doc, nodes); } node(index: number): SnapshotNode { const node = this.nodes[index]; if (!node) throw new RangeError(`snapshot node ${index} out of range`); return node; } indexOfId(id: number): number | undefined { return this.#byId.get(id); } /** Normalized `textContent` (cached). */ text(index: number): string { const node = this.node(index); let text = this.#text.get(index); if (text === undefined) { text = SKIPPED_TAGS.has(node.tag) ? "" : normalizeText(this.doc.tree.textContent(node.id)); this.#text.set(index, text); } return text; } isAncestor(ancestor: number, descendant: number): boolean { const a = this.node(ancestor); return descendant > ancestor && descendant <= a.end; } /** Positions of `index` and its descendants, pre-order. */ *subtree(index: number): Generator { const node = this.node(index); for (let i = index; i <= node.end; i++) yield i; } /** Next element sibling position, or `-1`. */ nextSibling(index: number): number { const node = this.node(index); if (node.parent < 0) return -1; const siblings = this.node(node.parent).children; const at = siblings.indexOf(index); return siblings[at + 1] ?? -1; } ancestors(index: number): number[] { const out: number[] = []; let current = this.node(index).parent; while (current >= 0) { out.push(current); current = this.node(current).parent; } return out; } /** Positions matching `selector` inside `scope` (a position), document order. */ select(selector: string, scope?: number): number[] { const ids = this.doc.tree.selectNodes(selector, scope === undefined ? undefined : this.node(scope).id); const out: number[] = []; for (const id of ids) { const index = this.#byId.get(id); if (index !== undefined) out.push(index); } return out; } /** Like {@link select}, but returns `null` for an invalid selector. */ trySelect(selector: string, scope?: number): number[] | null { try { return this.select(selector, scope); } catch { return null; } } /** `` position (or the root element). */ body(): number { return this.nodes.find((n) => n.tag === "body")?.index ?? 0; } /** True when any ancestor-or-self has one of `tags`. */ insideTag(index: number, tags: ReadonlySet): boolean { let current = index; while (current >= 0) { const node = this.node(current); if (tags.has(node.tag)) return true; current = node.parent; } return false; } }