/**
* 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/structure
*
* Repeated-structure detection on a {@link DomSnapshot}.
*
* Candidate record groups:
* - sibling elements sharing a structural signature (tag + normalized class
* tokens + role), merged across parents with the same ancestor signature
* (grids split into rows);
* - periodic sibling sequences (`tr.athing, tr, tr.spacer` repeated,
* `dt, dd` pairs) where one record spans several consecutive siblings;
* - `
` data rows with a header mapping.
*
* Groups are ranked by member count, text mass, link density, descendant
* diversity and page region, and each gets a CSS selector verified against
* the native tree (stable itemprop/data/role/class/id selectors first,
* parent-anchored variants next, hashed classes last; no `nth-*`).
*/
import {
type DomSnapshot,
SKIPPED_TAGS,
cssAttrValue,
cssEscapeIdent,
isHashedToken,
stableClassTokens,
} from "./dom.ts";
export type RecordGroupKind = "siblings" | "table" | "periodic";
export interface RecordGroup {
kind: RecordGroupKind;
/** CSS selector selecting the record anchors. */
selector: string;
/** `true` when {@link selector} returns exactly {@link anchors}. */
exact: boolean;
/** Anchor positions (document order). */
anchors: number[];
/** Elements per record: the anchor and `span - 1` following siblings. */
span: number;
/** Structure score (higher is more record-like). */
score: number;
signature: string;
/** Header text per column (tables). */
columns?: string[];
}
export interface DetectOptions {
/** Minimum records in a group. Default 2. */
minRecords?: number;
/** Maximum groups returned. Default 12. */
maxGroups?: number;
}
const MODIFIER_TOKEN =
/(^(is|has|js|u|state)-)|(--)|^(active|selected|current|featured|promo|promoted|sale|new|first|last|odd|even|hidden|visible|open|closed|sponsored|highlight|highlighted|disabled|clearfix|col-.*|row|lazy|loaded)$/i;
const CHROME_TOKENS = /\b(nav|navbar|menu|footer|header|breadcrumbs?|pagination|pager|sidebar|toolbar|cookie|banner|social|share|skip)\b/i;
const CHROME_TAGS: ReadonlySet = new Set(["nav", "header", "footer", "aside", "form", "select"]);
/** Structural signature: tag, non-modifier class tokens (hashed ones kept), role. */
export function nodeSignature(snap: DomSnapshot, index: number): string {
const node = snap.node(index);
const classes = (node.attrs.class ?? "")
.split(/\s+/)
.filter((token) => token && !MODIFIER_TOKEN.test(token))
.sort();
const role = node.attrs.role ? `[${node.attrs.role}]` : "";
return `${node.tag}${classes.length ? `.${classes.join(".")}` : ""}${role}`;
}
function childTagSet(snap: DomSnapshot, index: number): Set {
return new Set(snap.node(index).children.map((c) => snap.node(c).tag));
}
function jaccard(a: Set, b: Set): number {
if (a.size === 0 && b.size === 0) return 1;
let inter = 0;
for (const x of a) if (b.has(x)) inter++;
return inter / (a.size + b.size - inter);
}
/** Record rows: the anchor followed by `span - 1` element siblings. */
export function recordRows(snap: DomSnapshot, anchor: number, span: number): number[] {
const rows = [anchor];
let current = anchor;
for (let i = 1; i < span; i++) {
current = snap.nextSibling(current);
if (current < 0) break;
rows.push(current);
}
return rows;
}
/** Detect and rank candidate record groups. */
export function detectRecordGroups(snap: DomSnapshot, options: DetectOptions = {}): RecordGroup[] {
const minRecords = Math.max(2, options.minRecords ?? 2);
const maxGroups = options.maxGroups ?? 12;
const body = snap.body();
const raw: Array> = [];
// 1. Sibling groups, merged across parents sharing an ancestor signature.
const merged = new Map();
const periodicMerged = new Map>();
for (const index of snap.subtree(body)) {
const node = snap.node(index);
if (SKIPPED_TAGS.has(node.tag) || node.children.length < minRecords) continue;
const bySignature = new Map();
for (const child of node.children) {
const tag = snap.node(child).tag;
if (SKIPPED_TAGS.has(tag)) continue;
const signature = nodeSignature(snap, child);
const list = bySignature.get(signature);
if (list) list.push(child);
else bySignature.set(signature, [child]);
}
const parentKey = `${nodeSignature(snap, index)}<${node.parent >= 0 ? nodeSignature(snap, node.parent) : ""}`;
for (const [signature, members] of bySignature) {
if (members.length < minRecords) continue;
const key = `${signature}<${parentKey}`;
const list = merged.get(key);
if (list) list.push(...members);
else merged.set(key, [...members]);
}
const periodic = periodicGroup(snap, index, minRecords);
if (periodic) {
const key = `${periodic.signature}<${parentKey}`;
const existing = periodicMerged.get(key);
if (existing) existing.anchors.push(...periodic.anchors);
else periodicMerged.set(key, periodic);
}
}
for (const [key, members] of merged) {
const anchors = dropOutliers(snap, outermost(snap, members.sort((a, b) => a - b)));
if (anchors.length < minRecords) continue;
raw.push({ kind: "siblings", anchors, span: 1, signature: key.split("<")[0] ?? key });
const inner = innerAnchors(snap, anchors);
if (inner.length >= minRecords) {
raw.push({ kind: "siblings", anchors: inner, span: 1, signature: nodeSignature(snap, inner[0] as number) });
}
}
for (const group of periodicMerged.values()) {
if (group.anchors.length >= minRecords) raw.push(group);
}
// 2. Tables with a header row.
for (const table of snap.subtree(body)) {
if (snap.node(table).tag !== "table") continue;
const group = tableGroup(snap, table, minRecords);
if (group) raw.push(group);
}
// 3. Score, deduplicate, select.
const seen = new Map>();
for (const group of raw) {
const key = `${group.anchors.join(",")}|${group.span}`;
const existing = seen.get(key);
if (!existing || (group.columns && !existing.columns)) seen.set(key, group);
}
const scored = [...seen.values()]
.map((group) => ({ ...group, score: scoreGroup(snap, group.anchors, group.span) }))
.filter((group) => group.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, maxGroups * 2);
const out: RecordGroup[] = [];
for (const group of scored) {
const { selector, exact } = selectorForNodes(snap, group.anchors);
if (!selector) continue;
out.push({ ...group, selector, exact });
if (out.length >= maxGroups) break;
}
return out;
}
/** Remove members nested inside other members. */
function outermost(snap: DomSnapshot, members: number[]): number[] {
const out: number[] = [];
for (const member of members) {
const last = out[out.length - 1];
if (last !== undefined && snap.isAncestor(last, member)) continue;
out.push(member);
}
return out;
}
/** Drop members whose child tag set diverges from the group majority. */
function dropOutliers(snap: DomSnapshot, members: number[]): number[] {
if (members.length < 3) return members;
const sets = members.map((m) => childTagSet(snap, m));
const counts = new Map();
for (const set of sets) for (const tag of set) counts.set(tag, (counts.get(tag) ?? 0) + 1);
const majority = new Set([...counts].filter(([, n]) => n * 2 >= members.length).map(([tag]) => tag));
return members.filter((_, i) => jaccard(sets[i] as Set, majority) >= 0.34);
}
/**
* Wrapper descent: when every anchor wraps one content element (`li > article`),
* the wrapped elements form a tighter group (wrappers used as ad slots drop out).
*/
function innerAnchors(snap: DomSnapshot, anchors: number[]): number[] {
const inner: number[] = [];
let signature: string | null = null;
for (const anchor of anchors) {
const children = snap.node(anchor).children.filter((c) => !SKIPPED_TAGS.has(snap.node(c).tag));
if (children.length !== 1) continue;
const child = children[0] as number;
const childSignature = nodeSignature(snap, child);
if (signature === null) signature = childSignature;
if (childSignature === signature) inner.push(child);
}
return inner.length >= Math.max(2, Math.ceil(anchors.length * 0.6)) ? inner : [];
}
function periodicGroup(
snap: DomSnapshot,
parent: number,
minRecords: number,
): Omit | null {
const children = snap.node(parent).children.filter((c) => !SKIPPED_TAGS.has(snap.node(c).tag));
if (children.length < 4) return null;
const signatures = children.map((c) => nodeSignature(snap, c));
for (let period = 2; period <= 4; period++) {
if (children.length < period * minRecords) continue;
for (let phase = 0; phase < period; phase++) {
const pattern = signatures.slice(phase, phase + period);
if (new Set(pattern).size < 2) continue;
const anchorSignature = pattern[0] as string;
if (pattern.indexOf(anchorSignature, 1) !== -1) continue;
const anchors: number[] = [];
let matched = 0;
let compared = 0;
for (let i = phase; i + period <= children.length; i += period) {
let ok = true;
for (let j = 0; j < period; j++) {
compared++;
if (signatures[i + j] === pattern[j]) matched++;
else if (j === 0) ok = false;
}
if (ok) anchors.push(children[i] as number);
}
if (anchors.length < minRecords || compared === 0 || matched / compared < 0.85) continue;
return { kind: "periodic", anchors, span: period, signature: `${pattern.join("+")}` };
}
}
return null;
}
function tableGroup(
snap: DomSnapshot,
table: number,
minRecords: number,
): Omit | null {
const rows: number[] = [];
const collect = (index: number): void => {
for (const child of snap.node(index).children) {
const tag = snap.node(child).tag;
if (tag === "tr") rows.push(child);
else if (tag === "thead" || tag === "tbody" || tag === "tfoot") collect(child);
}
};
collect(table);
let columns: string[] | undefined;
const dataRows: number[] = [];
for (const row of rows) {
const cells = snap.node(row).children.filter((c) => ["td", "th"].includes(snap.node(c).tag));
const inHead = snap.node(snap.node(row).parent).tag === "thead";
const allHeader = cells.length > 0 && cells.every((c) => snap.node(c).tag === "th");
if ((inHead || allHeader) && !columns && dataRows.length === 0) {
columns = cells.map((c) => snap.text(c));
continue;
}
if (cells.some((c) => snap.node(c).tag === "td")) dataRows.push(row);
}
if (!columns || dataRows.length < minRecords) return null;
return { kind: "table", anchors: dataRows, span: 1, signature: "table>tr", columns };
}
function scoreGroup(snap: DomSnapshot, anchors: number[], span: number): number {
const sample = anchors.length > 25 ? anchors.filter((_, i) => i % Math.ceil(anchors.length / 25) === 0) : anchors;
let text = 0;
let linkText = 0;
let elements = 0;
let diversity = 0;
for (const anchor of sample) {
const tags = new Set();
for (const row of recordRows(snap, anchor, span)) {
text += snap.text(row).length;
for (const index of snap.subtree(row)) {
const node = snap.node(index);
elements++;
tags.add(node.tag);
if (node.tag === "a") linkText += snap.text(index).length;
}
}
diversity += tags.size;
}
const n = sample.length;
const avgText = text / n;
if (avgText < 2) return 0;
const avgElements = elements / n;
const linkDensity = Math.min(1, linkText / Math.max(1, text));
const avgDiversity = diversity / n;
let region = 1;
for (const ancestor of snap.ancestors(anchors[0] as number)) {
const node = snap.node(ancestor);
const tokens = `${node.attrs.class ?? ""} ${node.attrs.id ?? ""} ${node.attrs.role ?? ""}`;
if (CHROME_TAGS.has(node.tag) || CHROME_TOKENS.test(tokens)) {
region = 0.35;
break;
}
if (node.tag === "main" || node.attrs.role === "main") region = Math.max(region, 1.25);
}
return (
Math.log2(anchors.length + 1) *
Math.sqrt(Math.min(avgText, 400)) *
(1 + Math.min(avgDiversity, 8) / 4) *
(1 - 0.6 * linkDensity) *
(avgElements >= 3 ? 1 : 0.5) *
region
);
}
// ---------------------------------------------------------------------------
// Selector synthesis
// ---------------------------------------------------------------------------
const DATA_KEY_ATTRS = ["data-testid", "data-test", "data-qa", "data-component", "data-type", "data-role", "data-cy"];
/** Simple (compound) selectors describing every node of `nodes`, best first. */
export function simpleSelectors(snap: DomSnapshot, nodes: number[], allowHashed = false): string[] {
const first = snap.node(nodes[0] as number);
const tag = first.tag;
const sameTag = nodes.every((n) => snap.node(n).tag === tag);
const prefix = sameTag ? tag : "";
const out: string[] = [];
const common = (name: string): string | undefined => {
const value = first.attrs[name];
if (value === undefined) return undefined;
return nodes.every((n) => snap.node(n).attrs[name] === value) ? value : undefined;
};
const itemprop = common("itemprop");
if (itemprop) out.push(`${prefix}[itemprop=${cssAttrValue(itemprop)}]`);
const itemtype = common("itemtype");
if (itemtype) out.push(`${prefix}[itemtype=${cssAttrValue(itemtype)}]`);
for (const name of DATA_KEY_ATTRS) {
const value = common(name);
if (value) out.push(`${prefix}[${name}=${cssAttrValue(value)}]`);
}
const role = common("role");
if (role) out.push(`${prefix}[role=${cssAttrValue(role)}]`);
const classSets = nodes.map((n) => new Set(stableClassTokens(snap.node(n).attrs.class)));
const shared = [...(classSets[0] ?? [])].filter(
(token) => !MODIFIER_TOKEN.test(token) && classSets.every((set) => set.has(token)),
);
for (const token of shared) out.push(`${prefix}.${cssEscapeIdent(token)}`);
if (shared.length > 1) out.push(`${prefix}${shared.map((t) => `.${cssEscapeIdent(t)}`).join("")}`);
for (const name of Object.keys(first.attrs)) {
if (!name.startsWith("data-") || DATA_KEY_ATTRS.includes(name)) continue;
if (nodes.every((n) => snap.node(n).attrs[name] !== undefined)) out.push(`${prefix}[${name}]`);
}
const id = first.attrs.id;
if (nodes.length === 1 && id && /^[a-z][a-z_-]*$/i.test(id) && !isHashedToken(id)) out.push(`#${cssEscapeIdent(id)}`);
if (prefix) out.push(prefix);
if (allowHashed) {
const hashed = [...new Set((first.attrs.class ?? "").split(/\s+/))].filter(
(token) => token && isHashedToken(token) && nodes.every((n) => (snap.node(n).attrs.class ?? "").split(/\s+/).includes(token)),
);
for (const token of hashed) out.push(`${prefix}.${cssEscapeIdent(token)}`);
}
return [...new Set(out)];
}
function sameSet(a: number[], b: number[]): boolean {
if (a.length !== b.length) return false;
const set = new Set(a);
return b.every((x) => set.has(x));
}
/**
* Selector returning `nodes` (document scope), verified natively. Prefers an
* exact match; otherwise the highest-precision selector covering every node.
*/
export function selectorForNodes(snap: DomSnapshot, nodes: number[], scope?: number): { selector: string; exact: boolean } {
let best: { selector: string; precision: number } | null = null;
const consider = (selector: string): boolean => {
const result = snap.trySelect(selector, scope);
if (!result) return false;
if (sameSet(result, nodes)) return true;
const set = new Set(result);
if (nodes.every((n) => set.has(n))) {
const precision = nodes.length / result.length;
if (!best || precision > best.precision) best = { selector, precision };
}
return false;
};
for (const allowHashed of [false, true]) {
const own = simpleSelectors(snap, nodes, allowHashed);
for (const selector of own) if (consider(selector)) return { selector, exact: true };
// Parent-anchored variants, climbing up to three ancestor levels.
let level = nodes.map((n) => snap.node(n).parent);
let chain = "";
for (let depth = 0; depth < 3; depth++) {
if (level.some((p) => p < 0)) break;
const unique = [...new Set(level)];
const parents = simpleSelectors(snap, unique, allowHashed).slice(0, 4);
for (const parent of parents) {
for (const child of own.slice(0, 4)) {
const selector = `${parent} > ${chain}${child}`;
if (consider(selector)) return { selector, exact: true };
}
}
const tagOnly = snap.node(unique[0] as number).tag;
if (!unique.every((p) => snap.node(p).tag === tagOnly)) break;
chain = `${tagOnly} > ${chain}`;
level = unique.map((p) => snap.node(p).parent);
}
}
const fallback = best as { selector: string; precision: number } | null;
return fallback ? { selector: fallback.selector, exact: false } : { selector: "", exact: false };
}