HtmlXPathMatcher.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlXPathMatcher.kt
1package eu.friedcutlet.yokan.services.extensions.js23import eu.friedcutlet.yokan.services.files.BoundedCache45private val TagPattern = Regex("^([a-zA-Z*][a-zA-Z0-9-]*)")6private val AttributeEqualsPredicate = Regex("\\[@([\\w-]+)='([^']*)']")7private val ContainsClassPredicate = Regex("\\[contains\\(@class,'([^']*)'\\)]")8private val AttributeStep = Regex("/@([\\w-]+)")9private val MarkupTag = Regex("<[^>]+>")1011/**12 * Minimal XPath evaluator that mirrors the same trade-off as [HtmlSelectorMatcher]: support the13 * patterns most commonly used by community source extensions (tag predicates and `@attr`/`text()`14 * extraction) without taking a full DOM dependency.15 *16 * Supported expressions:17 * - `//tag` — all elements with that tag, returns inner HTML18 * - `//tag/@attr` — value of `attr` on each element19 * - `//tag[contains(@class,'foo')]` — class containment filter20 * - `//tag[@attr='value']` — attribute equality filter21 * - `//tag/text()` — concatenated text content of each element22 */23internal object HtmlXPathMatcher {24 // ponytail: fixed LRU of compiled expressions; extensions reuse a handful per source, raise if they churn.25 private val compiledExpressions = BoundedCache<String, Compiled>(maxEntries = 64, maxWeight = 64) { 1 }2627 fun match(html: String, expression: String): List<String> {28 if (html.isBlank() || expression.isBlank()) return emptyList()29 val compiled = compiledExpressions[expression]30 ?: compile(expression)?.also { compiledExpressions[expression] = it }31 ?: return emptyList()32 // Every match needs the literal closing tag, so a document without one (void tags like `img`)33 // is rejected in one pass instead of a lazy scan to the end of the document per candidate.34 if (compiled.closingTag != null && compiled.closingTag !in html) return emptyList()35 val results = mutableListOf<String>()36 compiled.element.findAll(html).forEach { match ->37 val attrs = match.groups["attrs"]?.value.orEmpty()38 val inner = match.groups["inner"]?.value.orEmpty()39 when {40 compiled.attributeValue != null -> {41 val value = compiled.attributeValue.find(attrs)?.groupValues?.getOrNull(1)42 if (!value.isNullOrEmpty()) results += value43 }44 compiled.wantsText -> {45 val text = inner.replace(MarkupTag, "").trim()46 if (text.isNotEmpty()) results += text47 }48 else -> if (inner.isNotBlank()) results += inner.trim()49 }50 }51 return results.distinct()52 }5354 private fun compile(expression: String): Compiled? {55 val trimmed = expression.trim().trimStart('/')56 val tag = TagPattern.find(trimmed)?.groupValues?.getOrNull(1) ?: return null57 val openTag = if (tag == "*") "[a-zA-Z][a-zA-Z0-9-]*" else tag58 val predicateAttrEq = AttributeEqualsPredicate.find(trimmed)59 val predicateContainsClass = ContainsClassPredicate.find(trimmed)60 val attrSelector = AttributeStep.find(trimmed.substringAfterLast(']'))?.groupValues?.getOrNull(1)61 val pattern = buildString {62 append("<")63 append(openTag)64 append("\\b")65 predicateAttrEq?.let { append("(?=[^>]*\\b${Regex.escape(it.groupValues[1])}=[\"']${Regex.escape(it.groupValues[2])}[\"'])") }66 predicateContainsClass?.let { append("(?=[^>]*class=[\"'][^\"']*\\b${Regex.escape(it.groupValues[1])}\\b[^\"']*[\"'])") }67 append("(?<attrs>[^>]*)>")68 append("(?<inner>[\\s\\S]*?)</")69 append(openTag)70 append(">")71 }72 return Compiled(73 element = Regex(pattern),74 // Only a plain tag name is a literal inside the pattern (`*` means any tag).75 closingTag = if (tag.startsWith('*')) null else "</$tag>",76 attributeValue = attrSelector?.let { Regex("\\b${Regex.escape(it)}=[\"']([^\"']*)[\"']") },77 wantsText = trimmed.endsWith("/text()"),78 )79 }8081 private class Compiled(82 val element: Regex,83 val closingTag: String?,84 val attributeValue: Regex?,85 val wantsText: Boolean,86 )87}88