Repository Public
1import Foundation23/// What the text typed in the unified address bar resolves to.4enum ResolvedInput: Equatable, Sendable {5 case url(URL)6 case search(URL)78 var url: URL {9 switch self {10 case .url(let u), .search(let u): return u11 }12 }1314 var isSearch: Bool { if case .search = self { return true }; return false }15}1617/// Turns free text into a navigation target: explicit URL, bare host, search shortcut or search query.18enum AddressResolver {19 /// Schemes a user may type and load directly in a tab.20 static let typedSchemes: Set<String> = ["http", "https", "file", "about"]21 /// Schemes that are never navigated to from typed text; the text is searched instead.22 static let neverTyped: Set<String> = ["javascript", "vbscript", "data", "blob"]2324 static func resolve(_ raw: String, engine: SearchEngine, engines: [SearchEngine] = SearchEngine.builtIn) -> ResolvedInput? {25 let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)26 guard !text.isEmpty else { return nil }2728 // 1. Search shortcut: "<shortcut> <query>" or "!<shortcut> <query>".29 if let space = text.firstIndex(where: { $0 == " " }) {30 var token = String(text[..<space]).lowercased()31 if token.hasPrefix("!") { token.removeFirst() }32 let rest = text[text.index(after: space)...].trimmingCharacters(in: .whitespaces)33 if !rest.isEmpty, let match = engines.first(where: { $0.shortcut == token }), let url = match.searchURL(for: rest) {34 return .search(url)35 }36 }3738 // 2. Anything containing whitespace is a query (URLs never contain raw spaces).39 if text.contains(where: { $0.isWhitespace }) { return search(text, engine) }4041 // 3. Explicit scheme.42 if let scheme = explicitScheme(in: text) {43 if neverTyped.contains(scheme) { return search(text, engine) }44 if typedSchemes.contains(scheme) {45 if let url = URL(string: text), isWellFormed(url) { return .url(url) }46 return search(text, engine)47 }48 // Other schemes (mailto:, tel:, …) are handed to the navigation policy, which asks before leaving the app.49 // A "scheme" containing a dot is really a mistyped host ("example.com:abc"): search it instead.50 if !scheme.contains("."), let url = URL(string: text) { return .url(url) }51 return search(text, engine)52 }5354 // 4. Bare host, with optional port/path.55 if let url = hostURL(from: text) { return .url(url) }5657 return search(text, engine)58 }5960 private static func search(_ text: String, _ engine: SearchEngine) -> ResolvedInput? {61 (engine.searchURL(for: text) ?? SearchEngine.fallback.searchURL(for: text)).map { .search($0) }62 }6364 /// Returns the lowercased scheme when `text` starts with `scheme:` and is not a `host:port` pair.65 static func explicitScheme(in text: String) -> String? {66 guard let colon = text.firstIndex(of: ":") else { return nil }67 let candidate = text[..<colon]68 guard let first = candidate.first, first.isLetter, first.isASCII,69 candidate.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "+-.".contains($0)) }) else { return nil }70 let after = text[text.index(after: colon)...]71 // "localhost:3000", "example.com:8080/path" → host:port, not a scheme.72 let portPart = after.prefix { $0 != "/" && $0 != "?" && $0 != "#" }73 if !portPart.isEmpty, portPart.allSatisfy({ $0.isASCII && $0.isNumber }), !after.hasPrefix("//") {74 return nil75 }76 return candidate.lowercased()77 }7879 private static func isWellFormed(_ url: URL) -> Bool {80 guard let scheme = url.scheme?.lowercased() else { return false }81 switch scheme {82 case "http", "https": return !(url.host ?? "").isEmpty83 case "file": return !url.path.isEmpty84 default: return true85 }86 }8788 private static func hostURL(from text: String) -> URL? {89 let hostEnd = text.firstIndex(where: { "/?#".contains($0) }) ?? text.endIndex90 var authority = String(text[..<hostEnd])91 guard !authority.isEmpty, !authority.contains("@") else { return nil }9293 var host = authority94 if authority.hasPrefix("[") {95 // IPv6 literal: [::1] or [::1]:808096 guard let close = authority.firstIndex(of: "]") else { return nil }97 host = String(authority[...close])98 let inner = host.dropFirst().dropLast()99 guard !inner.isEmpty, inner.allSatisfy({ $0.isHexDigit || $0 == ":" || $0 == "." }), inner.contains(":") else { return nil }100 let tail = authority[authority.index(after: close)...]101 guard tail.isEmpty || (tail.hasPrefix(":") && tail.dropFirst().allSatisfy(\.isNumber) && tail.count > 1) else { return nil }102 } else if let colon = authority.lastIndex(of: ":") {103 let port = authority[authority.index(after: colon)...]104 guard !port.isEmpty, port.allSatisfy({ $0.isASCII && $0.isNumber }), let value = Int(port), value <= 65535 else { return nil }105 host = String(authority[..<colon])106 }107 if host.hasSuffix(".") && host.count > 1 { host.removeLast(); authority = authority.replacingOccurrences(of: host + ".", with: host) }108109 let kind = classify(host: host)110 guard kind != .notAHost else { return nil }111 let scheme = kind == .local ? "http" : "https"112 return URL(string: scheme + "://" + authority + text[hostEnd...])113 }114115 enum HostKind { case local, remote, notAHost }116117 static func classify(host raw: String) -> HostKind {118 let host = raw.lowercased()119 if host.hasPrefix("[") { return .local }120 if host == "localhost" { return .local }121 let labels = host.split(separator: ".", omittingEmptySubsequences: false)122 guard labels.count >= 2, labels.allSatisfy({ !$0.isEmpty && $0.count <= 63 }) else { return .notAHost }123 // IPv4124 if labels.count == 4, labels.allSatisfy({ $0.allSatisfy(\.isNumber) && (Int($0) ?? 256) <= 255 }) {125 return .local126 }127 guard labels.allSatisfy({ label in128 label.allSatisfy { $0.isLetter || $0.isNumber || $0 == "-" } && !label.hasPrefix("-") && !label.hasSuffix("-")129 }) else { return .notAHost }130 guard let tld = labels.last else { return .notAHost }131 if ["localhost", "local", "test", "internal", "lan", "home"].contains(String(tld)) { return .local }132 // A TLD is letters only (or punycode); "file.txt"-like words still qualify, which matches other browsers,133 // but purely numeric endings such as "3.14" do not.134 let tldIsPlausible = tld.count >= 2 && (tld.allSatisfy(\.isLetter) || tld.hasPrefix("xn--"))135 return tldIsPlausible ? .remote : .notAHost136 }137}138