/** * 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/field-matcher * * Learns, for every schema leaf, a locator (relative CSS selector, label, * table column or structured-data path) plus a value accessor, and applies a * learned {@link ExtractionPlan} to a page. * * Candidates are generated from the nodes of sampled records and scored by: * - lexical similarity between the leaf name/description and node hints * (itemprop, class, id, data-*, rel, aria-label, dt/th labels, own text); * - a structural prior for the (type, tag, accessor) combination; * - type compatibility of the coerced values and their quality; * - coverage across records and value distinctiveness. * Leaves are assigned greedily by score; two leaves never share the same * extracted value sequence. */ import { type DomSnapshot, cssAttrValue, cssEscapeIdent, stableClassTokens } from "./dom.ts"; import { type Feature, type FieldTerms, conceptsOf, features, fieldTerms, lexicalScore } from "./lexicon.ts"; import { type CoerceContext, type FieldSpec, type LeafField, type NormalizedSchema, type ScalarType, coerceScalar, isFilled, leafFields, normalizeText, valueAt, } from "./schema.ts"; import { type StructuredEntry, structuredValue } from "./structured-data.ts"; import { type RecordGroup, recordRows, selectorForNodes } from "./structure.ts"; /** How a value is read from a located node. `auto` picks by field type. */ export type Accessor = "text" | "auto" | `attr:${string}`; export type LocatorStrategy = "css" | "self" | "label" | "column" | "structured"; export interface FieldLocator { /** Leaf key (`author.name`). */ key: string; strategy: LocatorStrategy; /** Row offset inside a multi-row record. */ offset?: number; /** CSS selector relative to the row (css) or inside the label value / cell. */ selector?: string; /** Normalized label text (label strategy). */ label?: string; /** Cell index (column strategy). */ column?: number; /** Structured-data address (structured strategy). */ path?: string; accessor: Accessor; /** Collect every match (array leaves). */ all?: boolean; confidence: number; } export interface ExtractionPlan { version: 1; kind: "list" | "object"; /** Record anchors (list) or content region (object); `""` means ``. */ recordSelector: string; /** Elements per record. */ span: number; fields: FieldLocator[]; } export interface LearnResult { plan: ExtractionPlan; /** Weighted leaf score in [0, 1] (required leaves count double). */ fit: number; /** Leaves without a locator. */ unresolved: string[]; } export interface ApplyResult { records: Array>; /** Fraction of records where each leaf is filled. */ fill: Map; } const CANDIDATE_SKIP: ReadonlySet = new Set([ "script", "style", "noscript", "template", "svg", "path", "br", "hr", "wbr", "iframe", "head", "title", "base", ]); const HEADING_TAGS: ReadonlySet = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]); const GENERIC_TAGS: ReadonlySet = new Set(["div", "span", "li", "ul", "ol", "section", "article", "tr", "tbody", "center", "font"]); const LABEL_TAGS: ReadonlySet = new Set(["dt", "th", "label"]); const LOOSE_LABEL_TAGS: ReadonlySet = new Set(["strong", "b", "span", "div", "p", "td", "em"]); const DATA_KEY_ATTRS = ["data-testid", "data-test", "data-qa", "data-field", "data-name", "data-cy"]; const URL_ATTRS = ["href", "src", "srcset", "data-src", "data-srcset", "data-original", "data-lazy-src", "content"]; const VALUE_ATTRS = ["datetime", "content", "value", "title", "aria-label", "alt"]; const MODIFIER = /(^(is|has|js|u|state)-)|(--)|^(active|selected|current|featured|promo|sale|new|first|last|odd|even|hidden|visible|lazy|loaded|disabled)$/i; // --------------------------------------------------------------------------- // Locator resolution and value reading (shared by learning and application) // --------------------------------------------------------------------------- function labelText(snap: DomSnapshot, index: number): string { return snap.text(index).toLowerCase().replace(/[::]\s*$/, "").trim(); } function isLabelNode(snap: DomSnapshot, index: number): boolean { const node = snap.node(index); const text = snap.text(index); if (!text || text.length > 40) return false; if (LABEL_TAGS.has(node.tag)) return true; return LOOSE_LABEL_TAGS.has(node.tag) && /[::]$/.test(text); } function cells(snap: DomSnapshot, row: number): number[] { return snap.node(row).children.filter((c) => { const tag = snap.node(c).tag; return tag === "td" || tag === "th"; }); } /** Nodes addressed by a DOM locator inside the record `rows`. */ export function resolveNodes(snap: DomSnapshot, rows: readonly number[], locator: Omit): number[] { const row = rows[locator.offset ?? 0]; if (row === undefined) return []; const within = (scope: number): number[] => locator.selector ? (snap.trySelect(locator.selector, scope) ?? []) : [scope]; switch (locator.strategy) { case "self": return [row]; case "css": return locator.selector ? (snap.trySelect(locator.selector, row) ?? []) : []; case "column": { const cell = cells(snap, row)[locator.column ?? -1]; return cell === undefined ? [] : within(cell); } case "label": { const out: number[] = []; for (const index of snap.subtree(row)) { if (!isLabelNode(snap, index) || labelText(snap, index) !== locator.label) continue; const value = snap.nextSibling(index); if (value >= 0) out.push(...within(value)); } return out; } default: return []; } } function readAccessor(snap: DomSnapshot, index: number, accessor: Accessor, spec: { type: string; format?: string }): string | null { const node = snap.node(index); if (accessor === "text") return snap.text(index) || null; if (accessor.startsWith("attr:")) return node.attrs[accessor.slice(5)] ?? null; const attrs = node.attrs; if (spec.format === "uri") { return attrs.href ?? attrs.src ?? attrs["data-src"] ?? attrs.srcset ?? attrs.content ?? (snap.text(index) || null); } if (spec.format === "date" || spec.format === "date-time") { return attrs.datetime ?? attrs.content ?? (snap.text(index) || attrs.title) ?? null; } return attrs.content ?? attrs.value ?? (snap.text(index) || null); } const AUTHOR_PREFIX = /^(by|par|von|posted by|written by|auteur\s*:)\s+/i; function coerceLeaf(raw: unknown, leaf: LeafField, ctx: CoerceContext): unknown { const spec = leaf.spec; const type: ScalarType = spec.type === "array" ? (spec.items?.type ?? "string") : (spec.type as ScalarType); const format = spec.type === "array" ? spec.items?.format : spec.format; let value = coerceScalar(raw, type, format, ctx); if (typeof value === "string" && type === "string" && !format && AUTHOR_PREFIX.test(value)) { const terms = fieldTerms(leaf); if (terms.concepts.has("author")) value = value.replace(AUTHOR_PREFIX, ""); } return value; } function setPath(record: Record, path: readonly string[], value: unknown): void { let target = record; for (let i = 0; i < path.length - 1; i++) { const key = path[i] as string; const next = target[key]; if (!next || typeof next !== "object" || Array.isArray(next)) target[key] = {}; target = target[key] as Record; } target[path[path.length - 1] as string] = value; } function emptyRecord(schema: NormalizedSchema): Record { const record: Record = {}; const empty = (field: FieldSpec): unknown => { if (field.type === "array") return []; if (field.type === "object") { const out: Record = {}; for (const child of field.properties ?? []) out[child.name] = empty(child); return out; } return null; }; for (const field of schema.fields) record[field.name] = empty(field); return record; } /** Content region for single-object extraction. */ export function contentRegion(snap: DomSnapshot): number { const body = snap.body(); for (const selector of ["main", "[role=main]", "#main", "#content"]) { const found = snap.trySelect(selector); if (found && found.length === 1) return found[0] as number; } const articles = snap.trySelect("article") ?? []; if (articles.length === 1) return articles[0] as number; return body; } /** Apply a plan to a snapshot. */ export function applyPlan( snap: DomSnapshot, plan: ExtractionPlan, schema: NormalizedSchema, ctx: CoerceContext, structured?: () => readonly StructuredEntry[], ): ApplyResult { const leaves = leafFields(schema); const byKey = new Map(leaves.map((leaf) => [leaf.key, leaf])); let anchors: number[]; if (plan.kind === "object") { const region = plan.recordSelector ? snap.trySelect(plan.recordSelector)?.[0] : snap.body(); anchors = region === undefined ? [snap.body()] : [region]; } else { const found = plan.recordSelector ? (snap.trySelect(plan.recordSelector) ?? []) : []; anchors = []; for (const anchor of found) { const last = anchors[anchors.length - 1]; if (last !== undefined && snap.isAncestor(last, anchor)) continue; anchors.push(anchor); } } const counts = new Map(); const required = leaves.filter((l) => l.required); const gate = required.length > 0 ? required : leaves; const records: Array> = []; for (const anchor of anchors) { const rows = recordRows(snap, anchor, Math.max(1, plan.span)); const record = emptyRecord(schema); for (const locator of plan.fields) { const leaf = byKey.get(locator.key); if (!leaf) continue; let value: unknown; if (locator.strategy === "structured") { const entries = structured?.() ?? []; const raw = structuredValue(entries, locator.path ?? ""); if (leaf.spec.type === "array") { const items = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]; value = items.map((item) => coerceLeaf(item, leaf, ctx)).filter((item) => item !== null); } else { value = coerceLeaf(Array.isArray(raw) ? raw[0] : raw, leaf, ctx); } } else { const nodes = resolveNodes(snap, rows, locator); if (leaf.spec.type === "array") { value = nodes .map((node) => coerceLeaf(readAccessor(snap, node, locator.accessor, leaf.spec.items ?? { type: "string" }), leaf, ctx)) .filter((item) => item !== null); } else { const node = nodes[0]; value = node === undefined ? null : coerceLeaf(readAccessor(snap, node, locator.accessor, leaf.spec), leaf, ctx); } } setPath(record, leaf.path, value ?? (leaf.spec.type === "array" ? [] : null)); } if (plan.kind === "list" && !gate.some((leaf) => isFilled(valueAt(record, leaf.path)))) continue; for (const leaf of leaves) { if (isFilled(valueAt(record, leaf.path))) counts.set(leaf.key, (counts.get(leaf.key) ?? 0) + 1); } records.push(record); } const fill = new Map(); for (const leaf of leaves) fill.set(leaf.key, records.length ? (counts.get(leaf.key) ?? 0) / records.length : 0); return { records, fill }; } // --------------------------------------------------------------------------- // Node features // --------------------------------------------------------------------------- function hrefFeatures(href: string | undefined, weight: number): Feature[] { if (!href || /^(https?:)?\/\//i.test(href) || href.startsWith("#")) return []; const [path = "", query = ""] = href.split("?"); const segments = path.split("/").filter(Boolean); const kept = segments.length > 1 ? segments.slice(0, -1) : segments; const out = features(kept.join(" "), weight); for (const pair of query.split("&")) { const key = pair.split("=")[0]; if (key) out.push(...features(key, weight * 0.6)); } return out; } function attributeFeatures(snap: DomSnapshot, index: number, scale: number): Feature[] { const attrs = snap.node(index).attrs; const out: Feature[] = []; const push = (text: string | undefined, weight: number) => { for (const f of features(text, weight * scale)) out.push(f); }; push(attrs.itemprop, 1); for (const token of stableClassTokens(attrs.class)) push(token, 0.9); push(attrs.id, 0.8); push(attrs.name, 0.9); push(attrs.rel, 0.9); push(attrs["aria-label"], 0.8); for (const name of DATA_KEY_ATTRS) push(attrs[name], 0.9); for (const name of Object.keys(attrs)) if (name.startsWith("data-")) push(name.slice(5), 0.6); return out; } function labelFeatures(snap: DomSnapshot, index: number, columns: readonly string[] | undefined, scale: number): Feature[] { const node = snap.node(index); if (node.parent < 0) return []; const siblings = snap.node(node.parent).children; const at = siblings.indexOf(index); const out: Feature[] = []; if ((node.tag === "td" || node.tag === "th") && columns) { const cellIndex = cells(snap, node.parent).indexOf(index); if (cellIndex >= 0) out.push(...features(columns[cellIndex], scale)); } const prev = at > 0 ? (siblings[at - 1] as number) : -1; if (prev >= 0 && isLabelNode(snap, prev)) out.push(...features(labelText(snap, prev), scale)); return out; } const TAG_HINTS: Record = { h1: "heading", h2: "heading", h3: "heading", h4: "heading", h5: "heading", h6: "heading", time: "time", img: "image", picture: "image", source: "image", address: "address", cite: "source", a: "link", }; class FeatureCache { readonly #cache = new Map(); constructor(private readonly snap: DomSnapshot, private readonly columns?: readonly string[]) {} /** Features of `index` inside record row `row` (ancestors up to the row). */ get(index: number, row: number): Feature[] { const key = `${index}:${row}`; let out = this.#cache.get(key); if (out) return out; const snap = this.snap; const node = snap.node(index); out = attributeFeatures(snap, index, 1); out.push(...labelFeatures(snap, index, this.columns, 1)); const hint = TAG_HINTS[node.tag]; if (hint) out.push({ token: hint, weight: 0.6 }); if (node.tag === "a") out.push(...hrefFeatures(node.attrs.href, 0.5)); const text = snap.text(index); if (text && text.length <= 40) out.push(...features(text, 0.5)); if (node.attrs.title && node.attrs.title.length <= 60) out.push(...features(node.attrs.title, 0.4)); let ancestor = node.parent; for (let depth = 0; depth < 2 && ancestor >= row && ancestor >= 0 && index !== row; depth++) { out.push(...attributeFeatures(snap, ancestor, 0.6)); out.push(...labelFeatures(snap, ancestor, this.columns, 0.8)); if (ancestor === row) break; ancestor = snap.node(ancestor).parent; } this.#cache.set(key, out); return out; } } function accessorFeatures(accessor: Accessor): Feature[] { if (accessor === "attr:href") return [{ token: "href", weight: 0.7 }]; if (accessor === "attr:src" || accessor === "attr:srcset" || accessor.startsWith("attr:data-src") || accessor === "attr:data-original") { return [{ token: "src", weight: 0.8 }]; } if (accessor === "attr:datetime") return [{ token: "datetime", weight: 0.9 }]; return []; } // --------------------------------------------------------------------------- // Candidate generation // --------------------------------------------------------------------------- interface CandidateLocator { strategy: Exclude; offset: number; selector?: string; label?: string; column?: number; } function candidateId(c: CandidateLocator): string { return `${c.strategy}|${c.offset}|${c.selector ?? ""}|${c.label ?? ""}|${c.column ?? ""}`; } /** Compound selectors describing one node (no ancestors). */ function nodeSimpleKeys(snap: DomSnapshot, index: number): string[] { const node = snap.node(index); const tag = node.tag; const attrs = node.attrs; const out: string[] = []; if (attrs.itemprop) out.push(`${tag}[itemprop=${cssAttrValue(attrs.itemprop)}]`); for (const name of DATA_KEY_ATTRS) if (attrs[name]) out.push(`[${name}=${cssAttrValue(attrs[name] as string)}]`); for (const token of stableClassTokens(attrs.class).filter((t) => !MODIFIER.test(t)).slice(0, 3)) { out.push(`${tag}.${cssEscapeIdent(token)}`); } const rel = attrs.rel?.split(/\s+/)[0]; if (rel) out.push(`${tag}[rel~=${cssAttrValue(rel)}]`); if (attrs["aria-label"] !== undefined) out.push(`${tag}[aria-label]`); if (tag === "time" && attrs.datetime !== undefined) out.push("time[datetime]"); const idPrefix = attrs.id ? /^([a-z][a-z_-]*?[_-])\d+$/i.exec(attrs.id) : null; if (idPrefix) out.push(`${tag}[id^=${cssAttrValue(idPrefix[1] as string)}]`); if (tag === "a" && attrs.href && !/^(https?:)?\/\//i.test(attrs.href)) { const prefix = /^([^?#]*\?[a-z_]+=|\/?[a-z][a-z_-]{1,30}\/)/i.exec(attrs.href); if (prefix) out.push(`a[href^=${cssAttrValue(prefix[1] as string)}]`); } if (!GENERIC_TAGS.has(tag)) out.push(tag); return out; } function positionPseudo(snap: DomSnapshot, index: number): string[] { const node = snap.node(index); if (node.parent < 0) return []; const siblings = snap.node(node.parent).children; if (siblings.length < 2) return []; const out: string[] = []; if (siblings[0] === index) out.push(":first-child"); if (siblings[siblings.length - 1] === index) out.push(":last-child"); return out; } function nodeKeys(snap: DomSnapshot, index: number, row: number): string[] { const node = snap.node(index); const simple = nodeSimpleKeys(snap, index); const out = [...simple]; const parent = node.parent; if (parent >= row) { let anchorKeys = nodeSimpleKeys(snap, parent).filter((k) => k !== snap.node(parent).tag); let chain = ""; if (anchorKeys.length === 0 && snap.node(parent).parent >= row && parent !== row) { const grand = snap.node(parent).parent; anchorKeys = nodeSimpleKeys(snap, grand).filter((k) => k !== snap.node(grand).tag); chain = `${snap.node(parent).tag} > `; if (anchorKeys.length === 0) anchorKeys = [snap.node(grand).tag]; } if (anchorKeys.length === 0) anchorKeys = [snap.node(parent).tag]; const anchor = anchorKeys[0] as string; out.push(`${anchor} > ${chain}${node.tag}`); for (const pseudo of positionPseudo(snap, index)) out.push(`${anchor} > ${chain}${node.tag}${pseudo}`); const own = simple.find((k) => k !== node.tag); if (own) out.push(`${anchor} > ${chain}${own}`); } return [...new Set(out)].slice(0, 12); } interface EvaluatedCandidate { locator: CandidateLocator; /** Per sampled record: matched nodes. */ nodes: number[][]; /** Row used as feature scope per record. */ rows: number[]; } function generateCandidates( snap: DomSnapshot, records: readonly number[][], isTable: boolean, maxNodesPerRecord: number, ): EvaluatedCandidate[] { const support = new Map(); const add = (locator: CandidateLocator, seen: Set) => { const id = candidateId(locator); if (seen.has(id)) return; seen.add(id); const entry = support.get(id); if (entry) entry.count++; else support.set(id, { locator, count: 1 }); }; for (const rows of records) { const seen = new Set(); rows.forEach((row, offset) => { let visited = 0; for (const index of snap.subtree(row)) { if (visited++ > maxNodesPerRecord) break; const node = snap.node(index); if (CANDIDATE_SKIP.has(node.tag)) continue; if ((node.tag === "meta" || node.tag === "link") && !node.attrs.itemprop) continue; if (index === row) { add({ strategy: "self", offset }, seen); continue; } for (const selector of nodeKeys(snap, index, row)) add({ strategy: "css", offset, selector }, seen); if (isLabelNode(snap, index)) { const value = snap.nextSibling(index); if (value >= 0) { const label = labelText(snap, index); add({ strategy: "label", offset, label }, seen); for (const tag of ["a", "img", "time"]) { if (snap.trySelect(tag, value)?.length) add({ strategy: "label", offset, label, selector: tag }, seen); } } } } if (isTable && snap.node(row).tag === "tr") { cells(snap, row).forEach((cell, column) => { add({ strategy: "column", offset, column }, seen); for (const tag of ["a", "img", "time"]) { if (snap.trySelect(tag, cell)?.length) add({ strategy: "column", offset, column, selector: tag }, seen); } }); } }); } const minSupport = Math.max(1, Math.ceil(records.length * 0.3)); const out: EvaluatedCandidate[] = []; for (const { locator, count } of [...support.values()].sort((a, b) => b.count - a.count)) { if (count < minSupport) continue; const nodes = records.map((rows) => resolveNodes(snap, rows, locator)); if (nodes.every((n) => n.length === 0)) continue; out.push({ locator, nodes, rows: records.map((rows) => rows[locator.offset] ?? -1) }); if (out.length >= 600) break; } return out; } // --------------------------------------------------------------------------- // Scoring // --------------------------------------------------------------------------- interface Scored { leaf: LeafField; candidate: EvaluatedCandidate; accessor: Accessor; score: number; lex: number; coverage: number; fingerprint: string; } function accessorsFor(snap: DomSnapshot, candidate: EvaluatedCandidate): Accessor[] { const out = new Set(["text"]); for (const nodes of candidate.nodes) { const first = nodes[0]; if (first === undefined) continue; const attrs = snap.node(first).attrs; for (const name of [...URL_ATTRS, ...VALUE_ATTRS]) if (attrs[name] !== undefined) out.add(`attr:${name}`); for (const [name, value] of Object.entries(attrs)) { if (name.startsWith("data-") && value.length > 0 && value.length <= 80 && !/^[[{]/.test(value)) out.add(`attr:${name}`); } } return [...out]; } function isInsideTitleish(snap: DomSnapshot, index: number, row: number): boolean { let current = index; for (let depth = 0; depth < 4 && current >= row && current >= 0; depth++) { const node = snap.node(current); if (HEADING_TAGS.has(node.tag)) return true; const tokens = `${node.attrs.class ?? ""} ${node.attrs.itemprop ?? ""}`.toLowerCase(); if (/(^|[\s_-])(title|titleline|headline|heading|name)([\s_-]|$)/.test(tokens)) return true; if (current === row) break; current = node.parent; } return false; } function structuralPrior( snap: DomSnapshot, leaf: LeafField, terms: FieldTerms, index: number, row: number, accessor: Accessor, ): number { const node = snap.node(index); const tag = node.tag; const spec = leaf.spec; const type = spec.type === "array" ? (spec.items?.type ?? "string") : spec.type; const format = spec.type === "array" ? spec.items?.format : spec.format; const attr = accessor.startsWith("attr:") ? accessor.slice(5) : ""; const isImageAttr = attr === "src" || attr === "srcset" || attr.startsWith("data-src") || attr === "data-original"; if (format === "uri") { if (terms.concepts.has("image")) { if (isImageAttr && (tag === "img" || tag === "source")) return attr === "src" ? 0.9 : 0.8; return attr === "content" ? 0.5 : 0.1; } if (attr === "href" && tag === "a") return isInsideTitleish(snap, index, row) && !leaf.parent ? 0.9 : 0.6; if (attr === "content") return 0.4; return isImageAttr ? 0.15 : 0.05; } if (format === "email") return attr === "href" ? 0.9 : accessor === "text" ? 0.6 : 0.1; if (format === "date" || format === "date-time") { if (attr === "datetime") return 1; if (attr === "content") return 0.7; if (attr === "title") return 0.6; if (accessor === "text") return tag === "time" ? 0.8 : 0.6; return 0.2; } if (type === "number" || type === "integer") { if (accessor === "text") return 0.6; if (attr === "content" || attr === "value" || attr.startsWith("data-")) return 0.55; if (attr === "aria-label") return 0.5; if (attr === "title") return 0.4; return 0; } if (type === "boolean") { if (accessor === "text") return 0.6; if (attr === "content" || attr === "href") return 0.5; return 0.2; } if (accessor === "text") { if (terms.concepts.has("title") && !leaf.parent) { if (HEADING_TAGS.has(tag) || (tag === "a" && isInsideTitleish(snap, index, row))) return 0.9; if (isInsideTitleish(snap, index, row)) return 0.75; return tag === "a" ? 0.55 : 0.45; } if (terms.concepts.has("description") && (tag === "p" || snap.text(index).length >= 60)) return 0.85; return 0.5; } if (attr === "content") return 0.5; if (attr === "title" || attr === "aria-label" || attr === "alt") return 0.3; if (attr.startsWith("data-")) return 0.35; return 0.05; } const RELATIVE_DATE = /\b(ago|yesterday|today|il y a|hier|aujourd)\b/i; const CURRENCY = /[$€£¥₹₽¢]|\b(usd|eur|gbp|chf|jpy|cad|aud)\b/i; function valueQuality(leaf: LeafField, terms: FieldTerms, raw: string, value: unknown): number { const spec = leaf.spec; const type = spec.type === "array" ? (spec.items?.type ?? "string") : spec.type; const format = spec.type === "array" ? spec.items?.format : spec.format; if (format === "date" || format === "date-time") return RELATIVE_DATE.test(raw) ? 0.5 : /^\d{4}-\d{2}-\d{2}/.test(raw.trim()) ? 1 : 0.9; if (format === "uri") { if (terms.concepts.has("image")) return /\.(jpe?g|png|webp|gif|avif|svg)(\?|$)/i.test(String(value)) ? 1 : 0.7; return 1; } if (type === "number" && terms.concepts.has("price")) return CURRENCY.test(raw) ? 1 : 0.85; if (type === "string" && typeof value === "string") { // Truncated link text ("A Light in the ...") loses to a complete attribute. if (/(\.\.\.|…)$/.test(value)) return 0.7; if (terms.concepts.has("title") && !leaf.parent) { if (/^[\d\s.,#()-]+$/.test(value)) return 0.2; if (value.length > 200) return 0.5; } if (terms.concepts.has("description") && value.length < 20) return 0.6; if (/^[\d\s.,%()+-]+$/.test(value) && !terms.concepts.has("sku") && !terms.concepts.has("rank")) return 0.6; if (raw.length > 300 && !terms.concepts.has("description")) return 0.5; } return 1; } interface ScoreOptions { single: boolean; ctx: CoerceContext; featureCache: FeatureCache; } function scoreCandidates( snap: DomSnapshot, leaves: readonly LeafField[], candidates: readonly EvaluatedCandidate[], options: ScoreOptions, ): Scored[] { const sampleSize = candidates[0]?.nodes.length ?? 0; const out: Scored[] = []; const coerceMemo = new Map(); const termsByLeaf = new Map(leaves.map((leaf) => [leaf.key, fieldTerms(leaf)])); for (const candidate of candidates) { const accessors = accessorsFor(snap, candidate); for (const accessor of accessors) { const rawFirst: Array = candidate.nodes.map((nodes) => { const first = nodes[0]; return first === undefined ? null : readAccessor(snap, first, accessor, { type: "string" }); }); if (rawFirst.every((v) => v === null || v === "")) continue; const extraFeatures = accessorFeatures(accessor); for (const leaf of leaves) { const terms = termsByLeaf.get(leaf.key) as FieldTerms; const isArray = leaf.spec.type === "array"; const typeKey = `${leaf.spec.type}:${leaf.spec.items?.type ?? ""}:${leaf.spec.format ?? leaf.spec.items?.format ?? ""}:${terms.concepts.has("author")}`; let ok = 0; let quality = 0; let lexSum = 0; let priorSum = 0; let multiplicity = 0; const values: string[] = []; candidate.nodes.forEach((nodes, r) => { const row = candidate.rows[r] as number; const targets = isArray ? nodes : nodes.slice(0, 1); let recordOk = false; let recordQuality = 0; const recordValues: string[] = []; for (const node of targets) { const raw = isArray ? readAccessor(snap, node, accessor, { type: "string" }) : rawFirst[r]; if (raw === null || raw === "") continue; const memoKey = `${typeKey}${raw}`; let value = coerceMemo.get(memoKey); if (value === undefined) { value = coerceLeaf(raw, leaf, options.ctx); coerceMemo.set(memoKey, value); } if (value === null) continue; recordOk = true; recordQuality = Math.max(recordQuality, valueQuality(leaf, terms, raw, value)); recordValues.push(String(value)); } if (!recordOk) { values.push(""); return; } const node = targets[0] as number; ok++; quality += recordQuality; multiplicity += recordValues.length; values.push(recordValues.join("")); const nodeFeatures = options.featureCache.get(node, row); lexSum += lexicalScore(terms, extraFeatures.length ? [...nodeFeatures, ...extraFeatures] : nodeFeatures); priorSum += structuralPrior(snap, leaf, terms, node, row, accessor); }); if (ok === 0) continue; const coverage = ok / sampleSize; if (!options.single && coverage < 0.25) continue; const lex = lexSum / ok; const prior = priorSum / ok; const strongPrior = leaf.spec.type === "string" && !leaf.spec.format ? prior >= 0.8 : prior >= 0.5; const minLex = options.single ? 0.45 : 0.3; if (lex < minLex && !(strongPrior && !options.single) && !(options.single && prior >= 0.9 && lex >= 0.2)) continue; const nonEmpty = values.filter(Boolean); const distinct = new Set(nonEmpty).size; let distinctFactor = 1; if (!options.single && leaf.spec.type !== "boolean" && nonEmpty.length >= 3) { if (distinct === 1) distinctFactor = 0.35; else if (distinct / nonEmpty.length < 0.5) distinctFactor = 0.85; } const firstNode = candidate.nodes.find((n) => n.length > 0)?.[0] as number; const specificity = accessor === "text" && snap.node(firstNode).children.length > 0 ? 0.92 : 1; const arrayFactor = isArray ? (multiplicity / ok > 1.2 ? 1.1 : 0.85) : 1; const score = Math.pow(coverage, 0.7) * (0.15 + 0.55 * lex + 0.3 * prior) * (quality / ok) * distinctFactor * specificity * arrayFactor; out.push({ leaf, candidate, accessor, score, lex, coverage, fingerprint: `${accessor === "text" ? "text" : "attr"}|${values.join("")}`, }); } } } return out; } function assign(scored: Scored[], leaves: readonly LeafField[], minScore: number): Map { scored.sort((a, b) => b.score - a.score); const chosen = new Map(); const usedFingerprints = new Set(); for (const item of scored) { if (item.score < minScore) break; if (chosen.has(item.leaf.key) || usedFingerprints.has(item.fingerprint)) continue; chosen.set(item.leaf.key, item); usedFingerprints.add(item.fingerprint); if (chosen.size === leaves.length) break; } return chosen; } function toLocator(item: Scored): FieldLocator { const locator: FieldLocator = { key: item.leaf.key, strategy: item.candidate.locator.strategy, accessor: item.accessor, confidence: Math.round(Math.min(1, item.score / 0.75) * 1000) / 1000, }; if (item.candidate.locator.offset) locator.offset = item.candidate.locator.offset; if (item.candidate.locator.selector) locator.selector = item.candidate.locator.selector; if (item.candidate.locator.label !== undefined) locator.label = item.candidate.locator.label; if (item.candidate.locator.column !== undefined) locator.column = item.candidate.locator.column; if (item.leaf.spec.type === "array") locator.all = true; return locator; } /** Title-like text leaves prefer the link inside the chosen node when it carries most of the text. */ function refineToLink(snap: DomSnapshot, records: readonly number[][], locator: FieldLocator, leaf: LeafField): void { if (locator.strategy !== "css" || locator.accessor !== "text" || !locator.selector || leaf.spec.type !== "string") return; if (!fieldTerms(leaf).concepts.has("title")) return; const refined = `${locator.selector} a`; let good = 0; let seen = 0; for (const rows of records) { const node = resolveNodes(snap, rows, locator)[0]; if (node === undefined) continue; if (snap.node(node).tag === "a") return; seen++; const link = resolveNodes(snap, rows, { ...locator, selector: refined })[0]; if (link === undefined) continue; const full = snap.text(node).length; const inner = snap.text(link).length; if (inner > 0 && inner >= full * 0.5) good++; } if (seen > 0 && good >= seen * 0.8) locator.selector = refined; } /** Switch truncated link text ("A Light in the ...") to a complete title/aria-label/alt attribute. */ function refineTruncated(snap: DomSnapshot, records: readonly number[][], locator: FieldLocator): void { if (locator.accessor !== "text" || locator.strategy === "structured") return; const nodes = records.map((rows) => resolveNodes(snap, rows, locator)[0]).filter((n): n is number => n !== undefined); const truncated = nodes.filter((n) => /(\.\.\.|…)$/.test(snap.text(n))); if (truncated.length === 0) return; for (const attr of ["title", "aria-label", "alt", "data-title"]) { const consistent = nodes.every((n) => { const value = snap.node(n).attrs[attr]; if (!value) return false; const text = snap.text(n); const stem = text.replace(/(\.\.\.|…)$/, "").trim(); return normalizeText(value) === text || (stem.length > 0 && normalizeText(value).startsWith(stem)); }); if (consistent) { locator.accessor = `attr:${attr}`; return; } } } function hintLocators(leaves: readonly LeafField[]): FieldLocator[] { const out: FieldLocator[] = []; for (const leaf of leaves) { if (!leaf.spec.selector) continue; out.push({ key: leaf.key, strategy: "css", selector: leaf.spec.selector, accessor: leaf.spec.selectorAttribute ? `attr:${leaf.spec.selectorAttribute}` : "auto", ...(leaf.spec.type === "array" ? { all: true } : {}), confidence: 1, }); } return out; } function fitOf(leaves: readonly LeafField[], locators: readonly FieldLocator[], fill?: Map): number { let total = 0; let weights = 0; const byKey = new Map(locators.map((l) => [l.key, l])); for (const leaf of leaves) { const weight = leaf.required ? 2 : 1; weights += weight; const locator = byKey.get(leaf.key); if (!locator) continue; total += weight * locator.confidence * (fill ? (fill.get(leaf.key) ?? 0) : 1); } return weights ? total / weights : 0; } export interface LearnOptions { ctx: CoerceContext; /** Records sampled per group. Default 30. */ sample?: number; /** Minimum assignment score. Default 0.25. */ minScore?: number; } /** Learn a list plan for one record group. */ export function learnListPlan( snap: DomSnapshot, group: Pick, schema: NormalizedSchema, options: LearnOptions, ): LearnResult { const leaves = leafFields(schema); const hinted = hintLocators(leaves); const hintedKeys = new Set(hinted.map((l) => l.key)); const pending = leaves.filter((leaf) => !hintedKeys.has(leaf.key)); const sampleSize = options.sample ?? 30; const step = Math.max(1, Math.ceil(group.anchors.length / sampleSize)); const sampled = group.anchors.filter((_, i) => i % step === 0); const records = sampled.map((anchor) => recordRows(snap, anchor, group.span)); const candidates = generateCandidates(snap, records, group.kind === "table", 400); const featureCache = new FeatureCache(snap, group.columns); const scored = scoreCandidates(snap, pending, candidates, { single: false, ctx: options.ctx, featureCache }); const chosen = assign(scored, pending, options.minScore ?? 0.25); const locators = [...hinted]; for (const leaf of pending) { const item = chosen.get(leaf.key); if (!item) continue; const locator = toLocator(item); refineToLink(snap, records, locator, leaf); refineTruncated(snap, records, locator); locators.push(locator); } const plan: ExtractionPlan = { version: 1, kind: "list", recordSelector: group.selector, span: group.span, fields: locators }; return { plan, fit: fitOf(leaves, locators), unresolved: leaves.filter((leaf) => !locators.some((l) => l.key === leaf.key)).map((leaf) => leaf.key), }; } /** Learn a single-object plan: structured data first, then the content region. */ export function learnObjectPlan( snap: DomSnapshot, schema: NormalizedSchema, structured: readonly StructuredEntry[], options: LearnOptions, ): LearnResult { const leaves = leafFields(schema); const locators = hintLocators(leaves); const done = new Set(locators.map((l) => l.key)); // 1. Structured data (JSON-LD, microdata, OpenGraph). const structuredScored: Array<{ leaf: LeafField; entry: StructuredEntry; score: number }> = []; for (const leaf of leaves) { if (done.has(leaf.key)) continue; const terms = fieldTerms(leaf); for (const entry of structured) { const lex = lexicalScore(terms, entry.features); if (lex < 0.6) continue; const raw = Array.isArray(entry.value) && leaf.spec.type !== "array" ? entry.value[0] : entry.value; const value = leaf.spec.type === "array" ? (Array.isArray(raw) ? raw : [raw]).map((v) => coerceLeaf(v, leaf, options.ctx)).filter((v) => v !== null) : coerceLeaf(raw, leaf, options.ctx); if (!isFilled(value)) continue; const score = lex * (entry.secondary ? 0.8 : 1) * (1 - 0.05 * entry.depth); structuredScored.push({ leaf, entry, score }); } } structuredScored.sort((a, b) => b.score - a.score); const usedPaths = new Set(); for (const item of structuredScored) { if (done.has(item.leaf.key) || usedPaths.has(item.entry.path)) continue; done.add(item.leaf.key); usedPaths.add(item.entry.path); locators.push({ key: item.leaf.key, strategy: "structured", path: item.entry.path, accessor: "auto", ...(item.leaf.spec.type === "array" ? { all: true } : {}), confidence: Math.round(Math.min(1, item.score) * 1000) / 1000, }); } // 2. DOM candidates inside the content region. const region = contentRegion(snap); const pending = leaves.filter((leaf) => !done.has(leaf.key)); let recordSelector = ""; if (region !== snap.body()) recordSelector = selectorForNodes(snap, [region]).selector; if (pending.length > 0) { const records = [[region]]; const candidates = generateCandidates(snap, records, false, 1500); const featureCache = new FeatureCache(snap); const scored = scoreCandidates(snap, pending, candidates, { single: true, ctx: options.ctx, featureCache }); const chosen = assign(scored, pending, options.minScore ?? 0.3); for (const leaf of pending) { const item = chosen.get(leaf.key); if (!item) continue; const locator = toLocator(item); refineToLink(snap, records, locator, leaf); locators.push(locator); } } const plan: ExtractionPlan = { version: 1, kind: "object", recordSelector, span: 1, fields: locators }; return { plan, fit: fitOf(leaves, locators), unresolved: leaves.filter((leaf) => !locators.some((l) => l.key === leaf.key)).map((leaf) => leaf.key), }; } /** Fit of an applied plan (locator confidence weighted by per-leaf fill rate). */ export function appliedFit(schema: NormalizedSchema, plan: ExtractionPlan, fill: Map): number { return fitOf(leafFields(schema), plan.fields, fill); } export { normalizeText, conceptsOf };