Files
ccn/Packages/Localization/Sources/Public/Methods/Negotiate.swift
T
2026-08-19 23:19:08 +02:00

199 lines
6.4 KiB
Swift

import Foundation
/// Negotiates the best supported language for a request from its `Accept-Language` header.
///
/// Bound to a bundle's catalog languages via ``LanguageList``, an instance is invoked like a function — through
/// ``callAsFunction(acceptLanguage:)`` — to resolve a header value to a supported language identifier, honouring the header's `q` weights as
/// RFC 9110 prescribes and falling back to the default language.
public struct Negotiate: Sendable {
// MARK: Properties
/// The supported languages and default language, derived from the bundle's String Catalog.
private let list: LanguageList
// MARK: Initializers
/// Creates a language negotiator backed by the given bundle's String Catalog.
/// - Parameter bundle: the bundle whose String Catalog defines the supported languages.
public init(
bundle: Bundle
) {
self.list = .init(bundle: bundle)
}
// MARK: Methods
/// Picks the best supported language for the given `Accept-Language` header value.
///
/// Invoked by calling the instance directly, for example `negotiate(acceptLanguage: header)`.
/// The header is parsed into its language ranges, which are ordered by descending `q` weight as RFC 9110 prescribes: an entry without a weight
/// counts as 1, entries weighted 0 are "not acceptable" and dropped, and equal weights keep the header order. Each tag is then matched against the
/// supported languages in turn — first by an exact match, then by its primary language subtag, so `de-AT` resolves to a supported `de` — while the
/// `*` wildcard accepts the default language. When the header is absent or matches nothing, the default language is returned.
/// - Parameter acceptLanguage: the raw `Accept-Language` header value, if any.
/// - Returns: the identifier of the supported language to serve.
public func callAsFunction(
acceptLanguage language: String?
) -> String {
guard let language else {
return list.default
}
let ranges = ranges(from: language)
guard !ranges.isEmpty else {
return list.default
}
let supported = list.all
for range in ranges {
if range.tag == .wildcard {
return list.default
}
if let match = match(range.tag, in: supported) {
return match
}
}
return list.default
}
}
// MARK: - Helpers
private extension Negotiate {
// MARK: Methods
/// Parses an `Accept-Language` header value into its ``LanguageRange`` list, ordered by preference.
///
/// Each comma-separated entry yields its language tag and `q` weight. The ranges are sorted by descending weight, entries weighted 0 are dropped
/// as "not acceptable", and equally weighted entries keep the header order.
/// - Parameter acceptLanguage: the raw `Accept-Language` header value.
/// - Returns: the language ranges, most preferred first.
func ranges(
from acceptLanguage: String
) -> [LanguageRange] {
acceptLanguage
.split(separator: .Separator.comma)
.compactMap(range(from:))
.filter { $0.quality > 0 }
.enumerated()
.sorted { lhs, rhs in
lhs.element.quality == rhs.element.quality
? lhs.offset < rhs.offset
: lhs.element.quality > rhs.element.quality
}
.map(\.element)
}
/// Parses a single `Accept-Language` header entry into its ``LanguageRange``.
///
/// The entry's language tag precedes the first `;`; a `q` parameter after it sets the weight.
/// A missing or malformed weight counts as 1, the highest preference, matching a tag sent without one.
/// - Parameter entry: a single comma-separated header entry.
/// - Returns: the entry's language range, or `nil` when it has no language tag.
func range(
from entry: Substring
) -> LanguageRange? {
let parts = entry.split(separator: .Separator.semicolon)
let tag = parts.first
.map(String.init)?
.trimmingCharacters(in: .whitespaces)
?? .empty
guard !tag.isEmpty else {
return nil
}
let quality = parts
.dropFirst()
.compactMap { parameter -> Double? in
let parameter = parameter
.trimmingCharacters(in: .whitespaces)
.lowercased()
guard parameter.hasPrefix(.Prefix.quality) else {
return nil
}
return Double(parameter.dropFirst(String.Prefix.quality.count))
}
.first
?? 1
return .init(
tag: tag,
quality: quality
)
}
/// Finds the supported language that best matches a single `Accept-Language` tag.
///
/// An exact, case-insensitive match wins; otherwise the tag's primary subtag is matched against the supported languages' primary subtags, so a
/// regional tag such as `de-AT` resolves to `de`.
/// - Parameters:
/// - tag: a single language tag from the header.
/// - supported: the supported language identifiers.
/// - Returns: the matching supported language, or `nil` when the tag matches none.
func match(
_ tag: String,
in supported: [String]
) -> String? {
let tag = tag.lowercased()
if let exact = supported.first(
where: { $0.lowercased() == tag }
) {
return exact
}
let primary = tag.primarySubtag
return supported.first {
$0.lowercased().primarySubtag == primary
}
}
}
// MARK: - Character+Extensions
private extension Character {
// MARK: Constants
enum Separator {
static let comma: Character = ","
static let dash: Character = "-"
static let semicolon: Character = ";"
}
}
// MARK: - String+Extensions
private extension String {
// MARK: Constants
static let empty: String = ""
static let wildcard: String = "*"
enum Prefix {
static let quality = "q="
}
/// The primary language subtag, i.e. everything before the first `-` (`de-AT` becomes `de`).
var primarySubtag: String {
split(separator: .Separator.dash)
.first
.map(String.init)
?? self
}
}