import Foundation import Darwin /// The web's url.Parse check, including the places where Go deliberately /// leaves percent escapes alone (opaque URLs and the query string). enum MarkdownLinks { static let schemes: Set = ["http", "https", "mailto"] static func allows(_ target: String) -> Bool { guard !target.prefix(while: { $0 != "#" }).unicodeScalars.contains(where: { $0.value < 32 || $0.value == 127 }) else { return false } guard let colon = target.firstIndex(of: ":"), schemes.contains(target[..= 128 || asciiAlphaNumeric($0) || "!$&'()*+,-.:;=[]_%~<>\"".utf8.contains($0) }) else { return false } // Go permits encoded non-ASCII host bytes and %25, not encoded // ASCII host characters such as %41 or %2f. let regex = try! NSRegularExpression(pattern: "%([0-9A-Fa-f]{2})") for match in regex.matches(in: host, range: NSRange(host.startIndex..., in: host)) { guard let range = Range(match.range(at: 1), in: host), let byte = UInt8(host[range], radix: 16) else { return false } if byte < 128 && byte != 37 { return false } } } return true } private static func validZone(_ value: String) -> Bool { let bytes = Array(value.utf8) guard !bytes.isEmpty else { return false } var i = 0 while i < bytes.count { let byte = bytes[i] if byte == 37 { guard i + 2 < bytes.count, let decoded = UInt8(String(decoding: bytes[(i+1)...(i+2)], as: UTF8.self), radix: 16), decoded == 37 || decoded == 32 || hostByte(decoded) else { return false } i += 3 } else { guard hostByte(byte) else { return false } i += 1 } } return true } private static func hostByte(_ b: UInt8) -> Bool { b >= 128 || asciiAlphaNumeric(b) || "!$&'()*+,-.:;=[]_~<>\"".utf8.contains(b) } private static func asciiAlphaNumeric(_ b: UInt8) -> Bool { (65...90).contains(b) || (97...122).contains(b) || (48...57).contains(b) } private static func validPort(_ port: String) -> Bool { port.isEmpty || port.first == ":" && port.utf8.dropFirst().allSatisfy { (48...57).contains($0) } } private static func badEscape(_ value: String) -> Bool { MarkdownDraft.matches(#"%(?![0-9A-Fa-f]{2})"#, value) } }