|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +#if canImport(CollectionsInternal) |
| 14 | +internal import CollectionsInternal |
| 15 | +#elseif canImport(OrderedCollections) |
| 16 | +internal import OrderedCollections |
| 17 | +#elseif canImport(_FoundationCollections) |
| 18 | +internal import _FoundationCollections |
| 19 | +#endif |
| 20 | + |
| 21 | +extension URL { |
| 22 | + /// A template for constructing a URL from variable expansions. |
| 23 | + /// |
| 24 | + /// This is an template that can be expanded into |
| 25 | + /// a ``URL`` by calling ``URL(template:variables:)``. |
| 26 | + /// |
| 27 | + /// Templating has a rich set of options for substituting various parts of URLs. See |
| 28 | + /// [RFC 6570](https://datatracker.ietf.org/doc/html/rfc6570) for |
| 29 | + /// details. |
| 30 | + /// |
| 31 | + /// ### Example 1 |
| 32 | + /// |
| 33 | + /// ```swift |
| 34 | + /// let template = URL.Template("http://www.example.com/foo{?query,number}")! |
| 35 | + /// let url = URL( |
| 36 | + /// template: template, |
| 37 | + /// variables: [ |
| 38 | + /// .query: "bar baz", |
| 39 | + /// .number: "234", |
| 40 | + /// ] |
| 41 | + /// ) |
| 42 | + /// |
| 43 | + /// extension URL.Template.VariableName { |
| 44 | + /// static var query: URL.Template.VariableName { .init("query") } |
| 45 | + /// static var number: URL.Template.VariableName { .init("number") } |
| 46 | + /// } |
| 47 | + /// ``` |
| 48 | + /// The resulting URL will be |
| 49 | + /// ```text |
| 50 | + /// http://www.example.com/foo?query=bar%20baz&number=234 |
| 51 | + /// ``` |
| 52 | + /// |
| 53 | + /// ### Usage |
| 54 | + /// |
| 55 | + /// Templates provide a description of a URL space and define how URLs can |
| 56 | + /// be constructed given specific variable values. Their intended use is, |
| 57 | + /// for example, to allow a server to communicate to a client how to |
| 58 | + /// construct URLs for particular resources. |
| 59 | + /// |
| 60 | + /// For each specific resource, an API contract is required to clearly |
| 61 | + /// define the variables applicable to that resource and its associated |
| 62 | + /// template. For example, such an API contract might specify that the |
| 63 | + /// variable `query` is mandatory and must be an alphanumeric string |
| 64 | + /// while the variable `number` is optional and must be a positive integer |
| 65 | + /// if provided. The server could then provide the client with a template |
| 66 | + /// such as `http://www.example.com/foo{?query,number}`, which the client |
| 67 | + /// can subsequently use to substitute variables accordingly. |
| 68 | + /// |
| 69 | + /// An API contract is necessary to define which substitutions are valid |
| 70 | + /// within a given URL space. There is no guarantee that every possible |
| 71 | + /// expansion of variable expressions corresponds to an existing resource |
| 72 | + /// URL; indeed, some expansions may not even produce a valid URL. Only |
| 73 | + /// the API specification itself can determine which expansions are |
| 74 | + /// expected to yield valid URLs corresponding to existing resources. |
| 75 | + /// |
| 76 | + /// ### Example 2 |
| 77 | + /// |
| 78 | + /// Here’s an example, that illustrates how to define a specific set of variables: |
| 79 | + /// ```swift |
| 80 | + /// struct MyQueryTemplate: Sendable, Hashable { |
| 81 | + /// var template: URL.Template |
| 82 | + /// |
| 83 | + /// init?(_ template: String) { |
| 84 | + /// guard let t = URL.Template(template) else { return nil } |
| 85 | + /// self.template = t |
| 86 | + /// } |
| 87 | + /// } |
| 88 | + /// |
| 89 | + /// struct MyQuery: Sendable, Hashable { |
| 90 | + /// var query: String |
| 91 | + /// var number: Int? |
| 92 | + /// |
| 93 | + /// var variables: [URL.Template.VariableName: URL.Template.Value] { |
| 94 | + /// var result: [URL.Template.VariableName: URL.Template.Value] = [ |
| 95 | + /// .query: .text(query) |
| 96 | + /// ] |
| 97 | + /// if let number { |
| 98 | + /// result[.number] = .text("\(number)") |
| 99 | + /// } |
| 100 | + /// return result |
| 101 | + /// } |
| 102 | + /// } |
| 103 | + /// |
| 104 | + /// extension URL.Template.VariableName { |
| 105 | + /// static var query: URL.Template.VariableName { .init("query") } |
| 106 | + /// static var number: URL.Template.VariableName { .init("number") } |
| 107 | + /// } |
| 108 | + /// |
| 109 | + /// extension URL { |
| 110 | + /// init?( |
| 111 | + /// template: MyQueryTemplate, |
| 112 | + /// query: MyQuery |
| 113 | + /// ) { |
| 114 | + /// self.init( |
| 115 | + /// template: template.template, |
| 116 | + /// variables: query.variables |
| 117 | + /// ) |
| 118 | + /// } |
| 119 | + /// } |
| 120 | + /// ``` |
| 121 | + @available(FoundationPreview 6.2, *) |
| 122 | + public struct Template: Sendable, Hashable { |
| 123 | + var elements: [Element] = [] |
| 124 | + |
| 125 | + enum Element: Sendable, Hashable { |
| 126 | + case literal(String) |
| 127 | + case expression(Expression) |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +// MARK: - Parse |
| 133 | + |
| 134 | +extension URL.Template { |
| 135 | + /// Creates a new template from its text form. |
| 136 | + /// |
| 137 | + /// The template string needs to be a valid RFC 6570 template. |
| 138 | + /// |
| 139 | + /// This will parse the template and return `nil` if the template is invalid. |
| 140 | + public init?(_ template: String) { |
| 141 | + do { |
| 142 | + self.init() |
| 143 | + |
| 144 | + var remainder = template[...] |
| 145 | + |
| 146 | + func copyLiteral(upTo end: String.Index) { |
| 147 | + guard remainder.startIndex < end else { return } |
| 148 | + let literal = remainder[remainder.startIndex..<end] |
| 149 | + let escaped = String(literal).normalizedAddingPercentEncoding( |
| 150 | + withAllowedCharacters: .unreservedReserved |
| 151 | + ) |
| 152 | + elements.append(.literal(escaped)) |
| 153 | + } |
| 154 | + |
| 155 | + while let match = remainder.firstMatch(of: URL.Template.Global.shared.uriTemplateRegex) { |
| 156 | + copyLiteral(upTo: match.range.lowerBound) |
| 157 | + let expression = try Expression(String(match.output.1)) |
| 158 | + elements.append(.expression(expression)) |
| 159 | + remainder = remainder[match.range.upperBound..<remainder.endIndex] |
| 160 | + } |
| 161 | + copyLiteral(upTo: remainder.endIndex) |
| 162 | + } catch { |
| 163 | + return nil |
| 164 | + } |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +// MARK: - |
| 169 | + |
| 170 | +extension URL.Template: CustomStringConvertible { |
| 171 | + public var description: String { |
| 172 | + elements.reduce(into: "") { |
| 173 | + $0.append("\($1)") |
| 174 | + } |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +extension URL.Template.Element: CustomStringConvertible { |
| 179 | + var description: String { |
| 180 | + switch self { |
| 181 | + case .literal(let l): l |
| 182 | + case .expression(let e): "{\(e)}" |
| 183 | + } |
| 184 | + } |
| 185 | +} |
0 commit comments