diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cebd42bea..1a41f29e2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,10 +13,6 @@ jobs: fail-fast: false matrix: image: - - swift:5.8-focal - - swift:5.8-jammy - - swift:5.9-focal - - swift:5.9-jammy - swift:5.10-focal - swift:5.10-jammy - swift:6.0-focal @@ -25,6 +21,8 @@ jobs: - swift:6.1-focal - swift:6.1-jammy - swift:6.1-noble + - swift:6.2-jammy + - swift:6.2-noble - swiftlang/swift:nightly-focal - swiftlang/swift:nightly-jammy container: ${{ matrix.image }} diff --git a/Package.swift b/Package.swift index 5e8bafa02..ce22f3cc3 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version: 5.8 +// swift-tools-version: 5.10 import PackageDescription @@ -6,7 +6,7 @@ let package = Package( name: "OpenAPIKit", platforms: [ .macOS(.v10_15), - .iOS(.v11) + .iOS(.v12) ], products: [ .library( diff --git a/README.md b/README.md index af529d64b..b1d83ca0a 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,24 @@ -[![sswg:sandbox|94x20](https://img.shields.io/badge/sswg-sandbox-lightgrey.svg)](https://github.com/swift-server/sswg/blob/master/process/incubation.md#sandbox-level) [![Swift 5.8+](http://img.shields.io/badge/Swift-5.8+-blue.svg)](https://swift.org) +[![sswg:sandbox|94x20](https://img.shields.io/badge/sswg-sandbox-lightgrey.svg)](https://github.com/swift-server/sswg/blob/master/process/incubation.md#sandbox-level) [![Swift 5.10+](http://img.shields.io/badge/Swift-5.10+-blue.svg)](https://swift.org) [![MIT license](http://img.shields.io/badge/license-MIT-lightgrey.svg)](http://opensource.org/licenses/MIT) ![Tests](https://github.com/mattpolzin/OpenAPIKit/actions/workflows/tests.yml/badge.svg?branch=main) # OpenAPIKit -A library containing Swift types that encode to- and decode from [OpenAPI 3.0.x](https://spec.openapis.org/oas/v3.0.4.html) and [OpenAPI 3.1.x](https://spec.openapis.org/oas/v3.1.1.html) Documents and their components. +A library containing Swift types that encode to- and decode from [OpenAPI 3.0.x](https://spec.openapis.org/oas/v3.0.4.html), [OpenAPI 3.1.x](https://spec.openapis.org/oas/v3.1.2.html), and [OpenAPI 3.2.x](https://spec.openapis.org/oas/v3.2.0.html) Documents and their components. OpenAPIKit follows semantic versioning despite the fact that the OpenAPI specificaiton does not. The following chart shows which OpenAPI specification versions and key features are supported by which OpenAPIKit versions. -| OpenAPIKit | Swift | OpenAPI v3.0 | OpenAPI v3.1 | External Dereferencing & Sendable | -|------------|-------|--------------|--------------|-----------------------------------| -| v2.x | 5.1+ | ✅ | | | -| v3.x | 5.1+ | ✅ | ✅ | | -| v4.x | 5.8+ | ✅ | ✅ | ✅ | +| OpenAPIKit | Swift | OpenAPI v3.0, v3.1 | External Dereferencing & Sendable | OpenAPI v3.2 | +|------------|-------|--------------------|-----------------------------------|--------------| +| v3.x | 5.1+ | ✅ | | | +| v4.x | 5.8+ | ✅ | ✅ | | +| v4.x | 5.8+ | ✅ | ✅ | ✅ | - [Usage](#usage) - [Migration](#migration) - - [1.x to 2.x](#1.x-to-2.x) - - [2.x to 3.x](#2.x-to-3.x) - - [3.x to 4.x](#3.x-to-4.x) + - [Older Versions](#older-versions) + - [3.x to 4.x](#3x-to-4x) + - [4.x to 5.x](#4x-to-5x) - [Decoding OpenAPI Documents](#decoding-openapi-documents) - [Decoding Errors](#decoding-errors) - [Encoding OpenAPI Documents](#encoding-openapi-documents) @@ -47,40 +47,25 @@ OpenAPIKit follows semantic versioning despite the fact that the OpenAPI specifi ## Usage ### Migration -#### 1.x to 2.x -If you are migrating from OpenAPIKit 1.x to OpenAPIKit 2.x, check out the [v2 migration guide](./documentation/v2_migration_guide.md). +#### Older Versions +- [`1.x` to `2.x`](./documentation/migration_guides/v2_migration_guide.md) +- [`2.x` to `3.x`](./documentation/migration_guides/v3_migration_guide.md) -#### 2.x to 3.x -If you are migrating from OpenAPIKit 2.x to OpenAPIKit 3.x, check out the [v3 migration guide](./documentation/v3_migration_guide.md). - -You will need to start being explicit about which of the two new modules you want to use in your project: `OpenAPIKit` (now supports OpenAPI spec v3.1) and/or `OpenAPIKit30` (continues to support OpenAPI spec v3.0 like the previous versions of OpenAPIKit did). - -In package manifests, dependencies will be one of: -``` -// v3.0 of spec: -dependencies: [.product(name: "OpenAPIKit30", package: "OpenAPIKit")] - -// v3.1 of spec: -dependencies: [.product(name: "OpenAPIKit", package: "OpenAPIKit")] -``` - -Your imports need to be specific as well: -```swift -// v3.0 of spec: -import OpenAPIKit30 +#### 3.x to 4.x +If you are migrating from OpenAPIKit 3.x to OpenAPIKit 4.x, check out the [v4 migration guide](./documentation/migration_guides/v4_migration_guide.md). -// v3.1 of spec: -import OpenAPIKit -``` +Be aware of the changes to minimum Swift version and minimum Yams version (although Yams is only a test dependency of OpenAPIKit). -It is recommended that you build your project against the `OpenAPIKit` module and only use `OpenAPIKit30` to support reading OpenAPI 3.0.x documents in and then [converting them](#supporting-openapi-30x-documents) to OpenAPI 3.1.x documents. The situation not supported yet by this strategy is where you need to write out an OpenAPI 3.0.x document (as opposed to 3.1.x). That is a planned feature but it has not yet been implemented. If your use-case benefits from reading in an OpenAPI 3.0.x document and also writing out an OpenAPI 3.0.x document then you can operate entirely against the `OpenAPIKit30` module. +#### 4.x to 5.x +If you are migrating from OpenAPIKit 4.x to OpenAPIKit 5.x, check out the [v5 migration guide](./documentation/migration_guides/v5_migration_guide.md). -#### 3.x to 4.x -If you are migrating from OpenAPIKit 3.x to OpenAPIKit 4.x, check out the [v4 migration guide](./documentation/v4_migration_guide.md). +Be aware of the change to minimum Swift version. ### Decoding OpenAPI Documents -Most documentation will focus on what it looks like to work with the `OpenAPIKit` module and OpenAPI 3.1.x documents. If you need to support OpenAPI 3.0.x documents, take a look at the section on [supporting OpenAPI 3.0.x documents](#supporting-openapi-30x-documents) before you get too deep into this library's docs. +Most documentation will focus on what it looks like to work with the `OpenAPIKit` module and OpenAPI 3.2.x documents. If you need to support OpenAPI 3.0.x documents, take a look at the section on [supporting OpenAPI 3.0.x documents](#supporting-openapi-30x-documents) before you get too deep into this library's docs. + +Version 3.2.x of the OpenAPI Specification is backwards compatible with version 3.1.x of the specification but it adds some new features. The OpenAPIKit types support these new features regardless of what the stated Document version is, but if a Document states that it is version 3.1.x and it uses OAS 3.2.x features then OpenAPIKit will produce a warning. If you run strict validations on the document, those warnings will be errors. If you choose not to run strict validations on the document, you can handle such a document leniently. You can decode a JSON OpenAPI document (i.e. using the `JSONDecoder` from **Foundation** library) or a YAML OpenAPI document (i.e. using the `YAMLDecoder` from the [**Yams**](https://github.com/jpsim/Yams) library) with the following code: ```swift @@ -148,21 +133,21 @@ You can use this same validation system to dig arbitrarily deep into an OpenAPI ### Supporting OpenAPI 3.0.x Documents If you need to operate on OpenAPI 3.0.x documents and only 3.0.x documents, you can use the `OpenAPIKit30` module throughout your code. -However, if you need to operate on both OpenAPI 3.0.x and 3.1.x documents, the recommendation is to use the OpenAPIKit compatibility layer to read in a 3.0.x document and convert it to a 3.1.x document so that you can use just the one set of Swift types throughout most of your program. An example of that follows. +However, if you need to operate on both OpenAPI 3.0.x and 3.1.x/3.2.x documents, the recommendation is to use the OpenAPIKit compatibility layer to read in a 3.0.x document and convert it to a 3.1.x or 3.2.x document so that you can use just the one set of Swift types throughout most of your program. An example of that follows. -In this example, only one file in the whole project needs to import `OpenAPIKit30` or `OpenAPIKitCompat`. Every other file would just import `OpenAPIKit` and work with the document in the 3.1.x format. +In this example, only one file in the whole project needs to import `OpenAPIKit30` or `OpenAPIKitCompat`. Every other file would just import `OpenAPIKit` and work with the document in the 3.2.x format. -#### Converting from 3.0.x to 3.1.x +#### Converting from 3.0.x to 3.2.x ```swift // import OpenAPIKit30 for OpenAPI 3.0 document support import OpenAPIKit30 -// import OpenAPIKit for OpenAPI 3.1 document support +// import OpenAPIKit for OpenAPI 3.2 document support import OpenAPIKit // import OpenAPIKitCompat to convert between the versions import OpenAPIKitCompat -// if most of your project just works with OpenAPI v3.1, most files only need to import OpenAPIKit. -// Only in the file where you are supporting converting from OpenAPI v3.0 to v3.1 do you need the +// if most of your project just works with OpenAPI v3.2, most files only need to import OpenAPIKit. +// Only in the file where you are supporting converting from OpenAPI v3.0 to v3.2 do you need the // other two imports. // we can support either version by attempting to parse an old version and then a new version if the old version fails @@ -171,12 +156,12 @@ let newDoc: OpenAPIKit.OpenAPI.Document oldDoc = try? JSONDecoder().decode(OpenAPI.Document.self, from: someFileData) -newDoc = oldDoc?.convert(to: .v3_1_1) ?? +newDoc = oldDoc?.convert(to: .v3_2_0) ?? (try! JSONDecoder().decode(OpenAPI.Document.self, from: someFileData)) -// ^ Here we simply fall-back to 3.1.x if loading as 3.0.x failed. You could do a more +// ^ Here we simply fall-back to 3.2.x if loading as 3.0.x failed. You could do a more // graceful job of this by determining up front which version to attempt to load or by // holding onto errors for each decode attempt so you can tell the user why the document -// failed to decode as neither 3.0.x nor 3.1.x if it fails in both cases. +// failed to decode as neither 3.0.x nor 3.2.x if it fails in both cases. ``` ### A note on dictionary ordering @@ -187,7 +172,7 @@ If retaining order is important for your use-case, I recommend the [**Yams**](ht The Foundation JSON encoding and decoding will be the most stable and battle-tested option with Yams as a pretty well established and stable option as well. FineJSON is lesser used (to my knowledge) but I have had success with it in the past. ### OpenAPI Document structure -The types used by this library largely mirror the object definitions found in the OpenAPI specification [version 3.1.1](https://spec.openapis.org/oas/v3.1.1.html) (`OpenAPIKit` module) and [version 3.0.4](https://spec.openapis.org/oas/v3.0.4.html) (`OpenAPIKit30` module). The [Project Status](#project-status) lists each object defined by the spec and the name of the respective type in this library. The project status page currently focuses on OpenAPI 3.1.x but for the purposes of determining what things are named and what is supported you can mostly infer the status of the OpenAPI 3.0.x support as well. +The types used by this library largely mirror the object definitions found in the OpenAPI specification [version 3.2.0](https://spec.openapis.org/oas/v3.2.0.html) (`OpenAPIKit` module) and [version 3.0.4](https://spec.openapis.org/oas/v3.0.4.html) (`OpenAPIKit30` module). The [Project Status](#project-status) lists each object defined by the spec and the name of the respective type in this library. The project status page currently focuses on OpenAPI 3.2.x but for the purposes of determining what things are named and what is supported you can mostly infer the status of the OpenAPI 3.0.x support as well. #### Document Root At the root there is an `OpenAPI.Document`. In addition to some information that applies to the entire API, the document contains `OpenAPI.Components` (essentially a dictionary of reusable components that can be referenced with `JSONReferences` and `OpenAPI.References`) and an `OpenAPI.PathItem.Map` (a dictionary of routes your API defines). @@ -210,7 +195,7 @@ A schema can be made **optional** (i.e. it can be omitted) with `JSONSchema.inte A schema can be made **nullable** with `JSONSchema.number(nullable: true)` or an existing schema can be asked for a `nullableSchemaObject()`. -Nullability highlights an important decision OpenAPIKit makes. The JSON Schema specification that dictates how OpenAPI v3.1 documents _encode_ nullability states that a nullable property is encoded as having the `null` type in addition to whatever other type(s) it has. So in OpenAPIKit you set `nullability` as a property of a schema, but when encoded/decoded it will represent the inclusion of absence of `null` in the list of `type`s of the schema. If you are using the `OpenAPIKit30` module then nullability is encoded as a `nullable` property per the OpenAPI 3.0.x specification. +Nullability highlights an important decision OpenAPIKit makes. The JSON Schema specification that dictates how OpenAPI v3.2 documents _encode_ nullability states that a nullable property is encoded as having the `null` type in addition to whatever other type(s) it has. So in OpenAPIKit you set `nullability` as a property of a schema, but when encoded/decoded it will represent the inclusion of absence of `null` in the list of `type`s of the schema. If you are using the `OpenAPIKit30` module then nullability is encoded as a `nullable` property per the OpenAPI 3.0.x specification. Some types of schemas can be further specialized with a **format**. For example, `JSONSchema.number(format: .double)` or `JSONSchema.string(format: .dateTime)`. @@ -311,7 +296,7 @@ let document = OpenAPI.Document( ``` #### Specification Extensions -Many OpenAPIKit types support [Specification Extensions](https://spec.openapis.org/oas/v3.1.1.html#specification-extensions). As described in the OpenAPI Specification, these extensions must be objects that are keyed with the prefix "x-". For example, a property named "specialProperty" on the root OpenAPI Object (`OpenAPI.Document`) is invalid but the property "x-specialProperty" is a valid specification extension. +Many OpenAPIKit types support [Specification Extensions](https://spec.openapis.org/oas/v3.2.0.html#specification-extensions). As described in the OpenAPI Specification, these extensions must be objects that are keyed with the prefix "x-". For example, a property named "specialProperty" on the root OpenAPI Object (`OpenAPI.Document`) is invalid but the property "x-specialProperty" is a valid specification extension. You can get or set specification extensions via the [`vendorExtensions`](https://mattpolzin.github.io/OpenAPIKit/documentation/openapikit/vendorextendable/vendorextensions-swift.property) property on any object that supports this feature. The keys are `Strings` beginning with the aforementioned "x-" prefix and the values are `AnyCodable`. If you set an extension without using the "x-" prefix, the prefix will be added upon encoding. diff --git a/Sources/OpenAPIKit/Document/Document.swift b/Sources/OpenAPIKit/Document/Document.swift index 2b3afa73d..d2a591c85 100644 --- a/Sources/OpenAPIKit/Document/Document.swift +++ b/Sources/OpenAPIKit/Document/Document.swift @@ -6,6 +6,7 @@ // import OpenAPIKitCore +import Foundation extension OpenAPI { /// The root of an OpenAPI 3.1 document. @@ -45,7 +46,7 @@ extension OpenAPI { /// /// See the documentation on `DereferencedDocument.resolved()` for more. /// - public struct Document: HasWarnings, CodableVendorExtendable, Sendable { + public struct Document: HasConditionalWarnings, HasWarnings, CodableVendorExtendable, Sendable { /// OpenAPI Spec "openapi" field. /// /// OpenAPIKit only explicitly supports versions that can be found in @@ -53,6 +54,9 @@ extension OpenAPI { /// by OpenAPIKit to a certain extent. public var openAPIVersion: Version + /// OpenAPI Spec "$self" field. + public var selfURI: URL? + /// Information about the API described by this OpenAPI Document. /// /// Licensing, Terms of Service, contact information, API version (the @@ -142,9 +146,11 @@ extension OpenAPI { public var vendorExtensions: [String: AnyCodable] public let warnings: [Warning] + public let conditionalWarnings: [(any Condition, OpenAPI.Warning)] public init( openAPIVersion: Version = .v3_1_1, + selfURI: URL? = nil, info: Info, servers: [Server], paths: PathItem.Map, @@ -156,6 +162,7 @@ extension OpenAPI { vendorExtensions: [String: AnyCodable] = [:] ) { self.openAPIVersion = openAPIVersion + self.selfURI = selfURI self.info = info self.servers = servers self.paths = paths @@ -167,13 +174,28 @@ extension OpenAPI { self.vendorExtensions = vendorExtensions self.warnings = [] + + self.conditionalWarnings = [ + // If $self is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "$self", value: selfURI, minimumVersion: .v3_2_0), + ].compactMap { $0 } } } } +fileprivate func nonNilVersionWarning(fieldName: String, value: Subject?, minimumVersion: OpenAPI.Document.Version) -> (any Condition, OpenAPI.Warning)? { + value.map { _ in + OpenAPI.Document.ConditionalWarnings.version( + lessThan: minimumVersion, + doesNotSupport: "The Document \(fieldName) field" + ) + } +} + extension OpenAPI.Document: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { lhs.openAPIVersion == rhs.openAPIVersion + && lhs.selfURI == rhs.selfURI && lhs.info == rhs.info && lhs.servers == rhs.servers && lhs.paths == rhs.paths @@ -449,21 +471,28 @@ extension OpenAPI.Document { /// specification releases a new patch version, OpenAPIKit will see a patch version release /// explicitly supports decoding documents of that new patch version before said version will /// succesfully decode as the `v3_1_x` case. - public enum Version: RawRepresentable, Equatable, Codable, Sendable { + public enum Version: RawRepresentable, Equatable, Comparable, Codable, Sendable { case v3_1_0 case v3_1_1 + case v3_1_2 case v3_1_x(x: Int) + case v3_2_0 + case v3_2_x(x: Int) + public init?(rawValue: String) { switch rawValue { case "3.1.0": self = .v3_1_0 case "3.1.1": self = .v3_1_1 + case "3.1.2": self = .v3_1_2 + case "3.2.0": self = .v3_2_0 default: let components = rawValue.split(separator: ".") guard components.count == 3 else { return nil } - guard components[0] == "3", components[1] == "1" else { + let minorVersion = components[1] + guard components[0] == "3", (minorVersion == "1" || minorVersion == "2") else { return nil } guard let patchVersion = Int(components[2], radix: 10) else { @@ -472,10 +501,17 @@ extension OpenAPI.Document { // to support newer versions released in the future without a breaking // change to the enumeration, bump the upper limit here to e.g. 2 or 3 // or 6: - guard patchVersion > 1 && patchVersion <= 2 else { - return nil + if minorVersion == "2" { + guard patchVersion > 0 && patchVersion <= 0 else { + return nil + } + self = .v3_2_x(x: patchVersion) + } else { + guard patchVersion > 2 && patchVersion <= 2 else { + return nil + } + self = .v3_1_x(x: patchVersion) } - self = .v3_1_x(x: patchVersion) } } @@ -483,7 +519,75 @@ extension OpenAPI.Document { switch self { case .v3_1_0: return "3.1.0" case .v3_1_1: return "3.1.1" + case .v3_1_2: return "3.1.2" case .v3_1_x(x: let x): return "3.1.\(x)" + + case .v3_2_0: return "3.2.0" + case .v3_2_x(x: let x): return "3.2.\(x)" + } + } + + public static func < (lhs: Self, rhs: Self) -> Bool { + switch lhs { + case .v3_1_0: + switch rhs { + case .v3_1_0: false + case .v3_1_1: true + case .v3_1_2: true + case .v3_1_x(x: let x): 0 < x + case .v3_2_0: true + case .v3_2_x(x: _): true + } + + case .v3_1_1: + switch rhs { + case .v3_1_0: false + case .v3_1_1: false + case .v3_1_2: true + case .v3_1_x(x: let y): 1 < y + case .v3_2_0: true + case .v3_2_x(x: _): true + } + + case .v3_1_2: + switch rhs { + case .v3_1_0: false + case .v3_1_1: false + case .v3_1_2: false + case .v3_1_x(x: let y): 2 < y + case .v3_2_0: true + case .v3_2_x(x: _): true + } + + case .v3_1_x(x: let x): + switch rhs { + case .v3_1_0: x < 0 + case .v3_1_1: x < 1 + case .v3_1_2: x < 2 + case .v3_1_x(x: let y): x < y + case .v3_2_0: true + case .v3_2_x(x: _): true + } + + case .v3_2_0: + switch rhs { + case .v3_1_0: false + case .v3_1_1: false + case .v3_1_2: false + case .v3_1_x(x: _): false + case .v3_2_0: false + case .v3_2_x(x: let y): 0 < y + } + + case .v3_2_x(x: let x): + switch rhs { + case .v3_1_0: false + case .v3_1_1: false + case .v3_1_2: false + case .v3_1_x(x: _): false + case .v3_2_0: x < 0 + case .v3_2_x(x: let y): x < y + } } } } @@ -520,6 +624,9 @@ extension OpenAPI.Document: Encodable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(openAPIVersion, forKey: .openAPIVersion) + + try container.encodeIfPresent(selfURI?.absoluteString, forKey: .selfURI) + try container.encode(info, forKey: .info) try container.encodeIfPresent(externalDocs, forKey: .externalDocs) @@ -579,6 +686,11 @@ extension OpenAPI.Document: Decodable { ) } + let selfURIString: String? = try container.decodeIfPresent(String.self, forKey: .selfURI) + selfURI = try selfURIString.map { + try decodeURIString($0, forKey: CodingKeys.selfURI, atPath: decoder.codingPath) + } + info = try container.decode(OpenAPI.Document.Info.self, forKey: .info) servers = try container.decodeIfPresent([OpenAPI.Server].self, forKey: .servers) ?? [] @@ -599,6 +711,11 @@ extension OpenAPI.Document: Decodable { self.warnings = warnings + self.conditionalWarnings = [ + // If $self is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "$self", value: selfURI, minimumVersion: .v3_2_0), + ].compactMap { $0 } + } catch let error as OpenAPI.Error.Decoding.Path { throw OpenAPI.Error.Decoding.Document(error) @@ -615,9 +732,34 @@ extension OpenAPI.Document: Decodable { } } +fileprivate func decodeURIString(_ str: String, forKey key: CodingKey, atPath path: [CodingKey]) throws -> URL { + let uri: URL? + #if canImport(FoundationEssentials) + uri = URL(string: str, encodingInvalidCharacters: false) + #elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + if #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) { + uri = URL(string: str, encodingInvalidCharacters: false) + } else { + uri = URL(string: str) + } + #else + uri = URL(string: str) + #endif + guard let uri else { + throw GenericError( + subjectName: key.stringValue, + details: "Failed to parse a valid URI from '\(str)'", + codingPath: path + ) + } + + return uri +} + extension OpenAPI.Document { internal enum CodingKeys: ExtendableCodingKey { case openAPIVersion + case selfURI case info case jsonSchemaDialect // TODO: implement parsing (https://github.com/mattpolzin/OpenAPIKit/issues/202) case servers @@ -632,6 +774,7 @@ extension OpenAPI.Document { static var allBuiltinKeys: [CodingKeys] { return [ .openAPIVersion, + .selfURI, .info, .jsonSchemaDialect, .servers, @@ -652,6 +795,8 @@ extension OpenAPI.Document { switch stringValue { case "openapi": self = .openAPIVersion + case "$self": + self = .selfURI case "info": self = .info case "jsonSchemaDialect": @@ -679,6 +824,8 @@ extension OpenAPI.Document { switch self { case .openAPIVersion: return "openapi" + case .selfURI: + return "$self" case .info: return "info" case .jsonSchemaDialect: diff --git a/Sources/OpenAPIKit/Either/Either+Convenience.swift b/Sources/OpenAPIKit/Either/Either+Convenience.swift index f468f0ca2..f9cd238dc 100644 --- a/Sources/OpenAPIKit/Either/Either+Convenience.swift +++ b/Sources/OpenAPIKit/Either/Either+Convenience.swift @@ -169,6 +169,8 @@ extension Either where B == OpenAPI.PathItem { head: OpenAPI.Operation? = nil, patch: OpenAPI.Operation? = nil, trace: OpenAPI.Operation? = nil, + query: OpenAPI.Operation? = nil, + additionalOperations: OrderedDictionary = [:], vendorExtensions: [String: AnyCodable] = [:] ) { self = .b( @@ -185,6 +187,8 @@ extension Either where B == OpenAPI.PathItem { head: head, patch: patch, trace: trace, + query: query, + additionalOperations: additionalOperations, vendorExtensions: vendorExtensions ) ) diff --git a/Sources/OpenAPIKit/Encoding and Decoding Errors/PathDecodingError.swift b/Sources/OpenAPIKit/Encoding and Decoding Errors/PathDecodingError.swift index 4de8c4e44..30023d0ab 100644 --- a/Sources/OpenAPIKit/Encoding and Decoding Errors/PathDecodingError.swift +++ b/Sources/OpenAPIKit/Encoding and Decoding Errors/PathDecodingError.swift @@ -104,7 +104,7 @@ extension OpenAPI.Error.Decoding.Path { internal init(_ error: DecodingError) { var codingPath = error.codingPathWithoutSubject.dropFirst() - let route = OpenAPI.Path(rawValue: codingPath.removeFirst().stringValue) + let route = OpenAPI.Path(rawValue: codingPath.removeFirstPathComponentString()) path = route context = .other(error) @@ -113,7 +113,7 @@ extension OpenAPI.Error.Decoding.Path { internal init(_ error: OpenAPI.Error.Decoding.Operation) { var codingPath = error.codingPath.dropFirst() - let route = OpenAPI.Path(rawValue: codingPath.removeFirst().stringValue) + let route = OpenAPI.Path(rawValue: codingPath.removeFirstPathComponentString()) path = route context = .endpoint(error) @@ -122,7 +122,7 @@ extension OpenAPI.Error.Decoding.Path { internal init(_ error: GenericError) { var codingPath = error.codingPath.dropFirst() - let route = OpenAPI.Path(rawValue: codingPath.removeFirst().stringValue) + let route = OpenAPI.Path(rawValue: codingPath.removeFirstPathComponentString()) path = route context = .inconsistency(error) @@ -148,7 +148,7 @@ extension OpenAPI.Error.Decoding.Path { // } var codingPath = eitherError.codingPath.dropFirst() - let route = OpenAPI.Path(rawValue: codingPath.removeFirst().stringValue) + let route = OpenAPI.Path(rawValue: codingPath.removeFirstPathComponentString()) path = route context = .neither(eitherError) diff --git a/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift new file mode 100644 index 000000000..ed4092da2 --- /dev/null +++ b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift @@ -0,0 +1,55 @@ +public protocol Condition: Equatable, Sendable { + /// Given an entire OpenAPI Document, determine the applicability of the + /// condition. + func applies(to: OpenAPI.Document) -> Bool +} + +public protocol HasConditionalWarnings { + /// Warnings that only apply if the paired condition is met. + /// + /// Among other things, this allows OpenAPIKit to generate a warning in + /// some nested type that only applies if the OpenAPI Standards version of + /// the document is less than a certain version. + var conditionalWarnings: [(any Condition, OpenAPI.Warning)] { get } +} + +extension HasConditionalWarnings { + public func applicableConditionalWarnings(for subject: OpenAPI.Document) -> [OpenAPI.Warning] { + conditionalWarnings.compactMap { (condition, warning) in + guard condition.applies(to: subject) else { return nil } + + return warning + } + } +} + +internal struct DocumentVersionCondition: Sendable, Condition { + enum Comparator: Sendable { + case lessThan + case equal + case greaterThan + } + + let version: OpenAPI.Document.Version + let comparator: Comparator + + func applies(to document: OpenAPI.Document) -> Bool { + switch comparator { + case .lessThan: document.openAPIVersion < version + + case .equal: document.openAPIVersion == version + + case .greaterThan: document.openAPIVersion > version + } + } +} + +internal extension OpenAPI.Document { + struct ConditionalWarnings { + static func version(lessThan version: OpenAPI.Document.Version, doesNotSupport subject: String) -> (any Condition, OpenAPI.Warning) { + let warning = OpenAPI.Warning.message("\(subject) is only supported for OpenAPI document versions \(version.rawValue) and later") + + return (DocumentVersionCondition(version: version, comparator: .lessThan), warning) + } + } +} diff --git a/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift b/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift index d9f25538f..cdc11150d 100644 --- a/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift +++ b/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift @@ -34,6 +34,13 @@ public struct DereferencedPathItem: Equatable { public let patch: DereferencedOperation? /// The dereferenced TRACE operation, if defined. public let trace: DereferencedOperation? + /// The dereferenced QUERY operation, if defined. + public let query: DereferencedOperation? + + /// Additional operations, keyed by all-caps HTTP method names. This + /// map MUST NOT contain any entries that can be represented by the + /// fixed fields on this type (e.g. `post`, `get`, etc.). + public let additionalOperations: OrderedDictionary public subscript(dynamicMember path: KeyPath) -> T { return underlyingPathItem[keyPath: path] @@ -64,6 +71,9 @@ public struct DereferencedPathItem: Equatable { self.head = try pathItem.head.map { try DereferencedOperation($0, resolvingIn: components, following: references) } self.patch = try pathItem.patch.map { try DereferencedOperation($0, resolvingIn: components, following: references) } self.trace = try pathItem.trace.map { try DereferencedOperation($0, resolvingIn: components, following: references) } + self.query = try pathItem.query.map { try DereferencedOperation($0, resolvingIn: components, following: references) } + + self.additionalOperations = try pathItem.additionalOperations.mapValues { try DereferencedOperation($0, resolvingIn: components, following: references) } var pathItem = pathItem if let name { @@ -80,22 +90,20 @@ extension DereferencedPathItem { /// Retrieve the operation for the given verb, if one is set for this path. public func `for`(_ verb: OpenAPI.HttpMethod) -> DereferencedOperation? { switch verb { - case .delete: - return self.delete - case .get: - return self.get - case .head: - return self.head - case .options: - return self.options - case .patch: - return self.patch - case .post: - return self.post - case .put: - return self.put - case .trace: - return self.trace + case .builtin(let builtin): + switch builtin { + case .delete: self.delete + case .get: self.get + case .head: self.head + case .options: self.options + case .patch: self.patch + case .post: self.post + case .put: self.put + case .trace: self.trace + case .query: self.query + } + case .other(let other): + additionalOperations[.other(other)] } } @@ -117,9 +125,11 @@ extension DereferencedPathItem { /// - Returns: An array of `Endpoints` with the method (i.e. `.get`) and the operation for /// the method. public var endpoints: [Endpoint] { - return OpenAPI.HttpMethod.allCases.compactMap { method in - self.for(method).map { .init(method: method, operation: $0) } + let builtins = OpenAPI.BuiltinHttpMethod.allCases.compactMap { method -> Endpoint? in + self.for(.builtin(method)).map { .init(method: .builtin(method), operation: $0) } } + + return builtins + additionalOperations.map { key, value in .init(method: key, operation: value) } } } @@ -151,6 +161,9 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { let oldHead = head let oldPatch = patch let oldTrace = trace + let oldQuery = query + + let oldAdditionalOperations = additionalOperations async let (newParameters, c1, m1) = oldParameters.externallyDereferenced(with: loader) // async let (newServers, c2, m2) = oldServers.externallyDereferenced(with: loader) @@ -162,6 +175,9 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { async let (newHead, c8, m8) = oldHead.externallyDereferenced(with: loader) async let (newPatch, c9, m9) = oldPatch.externallyDereferenced(with: loader) async let (newTrace, c10, m10) = oldTrace.externallyDereferenced(with: loader) + async let (newQuery, c11, m11) = oldQuery.externallyDereferenced(with: loader) + + async let (newAdditionalOperations, c12, m12) = oldAdditionalOperations.externallyDereferenced(with: loader) var pathItem = self var newComponents = try await c1 @@ -179,6 +195,8 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { pathItem.head = try await newHead pathItem.patch = try await newPatch pathItem.trace = try await newTrace + pathItem.query = try await newQuery + pathItem.additionalOperations = try await newAdditionalOperations try await newComponents.merge(c3) try await newComponents.merge(c4) @@ -188,6 +206,8 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { try await newComponents.merge(c8) try await newComponents.merge(c9) try await newComponents.merge(c10) + try await newComponents.merge(c11) + try await newComponents.merge(c12) try await newMessages += m3 try await newMessages += m4 @@ -197,6 +217,8 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { try await newMessages += m8 try await newMessages += m9 try await newMessages += m10 + try await newMessages += m11 + try await newMessages += m12 if let oldServers { async let (newServers, c2, m2) = oldServers.externallyDereferenced(with: loader) diff --git a/Sources/OpenAPIKit/Path Item/PathItem.swift b/Sources/OpenAPIKit/Path Item/PathItem.swift index a98654074..dd3445d2a 100644 --- a/Sources/OpenAPIKit/Path Item/PathItem.swift +++ b/Sources/OpenAPIKit/Path Item/PathItem.swift @@ -8,7 +8,9 @@ import OpenAPIKitCore extension OpenAPI { - /// OpenAPI Spec "Path Item Object" + /// OpenAPI Spec "Path Item Object" (although in the spec the Path Item + /// Object also includes reference support which OpenAPIKit implements via + /// the PathItem.Map type) /// /// See [OpenAPI Path Item Object](https://spec.openapis.org/oas/v3.1.1.html#path-item-object). /// @@ -21,7 +23,7 @@ extension OpenAPI { /// /// You can access an array of equatable `HttpMethod`/`Operation` paris with the /// `endpoints` property. - public struct PathItem: Equatable, CodableVendorExtendable, Sendable { + public struct PathItem: HasConditionalWarnings, CodableVendorExtendable, Sendable { public var summary: String? public var description: String? public var servers: [OpenAPI.Server]? @@ -52,6 +54,13 @@ extension OpenAPI { public var patch: Operation? /// The `TRACE` endpoint at this path, if one exists. public var trace: Operation? + /// The `QUERY` endpoint at this path, if one exists. + public var query: Operation? + + /// Additional operations, keyed by all-caps HTTP method names. This + /// map MUST NOT contain any entries that can be represented by the + /// fixed fields on this type (e.g. `post`, `get`, etc.). + public var additionalOperations: OrderedDictionary /// Dictionary of vendor extensions. /// @@ -60,6 +69,12 @@ extension OpenAPI { /// where the values are anything codable. public var vendorExtensions: [String: AnyCodable] + /// Warnings that apply conditionally depending on the OpenAPI Document + /// the PathItem belongs to. + /// + /// Check these with the `applicableConditionalWarnings(for:)` method. + public let conditionalWarnings: [(any Condition, OpenAPI.Warning)] + public init( summary: String? = nil, description: String? = nil, @@ -73,6 +88,8 @@ extension OpenAPI { head: Operation? = nil, patch: Operation? = nil, trace: Operation? = nil, + query: Operation? = nil, + additionalOperations: OrderedDictionary = [:], vendorExtensions: [String: AnyCodable] = [:] ) { self.summary = summary @@ -88,7 +105,16 @@ extension OpenAPI { self.head = head self.patch = patch self.trace = trace + self.query = query + self.additionalOperations = additionalOperations self.vendorExtensions = vendorExtensions + + self.conditionalWarnings = [ + // If query is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "query", value: query, minimumVersion: .v3_2_0), + // If there are additionalOperations defiend, the document must be OAS version 3.2.0 or greater + nonEmptyVersionWarning(fieldName: "additionalOperations", value: additionalOperations, minimumVersion: .v3_2_0) + ].compactMap { $0 } } /// Set the `GET` endpoint operation. @@ -130,9 +156,52 @@ extension OpenAPI { public mutating func trace(_ op: Operation?) { trace = op } + + /// Set the `QUERY` endpoint operation. + public mutating func query(_ op: Operation?) { + query = op + } + } +} + +extension OpenAPI.PathItem: Equatable { + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.summary == rhs.summary + && lhs.description == rhs.description + && lhs.servers == rhs.servers + && lhs.parameters == rhs.parameters + && lhs.get == rhs.get + && lhs.put == rhs.put + && lhs.post == rhs.post + && lhs.delete == rhs.delete + && lhs.options == rhs.options + && lhs.head == rhs.head + && lhs.patch == rhs.patch + && lhs.trace == rhs.trace + && lhs.query == rhs.query + && lhs.additionalOperations == rhs.additionalOperations + && lhs.vendorExtensions == rhs.vendorExtensions + } +} + +fileprivate func nonNilVersionWarning(fieldName: String, value: Subject?, minimumVersion: OpenAPI.Document.Version) -> (any Condition, OpenAPI.Warning)? { + value.map { _ in + OpenAPI.Document.ConditionalWarnings.version( + lessThan: minimumVersion, + doesNotSupport: "The PathItem \(fieldName) field" + ) } } +fileprivate func nonEmptyVersionWarning(fieldName: String, value: OrderedDictionary, minimumVersion: OpenAPI.Document.Version) -> (any Condition, OpenAPI.Warning)? { + if value.isEmpty { return nil } + + return OpenAPI.Document.ConditionalWarnings.version( + lessThan: minimumVersion, + doesNotSupport: "The PathItem \(fieldName) map" + ) +} + extension OpenAPI.PathItem { public typealias Map = OrderedDictionary, OpenAPI.PathItem>> } @@ -148,44 +217,49 @@ extension OpenAPI.PathItem { /// Retrieve the operation for the given verb, if one is set for this path. public func `for`(_ verb: OpenAPI.HttpMethod) -> OpenAPI.Operation? { switch verb { - case .delete: - return self.delete - case .get: - return self.get - case .head: - return self.head - case .options: - return self.options - case .patch: - return self.patch - case .post: - return self.post - case .put: - return self.put - case .trace: - return self.trace + case .builtin(let builtin): + switch builtin { + case .delete: self.delete + case .get: self.get + case .head: self.head + case .options: self.options + case .patch: self.patch + case .post: self.post + case .put: self.put + case .trace: self.trace + case .query: self.query + } + case .other(let other): + additionalOperations[.other(other)] } } /// Set the operation for the given verb, overwriting any already set operation for the same verb. public mutating func set(operation: OpenAPI.Operation?, for verb: OpenAPI.HttpMethod) { switch verb { - case .delete: - self.delete(operation) - case .get: - self.get(operation) - case .head: - self.head(operation) - case .options: - self.options(operation) - case .patch: - self.patch(operation) - case .post: - self.post(operation) - case .put: - self.put(operation) - case .trace: - self.trace(operation) + case .builtin(let builtin): + switch builtin { + case .delete: + self.delete(operation) + case .get: + self.get(operation) + case .head: + self.head(operation) + case .options: + self.options(operation) + case .patch: + self.patch(operation) + case .post: + self.post(operation) + case .put: + self.put(operation) + case .trace: + self.trace(operation) + case .query: + self.query(operation) + } + case .other(let other): + self.additionalOperations[.other(other)] = operation } } @@ -210,9 +284,11 @@ extension OpenAPI.PathItem { /// - Returns: An array of `Endpoints` with the method (i.e. `.get`) and the operation for /// the method. public var endpoints: [Endpoint] { - return OpenAPI.HttpMethod.allCases.compactMap { method in - self.for(method).map { .init(method: method, operation: $0) } + let builtins = OpenAPI.BuiltinHttpMethod.allCases.compactMap { method -> Endpoint? in + self.for(.builtin(method)).map { .init(method: .builtin(method), operation: $0) } } + + return builtins + additionalOperations.map { key, value in .init(method: key, operation: value) } } } @@ -256,6 +332,11 @@ extension OpenAPI.PathItem: Encodable { try container.encodeIfPresent(head, forKey: .head) try container.encodeIfPresent(patch, forKey: .patch) try container.encodeIfPresent(trace, forKey: .trace) + try container.encodeIfPresent(query, forKey: .query) + + if !additionalOperations.isEmpty { + try container.encode(additionalOperations, forKey: .additionalOperations) + } if VendorExtensionsConfiguration.isEnabled(for: encoder) { try encodeExtensions(to: &container) @@ -281,9 +362,37 @@ extension OpenAPI.PathItem: Decodable { head = try container.decodeIfPresent(OpenAPI.Operation.self, forKey: .head) patch = try container.decodeIfPresent(OpenAPI.Operation.self, forKey: .patch) trace = try container.decodeIfPresent(OpenAPI.Operation.self, forKey: .trace) + query = try container.decodeIfPresent(OpenAPI.Operation.self, forKey: .query) + + additionalOperations = try container.decodeIfPresent(OrderedDictionary.self, forKey: .additionalOperations) ?? [:] + + let disallowedMethods = builtinHttpMethods(in: additionalOperations) + if !disallowedMethods.isEmpty { + let disallowedMethodsString = disallowedMethods + .map(\.rawValue) + .joined(separator: ", ") + + throw GenericError(subjectName: "additionalOperations", details: "Additional Operations cannot contain operations that can be set directly on the Path Item. Found the following disallowed additional operations: \(disallowedMethodsString)", codingPath: decoder.codingPath, pathIncludesSubject: false) + } vendorExtensions = try Self.extensions(from: decoder) + + self.conditionalWarnings = [ + // If query is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "query", value: query, minimumVersion: .v3_2_0), + // If there are additionalOperations defiend, the document must be OAS version 3.2.0 or greater + nonEmptyVersionWarning(fieldName: "additionalOperations", value: additionalOperations, minimumVersion: .v3_2_0) + ].compactMap { $0 } } catch let error as DecodingError { + if let underlyingError = error.underlyingError as? KeyDecodingError { + throw OpenAPI.Error.Decoding.Path( + GenericError( + subjectName: error.subjectName, + details: underlyingError.localizedDescription, + codingPath: decoder.codingPath + ) + ) + } throw OpenAPI.Error.Decoding.Path(error) } catch let error as GenericError { @@ -299,6 +408,13 @@ extension OpenAPI.PathItem: Decodable { } } +fileprivate func builtinHttpMethods(in map: OrderedDictionary) -> [OpenAPI.HttpMethod] { + map.keys + .filter { + OpenAPI.BuiltinHttpMethod.allCases.map(\.rawValue).contains($0.rawValue.uppercased()) + } +} + extension OpenAPI.PathItem { internal enum CodingKeys: ExtendableCodingKey { case summary @@ -314,6 +430,9 @@ extension OpenAPI.PathItem { case head case patch case trace + case query + + case additionalOperations case extended(String) @@ -331,7 +450,10 @@ extension OpenAPI.PathItem { .options, .head, .patch, - .trace + .trace, + .query, + + .additionalOperations ] } @@ -365,6 +487,10 @@ extension OpenAPI.PathItem { self = .patch case "trace": self = .trace + case "query": + self = .query + case "additionalOperations": + self = .additionalOperations default: self = .extendedKey(for: stringValue) } @@ -396,6 +522,10 @@ extension OpenAPI.PathItem { return "patch" case .trace: return "trace" + case .query: + return "query" + case .additionalOperations: + return "additionalOperations" case .extended(let key): return key } diff --git a/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift b/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift index ed2a7062c..ed37d68a5 100644 --- a/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift +++ b/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift @@ -64,6 +64,13 @@ public struct ResolvedRoute: Equatable { public let patch: ResolvedEndpoint? /// The HTTP `TRACE` endpoint at this route. public let trace: ResolvedEndpoint? + /// The HTTP `QUERY` endpoint at this route. + public let query: ResolvedEndpoint? + + /// Additional operations, keyed by all-caps HTTP method names. This + /// map MUST NOT contain any entries that can be represented by the + /// fixed fields on this type (e.g. `post`, `get`, etc.). + public let additionalOperations: OrderedDictionary /// Create a ResolvedRoute. /// @@ -83,11 +90,18 @@ public struct ResolvedRoute: Equatable { servers: [OpenAPI.Server], endpoints: [ResolvedEndpoint] ) { - let endpoints = Dictionary( + let builtinEndpoints = Dictionary( endpoints.map { ($0.method, $0) }, uniquingKeysWith: { $1 } ) + let otherEndpoints = endpoints.compactMap { endpoint -> (key: OpenAPI.HttpMethod, value: ResolvedEndpoint)? in + switch endpoint.method { + case .builtin(_): return nil + case .other(_): return (key: endpoint.method, value: endpoint) + } + } + self.summary = summary self.description = description self.vendorExtensions = vendorExtensions @@ -95,19 +109,22 @@ public struct ResolvedRoute: Equatable { self.parameters = parameters self.servers = servers - self.get = endpoints[.get] - self.put = endpoints[.put] - self.post = endpoints[.post] - self.delete = endpoints[.delete] - self.options = endpoints[.options] - self.head = endpoints[.head] - self.patch = endpoints[.patch] - self.trace = endpoints[.trace] + self.get = builtinEndpoints[.builtin(.get)] + self.put = builtinEndpoints[.builtin(.put)] + self.post = builtinEndpoints[.builtin(.post)] + self.delete = builtinEndpoints[.builtin(.delete)] + self.options = builtinEndpoints[.builtin(.options)] + self.head = builtinEndpoints[.builtin(.head)] + self.patch = builtinEndpoints[.builtin(.patch)] + self.trace = builtinEndpoints[.builtin(.trace)] + self.query = builtinEndpoints[.builtin(.query)] + + self.additionalOperations = OrderedDictionary(otherEndpoints, uniquingKeysWith: { $1 }) } /// An array of all endpoints at this route. public var endpoints: [ResolvedEndpoint] { - [ + let builtins = [ self.get, self.put, self.post, @@ -115,29 +132,30 @@ public struct ResolvedRoute: Equatable { self.options, self.head, self.patch, - self.trace + self.trace, + self.query ].compactMap { $0 } + + return builtins + additionalOperations.values } /// Retrieve the endpoint for the given method, if one exists for this route. public func `for`(_ verb: OpenAPI.HttpMethod) -> ResolvedEndpoint? { switch verb { - case .delete: - return self.delete - case .get: - return self.get - case .head: - return self.head - case .options: - return self.options - case .patch: - return self.patch - case .post: - return self.post - case .put: - return self.put - case .trace: - return self.trace + case .builtin(let builtin): + switch builtin { + case .delete: self.delete + case .get: self.get + case .head: self.head + case .options: self.options + case .patch: self.patch + case .post: self.post + case .put: self.put + case .trace: self.trace + case .query: self.query + } + case .other(let other): + self.additionalOperations[.other(other)] } } diff --git a/Sources/OpenAPIKit/Schema Object/JSONSchemaContext.swift b/Sources/OpenAPIKit/Schema Object/JSONSchemaContext.swift index 443a15b42..b340f8557 100644 --- a/Sources/OpenAPIKit/Schema Object/JSONSchemaContext.swift +++ b/Sources/OpenAPIKit/Schema Object/JSONSchemaContext.swift @@ -1042,7 +1042,7 @@ extension JSONSchema.CoreContext: Decodable { .underlyingError( GenericError( subjectName: "OpenAPI Schema", - details: "Found 'nullable' property. This property is not supported by OpenAPI v3.1.x. OpenAPIKit has translated it into 'type: [\"null\", ...]'.", + details: "Found 'nullable' property. This property is not supported by OpenAPI v3.1.x. OpenAPIKit has translated it into 'type: [\"null\", ...]'", codingPath: container.codingPath ) ) diff --git a/Sources/OpenAPIKit/Tag.swift b/Sources/OpenAPIKit/Tag.swift index 47393cecb..27d9adf92 100644 --- a/Sources/OpenAPIKit/Tag.swift +++ b/Sources/OpenAPIKit/Tag.swift @@ -11,10 +11,20 @@ extension OpenAPI { /// OpenAPI Spec "Tag Object" /// /// See [OpenAPI Tag Object](https://spec.openapis.org/oas/v3.1.1.html#tag-object). - public struct Tag: Equatable, CodableVendorExtendable, Sendable { + public struct Tag: HasConditionalWarnings, CodableVendorExtendable, Sendable { public let name: String + /// Summary of the tag. Available for OAS 3.2.0 and greater. + public let summary: String? public let description: String? public let externalDocs: ExternalDocumentation? + /// The tag this tag is nested under. + public let parent: String? + /// A machine-readable string to categorize what sort of tag this is. + /// Any string value can be used, but some common options are provided + /// on OpenAPIKit's `Tag.Kind` type as static properties and more can + /// be found in the public registry: + /// https://spec.openapis.org/registry/tag-kind + public let kind: Kind? /// Dictionary of vendor extensions. /// @@ -23,17 +33,89 @@ extension OpenAPI { /// where the values are anything codable. public var vendorExtensions: [String: AnyCodable] + /// Warnings that apply conditionally depending on the OpenAPI Document + /// the Tag belongs to. + /// + /// Check these with the `applicableConditionalWarnings(for:)` method. + public let conditionalWarnings: [(any Condition, Warning)] + public init( name: String, + summary: String? = nil, description: String? = nil, externalDocs: ExternalDocumentation? = nil, + parent: String? = nil, + kind: Kind? = nil, vendorExtensions: [String: AnyCodable] = [:] ) { self.name = name + self.summary = summary self.description = description self.externalDocs = externalDocs + self.parent = parent + self.kind = kind self.vendorExtensions = vendorExtensions + + self.conditionalWarnings = [ + // If summary is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "summary", value: summary, minimumVersion: .v3_2_0), + // If parent is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "parent", value: parent, minimumVersion: .v3_2_0), + // If kind is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "kind", value: kind, minimumVersion: .v3_2_0) + ].compactMap { $0 } + } + } +} + +extension OpenAPI.Tag { + public struct Kind : ExpressibleByStringLiteral, Codable, Equatable, Sendable { + public let rawValue: String + + public init(stringLiteral: String) { + self.rawValue = stringLiteral } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + self.rawValue = try container.decode(String.self) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + try container.encode(rawValue) + } + } +} + +extension OpenAPI.Tag.Kind { + /// See https://spec.openapis.org/registry/tag-kind/audience.html + public static let audience: OpenAPI.Tag.Kind = "audience" + /// See https://spec.openapis.org/registry/tag-kind/badge.html + public static let badge: OpenAPI.Tag.Kind = "badge" + /// See https://spec.openapis.org/registry/tag-kind/nav.html + public static let nav: OpenAPI.Tag.Kind = "nav" +} + +fileprivate func nonNilVersionWarning(fieldName: String, value: Subject?, minimumVersion: OpenAPI.Document.Version) -> (any Condition, OpenAPI.Warning)? { + value.map { _ in + OpenAPI.Document.ConditionalWarnings.version( + lessThan: minimumVersion, + doesNotSupport: "The Tag \(fieldName) field" + ) + } +} + +extension OpenAPI.Tag: Equatable { + public static func == (lhs: Self, rhs: Self) -> Bool { + return lhs.name == rhs.name + && lhs.summary == rhs.summary + && lhs.description == rhs.description + && lhs.externalDocs == rhs.externalDocs + && lhs.parent == rhs.parent + && lhs.kind == rhs.kind + && lhs.vendorExtensions == rhs.vendorExtensions } } @@ -43,15 +125,31 @@ extension OpenAPI.Tag: ExpressibleByStringLiteral { } } -// MARK: - Describable +// MARK: - Describable & Summarizable -extension OpenAPI.Tag : OpenAPIDescribable { +extension OpenAPI.Tag : OpenAPISummarizable { public func overriddenNonNil(description: String?) -> OpenAPI.Tag { guard let description = description else { return self } return OpenAPI.Tag( name: name, + summary: summary, + description: description, + externalDocs: externalDocs, + parent: parent, + kind: kind, + vendorExtensions: vendorExtensions + ) + } + + public func overriddenNonNil(summary: String?) -> OpenAPI.Tag { + guard let summary = summary else { return self } + return OpenAPI.Tag( + name: name, + summary: summary, description: description, externalDocs: externalDocs, + parent: parent, + kind: kind, vendorExtensions: vendorExtensions ) } @@ -65,10 +163,16 @@ extension OpenAPI.Tag: Encodable { try container.encode(name, forKey: .name) + try container.encodeIfPresent(summary, forKey: .summary) + try container.encodeIfPresent(description, forKey: .description) try container.encodeIfPresent(externalDocs, forKey: .externalDocs) + try container.encodeIfPresent(parent, forKey: .parent) + + try container.encodeIfPresent(kind, forKey: .kind) + if VendorExtensionsConfiguration.isEnabled(for: encoder) { try encodeExtensions(to: &container) } @@ -81,26 +185,47 @@ extension OpenAPI.Tag: Decodable { name = try container.decode(String.self, forKey: .name) + summary = try container.decodeIfPresent(String.self, forKey: .summary) + description = try container.decodeIfPresent(String.self, forKey: .description) externalDocs = try container.decodeIfPresent(OpenAPI.ExternalDocumentation.self, forKey: .externalDocs) + parent = try container.decodeIfPresent(String.self, forKey: .parent) + + kind = try container.decodeIfPresent(Kind.self, forKey: .kind) + vendorExtensions = try Self.extensions(from: decoder) + + conditionalWarnings = [ + // If summary is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "summary", value: summary, minimumVersion: .v3_2_0), + // If parent is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "parent", value: parent, minimumVersion: .v3_2_0), + // If kind is non-nil, the document must be OAS version 3.2.0 or greater + nonNilVersionWarning(fieldName: "kind", value: kind, minimumVersion: .v3_2_0) + ].compactMap { $0 } } } extension OpenAPI.Tag { internal enum CodingKeys: ExtendableCodingKey { case name + case summary case description case externalDocs + case parent + case kind case extended(String) static var allBuiltinKeys: [CodingKeys] { return [ .name, + .summary, .description, - .externalDocs + .externalDocs, + .parent, + .kind ] } @@ -112,10 +237,16 @@ extension OpenAPI.Tag { switch stringValue { case "name": self = .name + case "summary": + self = .summary case "description": self = .description case "externalDocs": self = .externalDocs + case "parent": + self = .parent + case "kind": + self = .kind default: self = .extendedKey(for: stringValue) } @@ -125,10 +256,16 @@ extension OpenAPI.Tag { switch self { case .name: return "name" + case .summary: + return "summary" case .description: return "description" case .externalDocs: return "externalDocs" + case .parent: + return "parent" + case .kind: + return "kind" case .extended(let key): return key } diff --git a/Sources/OpenAPIKit/Validator/Validation.swift b/Sources/OpenAPIKit/Validator/Validation.swift index 3e9851d42..b60d88f6f 100644 --- a/Sources/OpenAPIKit/Validator/Validation.swift +++ b/Sources/OpenAPIKit/Validator/Validation.swift @@ -128,10 +128,12 @@ public struct ValidationError: Swift.Error, CustomStringConvertible, PathContext public var localizedDescription: String { description } public var description: String { + let reasonStr: any StringProtocol = + reason.last == "." ? reason.dropLast() : reason guard !codingPath.isEmpty else { - return "\(reason) at root of document" + return "\(reasonStr) at root of document" } - return "\(reason) at path: \(codingPath.stringValue)" + return "\(reasonStr) at path: \(codingPath.stringValue)" } } diff --git a/Sources/OpenAPIKit/Validator/Validator.swift b/Sources/OpenAPIKit/Validator/Validator.swift index 21373a22d..49e1b8fdc 100644 --- a/Sources/OpenAPIKit/Validator/Validator.swift +++ b/Sources/OpenAPIKit/Validator/Validator.swift @@ -545,9 +545,15 @@ extension _Validator: SingleValueEncodingContainer { fileprivate func collectWarnings(from value: Encodable, atKey key: CodingKey? = nil) { let pathTail = key.map { [$0] } ?? [] + var localWarnings = [Warning]() if let warnable = value as? HasWarnings { - warnings += warnable.warnings.map(contextualize(at: codingPath + pathTail)) + localWarnings += warnable.warnings } + if let conditionalWarnable = value as? HasConditionalWarnings { + localWarnings += conditionalWarnable.applicableConditionalWarnings(for: document) + } + + warnings += localWarnings.map(contextualize(at: codingPath + pathTail)) } } diff --git a/Sources/OpenAPIKit/_CoreReExport.swift b/Sources/OpenAPIKit/_CoreReExport.swift index 8f7ed5d46..a249fbc95 100644 --- a/Sources/OpenAPIKit/_CoreReExport.swift +++ b/Sources/OpenAPIKit/_CoreReExport.swift @@ -15,6 +15,7 @@ import OpenAPIKitCore public extension OpenAPI { + typealias BuiltinHttpMethod = OpenAPIKitCore.Shared.BuiltinHttpMethod typealias HttpMethod = OpenAPIKitCore.Shared.HttpMethod typealias ContentType = OpenAPIKitCore.Shared.ContentType typealias Error = OpenAPIKitCore.Error diff --git a/Sources/OpenAPIKit30/Document/Document.swift b/Sources/OpenAPIKit30/Document/Document.swift index 0cbab85c5..a47cafaee 100644 --- a/Sources/OpenAPIKit30/Document/Document.swift +++ b/Sources/OpenAPIKit30/Document/Document.swift @@ -685,7 +685,7 @@ internal func validateSecurityRequirements(in paths: OpenAPI.PathItem.Map, again } } -internal func validate(securityRequirements: [OpenAPI.SecurityRequirement], at path: OpenAPI.Path, for verb: OpenAPI.HttpMethod, against components: OpenAPI.Components) throws { +internal func validate(securityRequirements: [OpenAPI.SecurityRequirement], at path: OpenAPI.Path, for verb: OpenAPI.BuiltinHttpMethod, against components: OpenAPI.Components) throws { let securitySchemes = securityRequirements.flatMap { $0.keys } for securityScheme in securitySchemes { diff --git a/Sources/OpenAPIKit30/Operation/ResolvedEndpoint.swift b/Sources/OpenAPIKit30/Operation/ResolvedEndpoint.swift index ed33c127e..9d12735d3 100644 --- a/Sources/OpenAPIKit30/Operation/ResolvedEndpoint.swift +++ b/Sources/OpenAPIKit30/Operation/ResolvedEndpoint.swift @@ -52,7 +52,7 @@ public struct ResolvedEndpoint: Equatable { /// The HTTP method of this endpoint. /// /// e.g. GET, POST, PUT, PATCH, etc. - public let method: OpenAPI.HttpMethod + public let method: OpenAPI.BuiltinHttpMethod /// The path for this endpoint. public let path: OpenAPI.Path /// The parameters this endpoint accepts. diff --git a/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift b/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift index 542b8aa54..ae9d6e3be 100644 --- a/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift +++ b/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift @@ -77,7 +77,7 @@ public struct DereferencedPathItem: Equatable { extension DereferencedPathItem { /// Retrieve the operation for the given verb, if one is set for this path. - public func `for`(_ verb: OpenAPI.HttpMethod) -> DereferencedOperation? { + public func `for`(_ verb: OpenAPI.BuiltinHttpMethod) -> DereferencedOperation? { switch verb { case .delete: return self.delete @@ -95,10 +95,12 @@ extension DereferencedPathItem { return self.put case .trace: return self.trace + case .query: + return nil } } - public subscript(verb: OpenAPI.HttpMethod) -> DereferencedOperation? { + public subscript(verb: OpenAPI.BuiltinHttpMethod) -> DereferencedOperation? { get { return `for`(verb) } @@ -107,7 +109,7 @@ extension DereferencedPathItem { /// An `Endpoint` is the combination of an /// HTTP method and an operation. public struct Endpoint: Equatable { - public let method: OpenAPI.HttpMethod + public let method: OpenAPI.BuiltinHttpMethod public let operation: DereferencedOperation } @@ -116,7 +118,7 @@ extension DereferencedPathItem { /// - Returns: An array of `Endpoints` with the method (i.e. `.get`) and the operation for /// the method. public var endpoints: [Endpoint] { - return OpenAPI.HttpMethod.allCases.compactMap { method in + return OpenAPI.BuiltinHttpMethod.allCases.compactMap { method in self.for(method).map { .init(method: method, operation: $0) } } } diff --git a/Sources/OpenAPIKit30/Path Item/PathItem.swift b/Sources/OpenAPIKit30/Path Item/PathItem.swift index 3cbc5abc2..cceafda35 100644 --- a/Sources/OpenAPIKit30/Path Item/PathItem.swift +++ b/Sources/OpenAPIKit30/Path Item/PathItem.swift @@ -19,7 +19,7 @@ extension OpenAPI { /// The `GET` operation, for example, is accessed via the `.get` property. You can /// also use the subscript operator, passing it the `HTTPMethod` you want to access. /// - /// You can access an array of equatable `HttpMethod`/`Operation` paris with the + /// You can access an array of equatable `BuiltinHttpMethod`/`Operation` paris with the /// `endpoints` property. public struct PathItem: Equatable, CodableVendorExtendable, Sendable { public var summary: String? @@ -146,7 +146,7 @@ extension OrderedDictionary where Key == OpenAPI.Path { extension OpenAPI.PathItem { /// Retrieve the operation for the given verb, if one is set for this path. - public func `for`(_ verb: OpenAPI.HttpMethod) -> OpenAPI.Operation? { + public func `for`(_ verb: OpenAPI.BuiltinHttpMethod) -> OpenAPI.Operation? { switch verb { case .delete: return self.delete @@ -164,11 +164,13 @@ extension OpenAPI.PathItem { return self.put case .trace: return self.trace + case .query: + return nil } } /// Set the operation for the given verb, overwriting any already set operation for the same verb. - public mutating func set(operation: OpenAPI.Operation?, for verb: OpenAPI.HttpMethod) { + public mutating func set(operation: OpenAPI.Operation?, for verb: OpenAPI.BuiltinHttpMethod) { switch verb { case .delete: self.delete(operation) @@ -186,10 +188,13 @@ extension OpenAPI.PathItem { self.put(operation) case .trace: self.trace(operation) + case .query: + // not representable + print("The QUERY operation was not directly representable in the OAS standard until version 3.2.0") } } - public subscript(verb: OpenAPI.HttpMethod) -> OpenAPI.Operation? { + public subscript(verb: OpenAPI.BuiltinHttpMethod) -> OpenAPI.Operation? { get { return `for`(verb) } @@ -201,7 +206,7 @@ extension OpenAPI.PathItem { /// An `Endpoint` is the combination of an /// HTTP method and an operation. public struct Endpoint: Equatable { - public let method: OpenAPI.HttpMethod + public let method: OpenAPI.BuiltinHttpMethod public let operation: OpenAPI.Operation } @@ -210,7 +215,7 @@ extension OpenAPI.PathItem { /// - Returns: An array of `Endpoints` with the method (i.e. `.get`) and the operation for /// the method. public var endpoints: [Endpoint] { - return OpenAPI.HttpMethod.allCases.compactMap { method in + return OpenAPI.BuiltinHttpMethod.allCases.compactMap { method in self.for(method).map { .init(method: method, operation: $0) } } } diff --git a/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift b/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift index ed2a7062c..4d678b228 100644 --- a/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift +++ b/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift @@ -120,7 +120,7 @@ public struct ResolvedRoute: Equatable { } /// Retrieve the endpoint for the given method, if one exists for this route. - public func `for`(_ verb: OpenAPI.HttpMethod) -> ResolvedEndpoint? { + public func `for`(_ verb: OpenAPI.BuiltinHttpMethod) -> ResolvedEndpoint? { switch verb { case .delete: return self.delete @@ -138,10 +138,12 @@ public struct ResolvedRoute: Equatable { return self.put case .trace: return self.trace + case .query: + return nil } } - public subscript(verb: OpenAPI.HttpMethod) -> ResolvedEndpoint? { + public subscript(verb: OpenAPI.BuiltinHttpMethod) -> ResolvedEndpoint? { get { return `for`(verb) } diff --git a/Sources/OpenAPIKit30/_CoreReExport.swift b/Sources/OpenAPIKit30/_CoreReExport.swift index 8f7ed5d46..a249fbc95 100644 --- a/Sources/OpenAPIKit30/_CoreReExport.swift +++ b/Sources/OpenAPIKit30/_CoreReExport.swift @@ -15,6 +15,7 @@ import OpenAPIKitCore public extension OpenAPI { + typealias BuiltinHttpMethod = OpenAPIKitCore.Shared.BuiltinHttpMethod typealias HttpMethod = OpenAPIKitCore.Shared.HttpMethod typealias ContentType = OpenAPIKitCore.Shared.ContentType typealias Error = OpenAPIKitCore.Error diff --git a/Sources/OpenAPIKitCompat/Compat30To31.swift b/Sources/OpenAPIKitCompat/Compat30To31.swift index 88192c352..92928524a 100644 --- a/Sources/OpenAPIKitCompat/Compat30To31.swift +++ b/Sources/OpenAPIKitCompat/Compat30To31.swift @@ -430,8 +430,10 @@ extension OpenAPIKit30.OpenAPI.Tag: To31 { fileprivate func to31() -> OpenAPIKit.OpenAPI.Tag { OpenAPIKit.OpenAPI.Tag( name: name, + summary: nil, description: description, externalDocs: externalDocs?.to31(), + parent: nil, vendorExtensions: vendorExtensions ) } diff --git a/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/DecodingErrorExtensions.swift b/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/DecodingErrorExtensions.swift index f203b8f3b..7d98b7388 100644 --- a/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/DecodingErrorExtensions.swift +++ b/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/DecodingErrorExtensions.swift @@ -112,3 +112,11 @@ internal struct DecodingErrorWrapper: OpenAPIError { var codingPath: [CodingKey] { decodingError.codingPath } } + +public extension ArraySlice where Element == any CodingKey { + mutating func removeFirstPathComponentString() -> String { + guard !isEmpty else { return "" } + + return removeFirst().stringValue + } +} diff --git a/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIWarning.swift b/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIWarning.swift index 21aa92406..9ee5df67f 100644 --- a/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIWarning.swift +++ b/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIWarning.swift @@ -65,5 +65,6 @@ extension Warning: CustomStringConvertible { } public protocol HasWarnings { + /// Warnings generated while decoding an OpenAPI type. var warnings: [Warning] { get } } diff --git a/Sources/OpenAPIKitCore/Shared/ContentType.swift b/Sources/OpenAPIKitCore/Shared/ContentType.swift index 24880dde4..ab70fa763 100644 --- a/Sources/OpenAPIKitCore/Shared/ContentType.swift +++ b/Sources/OpenAPIKitCore/Shared/ContentType.swift @@ -305,7 +305,7 @@ extension Shared.ContentType.Builtin: RawRepresentable { case .woff: return "font/woff" case .woff2: return "font/woff2" case .xml: return "application/xml" - case .yaml: return "application/x-yaml" + case .yaml: return "application/yaml" case .zip: return "application/zip" case .anyApplication: return "application/*" @@ -359,6 +359,7 @@ extension Shared.ContentType.Builtin: RawRepresentable { case "font/woff2": self = .woff2 case "application/xml": self = .xml case "application/x-yaml": self = .yaml + case "application/yaml": self = .yaml case "application/zip": self = .zip case "application/*": self = .anyApplication diff --git a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift index 57481265e..f6f0f0d7a 100644 --- a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift +++ b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift @@ -9,10 +9,10 @@ extension Shared { /// Represents the HTTP methods supported by the /// OpenAPI Specification. /// - /// See [OpenAPI Path Item Object](https://spec.openapis.org/oas/v3.0.4.html#path-item-object) because the supported - /// HTTP methods are enumerated as properties on that + /// See [OpenAPI Path Item Object](https://spec.openapis.org/oas/v3.2.0.html#path-item-object) + /// because the supported HTTP methods are enumerated as properties on that /// object. - public enum HttpMethod: String, CaseIterable, Sendable { + public enum BuiltinHttpMethod: String, CaseIterable, Sendable { case get = "GET" case post = "POST" case patch = "PATCH" @@ -21,5 +21,102 @@ extension Shared { case head = "HEAD" case options = "OPTIONS" case trace = "TRACE" + case query = "QUERY" + } + + /// Represents an HTTP method. + /// + /// See [OpenAPI Path Item Object](https://spec.openapis.org/oas/v3.2.0.html#path-item-object). + /// + /// Methods are split into builtin methods (those representable as + /// properties on a Path Item Object) and other methods (those that can be + /// added to the `additionalOperations` of a Path Item Object). + /// + /// `HttpMethod` is `ExpressibleByStringLiteral` so you can write a + /// non-builtin method like "LINK" as: + /// `let linkMethod : OpenAPI.HttpMethod = "LINK"` + public enum HttpMethod: ExpressibleByStringLiteral, RawRepresentable, Equatable, Hashable, Codable, Sendable { + case builtin(BuiltinHttpMethod) + case other(String) + + public static let get = Self.builtin(.get) + public static let post = Self.builtin(.post) + public static let patch = Self.builtin(.patch) + public static let put = Self.builtin(.put) + public static let delete = Self.builtin(.delete) + public static let head = Self.builtin(.head) + public static let options = Self.builtin(.options) + public static let trace = Self.builtin(.trace) + public static let query = Self.builtin(.query) + + public var rawValue: String { + switch self { + case .builtin(let builtin): builtin.rawValue + case .other(let other): other + } + } + + public init?(rawValue: String) { + if let builtin = BuiltinHttpMethod.init(rawValue: rawValue) { + self = .builtin(builtin) + return + } + + let uppercasedValue = rawValue.uppercased() + if Self.additionalKnownUppercaseMethods.contains(uppercasedValue) && rawValue != uppercasedValue { + return nil + } + + // we accept that we do not know the correct capitalization for all + // possible method names and fall back to whatever the user has + // entered. + self = .other(rawValue) + } + + public init(stringLiteral value: String) { + if let valid = Self.init(rawValue: value) { + self = valid + return + } + // we accept that a value may be invalid if it has been hard coded + // as a literal because there is no compile-time evaluation and so + // no way to prevent this without sacrificing code cleanliness. + self = .other(value) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + + let attemptedMethod = try container.decode(String.self) + + if let value = Self.init(rawValue: attemptedMethod) { + self = value + return + } + + throw GenericError(subjectName: "HTTP Method", details: "Failed to decode an HTTP method from \(attemptedMethod). This method name must be an uppercased string", codingPath: decoder.codingPath) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + + try container.encode(self.rawValue) + } + + internal static let additionalKnownUppercaseMethods = [ + "LINK", + "CONNECT" + ] + } +} + +extension Shared.HttpMethod: StringConvertibleHintProvider { + public static func problem(with proposedString: String) -> String? { + let uppercasedValue = proposedString.uppercased() + if Self.additionalKnownUppercaseMethods.contains(uppercasedValue) && proposedString != uppercasedValue { + return "'\(proposedString)' must be uppercased" + } + + return nil } } diff --git a/Tests/OpenAPIKit30Tests/Validator/ValidatorTests.swift b/Tests/OpenAPIKit30Tests/Validator/ValidatorTests.swift index d8e3730af..dfd584fd8 100644 --- a/Tests/OpenAPIKit30Tests/Validator/ValidatorTests.swift +++ b/Tests/OpenAPIKit30Tests/Validator/ValidatorTests.swift @@ -1067,7 +1067,7 @@ final class ValidatorTests: XCTestCase { let validator = Validator.blank .validating( - "All server arrays have not in operations have more than 1 server", + "All server arrays not in operations have more than 1 server", check: \[OpenAPI.Server].count > 1, when: \.codingPath.count == 1 // server array is under root document (coding path count 1) || take(\.codingPath) { codingPath in @@ -1075,7 +1075,7 @@ final class ValidatorTests: XCTestCase { guard codingPath.count > 1 else { return false } let secondToLastPathComponent = codingPath.suffix(2).first!.stringValue - let httpMethods = OpenAPI.HttpMethod.allCases.map { $0.rawValue.lowercased() } + let httpMethods = OpenAPI.BuiltinHttpMethod.allCases.map { $0.rawValue.lowercased() } return !httpMethods.contains(secondToLastPathComponent) } diff --git a/Tests/OpenAPIKitCoreTests/ContentTypeTests.swift b/Tests/OpenAPIKitCoreTests/ContentTypeTests.swift index d3ed74883..e4c201153 100644 --- a/Tests/OpenAPIKitCoreTests/ContentTypeTests.swift +++ b/Tests/OpenAPIKitCoreTests/ContentTypeTests.swift @@ -66,6 +66,17 @@ final class ContentTypeTests: XCTestCase { } } + func test_x_yaml() { + // test that we support old x-yaml type but also prefer new official media type + let type1 = Shared.ContentType.init(rawValue: "application/yaml") + let type2 = Shared.ContentType.init(rawValue: "application/x-yaml") + + XCTAssertEqual(type1?.rawValue, "application/yaml") + XCTAssertEqual(type1, .yaml) + XCTAssertEqual(type2?.rawValue, "application/yaml") + XCTAssertEqual(type2, .yaml) + } + func test_goodParam() { let type = Shared.ContentType.init(rawValue: "text/html; charset=utf8") XCTAssertEqual(type?.warnings.count, 0) diff --git a/Tests/OpenAPIKitErrorReportingTests/SchemaErrorTests.swift b/Tests/OpenAPIKitErrorReportingTests/SchemaErrorTests.swift index deeb1f6cb..4aaca5ff4 100644 --- a/Tests/OpenAPIKitErrorReportingTests/SchemaErrorTests.swift +++ b/Tests/OpenAPIKitErrorReportingTests/SchemaErrorTests.swift @@ -76,7 +76,7 @@ final class SchemaErrorTests: XCTestCase { XCTAssertEqual(openAPIError.localizedDescription, """ - Problem encountered when parsing `OpenAPI Schema`: Found 'nullable' property. This property is not supported by OpenAPI v3.1.x. OpenAPIKit has translated it into 'type: ["null", ...]'.. at path: .paths['/hello/world'].get.responses.200.content['application/json'].schema + Problem encountered when parsing `OpenAPI Schema`: Found 'nullable' property. This property is not supported by OpenAPI v3.1.x. OpenAPIKit has translated it into 'type: ["null", ...]' at path: .paths['/hello/world'].get.responses.200.content['application/json'].schema """) XCTAssertEqual(openAPIError.codingPath.map { $0.stringValue }, [ "paths", diff --git a/Tests/OpenAPIKitTests/ComponentsTests.swift b/Tests/OpenAPIKitTests/ComponentsTests.swift index 00c5b10bd..0cbf875b7 100644 --- a/Tests/OpenAPIKitTests/ComponentsTests.swift +++ b/Tests/OpenAPIKitTests/ComponentsTests.swift @@ -581,7 +581,8 @@ extension ComponentsTests { options: op, head: op, patch: op, - trace: op + trace: op, + query: op ) ] ) @@ -614,6 +615,9 @@ extension ComponentsTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -646,6 +650,8 @@ extension ComponentsTests { "put" : { }, "trace" : { + }, + "query" : { } } } @@ -667,7 +673,8 @@ extension ComponentsTests { options: op, head: op, patch: op, - trace: op + trace: op, + query: op ) ] ) diff --git a/Tests/OpenAPIKitTests/Document/DocumentTests.swift b/Tests/OpenAPIKitTests/Document/DocumentTests.swift index 985c9faed..ce7d142e1 100644 --- a/Tests/OpenAPIKitTests/Document/DocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/DocumentTests.swift @@ -20,6 +20,7 @@ final class DocumentTests: XCTestCase { let _ = OpenAPI.Document( openAPIVersion: .v3_1_0, + selfURI: .init(string: "https://example.com/openapi")!, info: .init(title: "hi", version: "1.0"), servers: [ .init(url: URL(string: "https://google.com")!) @@ -48,24 +49,45 @@ final class DocumentTests: XCTestCase { let t2 = OpenAPI.Document.Version.v3_1_1 XCTAssertEqual(t2.rawValue, "3.1.1") - let t3 = OpenAPI.Document.Version.v3_1_x(x: 2) + let t3 = OpenAPI.Document.Version.v3_1_2 XCTAssertEqual(t3.rawValue, "3.1.2") let t4 = OpenAPI.Document.Version.v3_1_x(x: 8) XCTAssertEqual(t4.rawValue, "3.1.8") - let t5 = OpenAPI.Document.Version(rawValue: "3.1.0") - XCTAssertEqual(t5, .v3_1_0) + let t5 = OpenAPI.Document.Version.v3_2_0 + XCTAssertEqual(t5.rawValue, "3.2.0") - let t6 = OpenAPI.Document.Version(rawValue: "3.1.1") - XCTAssertEqual(t6, .v3_1_1) + let t6 = OpenAPI.Document.Version(rawValue: "3.1.0") + XCTAssertEqual(t6, .v3_1_0) - let t7 = OpenAPI.Document.Version(rawValue: "3.1.2") - XCTAssertEqual(t7, .v3_1_x(x: 2)) + let t7 = OpenAPI.Document.Version(rawValue: "3.1.1") + XCTAssertEqual(t7, .v3_1_1) + + let t8 = OpenAPI.Document.Version(rawValue: "3.1.2") + XCTAssertEqual(t8, .v3_1_2) // not a known version: - let t8 = OpenAPI.Document.Version(rawValue: "3.1.8") - XCTAssertNil(t8) + let t9 = OpenAPI.Document.Version(rawValue: "3.1.8") + XCTAssertNil(t9) + + let t10 = OpenAPI.Document.Version(rawValue: "3.2.8") + XCTAssertNil(t10) + } + + func test_compareOASVersions() { + let versions: [OpenAPI.Document.Version] = [ + .v3_1_0, + .v3_1_1, + .v3_1_2, + .v3_2_0 + ] + + for v1Idx in 0...(versions.count - 2) { + for v2Idx in (v1Idx + 1)...(versions.count - 1) { + XCTAssert(versions[v1Idx] < versions[v2Idx]) + } + } } func test_getRoutes() { @@ -114,7 +136,12 @@ final class DocumentTests: XCTestCase { "/hello": .init( get: .init(operationId: nil, responses: [:])), "/hello/world": .init( - put: .init(operationId: nil, responses: [:])) + put: .init(operationId: nil, responses: [:])), + "/hi/mom": .init( + additionalOperations: [ + "LINK": .init(operationId: nil, responses: [:]) + ] + ) ], components: .noComponents ) @@ -129,7 +156,12 @@ final class DocumentTests: XCTestCase { "/hello": .init( get: .init(operationId: "test", responses: [:])), "/hello/world": .init( - put: .init(operationId: nil, responses: [:])) + put: .init(operationId: nil, responses: [:])), + "/hi/mom": .init( + additionalOperations: [ + "LINK": .init(operationId: nil, responses: [:]) + ] + ) ], components: .noComponents ) @@ -144,12 +176,17 @@ final class DocumentTests: XCTestCase { "/hello": .init( get: .init(operationId: "test", responses: [:])), "/hello/world": .init( - put: .init(operationId: "two", responses: [:])) + put: .init(operationId: "two", responses: [:])), + "/hi/mom": .init( + additionalOperations: [ + "LINK": .init(operationId: "three", responses: [:]) + ] + ) ], components: .noComponents ) - XCTAssertEqual(t3.allOperationIds, ["test", "two"]) + XCTAssertEqual(t3.allOperationIds, ["test", "two", "three"]) // paths, one operation id (first one nil), no components, no webhooks let t4 = OpenAPI.Document( @@ -159,7 +196,12 @@ final class DocumentTests: XCTestCase { "/hello": .init( get: .init(operationId: nil, responses: [:])), "/hello/world": .init( - put: .init(operationId: "two", responses: [:])) + put: .init(operationId: "two", responses: [:])), + "/hi/mom": .init( + additionalOperations: [ + "LINK": .init(operationId: nil, responses: [:]) + ] + ) ], components: .noComponents ) @@ -669,6 +711,60 @@ extension DocumentTests { ) } + func test_specifySelfURI_encode() throws { + let document = OpenAPI.Document( + selfURI: .init(string: "https://example.com/openapi")!, + info: .init(title: "API", version: "1.0"), + servers: [], + paths: [:], + components: .noComponents + ) + let encodedDocument = try orderUnstableTestStringFromEncoding(of: document) + + assertJSONEquivalent( + encodedDocument, + """ + { + "$self" : "https:\\/\\/example.com\\/openapi", + "info" : { + "title" : "API", + "version" : "1.0" + }, + "openapi" : "3.1.1" + } + """ + ) + } + + func test_specifySelfURI_decode() throws { + let documentData = + """ + { + "$self": "https://example.com/openapi", + "info" : { + "title" : "API", + "version" : "1.0" + }, + "openapi" : "3.1.1", + "paths" : { + + } + } + """.data(using: .utf8)! + let document = try orderUnstableDecode(OpenAPI.Document.self, from: documentData) + + XCTAssertEqual( + document, + OpenAPI.Document( + selfURI: .init(string: "https://example.com/openapi")!, + info: .init(title: "API", version: "1.0"), + servers: [], + paths: [:], + components: .noComponents + ) + ) + } + func test_specifyPaths_encode() throws { let document = OpenAPI.Document( info: .init(title: "API", version: "1.0"), @@ -1044,7 +1140,7 @@ extension DocumentTests { func test_webhooks_encode() throws { let op = OpenAPI.Operation(responses: [:]) - let pathItem: OpenAPI.PathItem = .init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op) + let pathItem: OpenAPI.PathItem = .init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op, query: op) let pathItemTest: Either, OpenAPI.PathItem> = .pathItem(pathItem) let document = OpenAPI.Document( @@ -1092,6 +1188,9 @@ extension DocumentTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -1106,7 +1205,7 @@ extension DocumentTests { func test_webhooks_encode_decode() throws { let op = OpenAPI.Operation(responses: [:]) - let pathItem = OpenAPI.PathItem(get: op, put: op, post: op, options: op, head: op, patch: op, trace: op) + let pathItem = OpenAPI.PathItem(get: op, put: op, post: op, options: op, head: op, patch: op, trace: op, query: op) let document = OpenAPI.Document( info: .init(title: "API", version: "1.0"), @@ -1157,6 +1256,8 @@ extension DocumentTests { "put": { }, "trace": { + }, + "query": { } } } @@ -1172,7 +1273,7 @@ extension DocumentTests { servers: [], paths: [:], webhooks: [ - "webhook-test": .init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op) + "webhook-test": .init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op, query: op) ], components: .noComponents, externalDocs: .init(url: URL(string: "http://google.com")!) @@ -1182,7 +1283,7 @@ extension DocumentTests { func test_webhooks_noPaths_encode() throws { let op = OpenAPI.Operation(responses: [:]) - let pathItem: OpenAPI.PathItem = .init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op) + let pathItem: OpenAPI.PathItem = .init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op, query: op) let pathItemTest: Either, OpenAPI.PathItem> = .pathItem(pathItem) let document = OpenAPI.Document( @@ -1230,6 +1331,9 @@ extension DocumentTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -1271,6 +1375,8 @@ extension DocumentTests { "put": { }, "trace": { + }, + "query": { } } } @@ -1286,7 +1392,7 @@ extension DocumentTests { servers: [], paths: [:], webhooks: [ - "webhook-test": .pathItem(.init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op)) + "webhook-test": .pathItem(.init(get: op, put: op, post: op, delete: op, options: op, head: op, patch: op, trace: op, query: op)) ], components: .noComponents, externalDocs: .init(url: URL(string: "http://google.com")!) diff --git a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift index c968f1408..5ca4c9448 100644 --- a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift @@ -24,6 +24,8 @@ final class DereferencedPathItemTests: XCTestCase { XCTAssertNil(t1[.post]) XCTAssertNil(t1[.put]) XCTAssertNil(t1[.trace]) + XCTAssertNil(t1[.query]) + XCTAssertEqual(t1.additionalOperations, [:]) // test dynamic member lookup XCTAssertEqual(t1.summary, "test") @@ -41,10 +43,14 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [:]), head: .init(tags: "head op", responses: [:]), patch: .init(tags: "patch op", responses: [:]), - trace: .init(tags: "trace op", responses: [:]) + trace: .init(tags: "trace op", responses: [:]), + query: .init(tags: "query op", responses: [:]), + additionalOperations: [ + "LINK": .init(tags: "link op", responses: [:]) + ] ).dereferenced(in: .noComponents) - XCTAssertEqual(t1.endpoints.count, 8) + XCTAssertEqual(t1.endpoints.count, 10) XCTAssertEqual(t1.parameters.map { $0.schemaOrContent.schemaValue?.jsonSchema }, [.string]) XCTAssertEqual(t1[.delete]?.tags, ["delete op"]) XCTAssertEqual(t1[.get]?.tags, ["get op"]) @@ -54,6 +60,8 @@ final class DereferencedPathItemTests: XCTestCase { XCTAssertEqual(t1[.post]?.tags, ["post op"]) XCTAssertEqual(t1[.put]?.tags, ["put op"]) XCTAssertEqual(t1[.trace]?.tags, ["trace op"]) + XCTAssertEqual(t1[.query]?.tags, ["query op"]) + XCTAssertEqual(t1[.other("LINK")]?.tags, ["link op"]) } func test_referencedParameter() throws { @@ -101,7 +109,9 @@ final class DereferencedPathItemTests: XCTestCase { "options": .init(description: "options resp"), "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp"), + "link": .init(description: "link resp") ] ) let t1 = try OpenAPI.PathItem( @@ -112,10 +122,14 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]), + additionalOperations: [ + "LINK": .init(tags: "link op", responses: [200: .reference(.component(named: "link"))]) + ] ).dereferenced(in: components) - XCTAssertEqual(t1.endpoints.count, 8) + XCTAssertEqual(t1.endpoints.count, 10) XCTAssertEqual(t1[.delete]?.tags, ["delete op"]) XCTAssertEqual(t1[.delete]?.responses[status: 200]?.description, "delete resp") XCTAssertEqual(t1[.get]?.tags, ["get op"]) @@ -132,6 +146,10 @@ final class DereferencedPathItemTests: XCTestCase { XCTAssertEqual(t1[.put]?.responses[status: 200]?.description, "put resp") XCTAssertEqual(t1[.trace]?.tags, ["trace op"]) XCTAssertEqual(t1[.trace]?.responses[status: 200]?.description, "trace resp") + XCTAssertEqual(t1[.query]?.tags, ["query op"]) + XCTAssertEqual(t1[.query]?.responses[status: 200]?.description, "query resp") + XCTAssertEqual(t1[.other("LINK")]?.tags, ["link op"]) + XCTAssertEqual(t1[.other("LINK")]?.responses[status: 200]?.description, "link resp") } func test_missingReferencedGetResp() { @@ -143,7 +161,8 @@ final class DereferencedPathItemTests: XCTestCase { "options": .init(description: "options resp"), "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -155,7 +174,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -169,7 +189,8 @@ final class DereferencedPathItemTests: XCTestCase { "options": .init(description: "options resp"), "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -181,7 +202,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -195,7 +217,8 @@ final class DereferencedPathItemTests: XCTestCase { "options": .init(description: "options resp"), "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -207,7 +230,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -221,7 +245,8 @@ final class DereferencedPathItemTests: XCTestCase { "options": .init(description: "options resp"), "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -233,7 +258,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -247,7 +273,8 @@ final class DereferencedPathItemTests: XCTestCase { "delete": .init(description: "delete resp"), "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -259,7 +286,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -273,7 +301,8 @@ final class DereferencedPathItemTests: XCTestCase { "delete": .init(description: "delete resp"), "options": .init(description: "options resp"), "patch": .init(description: "patch resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -285,7 +314,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -299,7 +329,8 @@ final class DereferencedPathItemTests: XCTestCase { "delete": .init(description: "delete resp"), "options": .init(description: "options resp"), "head": .init(description: "head resp"), - "trace": .init(description: "trace resp") + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -311,7 +342,8 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) ).dereferenced(in: components) ) } @@ -325,7 +357,8 @@ final class DereferencedPathItemTests: XCTestCase { "delete": .init(description: "delete resp"), "options": .init(description: "options resp"), "head": .init(description: "head resp"), - "patch": .init(description: "patch resp") + "patch": .init(description: "patch resp"), + "query": .init(description: "query resp") ] ) XCTAssertThrowsError( @@ -337,7 +370,68 @@ final class DereferencedPathItemTests: XCTestCase { options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), - trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]) + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) + ).dereferenced(in: components) + ) + } + + func test_missingReferencedQueryResp() { + let components = OpenAPI.Components( + responses: [ + "get": .init(description: "get resp"), + "put": .init(description: "put resp"), + "post": .init(description: "post resp"), + "delete": .init(description: "delete resp"), + "options": .init(description: "options resp"), + "head": .init(description: "head resp"), + "patch": .init(description: "patch resp"), + "trace": .init(description: "trace resp") + ] + ) + XCTAssertThrowsError( + try OpenAPI.PathItem( + get: .init(tags: "get op", responses: [200: .reference(.component(named: "get"))]), + put: .init(tags: "put op", responses: [200: .reference(.component(named: "put"))]), + post: .init(tags: "post op", responses: [200: .reference(.component(named: "post"))]), + delete: .init(tags: "delete op", responses: [200: .reference(.component(named: "delete"))]), + options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), + head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), + patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]) + ).dereferenced(in: components) + ) + } + + func test_missingReferencedAdditionalOperationResp() { + let components = OpenAPI.Components( + responses: [ + "get": .init(description: "get resp"), + "put": .init(description: "put resp"), + "post": .init(description: "post resp"), + "delete": .init(description: "delete resp"), + "options": .init(description: "options resp"), + "head": .init(description: "head resp"), + "patch": .init(description: "patch resp"), + "trace": .init(description: "trace resp"), + "query": .init(description: "query resp") + ] + ) + XCTAssertThrowsError( + try OpenAPI.PathItem( + get: .init(tags: "get op", responses: [200: .reference(.component(named: "get"))]), + put: .init(tags: "put op", responses: [200: .reference(.component(named: "put"))]), + post: .init(tags: "post op", responses: [200: .reference(.component(named: "post"))]), + delete: .init(tags: "delete op", responses: [200: .reference(.component(named: "delete"))]), + options: .init(tags: "options op", responses: [200: .reference(.component(named: "options"))]), + head: .init(tags: "head op", responses: [200: .reference(.component(named: "head"))]), + patch: .init(tags: "patch op", responses: [200: .reference(.component(named: "patch"))]), + trace: .init(tags: "trace op", responses: [200: .reference(.component(named: "trace"))]), + query: .init(tags: "query op", responses: [200: .reference(.component(named: "query"))]), + additionalOperations: [ + "LINK": .init(tags: "link op", responses: [200: .reference(.component(named: "link"))]), + ] ).dereferenced(in: components) ) } diff --git a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift index 2a4000777..13087fbbd 100644 --- a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift @@ -54,7 +54,11 @@ final class PathItemTests: XCTestCase { options: op, head: op, patch: op, - trace: op + trace: op, + query: op, + additionalOperations: [ + "LINK": op + ] ) } @@ -71,6 +75,7 @@ final class PathItemTests: XCTestCase { XCTAssertNil(pathItem.head) XCTAssertNil(pathItem.patch) XCTAssertNil(pathItem.trace) + XCTAssertNil(pathItem.query) pathItem.get(op) XCTAssertEqual(pathItem.get, op) @@ -99,6 +104,9 @@ final class PathItemTests: XCTestCase { pathItem.trace(op) XCTAssertEqual(pathItem.trace, op) + pathItem.query(op) + XCTAssertEqual(pathItem.query, op) + // for/set/subscript pathItem = .init() XCTAssertNil(pathItem[.get]) @@ -109,6 +117,7 @@ final class PathItemTests: XCTestCase { XCTAssertNil(pathItem[.head]) XCTAssertNil(pathItem[.patch]) XCTAssertNil(pathItem[.trace]) + XCTAssertNil(pathItem[.query]) pathItem[.get] = op XCTAssertEqual(pathItem.for(.get), op) @@ -133,6 +142,9 @@ final class PathItemTests: XCTestCase { pathItem[.trace] = op XCTAssertEqual(pathItem.for(.trace), op) + + pathItem[.query] = op + XCTAssertEqual(pathItem.for(.query), op) } func test_initializePathItemMap() { @@ -140,6 +152,57 @@ final class PathItemTests: XCTestCase { "hello/world": .init(), ] } + + func test_endpointsAccessor() { + let op = OpenAPI.Operation(responses: [:]) + let pathItem = OpenAPI.PathItem( + summary: "summary", + description: "description", + servers: [OpenAPI.Server(url: URL(string: "http://google.com")!)], + parameters: [.parameter(name: "hello", context: .query, schema: .string)], + get: op, + put: op, + post: op, + delete: op, + options: op, + head: op, + patch: op, + trace: op, + query: op, + additionalOperations: [ + "LINK": op + ] + ) + + let expectedEndpoints : [EquatableEndpoint] = [ + .init(method: .get, operation: op), + .init(method: .put, operation: op), + .init(method: .post, operation: op), + .init(method: .delete, operation: op), + .init(method: .options, operation: op), + .init(method: .head, operation: op), + .init(method: .patch, operation: op), + .init(method: .trace, operation: op), + .init(method: .query, operation: op), + .init(method: "LINK", operation: op) + ] + + let actualEndpoints = pathItem.endpoints.map(equatableEndpoint) + + XCTAssertEqual(actualEndpoints.count, expectedEndpoints.count) + for endpoint in expectedEndpoints { + XCTAssert(actualEndpoints.contains(endpoint)) + } + } +} + +fileprivate struct EquatableEndpoint: Equatable { + let method: OpenAPI.HttpMethod + let operation: OpenAPI.Operation +} + +fileprivate func equatableEndpoint(_ endpoint: OpenAPI.PathItem.Endpoint) -> EquatableEndpoint { + return .init(method: endpoint.method, operation: endpoint.operation) } // MARK: Codable Tests @@ -264,7 +327,11 @@ extension PathItemTests { options: op, head: op, patch: op, - trace: op + trace: op, + query: op, + additionalOperations: [ + "LINK": op + ] ) let encodedPathItem = try orderUnstableTestStringFromEncoding(of: pathItem) @@ -273,6 +340,11 @@ extension PathItemTests { encodedPathItem, """ { + "additionalOperations" : { + "LINK" : { + + } + }, "delete" : { }, @@ -293,6 +365,9 @@ extension PathItemTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -321,11 +396,21 @@ extension PathItemTests { "put" : { }, "trace" : { + }, + "query" : { + }, + "additionalOperations": { + "LINK": { + }, + "CONNECT": { + }, + "unknown_method": { + }, } } """.data(using: .utf8)! - let pathItem = try orderUnstableDecode(OpenAPI.PathItem.self, from: pathItemData) + let pathItem = try orderStableDecode(OpenAPI.PathItem.self, from: pathItemData) let op = OpenAPI.Operation(responses: [:]) @@ -339,11 +424,85 @@ extension PathItemTests { options: op, head: op, patch: op, - trace: op + trace: op, + query: op, + additionalOperations: [ + "LINK": op, + "CONNECT": op, + "unknown_method": op + ] ) ) } + func test_disallowedAdditionalOperations_decode() throws { + // NOTE the one allowed method in the following is LINK which is there + // to ensure allowed methods do not show up in the error output. + let pathItemData = + """ + { + "additionalOperations": { + "LINK": { + }, + "DELETE" : { + }, + "GET" : { + }, + "HEAD" : { + }, + "OPTIONS" : { + }, + "PATCH" : { + }, + "POST" : { + }, + "PUT" : { + }, + "TRACE" : { + }, + "QUERY" : { + } + } + } + """.data(using: .utf8)! + + XCTAssertThrowsError(try orderStableDecode(OpenAPI.PathItem.self, from: pathItemData)) { error in + XCTAssertEqual(String(describing: OpenAPI.Error(from: error)), "Problem encountered when parsing `additionalOperations` under the `/` path: Additional Operations cannot contain operations that can be set directly on the Path Item. Found the following disallowed additional operations: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE, QUERY.") + } + } + + func test_invalidAdditionalOperation1_decode() throws { + let pathItemData = + """ + { + "additionalOperations": { + "connect": { + } + } + } + """.data(using: .utf8)! + + XCTAssertThrowsError(try orderUnstableDecode(OpenAPI.PathItem.self, from: pathItemData)) { error in + XCTAssertEqual(String(describing: OpenAPI.Error(from: error)), "Problem encountered when parsing `connect` under the `/` path: 'connect' must be uppercased.") + } + } + + func test_invalidAdditionalOperation2_decode() throws { + let pathItemData = + """ + { + "additionalOperations": { + "link": { + } + } + } + """.data(using: .utf8)! + + XCTAssertThrowsError(try orderUnstableDecode(OpenAPI.PathItem.self, from: pathItemData)) { error in + XCTAssertEqual(String(describing: OpenAPI.Error(from: error)), "Problem encountered when parsing `link` under the `/` path: 'link' must be uppercased.") + } + } + func test_pathComponents_encode() throws { let test: [OpenAPI.Path] = ["/hello/world", "hi/there"] diff --git a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift index 362b72eac..246fe1cf2 100644 --- a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift @@ -51,6 +51,16 @@ final class ResolvedRouteTests: XCTestCase { summary: "trace", responses: [200: .response(description: "hello world")] ), + query: .init( + summary: "query", + responses: [200: .response(description: "hello world")] + ), + additionalOperations: [ + "LINK": .init( + summary: "link", + responses: [200: .response(description: "hello world")] + ) + ], vendorExtensions: [ "test": "route" ] @@ -76,8 +86,10 @@ final class ResolvedRouteTests: XCTestCase { XCTAssertEqual(routes.first?.head?.endpointSummary, "head") XCTAssertEqual(routes.first?.patch?.endpointSummary, "patch") XCTAssertEqual(routes.first?.trace?.endpointSummary, "trace") + XCTAssertEqual(routes.first?.query?.endpointSummary, "query") + XCTAssertEqual(routes.first?.additionalOperations["LINK"]?.endpointSummary, "link") - XCTAssertEqual(routes.first?.endpoints.count, 8) + XCTAssertEqual(routes.first?.endpoints.count, 10) XCTAssertEqual(routes.first?.get, routes.first?[.get]) XCTAssertEqual(routes.first?.put, routes.first?[.put]) @@ -87,6 +99,8 @@ final class ResolvedRouteTests: XCTestCase { XCTAssertEqual(routes.first?.head, routes.first?[.head]) XCTAssertEqual(routes.first?.patch, routes.first?[.patch]) XCTAssertEqual(routes.first?.trace, routes.first?[.trace]) + XCTAssertEqual(routes.first?.query, routes.first?[.query]) + XCTAssertEqual(routes.first?.additionalOperations["LINK"], routes.first?[.other("LINK")]) } func test_pathServersTakePrecedence() throws { diff --git a/Tests/OpenAPIKitTests/TagTests.swift b/Tests/OpenAPIKitTests/TagTests.swift index 52251a3de..892aa2951 100644 --- a/Tests/OpenAPIKitTests/TagTests.swift +++ b/Tests/OpenAPIKitTests/TagTests.swift @@ -11,12 +11,16 @@ import OpenAPIKit final class TagTests: XCTestCase { func test_init() { let t1 = OpenAPI.Tag(name: "hello") + XCTAssertNil(t1.summary) XCTAssertNil(t1.description) XCTAssertNil(t1.externalDocs) + XCTAssertEqual(t1.conditionalWarnings.count, 0) - let t2 = OpenAPI.Tag(name: "hello", description: "world") + let t2 = OpenAPI.Tag(name: "hello", summary: "hi", description: "world") + XCTAssertEqual(t2.summary, "hi") XCTAssertEqual(t2.description, "world") XCTAssertNil(t2.externalDocs) + XCTAssertEqual(t2.conditionalWarnings.count, 1) let t3 = OpenAPI.Tag( name: "hello", @@ -28,11 +32,25 @@ final class TagTests: XCTestCase { let t4 = OpenAPI.Tag( name: "tag", + summary: "first", description: "orig" ).overriddenNonNil(description: "new") - .overriddenNonNil(summary: "no-op") + .overriddenNonNil(summary: "cool") .overriddenNonNil(description: nil) // no effect + XCTAssertEqual(t4.summary, "cool") XCTAssertEqual(t4.description, "new") + + let t5 = OpenAPI.Tag( + name: "hello", + parent: "otherTag" + ) + XCTAssertEqual(t5.parent, "otherTag") + + let t6 = OpenAPI.Tag( + name: "hello", + kind: .nav + ) + XCTAssertEqual(t6.kind, .nav) } } @@ -63,6 +81,40 @@ extension TagTests { let tag = try orderUnstableDecode(OpenAPI.Tag.self, from: tagData) XCTAssertEqual(tag, OpenAPI.Tag(name: "hello")) + XCTAssertEqual(tag.conditionalWarnings.count, 0) + } + + func test_nameAndSummary_encode() throws { + let tag = OpenAPI.Tag( + name: "hello", + summary: "world" + ) + let encodedTag = try orderUnstableTestStringFromEncoding(of: tag) + + assertJSONEquivalent( + encodedTag, + """ + { + "name" : "hello", + "summary" : "world" + } + """ + ) + } + + func test_nameAndSummary_decode() throws { + let tagData = + """ + { + "name": "hello", + "summary": "world" + } + """.data(using: .utf8)! + + let tag = try orderUnstableDecode(OpenAPI.Tag.self, from: tagData) + + XCTAssertEqual(tag, OpenAPI.Tag(name: "hello", summary: "world")) + XCTAssertEqual(tag.conditionalWarnings.count, 1) } func test_nameAndDescription_encode() throws { @@ -95,15 +147,85 @@ extension TagTests { let tag = try orderUnstableDecode(OpenAPI.Tag.self, from: tagData) XCTAssertEqual(tag, OpenAPI.Tag(name: "hello", description: "world")) + XCTAssertEqual(tag.conditionalWarnings.count, 0) + } + + func test_nameAndParent_encode() throws { + let tag = OpenAPI.Tag( + name: "hello", + parent: "otherTag" + ) + let encodedTag = try orderUnstableTestStringFromEncoding(of: tag) + + assertJSONEquivalent( + encodedTag, + """ + { + "name" : "hello", + "parent" : "otherTag" + } + """ + ) + } + + func test_nameAndParent_decode() throws { + let tagData = + """ + { + "name": "hello", + "parent": "otherTag" + } + """.data(using: .utf8)! + + let tag = try orderUnstableDecode(OpenAPI.Tag.self, from: tagData) + + XCTAssertEqual(tag, OpenAPI.Tag(name: "hello", parent: "otherTag")) + XCTAssertEqual(tag.conditionalWarnings.count, 1) + } + + func test_nameAndKind_encode() throws { + let tag = OpenAPI.Tag( + name: "hello", + kind: .badge + ) + let encodedTag = try orderUnstableTestStringFromEncoding(of: tag) + + assertJSONEquivalent( + encodedTag, + """ + { + "kind" : "badge", + "name" : "hello" + } + """ + ) + } + + func test_nameAndKind_decode() throws { + let tagData = + """ + { + "name": "hello", + "kind": "audience" + } + """.data(using: .utf8)! + + let tag = try orderUnstableDecode(OpenAPI.Tag.self, from: tagData) + + XCTAssertEqual(tag, OpenAPI.Tag(name: "hello", kind: .audience)) + XCTAssertEqual(tag.conditionalWarnings.count, 1) } func test_allFields_encode() throws { let tag = OpenAPI.Tag( name: "hello", + summary: "sum", description: "world", externalDocs: .init( url: URL(string: "http://google.com")! ), + parent: "otherTag", + kind: "mytag", vendorExtensions: ["x-specialFeature": false] ) let encodedTag = try orderUnstableTestStringFromEncoding(of: tag) @@ -116,7 +238,10 @@ extension TagTests { "externalDocs" : { "url" : "http:\\/\\/google.com" }, + "kind" : "mytag", "name" : "hello", + "parent" : "otherTag", + "summary" : "sum", "x-specialFeature" : false } """ @@ -128,10 +253,13 @@ extension TagTests { """ { "name": "hello", + "summary": "sum", "description": "world", "externalDocs": { "url": "http://google.com" }, + "parent": "otherTag", + "kind": "mytag", "x-specialFeature" : false } """.data(using: .utf8)! @@ -142,10 +270,14 @@ extension TagTests { tag, OpenAPI.Tag( name: "hello", + summary: "sum", description: "world", externalDocs: .init(url: URL(string: "http://google.com")!), + parent: "otherTag", + kind: "mytag", vendorExtensions: ["x-specialFeature": false] ) ) + XCTAssertEqual(tag.conditionalWarnings.count, 3) } } diff --git a/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift index e5ed9f59f..6c17f8b29 100644 --- a/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift +++ b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift @@ -1067,7 +1067,7 @@ final class ValidatorTests: XCTestCase { let validator = Validator.blank .validating( - "All server arrays have not in operations have more than 1 server", + "All server arrays not in operations have more than 1 server", check: \[OpenAPI.Server].count > 1, when: \.codingPath.count == 1 // server array is under root document (coding path count 1) || take(\.codingPath) { codingPath in @@ -1075,7 +1075,7 @@ final class ValidatorTests: XCTestCase { guard codingPath.count > 1 else { return false } let secondToLastPathComponent = codingPath.suffix(2).first!.stringValue - let httpMethods = OpenAPI.HttpMethod.allCases.map { $0.rawValue.lowercased() } + let httpMethods = OpenAPI.BuiltinHttpMethod.allCases.map { $0.rawValue.lowercased() } return !httpMethods.contains(secondToLastPathComponent) } @@ -1484,9 +1484,68 @@ final class ValidatorTests: XCTestCase { XCTAssertEqual(errors?.values.count, 1) XCTAssertEqual( errors?.localizedDescription, - "Problem encountered when parsing ``: \'gzip\' could not be parsed as a Content Type. Content Types should have the format \'/\'. at path: .paths[\'/test\'].get.responses.200.content" + "Problem encountered when parsing ``: \'gzip\' could not be parsed as a Content Type. Content Types should have the format \'/\' at path: .paths[\'/test\'].get.responses.200.content" ) XCTAssertEqual(errors?.values.first?.codingPathString, ".paths[\'/test\'].get.responses.200.content") } } + + func test_collectsConditionalTagWarningNotStrict() throws { + let docData = """ + { + "info": {"title": "test", "version": "1.0"}, + "openapi": "3.1.0", + "tags": [ {"name": "hi", "summary": "sum"} ] + } + """.data(using: .utf8)! + + let doc = try orderUnstableDecode(OpenAPI.Document.self, from: docData) + + XCTAssertEqual( + doc.tags?.first?.applicableConditionalWarnings(for: doc).first?.localizedDescription, + "The Tag summary field is only supported for OpenAPI document versions 3.2.0 and later" + ) + + let warnings = try doc.validate(strict: false) + + XCTAssertEqual(warnings.count, 1) + XCTAssertEqual( + warnings.first?.localizedDescription, + "Problem encountered when parsing ``: The Tag summary field is only supported for OpenAPI document versions 3.2.0 and later." + ) + XCTAssertEqual(warnings.first?.codingPathString, ".tags[0]") + + // now test that the warning does not apply for v3.2.0 and above + var doc2 = doc + doc2.openAPIVersion = .v3_2_0 + + try XCTAssertEqual(doc2.validate(strict: false).count, 0) + } + + func test_collectsConditionalTagWarningStrict() throws { + let docData = """ + { + "info": {"title": "test", "version": "1.0"}, + "openapi": "3.1.0", + "tags": [ {"name": "hi", "summary": "sum"} ] + } + """.data(using: .utf8)! + + let doc = try orderUnstableDecode(OpenAPI.Document.self, from: docData) + + XCTAssertEqual( + doc.tags?.first?.applicableConditionalWarnings(for: doc).first?.localizedDescription, + "The Tag summary field is only supported for OpenAPI document versions 3.2.0 and later" + ) + + XCTAssertThrowsError(try doc.validate(strict: true)) { error in + let errors = error as? ValidationErrorCollection + XCTAssertEqual(errors?.values.count, 1) + XCTAssertEqual( + errors?.localizedDescription, + "Problem encountered when parsing ``: The Tag summary field is only supported for OpenAPI document versions 3.2.0 and later at path: .tags[0]" + ) + XCTAssertEqual(errors?.values.first?.codingPathString, ".tags[0]") + } + } } diff --git a/documentation/v2_migration_guide.md b/documentation/migration_guides/v2_migration_guide.md similarity index 100% rename from documentation/v2_migration_guide.md rename to documentation/migration_guides/v2_migration_guide.md diff --git a/documentation/v3_migration_guide.md b/documentation/migration_guides/v3_migration_guide.md similarity index 100% rename from documentation/v3_migration_guide.md rename to documentation/migration_guides/v3_migration_guide.md diff --git a/documentation/v4_migration_guide.md b/documentation/migration_guides/v4_migration_guide.md similarity index 100% rename from documentation/v4_migration_guide.md rename to documentation/migration_guides/v4_migration_guide.md diff --git a/documentation/migration_guides/v5_migration_guide.md b/documentation/migration_guides/v5_migration_guide.md new file mode 100644 index 000000000..452cebf4e --- /dev/null +++ b/documentation/migration_guides/v5_migration_guide.md @@ -0,0 +1,72 @@ +## OpenAPIKit v5 Migration Guide +For general information on the v5 release, see the release notes on GitHub. The +rest of this guide will be formatted as a series of changes and what options you +have to migrate code from v4 to v5. You can also refer back to the release notes +for each of the v4 pre-releases for the most thorough look at what changed. + +This guide will not spend time on strictly additive features of version 5. See +the release notes, README, and documentation for information on new features. + +### Swift version support +OpenAPIKit v5.0 drops support for Swift versions prior to 5.10 (i.e. it supports +v5.10 and greater). + +### MacOS version support +Only relevant when compiling OpenAPIKit on iOS: Now v12+ is required. + +### OpenAPI Specification Versions +The OpenAPIKit module's `OpenAPI.Document.Version` enum gained `v3_1_2`, +`v3_2_0` and `v3_2_x(x: Int)`. + +If you have exhaustive switches over values of those types then your switch +statements will need to be updated. + +If you use `v3_1_x(x: 2)` you should replace it with `v3_1_2`. + +### Content Types +The `application/x-yaml` media type is officially superseded by +`application/yaml`. OpenAPIKit will continue to support reading the +`application/x-yaml` media type, but it will always choose to encode the YAML +media type as `application/yaml`. + +### Http Methods +The `OpenAPIKit30` module's `OpenAPI.HttpMethod` type has been renamed to +`OpenAPI.BuiltinHttpMethod` and gained the `.query` method (though this method +cannot be represented on the OAS 3.0.x Path Item Object). + +The `OpenAPI` module's `OpenAPI.HttpMethod` type has been updated to support +non-builtin HTTP methods with the pre-existing HTTP methods moving to the +`OpenAPI.BuiltinHttpMethod` type and `HttpMethod` having just two cases: +`.builtin(BuiltinHttpMethod)` and `.other(String)`. + +Switch statements over `OpenAPI.HttpMethod` should be updated to first check if +the method is builtin or not: +```swift +switch httpMethod { +case .builtin(let builtin): + switch builtin { + case .delete: // ... + case .get: // ... + case .head: // ... + case .options: // ... + case .patch: // ... + case .post: // ... + case .put: // ... + case .trace: // ... + case .query: // ... + } +case .other(let other): + // new stuff to handle here +} +``` + +You can continue to use static constructors on `OpenAPI.HttpMethod` to construct +builtin methods so the following code _does not need to change_: +```swift +let httpMethod : OpenAPI.HttpMethod = .post +``` + +### Errors +Some error messages have been tweaked in small ways. If you match on the +string descriptions of any OpenAPIKit errors, you may need to update the +expected values. diff --git a/documentation/specification_coverage.md b/documentation/specification_coverage.md index e390c7f65..92af640d8 100644 --- a/documentation/specification_coverage.md +++ b/documentation/specification_coverage.md @@ -112,6 +112,8 @@ For more information on the OpenAPIKit types, see the [full type documentation]( - [x] head - [x] patch - [x] trace +- [x] query +- [x] additionalOperations - [x] servers - [x] parameters - [x] specification extensions (`vendorExtensions`) @@ -220,8 +222,11 @@ For more information on the OpenAPIKit types, see the [full type documentation]( ### Tag Object (`OpenAPI.Tag`) - [x] name +- [x] summary - [x] description - [x] externalDocs +- [x] parent +- [x] kind - [x] specification extensions (`vendorExtensions`) ### Reference Object (`OpenAPI.Reference`)