package eu.friedcutlet.yokan.services.extensions.js import eu.friedcutlet.yokan.services.files.BoundedCache private val TagPattern = Regex("^([a-zA-Z*][a-zA-Z0-9-]*)") private val AttributeEqualsPredicate = Regex("\\[@([\\w-]+)='([^']*)']") private val ContainsClassPredicate = Regex("\\[contains\\(@class,'([^']*)'\\)]") private val AttributeStep = Regex("/@([\\w-]+)") private val MarkupTag = Regex("<[^>]+>") /** * Minimal XPath evaluator that mirrors the same trade-off as [HtmlSelectorMatcher]: support the * patterns most commonly used by community source extensions (tag predicates and `@attr`/`text()` * extraction) without taking a full DOM dependency. * * Supported expressions: * - `//tag` — all elements with that tag, returns inner HTML * - `//tag/@attr` — value of `attr` on each element * - `//tag[contains(@class,'foo')]` — class containment filter * - `//tag[@attr='value']` — attribute equality filter * - `//tag/text()` — concatenated text content of each element */ internal object HtmlXPathMatcher { // ponytail: fixed LRU of compiled expressions; extensions reuse a handful per source, raise if they churn. private val compiledExpressions = BoundedCache(maxEntries = 64, maxWeight = 64) { 1 } fun match(html: String, expression: String): List { if (html.isBlank() || expression.isBlank()) return emptyList() val compiled = compiledExpressions[expression] ?: compile(expression)?.also { compiledExpressions[expression] = it } ?: return emptyList() // Every match needs the literal closing tag, so a document without one (void tags like `img`) // is rejected in one pass instead of a lazy scan to the end of the document per candidate. if (compiled.closingTag != null && compiled.closingTag !in html) return emptyList() val results = mutableListOf() compiled.element.findAll(html).forEach { match -> val attrs = match.groups["attrs"]?.value.orEmpty() val inner = match.groups["inner"]?.value.orEmpty() when { compiled.attributeValue != null -> { val value = compiled.attributeValue.find(attrs)?.groupValues?.getOrNull(1) if (!value.isNullOrEmpty()) results += value } compiled.wantsText -> { val text = inner.replace(MarkupTag, "").trim() if (text.isNotEmpty()) results += text } else -> if (inner.isNotBlank()) results += inner.trim() } } return results.distinct() } private fun compile(expression: String): Compiled? { val trimmed = expression.trim().trimStart('/') val tag = TagPattern.find(trimmed)?.groupValues?.getOrNull(1) ?: return null val openTag = if (tag == "*") "[a-zA-Z][a-zA-Z0-9-]*" else tag val predicateAttrEq = AttributeEqualsPredicate.find(trimmed) val predicateContainsClass = ContainsClassPredicate.find(trimmed) val attrSelector = AttributeStep.find(trimmed.substringAfterLast(']'))?.groupValues?.getOrNull(1) val pattern = buildString { append("<") append(openTag) append("\\b") predicateAttrEq?.let { append("(?=[^>]*\\b${Regex.escape(it.groupValues[1])}=[\"']${Regex.escape(it.groupValues[2])}[\"'])") } predicateContainsClass?.let { append("(?=[^>]*class=[\"'][^\"']*\\b${Regex.escape(it.groupValues[1])}\\b[^\"']*[\"'])") } append("(?[^>]*)>") append("(?[\\s\\S]*?)") } return Compiled( element = Regex(pattern), // Only a plain tag name is a literal inside the pattern (`*` means any tag). closingTag = if (tag.startsWith('*')) null else "", attributeValue = attrSelector?.let { Regex("\\b${Regex.escape(it)}=[\"']([^\"']*)[\"']") }, wantsText = trimmed.endsWith("/text()"), ) } private class Compiled( val element: Regex, val closingTag: String?, val attributeValue: Regex?, val wantsText: Boolean, ) }