/// Link detection for transcript text: bare URLs, `` and the /// scheme filter every activated target passes through. Pure string logic. library; /// One bare link found in plain text: the visible range and its target. final class ChatTextLink { const ChatTextLink(this.start, this.end, this.target); final int start; final int end; final String target; @override bool operator ==(Object other) => other is ChatTextLink && other.start == start && other.end == end && other.target == target; @override int get hashCode => Object.hash(start, end, target); @override String toString() => 'ChatTextLink($start, $end, $target)'; } final RegExp _boundary = RegExp(r'[\p{L}\p{N}_@./\-]', unicode: true); final RegExp _whitespace = RegExp(r'\s'); final RegExp _wwwHost = RegExp( r'^www\.[\p{L}\p{N}-]+\.[\p{L}\p{N}]', unicode: true, caseSensitive: false, ); final RegExp _email = RegExp(r'^[^\s@<>()]+@[^\s@<>()]+\.[^\s@<>()]+$'); final RegExp _autolinkScheme = RegExp( r'^(?:https?://|mailto:)[^\s<>]+$', caseSensitive: false, ); const _trailingPunctuation = '.,;:!?*_~\'"'; const _closers = {')': '(', ']': '[', '}': '{'}; /// The activatable target for [url], or null. Only `http`/`https` with a host /// and `mailto` with an address pass; a `www.` host is opened over https. The /// transcript is untrusted model output, so `javascript:`, `data:`, `file:` and /// relative targets never activate. Uri? chatLinkUri(String url) { var value = url.trim(); if (value.toLowerCase().startsWith('www.')) value = 'https://$value'; final uri = Uri.tryParse(value); if (uri == null) return null; switch (uri.scheme.toLowerCase()) { case 'http' || 'https': return uri.host.isEmpty ? null : uri; case 'mailto': return uri.path.trim().isEmpty ? null : uri; default: return null; } } /// A bare `http(s)://` or `www.` link starting exactly at [index], with /// trailing sentence punctuation and unbalanced closing brackets trimmed. A /// link never starts in the middle of a word, path or address. String? bareLinkAt(String text, int index) { if (index > 0 && _boundary.hasMatch(text[index - 1])) return null; final head = text .substring(index, (index + 8).clamp(0, text.length)) .toLowerCase(); final www = head.startsWith('www.'); final prefix = head.startsWith('https://') ? 8 : head.startsWith('http://') ? 7 : www ? 4 : 0; if (prefix == 0) return null; var end = index; while (end < text.length && !_whitespace.hasMatch(text[end]) && !'<>"\'`'.contains(text[end])) { end += 1; } final url = trimLinkEnd(text.substring(index, end)); if (url.length <= prefix) return null; if (www && !_wwwHost.hasMatch(url)) return null; return chatLinkUri(url) == null ? null : url; } /// Drops trailing sentence punctuation, and a closing bracket only when the /// link does not open it too, so `(see https://x.com/a)` ends before `)` while /// `https://en.wikipedia.org/wiki/Dart_(language)` keeps it. String trimLinkEnd(String url) { var value = url; while (value.isNotEmpty) { final last = value[value.length - 1]; final opener = _closers[last]; if (_trailingPunctuation.contains(last)) { value = value.substring(0, value.length - 1); } else if (opener != null && _count(value, opener) < _count(value, last)) { value = value.substring(0, value.length - 1); } else { break; } } return value; } int _count(String text, String char) => char.allMatches(text).length; /// The target of an `` body: an `http(s)`/`mailto` URL or a bare /// email address. Anything else (HTML such as ``) is not a link. String? autolinkTarget(String inner) { if (_autolinkScheme.hasMatch(inner)) { return chatLinkUri(inner) == null ? null : inner; } if (_email.hasMatch(inner)) return 'mailto:$inner'; return null; } /// Bare links in plain (non-markdown) text, outside `` `code` `` spans and /// ```` ``` ```` fences, so an operator's pasted command is never linkified. List findTextLinks(String text) { final links = []; var i = 0; while (i < text.length) { if (text.startsWith('```', i)) { final close = text.indexOf('```', i + 3); if (close < 0) break; i = close + 3; continue; } if (text[i] == '`') { final close = text.indexOf('`', i + 1); if (close > i) { i = close + 1; continue; } } final url = bareLinkAt(text, i); if (url != null) { links.add(ChatTextLink(i, i + url.length, url)); i += url.length; } else { i += 1; } } return links; }