From cc44467e220228ba7e75207ebb0ff1ee1cdeb005 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 19 Sep 2025 21:06:51 -0500 Subject: [PATCH 01/30] move OAS 3.1.2 support to the base version enum --- Sources/OpenAPIKit/Document/Document.swift | 3 +++ Tests/OpenAPIKitTests/Document/DocumentTests.swift | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Sources/OpenAPIKit/Document/Document.swift b/Sources/OpenAPIKit/Document/Document.swift index 5126646e8..f7a3bde16 100644 --- a/Sources/OpenAPIKit/Document/Document.swift +++ b/Sources/OpenAPIKit/Document/Document.swift @@ -433,12 +433,14 @@ extension OpenAPI.Document { public enum Version: RawRepresentable, Equatable, Codable, Sendable { case v3_1_0 case v3_1_1 + case v3_1_2 case v3_1_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 default: let components = rawValue.split(separator: ".") guard components.count == 3 else { @@ -464,6 +466,7 @@ 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)" } } diff --git a/Tests/OpenAPIKitTests/Document/DocumentTests.swift b/Tests/OpenAPIKitTests/Document/DocumentTests.swift index 1c65f6c9c..cec87dd52 100644 --- a/Tests/OpenAPIKitTests/Document/DocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/DocumentTests.swift @@ -48,7 +48,7 @@ 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) @@ -61,7 +61,7 @@ final class DocumentTests: XCTestCase { XCTAssertEqual(t6, .v3_1_1) let t7 = OpenAPI.Document.Version(rawValue: "3.1.2") - XCTAssertEqual(t7, .v3_1_x(x: 2)) + XCTAssertEqual(t7, .v3_1_2) // not a known version: let t8 = OpenAPI.Document.Version(rawValue: "3.1.8") From f6671fa1598296304bac854f85d5e5442be902f7 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 13 Oct 2025 11:15:33 -0500 Subject: [PATCH 02/30] Add support for OAS 3.2.x version handling and the Tag summary field --- Sources/OpenAPIKit/Document/Document.swift | 89 +++++++++++++++++-- .../OpenAPIConditionalWarnings.swift | 55 ++++++++++++ Sources/OpenAPIKit/Tag.swift | 63 ++++++++++++- .../OpenAPIWarning.swift | 1 + .../Document/DocumentTests.swift | 37 ++++++-- Tests/OpenAPIKitTests/TagTests.swift | 50 ++++++++++- 6 files changed, 277 insertions(+), 18 deletions(-) create mode 100644 Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift diff --git a/Sources/OpenAPIKit/Document/Document.swift b/Sources/OpenAPIKit/Document/Document.swift index f7a3bde16..6e8ffdabe 100644 --- a/Sources/OpenAPIKit/Document/Document.swift +++ b/Sources/OpenAPIKit/Document/Document.swift @@ -430,23 +430,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 { @@ -455,10 +460,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) } } @@ -468,6 +480,73 @@ extension OpenAPI.Document { 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 + } } } } diff --git a/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift new file mode 100644 index 000000000..43a4c55fa --- /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/Tag.swift b/Sources/OpenAPIKit/Tag.swift index 47393cecb..c1d473910 100644 --- a/Sources/OpenAPIKit/Tag.swift +++ b/Sources/OpenAPIKit/Tag.swift @@ -11,8 +11,10 @@ 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? @@ -23,33 +25,73 @@ extension OpenAPI { /// where the values are anything codable. public var vendorExtensions: [String: AnyCodable] + public let conditionalWarnings: [(any Condition, Warning)] + public init( name: String, + summary: String? = nil, description: String? = nil, externalDocs: ExternalDocumentation? = nil, vendorExtensions: [String: AnyCodable] = [:] ) { self.name = name + self.summary = summary self.description = description self.externalDocs = externalDocs 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) + ].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 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.vendorExtensions == rhs.vendorExtensions + } +} + extension OpenAPI.Tag: ExpressibleByStringLiteral { public init(stringLiteral: String) { self.init(name: stringLiteral) } } -// 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, + 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, vendorExtensions: vendorExtensions @@ -65,6 +107,8 @@ 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) @@ -81,17 +125,25 @@ 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) 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) + ].compactMap { $0 } } } extension OpenAPI.Tag { internal enum CodingKeys: ExtendableCodingKey { case name + case summary case description case externalDocs case extended(String) @@ -99,6 +151,7 @@ extension OpenAPI.Tag { static var allBuiltinKeys: [CodingKeys] { return [ .name, + .summary, .description, .externalDocs ] @@ -112,6 +165,8 @@ extension OpenAPI.Tag { switch stringValue { case "name": self = .name + case "summary": + self = .summary case "description": self = .description case "externalDocs": @@ -125,6 +180,8 @@ extension OpenAPI.Tag { switch self { case .name: return "name" + case .summary: + return "summary" case .description: return "description" case .externalDocs: 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/Tests/OpenAPIKitTests/Document/DocumentTests.swift b/Tests/OpenAPIKitTests/Document/DocumentTests.swift index cec87dd52..88e462829 100644 --- a/Tests/OpenAPIKitTests/Document/DocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/DocumentTests.swift @@ -54,18 +54,39 @@ final class DocumentTests: XCTestCase { 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_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() { diff --git a/Tests/OpenAPIKitTests/TagTests.swift b/Tests/OpenAPIKitTests/TagTests.swift index 52251a3de..ce44c935c 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,10 +32,12 @@ 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") } } @@ -63,6 +69,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,11 +135,13 @@ 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_allFields_encode() throws { let tag = OpenAPI.Tag( name: "hello", + summary: "sum", description: "world", externalDocs: .init( url: URL(string: "http://google.com")! @@ -117,6 +159,7 @@ extension TagTests { "url" : "http:\\/\\/google.com" }, "name" : "hello", + "summary" : "sum", "x-specialFeature" : false } """ @@ -128,6 +171,7 @@ extension TagTests { """ { "name": "hello", + "summary": "sum", "description": "world", "externalDocs": { "url": "http://google.com" @@ -142,10 +186,12 @@ extension TagTests { tag, OpenAPI.Tag( name: "hello", + summary: "sum", description: "world", externalDocs: .init(url: URL(string: "http://google.com")!), vendorExtensions: ["x-specialFeature": false] ) ) + XCTAssertEqual(tag.conditionalWarnings.count, 1) } } From eb8cf763f960fab6ac64087b86d5e818a5f1c698 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 13 Oct 2025 12:00:39 -0500 Subject: [PATCH 03/30] Add conditional warnings to validator collection. Test the first such warning implemented. --- Sources/OpenAPIKit/Validator/Validator.swift | 8 ++- .../Validator/ValidatorTests.swift | 59 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) 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/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift index e5ed9f59f..1864058b2 100644 --- a/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift +++ b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift @@ -1489,4 +1489,63 @@ final class ValidatorTests: XCTestCase { 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]") + } + } } From fd04b6d7e53b62c722a542139c5ab4132e6b6a5f Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 19 Oct 2025 16:02:58 -0500 Subject: [PATCH 04/30] clean up errors that have always had extra punctuation --- Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift | 2 +- .../OpenAPIKit/Schema Object/JSONSchemaContext.swift | 2 +- Sources/OpenAPIKit/Validator/Validation.swift | 6 ++++-- .../SchemaErrorTests.swift | 2 +- Tests/OpenAPIKitTests/Validator/ValidatorTests.swift | 10 +++++----- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift index 43a4c55fa..ed4092da2 100644 --- a/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift +++ b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift @@ -47,7 +47,7 @@ internal struct DocumentVersionCondition: Sendable, Condition { 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.") + 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/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/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/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/Validator/ValidatorTests.swift b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift index 1864058b2..2278b8974 100644 --- a/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift +++ b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift @@ -1484,7 +1484,7 @@ 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") } @@ -1503,7 +1503,7 @@ final class ValidatorTests: XCTestCase { 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." + "The Tag summary field is only supported for OpenAPI document versions 3.2.0 and later" ) let warnings = try doc.validate(strict: false) @@ -1511,7 +1511,7 @@ final class ValidatorTests: XCTestCase { 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.." + "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]") @@ -1535,7 +1535,7 @@ final class ValidatorTests: XCTestCase { 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." + "The Tag summary field is only supported for OpenAPI document versions 3.2.0 and later" ) XCTAssertThrowsError(try doc.validate(strict: true)) { error in @@ -1543,7 +1543,7 @@ final class ValidatorTests: XCTestCase { 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]" + "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]") } From c7a722073b40a31407af44dcc0d6c86d65faf491 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 19 Oct 2025 16:24:35 -0500 Subject: [PATCH 05/30] add Tag support for the parent field --- Sources/OpenAPIKit/Tag.swift | 27 +++++++++++-- Sources/OpenAPIKitCompat/Compat30To31.swift | 2 + Tests/OpenAPIKitTests/TagTests.swift | 45 ++++++++++++++++++++- 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/Sources/OpenAPIKit/Tag.swift b/Sources/OpenAPIKit/Tag.swift index c1d473910..a61dc90a4 100644 --- a/Sources/OpenAPIKit/Tag.swift +++ b/Sources/OpenAPIKit/Tag.swift @@ -17,6 +17,8 @@ extension OpenAPI { public let summary: String? public let description: String? public let externalDocs: ExternalDocumentation? + /// The tag this tag is nested under. + public let parent: String? /// Dictionary of vendor extensions. /// @@ -32,17 +34,21 @@ extension OpenAPI { summary: String? = nil, description: String? = nil, externalDocs: ExternalDocumentation? = nil, + parent: String? = nil, vendorExtensions: [String: AnyCodable] = [:] ) { self.name = name self.summary = summary self.description = description self.externalDocs = externalDocs + self.parent = parent 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) + 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) ].compactMap { $0 } } } @@ -63,6 +69,7 @@ extension OpenAPI.Tag: Equatable { && lhs.summary == rhs.summary && lhs.description == rhs.description && lhs.externalDocs == rhs.externalDocs + && lhs.parent == rhs.parent && lhs.vendorExtensions == rhs.vendorExtensions } } @@ -83,6 +90,7 @@ extension OpenAPI.Tag : OpenAPISummarizable { summary: summary, description: description, externalDocs: externalDocs, + parent: parent, vendorExtensions: vendorExtensions ) } @@ -94,6 +102,7 @@ extension OpenAPI.Tag : OpenAPISummarizable { summary: summary, description: description, externalDocs: externalDocs, + parent: parent, vendorExtensions: vendorExtensions ) } @@ -113,6 +122,8 @@ extension OpenAPI.Tag: Encodable { try container.encodeIfPresent(externalDocs, forKey: .externalDocs) + try container.encodeIfPresent(parent, forKey: .parent) + if VendorExtensionsConfiguration.isEnabled(for: encoder) { try encodeExtensions(to: &container) } @@ -131,11 +142,15 @@ extension OpenAPI.Tag: Decodable { externalDocs = try container.decodeIfPresent(OpenAPI.ExternalDocumentation.self, forKey: .externalDocs) + parent = try container.decodeIfPresent(String.self, forKey: .parent) + 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) + 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) ].compactMap { $0 } } } @@ -146,6 +161,7 @@ extension OpenAPI.Tag { case summary case description case externalDocs + case parent case extended(String) static var allBuiltinKeys: [CodingKeys] { @@ -153,7 +169,8 @@ extension OpenAPI.Tag { .name, .summary, .description, - .externalDocs + .externalDocs, + .parent ] } @@ -171,6 +188,8 @@ extension OpenAPI.Tag { self = .description case "externalDocs": self = .externalDocs + case "parent": + self = .parent default: self = .extendedKey(for: stringValue) } @@ -186,6 +205,8 @@ extension OpenAPI.Tag { return "description" case .externalDocs: return "externalDocs" + case .parent: + return "parent" case .extended(let key): return key } 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/Tests/OpenAPIKitTests/TagTests.swift b/Tests/OpenAPIKitTests/TagTests.swift index ce44c935c..a5816e907 100644 --- a/Tests/OpenAPIKitTests/TagTests.swift +++ b/Tests/OpenAPIKitTests/TagTests.swift @@ -39,6 +39,12 @@ final class TagTests: XCTestCase { .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") } } @@ -138,6 +144,39 @@ extension TagTests { 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_allFields_encode() throws { let tag = OpenAPI.Tag( name: "hello", @@ -146,6 +185,7 @@ extension TagTests { externalDocs: .init( url: URL(string: "http://google.com")! ), + parent: "otherTag", vendorExtensions: ["x-specialFeature": false] ) let encodedTag = try orderUnstableTestStringFromEncoding(of: tag) @@ -159,6 +199,7 @@ extension TagTests { "url" : "http:\\/\\/google.com" }, "name" : "hello", + "parent" : "otherTag", "summary" : "sum", "x-specialFeature" : false } @@ -176,6 +217,7 @@ extension TagTests { "externalDocs": { "url": "http://google.com" }, + "parent": "otherTag", "x-specialFeature" : false } """.data(using: .utf8)! @@ -189,9 +231,10 @@ extension TagTests { summary: "sum", description: "world", externalDocs: .init(url: URL(string: "http://google.com")!), + parent: "otherTag", vendorExtensions: ["x-specialFeature": false] ) ) - XCTAssertEqual(tag.conditionalWarnings.count, 1) + XCTAssertEqual(tag.conditionalWarnings.count, 2) } } From b0353de0a4211cb4adc0c996f1628947b12621d1 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 19 Oct 2025 16:49:14 -0500 Subject: [PATCH 06/30] Add Tag support for the kind field --- Sources/OpenAPIKit/Tag.swift | 61 ++++++++++++++++++++++++++-- Tests/OpenAPIKitTests/TagTests.swift | 45 +++++++++++++++++++- 2 files changed, 102 insertions(+), 4 deletions(-) diff --git a/Sources/OpenAPIKit/Tag.swift b/Sources/OpenAPIKit/Tag.swift index a61dc90a4..4a910bb3e 100644 --- a/Sources/OpenAPIKit/Tag.swift +++ b/Sources/OpenAPIKit/Tag.swift @@ -19,6 +19,12 @@ extension OpenAPI { 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. /// @@ -35,6 +41,7 @@ extension OpenAPI { description: String? = nil, externalDocs: ExternalDocumentation? = nil, parent: String? = nil, + kind: Kind? = nil, vendorExtensions: [String: AnyCodable] = [:] ) { self.name = name @@ -42,18 +49,51 @@ extension OpenAPI { 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) + 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( @@ -70,6 +110,7 @@ extension OpenAPI.Tag: Equatable { && lhs.description == rhs.description && lhs.externalDocs == rhs.externalDocs && lhs.parent == rhs.parent + && lhs.kind == rhs.kind && lhs.vendorExtensions == rhs.vendorExtensions } } @@ -91,6 +132,7 @@ extension OpenAPI.Tag : OpenAPISummarizable { description: description, externalDocs: externalDocs, parent: parent, + kind: kind, vendorExtensions: vendorExtensions ) } @@ -103,6 +145,7 @@ extension OpenAPI.Tag : OpenAPISummarizable { description: description, externalDocs: externalDocs, parent: parent, + kind: kind, vendorExtensions: vendorExtensions ) } @@ -124,6 +167,8 @@ extension OpenAPI.Tag: Encodable { try container.encodeIfPresent(parent, forKey: .parent) + try container.encodeIfPresent(kind, forKey: .kind) + if VendorExtensionsConfiguration.isEnabled(for: encoder) { try encodeExtensions(to: &container) } @@ -144,13 +189,17 @@ extension OpenAPI.Tag: Decodable { 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) + 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 } } } @@ -162,6 +211,7 @@ extension OpenAPI.Tag { case description case externalDocs case parent + case kind case extended(String) static var allBuiltinKeys: [CodingKeys] { @@ -170,7 +220,8 @@ extension OpenAPI.Tag { .summary, .description, .externalDocs, - .parent + .parent, + .kind ] } @@ -190,6 +241,8 @@ extension OpenAPI.Tag { self = .externalDocs case "parent": self = .parent + case "kind": + self = .kind default: self = .extendedKey(for: stringValue) } @@ -207,6 +260,8 @@ extension OpenAPI.Tag { return "externalDocs" case .parent: return "parent" + case .kind: + return "kind" case .extended(let key): return key } diff --git a/Tests/OpenAPIKitTests/TagTests.swift b/Tests/OpenAPIKitTests/TagTests.swift index a5816e907..892aa2951 100644 --- a/Tests/OpenAPIKitTests/TagTests.swift +++ b/Tests/OpenAPIKitTests/TagTests.swift @@ -45,6 +45,12 @@ final class TagTests: XCTestCase { parent: "otherTag" ) XCTAssertEqual(t5.parent, "otherTag") + + let t6 = OpenAPI.Tag( + name: "hello", + kind: .nav + ) + XCTAssertEqual(t6.kind, .nav) } } @@ -177,6 +183,39 @@ extension TagTests { 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", @@ -186,6 +225,7 @@ extension TagTests { url: URL(string: "http://google.com")! ), parent: "otherTag", + kind: "mytag", vendorExtensions: ["x-specialFeature": false] ) let encodedTag = try orderUnstableTestStringFromEncoding(of: tag) @@ -198,6 +238,7 @@ extension TagTests { "externalDocs" : { "url" : "http:\\/\\/google.com" }, + "kind" : "mytag", "name" : "hello", "parent" : "otherTag", "summary" : "sum", @@ -218,6 +259,7 @@ extension TagTests { "url": "http://google.com" }, "parent": "otherTag", + "kind": "mytag", "x-specialFeature" : false } """.data(using: .utf8)! @@ -232,9 +274,10 @@ extension TagTests { description: "world", externalDocs: .init(url: URL(string: "http://google.com")!), parent: "otherTag", + kind: "mytag", vendorExtensions: ["x-specialFeature": false] ) ) - XCTAssertEqual(tag.conditionalWarnings.count, 2) + XCTAssertEqual(tag.conditionalWarnings.count, 3) } } From 2622494b6076197664f66051367cb4f03d8f59d7 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 19 Oct 2025 19:48:38 -0500 Subject: [PATCH 07/30] drop Swift support prior to 5.10 --- .github/workflows/tests.yml | 4 ---- README.md | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cebd42bea..a3fab25c4 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 diff --git a/README.md b/README.md index a7c95c4fb..98278a4f3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![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/workflows/Tests/badge.svg) From 5ab7759ee0a587a03a92fb29eda84919a8df4558 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 19 Oct 2025 20:12:30 -0500 Subject: [PATCH 08/30] add swift 6.2 CI into the matrix --- .github/workflows/tests.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a3fab25c4..1a41f29e2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -21,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 }} From 4067f8306e759463bebdbcad0c18e9c9c94243a1 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 20 Oct 2025 09:02:44 -0500 Subject: [PATCH 09/30] support and prefer new official yaml media type --- Sources/OpenAPIKitCore/Shared/ContentType.swift | 3 ++- Tests/OpenAPIKitCoreTests/ContentTypeTests.swift | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) 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/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) From efa684ce73ffea4355c2c7fa5b6fc518fa18726f Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Thu, 23 Oct 2025 11:19:43 -0500 Subject: [PATCH 10/30] use swift tools version that aligns with minimum supported swift version --- Package.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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( From 74e8bb76a2373d667f0791e66ce3729b6e75d808 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 20 Oct 2025 09:41:15 -0500 Subject: [PATCH 11/30] Add new HTTP QUERY method support --- .../Either/Either+Convenience.swift | 2 + .../Path Item/DereferencedPathItem.swift | 10 ++ Sources/OpenAPIKit/Path Item/PathItem.swift | 27 +++++- .../OpenAPIKit/Path Item/ResolvedRoute.swift | 8 +- .../Path Item/DereferencedPathItem.swift | 2 + Sources/OpenAPIKit30/Path Item/PathItem.swift | 5 + .../Path Item/ResolvedRoute.swift | 2 + .../OpenAPIKitCore/Shared/HttpMethod.swift | 1 + Tests/OpenAPIKitTests/ComponentsTests.swift | 11 ++- .../Document/DocumentTests.swift | 20 +++- .../Path Item/DereferencedPathItemTests.swift | 93 ++++++++++++++----- .../Path Item/PathItemTests.swift | 22 ++++- .../Path Item/ResolvedRouteTests.swift | 8 +- documentation/specification_coverage.md | 1 + 14 files changed, 177 insertions(+), 35 deletions(-) diff --git a/Sources/OpenAPIKit/Either/Either+Convenience.swift b/Sources/OpenAPIKit/Either/Either+Convenience.swift index f468f0ca2..7900a13d3 100644 --- a/Sources/OpenAPIKit/Either/Either+Convenience.swift +++ b/Sources/OpenAPIKit/Either/Either+Convenience.swift @@ -169,6 +169,7 @@ extension Either where B == OpenAPI.PathItem { head: OpenAPI.Operation? = nil, patch: OpenAPI.Operation? = nil, trace: OpenAPI.Operation? = nil, + query: OpenAPI.Operation? = nil, vendorExtensions: [String: AnyCodable] = [:] ) { self = .b( @@ -185,6 +186,7 @@ extension Either where B == OpenAPI.PathItem { head: head, patch: patch, trace: trace, + query: query, vendorExtensions: vendorExtensions ) ) diff --git a/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift b/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift index d9f25538f..09a7edc12 100644 --- a/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift +++ b/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift @@ -34,6 +34,8 @@ 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? public subscript(dynamicMember path: KeyPath) -> T { return underlyingPathItem[keyPath: path] @@ -64,6 +66,7 @@ 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) } var pathItem = pathItem if let name { @@ -96,6 +99,8 @@ extension DereferencedPathItem { return self.put case .trace: return self.trace + case .query: + return self.query } } @@ -151,6 +156,7 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { let oldHead = head let oldPatch = patch let oldTrace = trace + let oldQuery = query async let (newParameters, c1, m1) = oldParameters.externallyDereferenced(with: loader) // async let (newServers, c2, m2) = oldServers.externallyDereferenced(with: loader) @@ -162,6 +168,7 @@ 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) var pathItem = self var newComponents = try await c1 @@ -179,6 +186,7 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { pathItem.head = try await newHead pathItem.patch = try await newPatch pathItem.trace = try await newTrace + pathItem.query = try await newQuery try await newComponents.merge(c3) try await newComponents.merge(c4) @@ -188,6 +196,7 @@ 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 newMessages += m3 try await newMessages += m4 @@ -197,6 +206,7 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { try await newMessages += m8 try await newMessages += m9 try await newMessages += m10 + try await newMessages += m11 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..41d768134 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). /// @@ -52,6 +54,8 @@ 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? /// Dictionary of vendor extensions. /// @@ -73,6 +77,7 @@ extension OpenAPI { head: Operation? = nil, patch: Operation? = nil, trace: Operation? = nil, + query: Operation? = nil, vendorExtensions: [String: AnyCodable] = [:] ) { self.summary = summary @@ -88,6 +93,7 @@ extension OpenAPI { self.head = head self.patch = patch self.trace = trace + self.query = query self.vendorExtensions = vendorExtensions } @@ -130,6 +136,11 @@ extension OpenAPI { public mutating func trace(_ op: Operation?) { trace = op } + + /// Set the `QUERY` endpoint operation. + public mutating func query(_ op: Operation?) { + query = op + } } } @@ -164,6 +175,8 @@ extension OpenAPI.PathItem { return self.put case .trace: return self.trace + case .query: + return self.query } } @@ -186,6 +199,8 @@ extension OpenAPI.PathItem { self.put(operation) case .trace: self.trace(operation) + case .query: + self.query(operation) } } @@ -256,6 +271,7 @@ 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 VendorExtensionsConfiguration.isEnabled(for: encoder) { try encodeExtensions(to: &container) @@ -281,6 +297,7 @@ 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) vendorExtensions = try Self.extensions(from: decoder) } catch let error as DecodingError { @@ -314,6 +331,7 @@ extension OpenAPI.PathItem { case head case patch case trace + case query case extended(String) @@ -331,7 +349,8 @@ extension OpenAPI.PathItem { .options, .head, .patch, - .trace + .trace, + .query ] } @@ -365,6 +384,8 @@ extension OpenAPI.PathItem { self = .patch case "trace": self = .trace + case "query": + self = .query default: self = .extendedKey(for: stringValue) } @@ -396,6 +417,8 @@ extension OpenAPI.PathItem { return "patch" case .trace: return "trace" + case .query: + return "query" case .extended(let key): return key } diff --git a/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift b/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift index ed2a7062c..c15ef5bb9 100644 --- a/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift +++ b/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift @@ -64,6 +64,8 @@ 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? /// Create a ResolvedRoute. /// @@ -103,6 +105,7 @@ public struct ResolvedRoute: Equatable { self.head = endpoints[.head] self.patch = endpoints[.patch] self.trace = endpoints[.trace] + self.query = endpoints[.query] } /// An array of all endpoints at this route. @@ -115,7 +118,8 @@ public struct ResolvedRoute: Equatable { self.options, self.head, self.patch, - self.trace + self.trace, + self.query ].compactMap { $0 } } @@ -138,6 +142,8 @@ public struct ResolvedRoute: Equatable { return self.put case .trace: return self.trace + case .query: + return self.query } } diff --git a/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift b/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift index 542b8aa54..a20db00e5 100644 --- a/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift +++ b/Sources/OpenAPIKit30/Path Item/DereferencedPathItem.swift @@ -95,6 +95,8 @@ extension DereferencedPathItem { return self.put case .trace: return self.trace + case .query: + return nil } } diff --git a/Sources/OpenAPIKit30/Path Item/PathItem.swift b/Sources/OpenAPIKit30/Path Item/PathItem.swift index 3cbc5abc2..fae4078dd 100644 --- a/Sources/OpenAPIKit30/Path Item/PathItem.swift +++ b/Sources/OpenAPIKit30/Path Item/PathItem.swift @@ -164,6 +164,8 @@ extension OpenAPI.PathItem { return self.put case .trace: return self.trace + case .query: + return nil } } @@ -186,6 +188,9 @@ 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") } } diff --git a/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift b/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift index ed2a7062c..4f4e27c12 100644 --- a/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift +++ b/Sources/OpenAPIKit30/Path Item/ResolvedRoute.swift @@ -138,6 +138,8 @@ public struct ResolvedRoute: Equatable { return self.put case .trace: return self.trace + case .query: + return nil } } diff --git a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift index 57481265e..356dbd354 100644 --- a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift +++ b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift @@ -21,5 +21,6 @@ extension Shared { case head = "HEAD" case options = "OPTIONS" case trace = "TRACE" + case query = "QUERY" } } 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 d57cbd4aa..166e12879 100644 --- a/Tests/OpenAPIKitTests/Document/DocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/DocumentTests.swift @@ -1065,7 +1065,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( @@ -1113,6 +1113,9 @@ extension DocumentTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -1127,7 +1130,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"), @@ -1178,6 +1181,8 @@ extension DocumentTests { "put": { }, "trace": { + }, + "query": { } } } @@ -1193,7 +1198,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")!) @@ -1203,7 +1208,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( @@ -1251,6 +1256,9 @@ extension DocumentTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -1292,6 +1300,8 @@ extension DocumentTests { "put": { }, "trace": { + }, + "query": { } } } @@ -1307,7 +1317,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..1f097ab3f 100644 --- a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift @@ -24,6 +24,7 @@ final class DereferencedPathItemTests: XCTestCase { XCTAssertNil(t1[.post]) XCTAssertNil(t1[.put]) XCTAssertNil(t1[.trace]) + XCTAssertNil(t1[.query]) // test dynamic member lookup XCTAssertEqual(t1.summary, "test") @@ -41,10 +42,11 @@ 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: [:]) ).dereferenced(in: .noComponents) - XCTAssertEqual(t1.endpoints.count, 8) + XCTAssertEqual(t1.endpoints.count, 9) XCTAssertEqual(t1.parameters.map { $0.schemaOrContent.schemaValue?.jsonSchema }, [.string]) XCTAssertEqual(t1[.delete]?.tags, ["delete op"]) XCTAssertEqual(t1[.get]?.tags, ["get op"]) @@ -54,6 +56,7 @@ 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"]) } func test_referencedParameter() throws { @@ -101,7 +104,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") ] ) let t1 = try OpenAPI.PathItem( @@ -112,10 +116,11 @@ 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) - XCTAssertEqual(t1.endpoints.count, 8) + XCTAssertEqual(t1.endpoints.count, 9) XCTAssertEqual(t1[.delete]?.tags, ["delete op"]) XCTAssertEqual(t1[.delete]?.responses[status: 200]?.description, "delete resp") XCTAssertEqual(t1[.get]?.tags, ["get op"]) @@ -132,6 +137,8 @@ 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") } func test_missingReferencedGetResp() { @@ -143,7 +150,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 +163,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 +178,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 +191,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 +206,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 +219,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 +234,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 +247,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 +262,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 +275,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 +290,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 +303,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 +318,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 +331,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 +346,36 @@ 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( + 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_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( @@ -337,7 +387,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) ) } diff --git a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift index 2a4000777..4074021c0 100644 --- a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift @@ -54,7 +54,8 @@ final class PathItemTests: XCTestCase { options: op, head: op, patch: op, - trace: op + trace: op, + query: op ) } @@ -71,6 +72,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 +101,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 +114,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 +139,9 @@ final class PathItemTests: XCTestCase { pathItem[.trace] = op XCTAssertEqual(pathItem.for(.trace), op) + + pathItem[.query] = op + XCTAssertEqual(pathItem.for(.query), op) } func test_initializePathItemMap() { @@ -264,7 +273,8 @@ extension PathItemTests { options: op, head: op, patch: op, - trace: op + trace: op, + query: op ) let encodedPathItem = try orderUnstableTestStringFromEncoding(of: pathItem) @@ -293,6 +303,9 @@ extension PathItemTests { }, "put" : { + }, + "query" : { + }, "trace" : { @@ -321,6 +334,8 @@ extension PathItemTests { "put" : { }, "trace" : { + }, + "query" : { } } """.data(using: .utf8)! @@ -339,7 +354,8 @@ extension PathItemTests { options: op, head: op, patch: op, - trace: op + trace: op, + query: op ) ) } diff --git a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift index 362b72eac..96d4b8214 100644 --- a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift @@ -51,6 +51,10 @@ final class ResolvedRouteTests: XCTestCase { summary: "trace", responses: [200: .response(description: "hello world")] ), + query: .init( + summary: "query", + responses: [200: .response(description: "hello world")] + ), vendorExtensions: [ "test": "route" ] @@ -76,8 +80,9 @@ 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?.endpoints.count, 8) + XCTAssertEqual(routes.first?.endpoints.count, 9) XCTAssertEqual(routes.first?.get, routes.first?[.get]) XCTAssertEqual(routes.first?.put, routes.first?[.put]) @@ -87,6 +92,7 @@ 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]) } func test_pathServersTakePrecedence() throws { diff --git a/documentation/specification_coverage.md b/documentation/specification_coverage.md index e390c7f65..761130a35 100644 --- a/documentation/specification_coverage.md +++ b/documentation/specification_coverage.md @@ -112,6 +112,7 @@ For more information on the OpenAPIKit types, see the [full type documentation]( - [x] head - [x] patch - [x] trace +- [x] query - [x] servers - [x] parameters - [x] specification extensions (`vendorExtensions`) From da796344b798c2c7767b5af8c22116ee8442c9e7 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 20 Oct 2025 11:04:38 -0500 Subject: [PATCH 12/30] Add OAS 3.2.0 warning for PathItems with query endpoints --- Sources/OpenAPIKit/Path Item/PathItem.swift | 46 ++++++++++++++++++++- Sources/OpenAPIKit/Tag.swift | 4 ++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/Sources/OpenAPIKit/Path Item/PathItem.swift b/Sources/OpenAPIKit/Path Item/PathItem.swift index 41d768134..9f737c51f 100644 --- a/Sources/OpenAPIKit/Path Item/PathItem.swift +++ b/Sources/OpenAPIKit/Path Item/PathItem.swift @@ -23,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]? @@ -64,6 +64,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, @@ -95,6 +101,11 @@ extension OpenAPI { self.trace = trace self.query = query 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) + ].compactMap { $0 } } /// Set the `GET` endpoint operation. @@ -144,6 +155,34 @@ extension OpenAPI { } } +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.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" + ) + } +} + extension OpenAPI.PathItem { public typealias Map = OrderedDictionary, OpenAPI.PathItem>> } @@ -300,6 +339,11 @@ extension OpenAPI.PathItem: Decodable { query = try container.decodeIfPresent(OpenAPI.Operation.self, forKey: .query) 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) + ].compactMap { $0 } } catch let error as DecodingError { throw OpenAPI.Error.Decoding.Path(error) diff --git a/Sources/OpenAPIKit/Tag.swift b/Sources/OpenAPIKit/Tag.swift index 4a910bb3e..27d9adf92 100644 --- a/Sources/OpenAPIKit/Tag.swift +++ b/Sources/OpenAPIKit/Tag.swift @@ -33,6 +33,10 @@ 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( From 4b75af77627e3c2310d79b4d1c0bf22e30aa0796 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 21 Oct 2025 10:36:03 -0500 Subject: [PATCH 13/30] Add additionalOperations to PathItem type. Expand HttpMethod type to support additional methods not built into library. --- .../Either/Either+Convenience.swift | 2 + .../PathDecodingError.swift | 8 +- .../Path Item/DereferencedPathItem.swift | 52 +++--- Sources/OpenAPIKit/Path Item/PathItem.swift | 145 ++++++++++++----- .../OpenAPIKit/Path Item/ResolvedRoute.swift | 70 ++++---- Sources/OpenAPIKit/_CoreReExport.swift | 1 + Sources/OpenAPIKit30/Document/Document.swift | 2 +- .../Operation/ResolvedEndpoint.swift | 2 +- .../Path Item/DereferencedPathItem.swift | 8 +- Sources/OpenAPIKit30/Path Item/PathItem.swift | 12 +- .../Path Item/ResolvedRoute.swift | 4 +- Sources/OpenAPIKit30/_CoreReExport.swift | 1 + .../DecodingErrorExtensions.swift | 8 + .../OpenAPIKitCore/Shared/HttpMethod.swift | 87 +++++++++- .../Validator/ValidatorTests.swift | 4 +- .../Path Item/DereferencedPathItemTests.swift | 53 +++++- .../Path Item/PathItemTests.swift | 151 +++++++++++++++++- .../Path Item/ResolvedRouteTests.swift | 10 +- .../Validator/ValidatorTests.swift | 4 +- 19 files changed, 501 insertions(+), 123 deletions(-) diff --git a/Sources/OpenAPIKit/Either/Either+Convenience.swift b/Sources/OpenAPIKit/Either/Either+Convenience.swift index 7900a13d3..f9cd238dc 100644 --- a/Sources/OpenAPIKit/Either/Either+Convenience.swift +++ b/Sources/OpenAPIKit/Either/Either+Convenience.swift @@ -170,6 +170,7 @@ extension Either where B == OpenAPI.PathItem { patch: OpenAPI.Operation? = nil, trace: OpenAPI.Operation? = nil, query: OpenAPI.Operation? = nil, + additionalOperations: OrderedDictionary = [:], vendorExtensions: [String: AnyCodable] = [:] ) { self = .b( @@ -187,6 +188,7 @@ extension Either where B == OpenAPI.PathItem { 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/Path Item/DereferencedPathItem.swift b/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift index 09a7edc12..cdc11150d 100644 --- a/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift +++ b/Sources/OpenAPIKit/Path Item/DereferencedPathItem.swift @@ -37,6 +37,11 @@ public struct DereferencedPathItem: Equatable { /// 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] } @@ -68,6 +73,8 @@ public struct DereferencedPathItem: Equatable { 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 { pathItem.vendorExtensions[OpenAPI.Components.componentNameExtension] = .init(name) @@ -83,24 +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 .query: - return self.query + 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)] } } @@ -122,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) } } } @@ -158,6 +163,8 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { 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) async let (newGet, c3, m3) = oldGet.externallyDereferenced(with: loader) @@ -170,6 +177,8 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { 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 var newMessages = try await m1 @@ -187,6 +196,7 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { 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) @@ -197,6 +207,7 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { 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 @@ -207,6 +218,7 @@ extension OpenAPI.PathItem: ExternallyDereferenceable { 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 9f737c51f..dd3445d2a 100644 --- a/Sources/OpenAPIKit/Path Item/PathItem.swift +++ b/Sources/OpenAPIKit/Path Item/PathItem.swift @@ -57,6 +57,11 @@ extension OpenAPI { /// 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. /// /// These should be of the form: @@ -84,6 +89,7 @@ extension OpenAPI { patch: Operation? = nil, trace: Operation? = nil, query: Operation? = nil, + additionalOperations: OrderedDictionary = [:], vendorExtensions: [String: AnyCodable] = [:] ) { self.summary = summary @@ -100,11 +106,14 @@ extension OpenAPI { 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) + 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 } } @@ -170,6 +179,7 @@ extension OpenAPI.PathItem: Equatable { && lhs.patch == rhs.patch && lhs.trace == rhs.trace && lhs.query == rhs.query + && lhs.additionalOperations == rhs.additionalOperations && lhs.vendorExtensions == rhs.vendorExtensions } } @@ -183,6 +193,15 @@ fileprivate func nonNilVersionWarning(fieldName: String, value: Subject } } +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>> } @@ -198,48 +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 .query: - return self.query + 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 .query: - self.query(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 } } @@ -264,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) } } } @@ -312,6 +334,10 @@ extension OpenAPI.PathItem: Encodable { 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) } @@ -338,13 +364,35 @@ extension OpenAPI.PathItem: Decodable { 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) + 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 { @@ -360,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 @@ -377,6 +432,8 @@ extension OpenAPI.PathItem { case trace case query + case additionalOperations + case extended(String) static var allBuiltinKeys: [CodingKeys] { @@ -394,7 +451,9 @@ extension OpenAPI.PathItem { .head, .patch, .trace, - .query + .query, + + .additionalOperations ] } @@ -430,6 +489,8 @@ extension OpenAPI.PathItem { self = .trace case "query": self = .query + case "additionalOperations": + self = .additionalOperations default: self = .extendedKey(for: stringValue) } @@ -463,6 +524,8 @@ extension OpenAPI.PathItem { 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 c15ef5bb9..ed37d68a5 100644 --- a/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift +++ b/Sources/OpenAPIKit/Path Item/ResolvedRoute.swift @@ -67,6 +67,11 @@ public struct ResolvedRoute: Equatable { /// 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. /// /// `ResolvedRoute` creation is only publicly @@ -85,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 @@ -97,20 +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.query = endpoints[.query] + 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, @@ -121,29 +135,27 @@ public struct ResolvedRoute: Equatable { 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 .query: - return self.query + 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/_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 a20db00e5..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 @@ -100,7 +100,7 @@ extension DereferencedPathItem { } } - public subscript(verb: OpenAPI.HttpMethod) -> DereferencedOperation? { + public subscript(verb: OpenAPI.BuiltinHttpMethod) -> DereferencedOperation? { get { return `for`(verb) } @@ -109,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 } @@ -118,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 fae4078dd..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 @@ -170,7 +170,7 @@ extension OpenAPI.PathItem { } /// 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) @@ -194,7 +194,7 @@ extension OpenAPI.PathItem { } } - public subscript(verb: OpenAPI.HttpMethod) -> OpenAPI.Operation? { + public subscript(verb: OpenAPI.BuiltinHttpMethod) -> OpenAPI.Operation? { get { return `for`(verb) } @@ -206,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 } @@ -215,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 4f4e27c12..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 @@ -143,7 +143,7 @@ public struct ResolvedRoute: Equatable { } } - 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/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/Shared/HttpMethod.swift b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift index 356dbd354..b6b3579c7 100644 --- a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift +++ b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift @@ -12,7 +12,7 @@ extension Shared { /// 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 /// object. - public enum HttpMethod: String, CaseIterable, Sendable { + public enum BuiltinHttpMethod: String, CaseIterable, Sendable { case get = "GET" case post = "POST" case patch = "PATCH" @@ -23,4 +23,89 @@ extension Shared { case trace = "TRACE" case query = "QUERY" } + + 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/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift index 1f097ab3f..5ca4c9448 100644 --- a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift @@ -25,6 +25,7 @@ final class DereferencedPathItemTests: XCTestCase { XCTAssertNil(t1[.put]) XCTAssertNil(t1[.trace]) XCTAssertNil(t1[.query]) + XCTAssertEqual(t1.additionalOperations, [:]) // test dynamic member lookup XCTAssertEqual(t1.summary, "test") @@ -43,10 +44,13 @@ final class DereferencedPathItemTests: XCTestCase { head: .init(tags: "head op", responses: [:]), patch: .init(tags: "patch op", responses: [:]), trace: .init(tags: "trace op", responses: [:]), - query: .init(tags: "query op", responses: [:]) + query: .init(tags: "query op", responses: [:]), + additionalOperations: [ + "LINK": .init(tags: "link op", responses: [:]) + ] ).dereferenced(in: .noComponents) - XCTAssertEqual(t1.endpoints.count, 9) + 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"]) @@ -57,6 +61,7 @@ final class DereferencedPathItemTests: XCTestCase { 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 { @@ -105,7 +110,8 @@ final class DereferencedPathItemTests: XCTestCase { "head": .init(description: "head resp"), "patch": .init(description: "patch resp"), "trace": .init(description: "trace resp"), - "query": .init(description: "query resp") + "query": .init(description: "query resp"), + "link": .init(description: "link resp") ] ) let t1 = try OpenAPI.PathItem( @@ -117,10 +123,13 @@ final class DereferencedPathItemTests: XCTestCase { 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"))]) + 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, 9) + 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"]) @@ -139,6 +148,8 @@ final class DereferencedPathItemTests: XCTestCase { 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() { @@ -392,4 +403,36 @@ final class DereferencedPathItemTests: XCTestCase { ).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 4074021c0..13087fbbd 100644 --- a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift @@ -55,7 +55,10 @@ final class PathItemTests: XCTestCase { head: op, patch: op, trace: op, - query: op + query: op, + additionalOperations: [ + "LINK": op + ] ) } @@ -149,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 @@ -274,7 +328,10 @@ extension PathItemTests { head: op, patch: op, trace: op, - query: op + query: op, + additionalOperations: [ + "LINK": op + ] ) let encodedPathItem = try orderUnstableTestStringFromEncoding(of: pathItem) @@ -283,6 +340,11 @@ extension PathItemTests { encodedPathItem, """ { + "additionalOperations" : { + "LINK" : { + + } + }, "delete" : { }, @@ -336,11 +398,19 @@ extension PathItemTests { "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: [:]) @@ -355,11 +425,84 @@ extension PathItemTests { head: op, patch: op, trace: op, - query: 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 96d4b8214..246fe1cf2 100644 --- a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift @@ -55,6 +55,12 @@ final class ResolvedRouteTests: XCTestCase { summary: "query", responses: [200: .response(description: "hello world")] ), + additionalOperations: [ + "LINK": .init( + summary: "link", + responses: [200: .response(description: "hello world")] + ) + ], vendorExtensions: [ "test": "route" ] @@ -81,8 +87,9 @@ final class ResolvedRouteTests: XCTestCase { 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, 9) + XCTAssertEqual(routes.first?.endpoints.count, 10) XCTAssertEqual(routes.first?.get, routes.first?[.get]) XCTAssertEqual(routes.first?.put, routes.first?[.put]) @@ -93,6 +100,7 @@ final class ResolvedRouteTests: XCTestCase { 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/Validator/ValidatorTests.swift b/Tests/OpenAPIKitTests/Validator/ValidatorTests.swift index 2278b8974..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) } From 832263a03a932705b0a27b95a13bb95e6c8a1f7f Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 24 Oct 2025 09:25:16 -0500 Subject: [PATCH 14/30] catch the spec coverage list up --- documentation/specification_coverage.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/documentation/specification_coverage.md b/documentation/specification_coverage.md index 761130a35..92af640d8 100644 --- a/documentation/specification_coverage.md +++ b/documentation/specification_coverage.md @@ -113,6 +113,7 @@ For more information on the OpenAPIKit types, see the [full type documentation]( - [x] patch - [x] trace - [x] query +- [x] additionalOperations - [x] servers - [x] parameters - [x] specification extensions (`vendorExtensions`) @@ -221,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`) From 0550e8a7c1ffffd0fbc3caba9fcda35b623aaf20 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 24 Oct 2025 10:29:10 -0500 Subject: [PATCH 15/30] update README and begin writing migration guide --- README.md | 81 ++++++++----------- .../v2_migration_guide.md | 0 .../v3_migration_guide.md | 0 .../v4_migration_guide.md | 0 .../migration_guides/v5_migration_guide.md | 72 +++++++++++++++++ 5 files changed, 105 insertions(+), 48 deletions(-) rename documentation/{ => migration_guides}/v2_migration_guide.md (100%) rename documentation/{ => migration_guides}/v3_migration_guide.md (100%) rename documentation/{ => migration_guides}/v4_migration_guide.md (100%) create mode 100644 documentation/migration_guides/v5_migration_guide.md diff --git a/README.md b/README.md index 5c9591a79..b1d83ca0a 100644 --- a/README.md +++ b/README.md @@ -4,21 +4,21 @@ # 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/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. From 495a63d12c7fedb7efbd01da4248a5e440895d94 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Fri, 24 Oct 2025 10:35:18 -0500 Subject: [PATCH 16/30] add a few more tidbits to the docs for the HttpMethod type --- Sources/OpenAPIKitCore/Shared/HttpMethod.swift | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift index b6b3579c7..f6f0f0d7a 100644 --- a/Sources/OpenAPIKitCore/Shared/HttpMethod.swift +++ b/Sources/OpenAPIKitCore/Shared/HttpMethod.swift @@ -9,8 +9,8 @@ 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 BuiltinHttpMethod: String, CaseIterable, Sendable { case get = "GET" @@ -24,6 +24,17 @@ extension Shared { 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) From 38b3deb1270902c9568ae7abf64810dafedcac25 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 26 Oct 2025 19:57:45 -0500 Subject: [PATCH 17/30] support oas 3.2.0 $self property of the Document object --- Sources/OpenAPIKit/Document/Document.swift | 67 ++++++++++++++- .../Document/DocumentTests.swift | 85 +++++++++++++++++-- 2 files changed, 146 insertions(+), 6 deletions(-) diff --git a/Sources/OpenAPIKit/Document/Document.swift b/Sources/OpenAPIKit/Document/Document.swift index 93119bf8a..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 @@ -602,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) @@ -661,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) ?? [] @@ -681,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) @@ -697,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 @@ -714,6 +774,7 @@ extension OpenAPI.Document { static var allBuiltinKeys: [CodingKeys] { return [ .openAPIVersion, + .selfURI, .info, .jsonSchemaDialect, .servers, @@ -734,6 +795,8 @@ extension OpenAPI.Document { switch stringValue { case "openapi": self = .openAPIVersion + case "$self": + self = .selfURI case "info": self = .info case "jsonSchemaDialect": @@ -761,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/Tests/OpenAPIKitTests/Document/DocumentTests.swift b/Tests/OpenAPIKitTests/Document/DocumentTests.swift index 166e12879..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")!) @@ -135,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 ) @@ -150,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 ) @@ -165,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( @@ -180,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 ) @@ -690,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"), From 71912da60436567a034165fbdbdd6e48ad72eceb Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 27 Oct 2025 08:45:43 -0500 Subject: [PATCH 18/30] Add new querystring parameter location --- Sources/OpenAPIKit/Parameter/Parameter.swift | 13 ++++++++++++ .../Parameter/ParameterContext.swift | 16 ++++++++++++++- .../Parameter/ParameterContextLocation.swift | 20 +++++++++++++++++++ .../Parameter/ParameterSchemaContext.swift | 2 ++ Sources/OpenAPIKit/_CoreReExport.swift | 4 ---- .../Parameter/ParameterContextLocation.swift | 19 ++++++++++++++++++ Sources/OpenAPIKit30/_CoreReExport.swift | 4 ---- .../Shared/ParameterContextLocation.swift | 17 ---------------- 8 files changed, 69 insertions(+), 26 deletions(-) create mode 100644 Sources/OpenAPIKit/Parameter/ParameterContextLocation.swift create mode 100644 Sources/OpenAPIKit30/Parameter/ParameterContextLocation.swift delete mode 100644 Sources/OpenAPIKitCore/Shared/ParameterContextLocation.swift diff --git a/Sources/OpenAPIKit/Parameter/Parameter.swift b/Sources/OpenAPIKit/Parameter/Parameter.swift index 20b3843ad..754a32ad3 100644 --- a/Sources/OpenAPIKit/Parameter/Parameter.swift +++ b/Sources/OpenAPIKit/Parameter/Parameter.swift @@ -254,6 +254,9 @@ extension OpenAPI.Parameter: Encodable { case .cookie(required: let req): required = req location = .cookie + case .querystring(required: let req): + required = req + location = .querystring } try container.encode(location, forKey: .parameterLocation) @@ -307,6 +310,8 @@ extension OpenAPI.Parameter: Decodable { context = .path case .cookie: context = .cookie(required: required) + case .querystring: + context = .querystring(required: required) } let maybeContent = try container.decodeIfPresent(OpenAPI.Content.Map.self, forKey: .content) @@ -318,6 +323,14 @@ extension OpenAPI.Parameter: Decodable { maybeSchema = nil } + if location == .querystring && maybeSchema != nil { + throw GenericError( + subjectName: name, + details: "`schema` and `style` are disallowed for `querystring` parameters", + codingPath: decoder.codingPath + ) + } + switch (maybeContent, maybeSchema) { case (let content?, nil): schemaOrContent = .init(content) diff --git a/Sources/OpenAPIKit/Parameter/ParameterContext.swift b/Sources/OpenAPIKit/Parameter/ParameterContext.swift index d017b7c67..e4530d238 100644 --- a/Sources/OpenAPIKit/Parameter/ParameterContext.swift +++ b/Sources/OpenAPIKit/Parameter/ParameterContext.swift @@ -21,6 +21,7 @@ extension OpenAPI.Parameter { case header(required: Bool) case path case cookie(required: Bool) + case querystring(required: Bool) public static func query(required: Bool) -> Context { return .query(required: required, allowEmptyValue: false) } @@ -36,6 +37,9 @@ extension OpenAPI.Parameter { /// An optional cookie parameter. public static var cookie: Context { return .cookie(required: false) } + /// An optional querystring parameter. + public static var querystring: Context { return .querystring(required: false) } + public var inQuery: Bool { guard case .query = self else { return false @@ -59,11 +63,19 @@ extension OpenAPI.Parameter { return true } + public var inQuerystring: Bool { + guard case .querystring = self else { + return false + } + return true + } + public var required: Bool { switch self { case .query(required: let required, allowEmptyValue: _), .header(required: let required), - .cookie(required: let required): + .cookie(required: let required), + .querystring(required: let required): return required case .path: return true @@ -83,6 +95,8 @@ extension OpenAPI.Parameter.Context { return .path case .cookie: return .cookie + case .querystring: + return .querystring } } } diff --git a/Sources/OpenAPIKit/Parameter/ParameterContextLocation.swift b/Sources/OpenAPIKit/Parameter/ParameterContextLocation.swift new file mode 100644 index 000000000..7c5099b4d --- /dev/null +++ b/Sources/OpenAPIKit/Parameter/ParameterContextLocation.swift @@ -0,0 +1,20 @@ +// +// ParameterContextLocation.swift +// +// +// Created by Mathew Polzin on 12/24/22. +// + +import OpenAPIKitCore + +extension OpenAPI.Parameter.Context { + public enum Location: String, CaseIterable, Codable { + case query + case header + case path + case cookie + case querystring + } +} + +extension OpenAPI.Parameter.Context.Location: Validatable {} diff --git a/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift b/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift index f8828da2e..2928db7d2 100644 --- a/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift +++ b/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift @@ -143,6 +143,8 @@ extension OpenAPI.Parameter.SchemaContext.Style { return .simple case .header: return .simple + case .querystring: + return .simple } } diff --git a/Sources/OpenAPIKit/_CoreReExport.swift b/Sources/OpenAPIKit/_CoreReExport.swift index a249fbc95..997063193 100644 --- a/Sources/OpenAPIKit/_CoreReExport.swift +++ b/Sources/OpenAPIKit/_CoreReExport.swift @@ -31,10 +31,6 @@ public extension OpenAPI.SecurityScheme { typealias Location = OpenAPIKitCore.Shared.SecuritySchemeLocation } -public extension OpenAPI.Parameter.Context { - typealias Location = OpenAPIKitCore.Shared.ParameterContextLocation -} - public extension OpenAPI.Parameter.SchemaContext { typealias Style = OpenAPIKitCore.Shared.ParameterSchemaContextStyle } diff --git a/Sources/OpenAPIKit30/Parameter/ParameterContextLocation.swift b/Sources/OpenAPIKit30/Parameter/ParameterContextLocation.swift new file mode 100644 index 000000000..89d323021 --- /dev/null +++ b/Sources/OpenAPIKit30/Parameter/ParameterContextLocation.swift @@ -0,0 +1,19 @@ +// +// ParameterContextLocation.swift +// +// +// Created by Mathew Polzin on 12/24/22. +// + +import OpenAPIKitCore + +extension OpenAPI.Parameter.Context { + public enum Location: String, CaseIterable, Codable { + case query + case header + case path + case cookie + } +} + +extension OpenAPI.Parameter.Context.Location: Validatable {} diff --git a/Sources/OpenAPIKit30/_CoreReExport.swift b/Sources/OpenAPIKit30/_CoreReExport.swift index a249fbc95..997063193 100644 --- a/Sources/OpenAPIKit30/_CoreReExport.swift +++ b/Sources/OpenAPIKit30/_CoreReExport.swift @@ -31,10 +31,6 @@ public extension OpenAPI.SecurityScheme { typealias Location = OpenAPIKitCore.Shared.SecuritySchemeLocation } -public extension OpenAPI.Parameter.Context { - typealias Location = OpenAPIKitCore.Shared.ParameterContextLocation -} - public extension OpenAPI.Parameter.SchemaContext { typealias Style = OpenAPIKitCore.Shared.ParameterSchemaContextStyle } diff --git a/Sources/OpenAPIKitCore/Shared/ParameterContextLocation.swift b/Sources/OpenAPIKitCore/Shared/ParameterContextLocation.swift deleted file mode 100644 index 1a36cc8e0..000000000 --- a/Sources/OpenAPIKitCore/Shared/ParameterContextLocation.swift +++ /dev/null @@ -1,17 +0,0 @@ -// -// ParameterContextLocation.swift -// -// -// Created by Mathew Polzin on 12/24/22. -// - -extension Shared { - public enum ParameterContextLocation: String, CaseIterable, Codable { - case query - case header - case path - case cookie - } -} - -extension Shared.ParameterContextLocation: Validatable {} From 79ab6d845e0c60e84034328abb5f903f58e3ddab Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 27 Oct 2025 09:41:51 -0500 Subject: [PATCH 19/30] move parameter schema or content into parameter context --- .../Parameter/DereferencedParameter.swift | 59 +- Sources/OpenAPIKit/Parameter/Parameter.swift | 534 +++++++++++++----- .../Parameter/ParameterContext.swift | 93 ++- .../Parameter/ParameterSchemaContext.swift | 65 ++- Sources/OpenAPIKitCompat/Compat30To31.swift | 46 +- .../DocumentConversionTests.swift | 7 +- Tests/OpenAPIKitTests/ComponentsTests.swift | 8 +- Tests/OpenAPIKitTests/EaseOfUseTests.swift | 66 +-- .../OpenAPIReferenceTests.swift | 2 +- .../DereferencedOperationTests.swift | 9 +- .../Operation/OperationTests.swift | 2 +- .../Operation/ResolvedEndpointTests.swift | 12 +- .../DereferencedParameterTests.swift | 21 +- .../Parameter/ParameterContextTests.swift | 34 +- .../Parameter/ParameterSchemaTests.swift | 17 +- .../Parameter/ParameterTests.swift | 205 +++---- .../Path Item/DereferencedPathItemTests.swift | 4 +- .../Path Item/PathItemTests.swift | 8 +- .../Path Item/ResolvedRouteTests.swift | 2 +- .../Validator/BuiltinValidationTests.swift | 26 +- .../Validation+ConvenienceTests.swift | 8 +- 21 files changed, 787 insertions(+), 441 deletions(-) diff --git a/Sources/OpenAPIKit/Parameter/DereferencedParameter.swift b/Sources/OpenAPIKit/Parameter/DereferencedParameter.swift index 4b5002ca3..23c079e82 100644 --- a/Sources/OpenAPIKit/Parameter/DereferencedParameter.swift +++ b/Sources/OpenAPIKit/Parameter/DereferencedParameter.swift @@ -90,26 +90,59 @@ extension OpenAPI.Parameter: ExternallyDereferenceable { // next line: // let (newSchemaOrContent, components) = try await schemaOrContent.externallyDereferenced(with: loader) - let newSchemaOrContent: Either + let newContext: OpenAPI.Parameter.Context let newComponents: OpenAPI.Components let newMessages: [Loader.Message] - switch schemaOrContent { - case .a(let schemaContext): - let (context, components, messages) = try await schemaContext.externallyDereferenced(with: loader) - newSchemaOrContent = .a(context) - newComponents = components - newMessages = messages - case .b(let contentMap): - let (map, components, messages) = try await contentMap.externallyDereferenced(with: loader) - newSchemaOrContent = .b(map) - newComponents = components - newMessages = messages + switch context { + case .query(required: let required, allowEmptyValue: let allowEmptyValue, schemaOrContent: let schemaOrContent): + let newSchemaOrContent: Either + (newSchemaOrContent, newComponents, newMessages) = try await externallyDereference(schemaOrContent: schemaOrContent, with: Loader.self) + + newContext = .query(required: required, allowEmptyValue: allowEmptyValue, schemaOrContent: newSchemaOrContent) + + case .header(required: let required, schemaOrContent: let schemaOrContent): + let newSchemaOrContent: Either + (newSchemaOrContent, newComponents, newMessages) = try await externallyDereference(schemaOrContent: schemaOrContent, with: Loader.self) + + newContext = .header(required: required, schemaOrContent: newSchemaOrContent) + + case .path(schemaOrContent: let schemaOrContent): + let newSchemaOrContent: Either + (newSchemaOrContent, newComponents, newMessages) = try await externallyDereference(schemaOrContent: schemaOrContent, with: Loader.self) + + newContext = .path(schemaOrContent: newSchemaOrContent) + + case .cookie(required: let required, schemaOrContent: let schemaOrContent): + let newSchemaOrContent: Either + (newSchemaOrContent, newComponents, newMessages) = try await externallyDereference(schemaOrContent: schemaOrContent, with: Loader.self) + + newContext = .cookie(required: required, schemaOrContent: newSchemaOrContent) + + case .querystring(required: let required, content: let content): + let newContent: OpenAPI.Content.Map + (newContent, newComponents, newMessages) = try await content.externallyDereferenced(with: Loader.self) + + newContext = .querystring(required: required, content: newContent) } var newParameter = self - newParameter.schemaOrContent = newSchemaOrContent + newParameter.context = newContext return (newParameter, newComponents, newMessages) } } + +fileprivate func externallyDereference( + schemaOrContent: Either, + with loader: Loader.Type +) async throws -> (Either, OpenAPI.Components, [Loader.Message]) { + switch schemaOrContent { + case .a(let schemaContext): + let (context, components, messages) = try await schemaContext.externallyDereferenced(with: loader) + return (.a(context), components, messages) + case .b(let contentMap): + let (map, components, messages) = try await contentMap.externallyDereferenced(with: loader) + return (.b(map), components, messages) + } +} diff --git a/Sources/OpenAPIKit/Parameter/Parameter.swift b/Sources/OpenAPIKit/Parameter/Parameter.swift index 754a32ad3..1d0332a85 100644 --- a/Sources/OpenAPIKit/Parameter/Parameter.swift +++ b/Sources/OpenAPIKit/Parameter/Parameter.swift @@ -25,22 +25,6 @@ extension OpenAPI { /// if unspecified and only gets encoded if true. public var deprecated: Bool // default is false - /// OpenAPI Spec "content" or "schema" properties. - /// - /// You can access the schema context (if it is in use for - /// this parameter) with `schemaOrContent.schemaContextValue`. - /// The schema context contains lots of information detailed in the - /// OpenAPI specification under the **Parameter Object** section. - /// - /// You can directly access the underlying `JSONSchema` with - /// `schemaOrContent.schemaValue`. If the schema is a reference - /// instead of an inline value, `schemaOrContent.schemaReference` - /// will get you the reference. - /// - /// You can access the content map (if it is in use for - /// this parameter) with `schemaOrContent.contentValue`. - public var schemaOrContent: Either - /// Dictionary of vendor extensions. /// /// These should be of the form: @@ -58,88 +42,45 @@ extension OpenAPI { /// parameter. public var location: Context.Location { return context.location } - /// Create a parameter with an `Either`. - public init( - name: String, - context: Context, - schemaOrContent: Either, - description: String? = nil, - deprecated: Bool = false, - vendorExtensions: [String: AnyCodable] = [:] - ) { - self.name = name - self.context = context - self.schemaOrContent = schemaOrContent - self.description = description - self.deprecated = deprecated - self.vendorExtensions = vendorExtensions - } - - /// Create a parameter with a `SchemaContext`. - public init( - name: String, - context: Context, - schema: SchemaContext, - description: String? = nil, - deprecated: Bool = false, - vendorExtensions: [String: AnyCodable] = [:] - ) { - self.name = name - self.context = context - self.schemaOrContent = .init(schema) - self.description = description - self.deprecated = deprecated - self.vendorExtensions = vendorExtensions - } - - /// Create a parameter with a `JSONSchema` and the default - /// `style` for the given `Context`. - public init( - name: String, - context: Context, - schema: JSONSchema, - description: String? = nil, - deprecated: Bool = false, - vendorExtensions: [String: AnyCodable] = [:] - ) { - self.name = name - self.context = context - self.schemaOrContent = .init(SchemaContext(schema, style: .default(for: context))) - self.description = description - self.deprecated = deprecated - self.vendorExtensions = vendorExtensions - } - - /// Create a parameter with a reference to a `JSONSchema` - /// and the default `style` for the given `Context`. - public init( - name: String, - context: Context, - schemaReference: OpenAPI.Reference, - description: String? = nil, - deprecated: Bool = false, - vendorExtensions: [String: AnyCodable] = [:] - ) { - self.name = name - self.context = context - self.schemaOrContent = .init(SchemaContext(schemaReference: schemaReference, style: .default(for: context))) - self.description = description - self.deprecated = deprecated - self.vendorExtensions = vendorExtensions + /// OpenAPI Spec "content" or "schema" properties. + /// + /// You can access the schema context (if it is in use for + /// this parameter) with `schemaOrContent.schemaContextValue`. + /// The schema context contains lots of information detailed in the + /// OpenAPI specification under the **Parameter Object** section. + /// + /// You can directly access the underlying `JSONSchema` with + /// `schemaOrContent.schemaValue`. If the schema is a reference + /// instead of an inline value, `schemaOrContent.schemaReference` + /// will get you the reference. + /// + /// You can access the content map (if it is in use for + /// this parameter) with `schemaOrContent.contentValue`. + public var schemaOrContent: Either { + switch context { + case .query(required: _, allowEmptyValue: _, schemaOrContent: let schemaOrContent): + return schemaOrContent + case .header(required: _, schemaOrContent: let schemaOrContent): + return schemaOrContent + case .path(schemaOrContent: let schemaOrContent): + return schemaOrContent + case .cookie(required: _, schemaOrContent: let schemaOrContent): + return schemaOrContent + case .querystring(required: _, content: let content): + return .content(content) + } } - /// Create a parameter with a `Content.Map`. + /// Create a parameter. public init( name: String, context: Context, - content: OpenAPI.Content.Map, description: String? = nil, deprecated: Bool = false, vendorExtensions: [String: AnyCodable] = [:] ) { self.name = name self.context = context - self.schemaOrContent = .init(content) self.description = description self.deprecated = deprecated self.vendorExtensions = vendorExtensions @@ -157,6 +98,328 @@ extension OpenAPI.Parameter { public typealias Array = [Either, OpenAPI.Parameter>] } +// MARK: Convenience constructors +extension OpenAPI.Parameter { + public static func cookie( + name: String, + required: Bool = false, + schemaOrContent: Either, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .cookie(required: required, schemaOrContent: schemaOrContent), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func cookie( + name: String, + required: Bool = false, + content: OpenAPI.Content.Map, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .cookie( + required: required, + content: content + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func cookie( + name: String, + required: Bool = false, + schema: JSONSchema, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .cookie( + required: required, + schema: schema + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func cookie( + name: String, + required: Bool = false, + schemaReference: OpenAPI.Reference, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .cookie( + required: required, + schemaOrContent: .schema(.init(schemaReference: schemaReference, style: .default(for: .cookie))) + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func header( + name: String, + required: Bool = false, + schemaOrContent: Either, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .header(required: required, schemaOrContent: schemaOrContent), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func header( + name: String, + required: Bool = false, + content: OpenAPI.Content.Map, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .header( + required: required, + content: content + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func header( + name: String, + required: Bool = false, + schema: JSONSchema, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .header( + required: required, + schema: schema + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func header( + name: String, + required: Bool = false, + schemaReference: OpenAPI.Reference, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .header( + required: required, + schemaOrContent: .schema(.init(schemaReference: schemaReference, style: .default(for: .header))) + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func path( + name: String, + schemaOrContent: Either, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .path(schemaOrContent: schemaOrContent), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func path( + name: String, + content: OpenAPI.Content.Map, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .path(content: content), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func path( + name: String, + schema: JSONSchema, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .path(schema: schema), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func path( + name: String, + schemaReference: OpenAPI.Reference, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .path(schemaOrContent: .schema(.init(schemaReference: schemaReference, style: .default(for: .path)))), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func query( + name: String, + required: Bool = false, + allowEmptyValue: Bool = false, + schemaOrContent: Either, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .query(required: required, allowEmptyValue: allowEmptyValue, schemaOrContent: schemaOrContent), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func query( + name: String, + required: Bool = false, + allowEmptyValue: Bool = false, + content: OpenAPI.Content.Map, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .query( + required: required, + allowEmptyValue: allowEmptyValue, + content: content + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func query( + name: String, + required: Bool = false, + allowEmptyValue: Bool = false, + schema: JSONSchema, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .query( + required: required, + allowEmptyValue: allowEmptyValue, + schema: schema + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func query( + name: String, + required: Bool = false, + allowEmptyValue: Bool = false, + schemaReference: OpenAPI.Reference, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .query( + required: required, + allowEmptyValue: allowEmptyValue, + schemaOrContent: .schema(.init(schemaReference: schemaReference, style: .default(for: .query))) + ), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } + + public static func querystring( + name: String, + required: Bool = false, + content: OpenAPI.Content.Map, + description: String? = nil, + deprecated: Bool = false, + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + name: name, + context: .querystring(content: content), + description: description, + deprecated: deprecated, + vendorExtensions: vendorExtensions + ) + } +} + extension OpenAPI.Parameter { /// A parameter identity is just a hashable struct /// containing exactly the things that differentiate @@ -173,11 +436,10 @@ extension OpenAPI.Parameter { // OpenAPI.PathItem.Array.Element => extension Either where A == OpenAPI.Reference, B == OpenAPI.Parameter { - /// Construct a parameter using a `JSONSchema`. + /// Construct a parameter. public static func parameter( name: String, context: OpenAPI.Parameter.Context, - schema: JSONSchema, description: String? = nil, deprecated: Bool = false, vendorExtensions: [String: AnyCodable] = [:] @@ -186,28 +448,6 @@ extension Either where A == OpenAPI.Reference, B == OpenAPI.P .init( name: name, context: context, - schema: schema, - description: description, - deprecated: deprecated, - vendorExtensions: vendorExtensions - ) - ) - } - - /// Construct a parameter using a `Content.Map`. - public static func parameter( - name: String, - context: OpenAPI.Parameter.Context, - content: OpenAPI.Content.Map, - description: String? = nil, - deprecated: Bool = false, - vendorExtensions: [String: AnyCodable] = [:] - ) -> Self { - return .b( - .init( - name: name, - context: context, - content: content, description: description, deprecated: deprecated, vendorExtensions: vendorExtensions @@ -238,23 +478,23 @@ extension OpenAPI.Parameter: Encodable { let required: Bool let location: Context.Location switch context { - case .query(required: let req, allowEmptyValue: let allowEmptyValue): + case .query(required: let req, allowEmptyValue: let allowEmptyValue, schemaOrContent: _): required = req location = .query if allowEmptyValue { try container.encode(allowEmptyValue, forKey: .allowEmptyValue) } - case .header(required: let req): + case .header(required: let req, schemaOrContent: _): required = req location = .header - case .path: + case .path(schemaOrContent: _): required = true location = .path - case .cookie(required: let req): + case .cookie(required: let req, schemaOrContent: _): required = req location = .cookie - case .querystring(required: let req): + case .querystring(required: let req, content: _): required = req location = .querystring } @@ -266,7 +506,7 @@ extension OpenAPI.Parameter: Encodable { switch schemaOrContent { case .a(let schema): - try schema.encode(to: encoder, for: context) + try schema.encode(to: encoder, for: location) case .b(let contentMap): try container.encode(contentMap, forKey: .content) } @@ -293,44 +533,16 @@ extension OpenAPI.Parameter: Decodable { let required = try container.decodeIfPresent(Bool.self, forKey: .required) ?? false let location = try container.decode(Context.Location.self, forKey: .parameterLocation) - switch location { - case .query: - let allowEmptyValue = try container.decodeIfPresent(Bool.self, forKey: .allowEmptyValue) ?? false - context = .query(required: required, allowEmptyValue: allowEmptyValue) - case .header: - context = .header(required: required) - case .path: - if !required { - throw GenericError( - subjectName: name, - details: "positional path parameters must be explicitly set to required", - codingPath: decoder.codingPath - ) - } - context = .path - case .cookie: - context = .cookie(required: required) - case .querystring: - context = .querystring(required: required) - } - let maybeContent = try container.decodeIfPresent(OpenAPI.Content.Map.self, forKey: .content) let maybeSchema: SchemaContext? if container.contains(.schema) { - maybeSchema = try SchemaContext(from: decoder, for: context) + maybeSchema = try SchemaContext(from: decoder, for: location) } else { maybeSchema = nil } - if location == .querystring && maybeSchema != nil { - throw GenericError( - subjectName: name, - details: "`schema` and `style` are disallowed for `querystring` parameters", - codingPath: decoder.codingPath - ) - } - + let schemaOrContent: Either switch (maybeContent, maybeSchema) { case (let content?, nil): schemaOrContent = .init(content) @@ -350,6 +562,34 @@ extension OpenAPI.Parameter: Decodable { ) } + switch location { + case .query: + let allowEmptyValue = try container.decodeIfPresent(Bool.self, forKey: .allowEmptyValue) ?? false + context = .query(required: required, allowEmptyValue: allowEmptyValue, schemaOrContent: schemaOrContent) + case .header: + context = .header(required: required, schemaOrContent: schemaOrContent) + case .path: + if !required { + throw GenericError( + subjectName: name, + details: "positional path parameters must be explicitly set to required", + codingPath: decoder.codingPath + ) + } + context = .path(schemaOrContent: schemaOrContent) + case .cookie: + context = .cookie(required: required, schemaOrContent: schemaOrContent) + case .querystring: + guard case .b(let content) = schemaOrContent else { + throw GenericError( + subjectName: name, + details: "`schema` and `style` are disallowed for `querystring` parameters", + codingPath: decoder.codingPath + ) + } + context = .querystring(required: required, content: content) + } + description = try container.decodeIfPresent(String.self, forKey: .description) deprecated = try container.decodeIfPresent(Bool.self, forKey: .deprecated) ?? false diff --git a/Sources/OpenAPIKit/Parameter/ParameterContext.swift b/Sources/OpenAPIKit/Parameter/ParameterContext.swift index e4530d238..5b8ab5f5e 100644 --- a/Sources/OpenAPIKit/Parameter/ParameterContext.swift +++ b/Sources/OpenAPIKit/Parameter/ParameterContext.swift @@ -17,28 +17,78 @@ extension OpenAPI.Parameter { /// `required: true` to the context construction. /// Path parameters are always required. public enum Context: Equatable, Sendable { - case query(required: Bool, allowEmptyValue: Bool) - case header(required: Bool) - case path - case cookie(required: Bool) - case querystring(required: Bool) + case query(required: Bool, allowEmptyValue: Bool, schemaOrContent: Either) + case header(required: Bool, schemaOrContent: Either) + case path(schemaOrContent: Either) + case cookie(required: Bool, schemaOrContent: Either) + case querystring(required: Bool, content: OpenAPI.Content.Map) - public static func query(required: Bool) -> Context { return .query(required: required, allowEmptyValue: false) } + /// A query parameter that does not allow empty values. + public static func query( + required: Bool = false, + schemaOrContent: Either + ) -> Context { return .query(required: required, allowEmptyValue: false, schemaOrContent: schemaOrContent) } - public static func query(allowEmptyValue: Bool) -> Context { return .query(required: false, allowEmptyValue: allowEmptyValue) } + /// A query parameter that is not required. + public static func query( + allowEmptyValue: Bool, + schemaOrContent: Either + ) -> Context { return .query(required: false, allowEmptyValue: allowEmptyValue, schemaOrContent: schemaOrContent) } - /// An optional query parameter that does not allow - /// empty values. - public static var query: Context { return .query(required: false, allowEmptyValue: false) } + public static func query( + required: Bool = false, + allowEmptyValue: Bool = false, + schema: JSONSchema + ) -> Context { return .query(required: required, allowEmptyValue: allowEmptyValue, schemaOrContent: .schema(.init(schema, style: .default(for: .query)))) } + + public static func query( + required: Bool = false, + allowEmptyValue: Bool = false, + content: OpenAPI.Content.Map + ) -> Context { return .query(required: required, allowEmptyValue: allowEmptyValue, schemaOrContent: .content(content)) } /// An optional header parameter. - public static var header: Context { return .header(required: false) } + public static func header( + schemaOrContent: Either + ) -> Context { return .header(required: false, schemaOrContent: schemaOrContent) } + + public static func header( + required: Bool = false, + schema: JSONSchema + ) -> Context { return .header(required: required, schemaOrContent: .schema(.init(schema, style: .default(for: .header)))) } + + public static func header( + required: Bool = false, + content: OpenAPI.Content.Map + ) -> Context { return .header(required: required, schemaOrContent: .content(content)) } /// An optional cookie parameter. - public static var cookie: Context { return .cookie(required: false) } + public static func cookie( + schemaOrContent: Either + ) -> Context { return .cookie(required: false, schemaOrContent: schemaOrContent) } + + public static func cookie( + required: Bool = false, + schema: JSONSchema + ) -> Context { return .cookie(required: required, schemaOrContent: .schema(.init(schema, style: .default(for: .cookie)))) } + + public static func cookie( + required: Bool = false, + content: OpenAPI.Content.Map + ) -> Context { return .cookie(required: required, schemaOrContent: .content(content)) } + + public static func path( + schema: JSONSchema + ) -> Context { return .path(schemaOrContent: .schema(.init(schema, style: .default(for: .path)))) } + + public static func path( + content: OpenAPI.Content.Map + ) -> Context { return .path(schemaOrContent: .content(content)) } /// An optional querystring parameter. - public static var querystring: Context { return .querystring(required: false) } + public static func querystring( + content: OpenAPI.Content.Map + ) -> Context { return .querystring(required: false, content: content) } public var inQuery: Bool { guard case .query = self else { @@ -54,7 +104,12 @@ extension OpenAPI.Parameter { return true } - public var inPath: Bool { return self == .path } + public var inPath: Bool { + guard case .path = self else { + return false + } + return true + } public var inCookie: Bool { guard case .cookie = self else { @@ -72,12 +127,12 @@ extension OpenAPI.Parameter { public var required: Bool { switch self { - case .query(required: let required, allowEmptyValue: _), - .header(required: let required), - .cookie(required: let required), - .querystring(required: let required): + case .query(required: let required, allowEmptyValue: _, schemaOrContent: _), + .header(required: let required, schemaOrContent: _), + .cookie(required: let required, schemaOrContent: _), + .querystring(required: let required, content: _): return required - case .path: + case .path(schemaOrContent: _): return true } } diff --git a/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift b/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift index 2928db7d2..c3ef75243 100644 --- a/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift +++ b/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift @@ -127,13 +127,52 @@ extension OpenAPI.Parameter { } } +extension OpenAPI.Parameter.SchemaContext { + public static func schema(_ schema: JSONSchema, + style: Style, + explode: Bool, + allowReserved: Bool = false, + examples: OpenAPI.Example.Map? = nil) -> Self { + .init(schema, style: style, explode: explode, allowReserved: allowReserved, examples: examples) + } + + public static func schema(_ schema: JSONSchema, + style: Style, + allowReserved: Bool = false, + examples: OpenAPI.Example.Map? = nil) -> Self { + .init(schema, style: style, allowReserved: allowReserved, examples: examples) + } + + public static func schemaReference(_ reference: OpenAPI.Reference, + style: Style, + explode: Bool, + allowReserved: Bool = false, + examples: OpenAPI.Example.Map? = nil) -> Self { + .init(schemaReference: reference, + style: style, + explode: explode, + allowReserved: allowReserved, + examples: examples) + } + + public static func schemaReference(_ reference: OpenAPI.Reference, + style: Style, + allowReserved: Bool = false, + examples: OpenAPI.Example.Map? = nil) -> Self { + .init(schemaReference: reference, + style: style, + allowReserved: allowReserved, + examples: examples) + } +} + extension OpenAPI.Parameter.SchemaContext.Style { /// Get the default `Style` for the given location /// per the OpenAPI Specification. /// /// See the `style` fixed field under /// [OpenAPI Parameter Object](https://spec.openapis.org/oas/v3.1.1.html#parameter-object). - public static func `default`(for location: OpenAPI.Parameter.Context) -> Self { + public static func `default`(for location: OpenAPI.Parameter.Context.Location) -> Self { switch location { case .query: return .form @@ -148,6 +187,26 @@ extension OpenAPI.Parameter.SchemaContext.Style { } } + /// Get the default `Style` for the given context + /// per the OpenAPI Specification. + /// + /// See the `style` fixed field under + /// [OpenAPI Parameter Object](https://spec.openapis.org/oas/v3.1.1.html#parameter-object). + public static func `default`(for context: OpenAPI.Parameter.Context) -> Self { + switch context { + case .query: + return .form + case .cookie: + return .form + case .path: + return .simple + case .header: + return .simple + case .querystring: + return .simple + } + } + internal var defaultExplode: Bool { switch self { case .form: @@ -173,7 +232,7 @@ extension OpenAPI.Parameter.SchemaContext { } extension OpenAPI.Parameter.SchemaContext { - public func encode(to encoder: Encoder, for location: OpenAPI.Parameter.Context) throws { + public func encode(to encoder: Encoder, for location: OpenAPI.Parameter.Context.Location) throws { var container = encoder.container(keyedBy: CodingKeys.self) if style != Style.default(for: location) { @@ -199,7 +258,7 @@ extension OpenAPI.Parameter.SchemaContext { } extension OpenAPI.Parameter.SchemaContext { - public init(from decoder: Decoder, for location: OpenAPI.Parameter.Context) throws { + public init(from decoder: Decoder, for location: OpenAPI.Parameter.Context.Location) throws { let container = try decoder.container(keyedBy: CodingKeys.self) schema = try container.decode(Either, JSONSchema>.self, forKey: .schema) diff --git a/Sources/OpenAPIKitCompat/Compat30To31.swift b/Sources/OpenAPIKitCompat/Compat30To31.swift index 92928524a..06b210672 100644 --- a/Sources/OpenAPIKitCompat/Compat30To31.swift +++ b/Sources/OpenAPIKitCompat/Compat30To31.swift @@ -100,16 +100,8 @@ extension OpenAPIKit30.OpenAPI.Server: To31 { extension OpenAPIKit30.OpenAPI.Header: To31 { fileprivate func to31() -> OpenAPIKit.OpenAPI.Header { - let newSchemaOrContent: Either - switch schemaOrContent { - case .a(let context): - newSchemaOrContent = .a(context.to31()) - case .b(let contentMap): - newSchemaOrContent = .b(contentMap.mapValues { $0.to31() }) - } - - return OpenAPIKit.OpenAPI.Header( - schemaOrContent: newSchemaOrContent, + OpenAPIKit.OpenAPI.Header( + schemaOrContent: schemaOrContent.to31(), description: description, required: `required`, deprecated: deprecated, @@ -118,17 +110,28 @@ extension OpenAPIKit30.OpenAPI.Header: To31 { } } -extension OpenAPIKit30.OpenAPI.Parameter.Context: To31 { - fileprivate func to31() -> OpenAPIKit.OpenAPI.Parameter.Context { +extension Either where A == OpenAPIKit30.OpenAPI.Parameter.SchemaContext, B == OpenAPIKit30.OpenAPI.Content.Map { + fileprivate func to31() -> Either { + switch self { + case .a(let context): + .a(context.to31()) + case .b(let contentMap): + .b(contentMap.mapValues { $0.to31() }) + } + } +} + +extension OpenAPIKit30.OpenAPI.Parameter.Context { + fileprivate func to31(with schemaOrContent: Either) -> OpenAPIKit.OpenAPI.Parameter.Context { switch self { case .query(required: let required, allowEmptyValue: let allowEmptyValue): - return .query(required: required, allowEmptyValue: allowEmptyValue) + return .query(required: required, allowEmptyValue: allowEmptyValue, schemaOrContent: schemaOrContent.to31()) case .header(required: let required): - return .header(required: required) + return .header(required: required, schemaOrContent: schemaOrContent.to31()) case .path: - return .path + return .path(schemaOrContent: schemaOrContent.to31()) case .cookie(required: let required): - return .cookie(required: required) + return .cookie(required: required, schemaOrContent: schemaOrContent.to31()) } } } @@ -242,18 +245,9 @@ extension OpenAPIKit30.OpenAPI.Content: To31 { extension OpenAPIKit30.OpenAPI.Parameter: To31 { fileprivate func to31() -> OpenAPIKit.OpenAPI.Parameter { - let newSchemaOrContent: Either - switch schemaOrContent { - case .a(let context): - newSchemaOrContent = .a(context.to31()) - case .b(let contentMap): - newSchemaOrContent = .b(contentMap.mapValues { $0.to31() }) - } - return OpenAPIKit.OpenAPI.Parameter( name: name, - context: context.to31(), - schemaOrContent: newSchemaOrContent, + context: context.to31(with: schemaOrContent), description: description, deprecated: deprecated, vendorExtensions: vendorExtensions diff --git a/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift b/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift index 100430d22..4f73d05d2 100644 --- a/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift +++ b/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift @@ -996,14 +996,14 @@ fileprivate func assertEqualNewToOld(_ newParam: OpenAPIKit.OpenAPI.Parameter, _ fileprivate func assertEqualNewToOld(_ newParamContext: OpenAPIKit.OpenAPI.Parameter.Context, _ oldParamContext: OpenAPIKit30.OpenAPI.Parameter.Context) { switch (newParamContext, oldParamContext) { - case (.query(required: let req, allowEmptyValue: let empty), .query(required: let req2, allowEmptyValue: let empty2)): + case (.query(required: let req, allowEmptyValue: let empty, schemaOrContent: _), .query(required: let req2, allowEmptyValue: let empty2)): XCTAssertEqual(req, req2) XCTAssertEqual(empty, empty2) - case (.header(required: let req), .header(required: let req2)): + case (.header(required: let req, schemaOrContent: _), .header(required: let req2)): XCTAssertEqual(req, req2) case (.path, .path): break - case (.cookie(required: let req), .cookie(required: let req2)): + case (.cookie(required: let req, schemaOrContent: _), .cookie(required: let req2)): XCTAssertEqual(req, req2) default: XCTFail("Parameter contexts are not equal. \(newParamContext) / \(oldParamContext)") @@ -1137,6 +1137,7 @@ fileprivate func assertEqualNewToOld(_ newSchema: OpenAPIKit.JSONSchema, _ oldSc case .number(let coreContext, let numericContext): let newNumericContext = try XCTUnwrap(newSchema.numberContext) // TODO: compare number contexts + // try assertEqualNewToOld(newNumericContext, numericContext) try assertEqualNewToOld(newCoreContext, coreContext) case .integer(let coreContext, let integerContext): diff --git a/Tests/OpenAPIKitTests/ComponentsTests.swift b/Tests/OpenAPIKitTests/ComponentsTests.swift index 0cbf875b7..8f603962b 100644 --- a/Tests/OpenAPIKitTests/ComponentsTests.swift +++ b/Tests/OpenAPIKitTests/ComponentsTests.swift @@ -99,7 +99,7 @@ final class ComponentsTests: XCTestCase { "two": .init(description: "hello", content: [:]) ], parameters: [ - "three": .init(name: "hello", context: .query, schema: .string) + "three": .init(name: "hello", context: .query(schema: .string)) ], examples: [ "four": .init(value: .init(URL(string: "hello.com/hello")!)) @@ -139,7 +139,7 @@ final class ComponentsTests: XCTestCase { XCTAssertEqual(components[ref1], .string) XCTAssertEqual(components[ref2], .init(description: "hello", content: [:])) - XCTAssertEqual(components[ref3], .init(name: "hello", context: .query, schema: .string)) + XCTAssertEqual(components[ref3], .init(name: "hello", context: .query(schema: .string))) XCTAssertEqual(components[ref4], .init(value: .init(URL(string: "hello.com/hello")!))) XCTAssertEqual(components[ref5], .init(content: [:])) XCTAssertEqual(components[ref6], .init(schema: .string)) @@ -284,7 +284,7 @@ extension ComponentsTests { "two": .init(description: "hello", content: [:]) ], parameters: [ - "three": .init(name: "hi", context: .query, content: [:]) + "three": .init(name: "hi", context: .query(content: [:])) ], examples: [ "four": .init(value: .init(URL(string: "http://address.com")!)) @@ -506,7 +506,7 @@ extension ComponentsTests { "two": .init(description: "hello", content: [:]) ], parameters: [ - "three": .init(name: "hi", context: .query, content: [:]) + "three": .init(name: "hi", context: .query(content: [:])) ], examples: [ "four": .init(value: .init(URL(string: "http://address.com")!)) diff --git a/Tests/OpenAPIKitTests/EaseOfUseTests.swift b/Tests/OpenAPIKitTests/EaseOfUseTests.swift index 45854c598..d8ecabe81 100644 --- a/Tests/OpenAPIKitTests/EaseOfUseTests.swift +++ b/Tests/OpenAPIKitTests/EaseOfUseTests.swift @@ -39,8 +39,7 @@ final class DeclarativeEaseOfUseTests: XCTestCase { parameters: [ .parameter( name: "param", - context: .path, - schema: .string + context: .path(schema: .string) ) ], get: .init( @@ -51,12 +50,14 @@ final class DeclarativeEaseOfUseTests: XCTestCase { .reference(.component( named: "filter")), .parameter( name: "Content-Type", - context: .header(required: false), - schema: .string( - allowedValues: [ - .init(OpenAPI.ContentType.json.rawValue), - .init(OpenAPI.ContentType.txt.rawValue) - ] + context: .header( + required: false, + schema: .string( + allowedValues: [ + .init(OpenAPI.ContentType.json.rawValue), + .init(OpenAPI.ContentType.txt.rawValue) + ] + ) ) ) ], @@ -116,16 +117,18 @@ final class DeclarativeEaseOfUseTests: XCTestCase { parameters: [ "filter": .init( name: "filter", - context: .query(required: false), - schema: .init( - .object( - properties: [ - "size": .integer, - "shape": .string(allowedValues: [ "round", "square" ]) - ] - ), - style: .deepObject, - explode: true + context: .query( + required: false, + schemaOrContent: .schema(.init( + .object( + properties: [ + "size": .integer, + "shape": .string(allowedValues: [ "round", "square" ]) + ] + ), + style: .deepObject, + explode: true + )) ) ) ] @@ -168,12 +171,13 @@ final class DeclarativeEaseOfUseTests: XCTestCase { .reference(.component( named: "filter")), .parameter( name: "Content-Type", - context: .header(required: false), - schema: .string( - allowedValues: [ - .init(OpenAPI.ContentType.json.rawValue), - .init(OpenAPI.ContentType.txt.rawValue) - ] + context: .header(required: false, + schema: .string( + allowedValues: [ + .init(OpenAPI.ContentType.json.rawValue), + .init(OpenAPI.ContentType.txt.rawValue) + ] + ) ) ) ], @@ -232,8 +236,7 @@ final class DeclarativeEaseOfUseTests: XCTestCase { parameters: [ .parameter( name: "param", - context: .path, - schema: .string + context: .path(schema: .string) ) ], get: testSHOW_endpoint, @@ -245,10 +248,10 @@ final class DeclarativeEaseOfUseTests: XCTestCase { "string_schema": .string ], parameters: [ - "filter": .init( + "filter": .query( name: "filter", - context: .query(required: false), - schema: .init( + required: false, + schemaOrContent: .schema(.init( .object( properties: [ "size": .integer, @@ -258,7 +261,7 @@ final class DeclarativeEaseOfUseTests: XCTestCase { style: .deepObject, explode: true ) - ) + )) ] ) @@ -517,8 +520,7 @@ fileprivate let testDocument = OpenAPI.Document( parameters: [ .parameter( name: "id", - context: .path, - schema: .string + context: .path(schema: .string) ) ], get: OpenAPI.Operation( diff --git a/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift b/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift index 925885bcc..b192b1bbe 100644 --- a/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift +++ b/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift @@ -84,7 +84,7 @@ final class OpenAPIReferenceTests: XCTestCase { "hello": .init(description: "description") ], parameters: [ - "hello": .init(name: "name", context: .path, content: [:], description: "description") + "hello": .path(name: "name", content: [:], description: "description") ], examples: [ "hello": .init(summary: "summary", description: "description", value: .b("")) diff --git a/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift b/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift index 611528269..1409cfa74 100644 --- a/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift +++ b/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift @@ -25,8 +25,7 @@ final class DereferencedOperationTests: XCTestCase { parameters: [ .parameter( name: "test", - context: .header, - schema: .string + context: .header(schema: .string) ) ], requestBody: OpenAPI.Request(content: [.json: .init(schema: .string)]), @@ -44,9 +43,8 @@ final class DereferencedOperationTests: XCTestCase { func test_parameterReference() throws { let components = OpenAPI.Components( parameters: [ - "test": .init( + "test": .header( name: "test", - context: .header, schema: .string ) ] @@ -59,9 +57,8 @@ final class DereferencedOperationTests: XCTestCase { ).dereferenced(in: components) XCTAssertEqual( t1.parameters.first?.underlyingParameter, - .init( + .header( name: "test", - context: .header, schema: .string, vendorExtensions: ["x-component-name": "test"] ) diff --git a/Tests/OpenAPIKitTests/Operation/OperationTests.swift b/Tests/OpenAPIKitTests/Operation/OperationTests.swift index a5bea626f..6cd175652 100644 --- a/Tests/OpenAPIKitTests/Operation/OperationTests.swift +++ b/Tests/OpenAPIKitTests/Operation/OperationTests.swift @@ -23,7 +23,7 @@ final class OperationTests: XCTestCase { description: "description", externalDocs: .init(url: URL(string: "https://google.com")!), operationId: "123", - parameters: [.parameter(name: "hi", context: .query, schema: .string)], + parameters: [.parameter(name: "hi", context: .query(schema: .string))], requestBody: .init(content: [:]), responses: [:], callbacks: [:], diff --git a/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift b/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift index 6cd40b9ef..dcac3c9bd 100644 --- a/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift +++ b/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift @@ -205,14 +205,14 @@ final class ResolvedEndpointTests: XCTestCase { "/hello/world": .init( summary: "routeSummary", description: "routeDescription", - parameters: [.parameter(name: "one", context: .header, schema: .string)], + parameters: [.parameter(name: "one", context: .header(schema: .string))], get: .init( tags: "a", "b", summary: "endpointSummary", description: "endpointDescription", externalDocs: .init(url: URL(string: "http://website.com")!), operationId: "hi there", - parameters: [.parameter(name: "two", context: .query, schema: .string)], + parameters: [.parameter(name: "two", context: .query(schema: .string))], requestBody: .init(description: "requestBody", content: [:]), responses: [200: .response(description: "hello world")], deprecated: true, @@ -243,14 +243,14 @@ final class ResolvedEndpointTests: XCTestCase { "/hello/world": .init( summary: "routeSummary", description: "routeDescription", - parameters: [.parameter(name: "one", context: .header, schema: .string)], + parameters: [.parameter(name: "one", context: .header(schema: .string))], get: .init( tags: "a", "b", summary: "endpointSummary", description: "endpointDescription", externalDocs: .init(url: URL(string: "http://website.com")!), operationId: "hi there", - parameters: [.parameter(name: "one", context: .header, schema: .integer)], + parameters: [.parameter(name: "one", context: .header(schema: .integer))], requestBody: .init(description: "requestBody", content: [:]), responses: [200: .response(description: "hello world")], deprecated: true, @@ -445,14 +445,14 @@ final class ResolvedEndpointTests: XCTestCase { "/hello/world": .init( summary: "routeSummary", description: "routeDescription", - parameters: [.parameter(name: "one", context: .header(required: true), schema: .string)], + parameters: [.parameter(name: "one", context: .header(required: true, schema: .string))], get: .init( tags: "a", "b", summary: "endpointSummary", description: "endpointDescription", externalDocs: .init(url: URL(string: "http://website.com")!), operationId: "hi there", - parameters: [.parameter(name: "two", context: .query, schema: .string)], + parameters: [.parameter(name: "two", context: .query(schema: .string))], requestBody: .init(description: "requestBody", content: [:]), responses: [200: .response(description: "hello world")], deprecated: true, diff --git a/Tests/OpenAPIKitTests/Parameter/DereferencedParameterTests.swift b/Tests/OpenAPIKitTests/Parameter/DereferencedParameterTests.swift index 126d3acc0..559491a89 100644 --- a/Tests/OpenAPIKitTests/Parameter/DereferencedParameterTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/DereferencedParameterTests.swift @@ -10,14 +10,13 @@ import OpenAPIKit final class DereferencedParameterTests: XCTestCase { func test_inlineSchemaParameter() throws { - let t1 = try OpenAPI.Parameter( + let t1 = try OpenAPI.Parameter.header( name: "test", - context: .header, schema: .string ).dereferenced(in: .noComponents) XCTAssertEqual(t1.name, "test") - XCTAssertEqual(t1.context, .header) + XCTAssertEqual(t1.context, .header(schema: .string)) XCTAssertEqual( t1.schemaOrContent.schemaContextValue, try OpenAPI.Parameter.SchemaContext.header(.string).dereferenced(in: .noComponents) @@ -25,16 +24,17 @@ final class DereferencedParameterTests: XCTestCase { XCTAssertEqual(t1.schemaOrContent.schemaValue?.jsonSchema, .string) XCTAssertNil(t1.schemaOrContent.contentValue) - let t2 = try OpenAPI.Parameter( + let t2 = try OpenAPI.Parameter.path( name: "test2", - context: .path, content: [ .anyText: .init(schema: .string) ] ).dereferenced(in: .noComponents) XCTAssertEqual(t2.name, "test2") - XCTAssertEqual(t2.context, .path) + XCTAssertEqual(t2.context, .path(content: [ + .anyText: .init(schema: .string) + ])) XCTAssertEqual( t2.schemaOrContent.contentValue, [ @@ -46,9 +46,8 @@ final class DereferencedParameterTests: XCTestCase { } func test_inlineContentParameter() throws { - let t1 = try OpenAPI.Parameter( + let t1 = try OpenAPI.Parameter.header( name: "test", - context: .header, content: [ .json: .init(schema: .string) ] @@ -63,9 +62,8 @@ final class DereferencedParameterTests: XCTestCase { "test": .string ] ) - let t1 = try OpenAPI.Parameter( + let t1 = try OpenAPI.Parameter.header( name: "test", - context: .header, schemaReference: .component(named: "test") ).dereferenced(in: components) @@ -81,9 +79,8 @@ final class DereferencedParameterTests: XCTestCase { "test": .string ] ) - let t1 = try OpenAPI.Parameter( + let t1 = try OpenAPI.Parameter.header( name: "test", - context: .header, content: [.json: .init(schemaReference: .component(named: "test"))] ).dereferenced(in: components) diff --git a/Tests/OpenAPIKitTests/Parameter/ParameterContextTests.swift b/Tests/OpenAPIKitTests/Parameter/ParameterContextTests.swift index 1e75cd68f..ad93d2b0d 100644 --- a/Tests/OpenAPIKitTests/Parameter/ParameterContextTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/ParameterContextTests.swift @@ -12,24 +12,24 @@ final class ParameterContextTests: XCTestCase { typealias Context = OpenAPI.Parameter.Context func test_query() { - let t1: Context = .query - XCTAssertEqual(t1, Context.query(required: false, allowEmptyValue: false)) + let t1: Context = .query(schema: .string) + XCTAssertEqual(t1, Context.query(required: false, allowEmptyValue: false, schema: .string)) XCTAssertFalse(t1.required) XCTAssertTrue(t1.inQuery) XCTAssertFalse(t1.inHeader) XCTAssertFalse(t1.inPath) XCTAssertFalse(t1.inCookie) - let t2: Context = .query(allowEmptyValue: true) - XCTAssertEqual(t2, Context.query(required: false, allowEmptyValue: true)) + let t2: Context = .query(allowEmptyValue: true, schema: .string) + XCTAssertEqual(t2, Context.query(required: false, allowEmptyValue: true, schema: .string)) XCTAssertFalse(t2.required) XCTAssertTrue(t2.inQuery) XCTAssertFalse(t2.inHeader) XCTAssertFalse(t2.inPath) XCTAssertFalse(t2.inCookie) - let t3: Context = .query(required: true) - XCTAssertEqual(t3, Context.query(required: true, allowEmptyValue: false)) + let t3: Context = .query(required: true, schema: .string) + XCTAssertEqual(t3, Context.query(required: true, allowEmptyValue: false, schema: .string)) XCTAssertTrue(t3.required) XCTAssertTrue(t3.inQuery) XCTAssertFalse(t3.inHeader) @@ -38,31 +38,31 @@ final class ParameterContextTests: XCTestCase { } func test_header() { - let t1: Context = .header - XCTAssertEqual(t1, Context.header(required: false)) + let t1: Context = .header(schema: .string) + XCTAssertEqual(t1, Context.header(required: false, schema: .string)) XCTAssertFalse(t1.required) XCTAssertTrue(t1.inHeader) XCTAssertFalse(t1.inQuery) XCTAssertFalse(t1.inPath) XCTAssertFalse(t1.inCookie) - XCTAssertTrue(Context.header(required: true).required) + XCTAssertTrue(Context.header(required: true, schema: .string).required) } func test_cookie() { - let t1: Context = .cookie - XCTAssertEqual(t1, Context.cookie(required: false)) + let t1: Context = .cookie(schema: .string) + XCTAssertEqual(t1, Context.cookie(required: false, schema: .string)) XCTAssertFalse(t1.required) XCTAssertTrue(t1.inCookie) XCTAssertFalse(t1.inQuery) XCTAssertFalse(t1.inPath) XCTAssertFalse(t1.inHeader) - XCTAssertTrue(Context.cookie(required: true).required) + XCTAssertTrue(Context.cookie(required: true, schema: .string).required) } func test_path() { - let t1: Context = .path + let t1: Context = .path(schema: .string) XCTAssertTrue(t1.required) XCTAssertTrue(t1.inPath) XCTAssertFalse(t1.inQuery) @@ -71,10 +71,10 @@ final class ParameterContextTests: XCTestCase { } func test_location() { - let t1: Context = .cookie - let t2: Context = .header - let t3: Context = .path - let t4: Context = .query + let t1: Context = .cookie(schema: .string) + let t2: Context = .header(schema: .string) + let t3: Context = .path(schema: .string) + let t4: Context = .query(schema: .string) XCTAssertEqual(t1.location, .cookie) XCTAssertEqual(t2.location, .header) diff --git a/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift b/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift index 35ea9da84..5300f8f3b 100644 --- a/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift @@ -531,7 +531,7 @@ fileprivate struct SchemaWrapper: Codable { let location: TestLocation let schema: OpenAPI.Parameter.SchemaContext - init(location: OpenAPI.Parameter.Context, schema: OpenAPI.Parameter.SchemaContext) { + init(location: OpenAPI.Parameter.Context.Location, schema: OpenAPI.Parameter.SchemaContext) { self.location = .init(location) self.schema = schema } @@ -546,22 +546,25 @@ fileprivate struct SchemaWrapper: Codable { case header case path case cookie + case querystring - var paramLoc: OpenAPI.Parameter.Context { + var paramLoc: OpenAPI.Parameter.Context.Location { switch self { - case .query: return .query - case .header: return .header - case .path: return .path - case .cookie: return .cookie + case .query: .query + case .header: .header + case .path: .path + case .cookie: .cookie + case .querystring: .querystring } } - init(_ paramLoc: OpenAPI.Parameter.Context) { + init(_ paramLoc: OpenAPI.Parameter.Context.Location) { switch paramLoc { case .query: self = .query case .header: self = .header case .path: self = .path case .cookie: self = .cookie + case .querystring: self = .querystring } } } diff --git a/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift b/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift index 6e86c40aa..bb8bd8035 100644 --- a/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift @@ -10,18 +10,18 @@ import OpenAPIKit final class ParameterTests: XCTestCase { func test_initialize() { - let t1 = OpenAPI.Parameter( + let t1 = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie(required: true), + required: true, schemaOrContent: .init([.json: OpenAPI.Content(schema: .string)]), description: "hi", deprecated: true ) XCTAssertTrue(t1.required) - let t2 = OpenAPI.Parameter( + let t2 = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie(required: true), + required: true, schemaOrContent: .content([.json: OpenAPI.Content(schema: .string)]), description: "hi", deprecated: true @@ -29,46 +29,21 @@ final class ParameterTests: XCTestCase { XCTAssertTrue(t2.deprecated) XCTAssertEqual(t1, t2) - let t4 = OpenAPI.Parameter( + let t6 = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie(required: false), - schema: .init(.string, style: .default(for: .cookie)), - description: "hi", - deprecated: false - ) - XCTAssertFalse(t4.required) - - let t5 = OpenAPI.Parameter( - name: "hello", - context: .cookie, - schema: .string - ) - XCTAssertFalse(t5.deprecated) - - let t6 = OpenAPI.Parameter( - name: "hello", - context: .cookie, schemaOrContent: .schema(.init(.string, style: .default(for: .cookie))) ) - XCTAssertEqual(t5, t6) + XCTAssertFalse(t6.required) - let _ = OpenAPI.Parameter( + let _ = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie, schemaReference: .component( named: "hello") ) - - let _ = OpenAPI.Parameter( - name: "hello", - context: .cookie, - content: [.json: OpenAPI.Content(schema: .string)] - ) } func test_schemaAccess() { - let t1 = OpenAPI.Parameter( + let t1 = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie, schemaOrContent: .schema(.init(.string, style: .default(for: .cookie))) ) @@ -79,9 +54,8 @@ final class ParameterTests: XCTestCase { XCTAssertEqual(t1.schemaOrContent.schemaContextValue, .init(.string, style: .default(for: .cookie))) XCTAssertEqual(t1.schemaOrContent.schemaContextValue?.schema.schemaValue, t1.schemaOrContent.schemaValue) - let t2 = OpenAPI.Parameter( + let t2 = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie, schemaReference: .component( named: "hello") ) @@ -91,9 +65,8 @@ final class ParameterTests: XCTestCase { XCTAssertEqual(t2.schemaOrContent.schemaReference, .component( named: "hello")) XCTAssertEqual(t2.schemaOrContent.schemaContextValue?.schema.reference, t2.schemaOrContent.schemaReference) - let t3 = OpenAPI.Parameter( + let t3 = OpenAPI.Parameter.path( name: "hello", - context: .path, content: [:] ) @@ -105,10 +78,10 @@ final class ParameterTests: XCTestCase { func test_parameterArray() { let t1: OpenAPI.Parameter.Array = [ - .parameter(OpenAPI.Parameter(name: "hello", context: .cookie, schema: .string)), - .parameter(name: "hello", context: .cookie, schema: .string), - .parameter(OpenAPI.Parameter(name: "hello", context: .cookie, content: [.json: OpenAPI.Content(schema: .string)])), - .parameter(name: "hello", context: .cookie, content: [.json: OpenAPI.Content(schema: .string)]), + .parameter(OpenAPI.Parameter.cookie(name: "hello", schema: .string)), + .parameter(name: "hello", context: .cookie(schema: .string)), + .parameter(OpenAPI.Parameter.cookie(name: "hello", content: [.json: OpenAPI.Content(schema: .string)])), + .parameter(name: "hello", context: .cookie(content: [.json: OpenAPI.Content(schema: .string)])), .reference(.component( named: "hello")) ] @@ -119,7 +92,7 @@ final class ParameterTests: XCTestCase { XCTAssertNotEqual(t1[4], t1[2]) XCTAssertNotEqual(t1[4], t1[3]) - XCTAssertEqual(t1[0].parameterValue, OpenAPI.Parameter(name: "hello", context: .cookie, schema: .string)) + XCTAssertEqual(t1[0].parameterValue, OpenAPI.Parameter.cookie(name: "hello", schema: .string)) XCTAssertEqual(t1[4].reference, .component( named: "hello")) } } @@ -127,9 +100,8 @@ final class ParameterTests: XCTestCase { // MARK: - Codable Tests extension ParameterTests { func test_minimalContent_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.path( name: "hello", - context: .path, content: [ .json: .init(schema: .string)] ) @@ -175,9 +147,8 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.path( name: "hello", - context: .path, content: [ .json: .init(schema: .string)] ) ) @@ -185,9 +156,8 @@ extension ParameterTests { } func test_minimalSchema_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string ) @@ -225,18 +195,16 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string ) ) } func test_queryParam_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.query( name: "hello", - context: .query, schema: .string ) @@ -273,9 +241,8 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .query) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.query( name: "hello", - context: .query, schema: .string ) ) @@ -287,9 +254,9 @@ extension ParameterTests { } func test_queryParamAllowEmpty_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.query( name: "hello", - context: .query(allowEmptyValue: true), + allowEmptyValue: true, schema: .string ) @@ -327,18 +294,18 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.query( name: "hello", - context: .query(allowEmptyValue: true), + allowEmptyValue: true, schema: .string ) ) } func test_requiredQueryParam_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.query( name: "hello", - context: .query(required: true), + required: true, schema: .string ) @@ -376,18 +343,17 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.query( name: "hello", - context: .query(required: true), + required: true, schema: .string ) ) } func test_headerParam_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.header( name: "hello", - context: .header, schema: .string ) @@ -424,18 +390,17 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .header) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.header( name: "hello", - context: .header, schema: .string ) ) } func test_requiredHeaderParam_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.header( name: "hello", - context: .header(required: true), + required: true, schema: .string ) @@ -473,18 +438,17 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.header( name: "hello", - context: .header(required: true), + required: true, schema: .string ) ) } func test_cookieParam_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie, schema: .string ) @@ -521,18 +485,17 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .cookie) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.cookie( name: "hello", - context: .cookie, schema: .string ) ) } func test_requiredCookieParam_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.cookie( name: "hello", - context: .cookie(required: true), + required: true, schema: .string ) @@ -570,18 +533,17 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.cookie( name: "hello", - context: .cookie(required: true), + required: true, schema: .string ) ) } func test_deprecated_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string, deprecated: true ) @@ -622,9 +584,8 @@ extension ParameterTests { XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string, deprecated: true ) @@ -632,9 +593,8 @@ extension ParameterTests { } func test_description_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string, description: "world" ) @@ -676,9 +636,8 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .path) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string, description: "world" ) @@ -686,13 +645,15 @@ extension ParameterTests { } func test_example_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.header( name: "hello", - context: .header(required: true), - schema: .init( - .string, - style: .default(for: .header), - example: "hello string" + required: true, + schemaOrContent: .schema( + .init( + .string, + style: .default(for: .header), + example: "hello string" + ) ) ) @@ -733,29 +694,33 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .header) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.header( name: "hello", - context: .header(required: true), - schema: .init( - .string, - style: .default(for: .header), - example: "hello string" + required: true, + schemaOrContent: .schema( + .init( + .string, + style: .default(for: .header), + example: "hello string" + ) ) ) ) } func test_examples_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.header( name: "hello", - context: .header(required: true), - schema: .init( - .string, - style: .default(for: .header), - allowReserved: true, - examples: [ - "test": .example(value: .init(URL(string: "http://website.com")!)) - ] + required: true, + schemaOrContent: .schema( + .init( + .string, + style: .default(for: .header), + allowReserved: true, + examples: [ + "test": .example(value: .init(URL(string: "http://website.com")!)) + ] + ) ) ) @@ -806,25 +771,26 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .header) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.header( name: "hello", - context: .header(required: true), - schema: .init( - .string, - style: .default(for: .header), - allowReserved: true, - examples: [ - "test": .example(value: .init(URL(string: "http://website.com")!)) - ] + required: true, + schemaOrContent: .schema( + .init( + .string, + style: .default(for: .header), + allowReserved: true, + examples: [ + "test": .example(value: .init(URL(string: "http://website.com")!)) + ] + ) ) ) ) } func test_vendorExtension_encode() throws { - let parameter = OpenAPI.Parameter( + let parameter = OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string, description: "world", vendorExtensions: ["x-specialFeature": .init(["hello", "world"])] @@ -875,9 +841,8 @@ extension ParameterTests { XCTAssertEqual(parameter.location, .path) XCTAssertEqual( parameter, - OpenAPI.Parameter( + OpenAPI.Parameter.path( name: "hello", - context: .path, schema: .string, description: "world", vendorExtensions: ["x-specialFeature": .init(["hello", "world"])] diff --git a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift index 5ca4c9448..3a48d3f33 100644 --- a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift @@ -34,7 +34,7 @@ final class DereferencedPathItemTests: XCTestCase { func test_inlinedOperationsAndParameters() throws { let t1 = try OpenAPI.PathItem( parameters: [ - .parameter(name: "param", context: .header, schema: .string) + .parameter(name: "param", context: .header(schema: .string)) ], get: .init(tags: "get op", responses: [:]), put: .init(tags: "put op", responses: [:]), @@ -67,7 +67,7 @@ final class DereferencedPathItemTests: XCTestCase { func test_referencedParameter() throws { let components = OpenAPI.Components( parameters: [ - "test": .init(name: "param", context: .header, schema: .string) + "test": .init(name: "param", context: .header(schema: .string)) ] ) let t1 = try OpenAPI.PathItem( diff --git a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift index 13087fbbd..367aff363 100644 --- a/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/PathItemTests.swift @@ -46,7 +46,7 @@ final class PathItemTests: XCTestCase { summary: "summary", description: "description", servers: [OpenAPI.Server(url: URL(string: "http://google.com")!)], - parameters: [.parameter(name: "hello", context: .query, schema: .string)], + parameters: [.parameter(name: "hello", context: .query(schema: .string))], get: op, put: op, post: op, @@ -159,7 +159,7 @@ final class PathItemTests: XCTestCase { summary: "summary", description: "description", servers: [OpenAPI.Server(url: URL(string: "http://google.com")!)], - parameters: [.parameter(name: "hello", context: .query, schema: .string)], + parameters: [.parameter(name: "hello", context: .query(schema: .string))], get: op, put: op, post: op, @@ -240,7 +240,7 @@ extension PathItemTests { summary: "summary", description: "description", servers: [OpenAPI.Server(url: URL(string: "http://google.com")!)], - parameters: [.parameter(name: "hello", context: .query, schema: .string)], + parameters: [.parameter(name: "hello", context: .query(schema: .string))], vendorExtensions: ["x-specialFeature": .init(["hello", "world"])] ) @@ -310,7 +310,7 @@ extension PathItemTests { summary: "summary", description: "description", servers: [OpenAPI.Server(url: URL(string: "http://google.com")!)], - parameters: [.parameter(name: "hello", context: .query, schema: .string)], + parameters: [.parameter(name: "hello", context: .query(schema: .string))], vendorExtensions: ["x-specialFeature": .init(["hello", "world"])] ) ) diff --git a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift index 246fe1cf2..5b611aa9b 100644 --- a/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/ResolvedRouteTests.swift @@ -18,7 +18,7 @@ final class ResolvedRouteTests: XCTestCase { summary: "routeSummary", description: "routeDescription", servers: [], - parameters: [.parameter(name: "id", context: .path, schema: .integer)], + parameters: [.parameter(name: "id", context: .path(schema: .integer))], get: .init( summary: "get", responses: [200: .response(description: "hello world")] diff --git a/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift b/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift index a7a07cc51..25a761ae9 100644 --- a/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift +++ b/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift @@ -207,7 +207,7 @@ final class BuiltinValidationTests: XCTestCase { paths: [ "/hello/world/{idx}": .init( parameters: [ - .parameter(name: "idx", context: .path, schema: .string) + .parameter(name: "idx", context: .path(schema: .string)) ], get: .init( responses: [:] @@ -229,7 +229,7 @@ final class BuiltinValidationTests: XCTestCase { "/hello/world/{idx}": .init( get: .init( parameters: [ - .parameter(name: "idx", context: .path, schema: .string) + .parameter(name: "idx", context: .path(schema: .string)) ], responses: [:] ) @@ -496,8 +496,8 @@ final class BuiltinValidationTests: XCTestCase { "/hello": .init( get: .init( parameters: [ - .parameter(name: "hiya", context: .path, schema: .string), - .parameter(name: "hiya", context: .path, schema: .string) + .parameter(name: "hiya", context: .path(schema: .string)), + .parameter(name: "hiya", context: .path(schema: .string)) ], responses: [ 200: .response(description: "hi") @@ -524,9 +524,9 @@ final class BuiltinValidationTests: XCTestCase { "/hello": .init( get: .init( parameters: [ - .parameter(name: "hiya", context: .query, schema: .string), - .parameter(name: "hiya", context: .path, schema: .string), // changes parameter location but not name - .parameter(name: "cool", context: .path, schema: .string) // changes parameter name but not location + .parameter(name: "hiya", context: .query(schema: .string)), + .parameter(name: "hiya", context: .path(schema: .string)), // changes parameter location but not name + .parameter(name: "cool", context: .path(schema: .string)) // changes parameter name but not location ], responses: [ 200: .response(description: "hi") @@ -646,8 +646,8 @@ final class BuiltinValidationTests: XCTestCase { paths: [ "/hello": .init( parameters: [ - .parameter(name: "hiya", context: .query, schema: .string), - .parameter(name: "hiya", context: .query, schema: .string) + .parameter(name: "hiya", context: .query(schema: .string)), + .parameter(name: "hiya", context: .query(schema: .string)) ], get: .init( responses: [ @@ -674,9 +674,9 @@ final class BuiltinValidationTests: XCTestCase { paths: [ "/hello": .init( parameters: [ - .parameter(name: "hiya", context: .query, schema: .string), - .parameter(name: "hiya", context: .path, schema: .string), // changes parameter location but not name - .parameter(name: "cool", context: .path, schema: .string) // changes parameter name but not location + .parameter(name: "hiya", context: .query(schema: .string)), + .parameter(name: "hiya", context: .path(schema: .string)), // changes parameter location but not name + .parameter(name: "cool", context: .path(schema: .string)) // changes parameter name but not location ], get: .init( responses: [ @@ -845,7 +845,7 @@ final class BuiltinValidationTests: XCTestCase { "response1": .init(description: "test") ], parameters: [ - "parameter1": .init(name: "test", context: .header, schema: .string) + "parameter1": .init(name: "test", context: .header(schema: .string)) ], examples: [ "example1": .init(value: .b("hello")) diff --git a/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift b/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift index 61f028303..61ec37a7a 100644 --- a/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift +++ b/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift @@ -296,8 +296,8 @@ final class ValidationConvenienceTests: XCTestCase { ], components: .init( parameters: [ - "test1": .init(name: "test", context: .header, content: [:]), - "test2": .init(name: "test2", context: .query, content: [:]) + "test1": .init(name: "test", context: .header(content: [:])), + "test2": .init(name: "test2", context: .query(content: [:])) ] ) ) @@ -338,8 +338,8 @@ final class ValidationConvenienceTests: XCTestCase { ], components: .init( parameters: [ - "test1": .init(name: "test", context: .header, content: [:]), - "test2": .init(name: "test2", context: .query, content: [:]) + "test1": .init(name: "test", context: .header(content: [:])), + "test2": .init(name: "test2", context: .query(content: [:])) ] ) ) From cb27c62132be697fb91c95f0a6964d36bc243bdd Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Sun, 9 Nov 2025 16:55:19 -0600 Subject: [PATCH 20/30] update migration guide --- .../migration_guides/v5_migration_guide.md | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/documentation/migration_guides/v5_migration_guide.md b/documentation/migration_guides/v5_migration_guide.md index 452cebf4e..cabb0b268 100644 --- a/documentation/migration_guides/v5_migration_guide.md +++ b/documentation/migration_guides/v5_migration_guide.md @@ -66,6 +66,89 @@ builtin methods so the following code _does not need to change_: let httpMethod : OpenAPI.HttpMethod = .post ``` +### Parameters +There are no breaking changes for the `OpenAPIKit30` module (OAS 3.0.x +specification). + +For the `OpenAPIKit` module (OAS 3.1.x and 3.2.x versions) read on. + +An additional parameter location of `querystring` has been added. This is a +breaking change to code that exhaustively switches on `OpenAPI.Parameter.Context` +or `OpenAPI.Parameter.Context.Location`. + +To support the new `querystring` location, `schemaOrContent` has been moved into +the `OpenAPI.Parameter.Context` because it only applies to locations other than +`querystring`. You can still access `schemaOrContent` as a property on the +`Parameter`. Code that pattern matches on cases of `OpenAPI.Parameter.Context` +will need to add the new `schemaOrContent` values associated with each case. + +```swift +// BEFORE +switch parameter.context { +case .query(required: _) +} + +// AFTER +switch parameter.context { +case .query(required: _, schemaOrContent: _) +} +``` + +#### Constructors +The following only applies if you construct parameters in-code (use Swift to +build an OpenAPI Document). + +Unfortunately, the change that made `schemaOrContent` not apply to all possible +locations means that the existing convenience constructors and static functions +that created parameters in-code do not make sense anymore. There were fairly +substantial changes to what is available with an aim to continue to offer +simular convenience as before. + +Following are a few changes you made need to make with examples. + +Code that populates the `parameters` array of the `OpenAPI.Operation` type with the +`.parameter(name:,context:,schema:)` function needs to be updated. The `schema` +has moved into the `context` so you change your code in the following way: +```swift +// BEFORE +.parameter( + name: "name", + context: .header, + schema: .string +) + +// AFTER +.parameter( + name: "name", + context: .header(schema: .string) +) +``` + +Code that initializes `OpenAPI.Parameter` via one of its `init` functions will +most likely need to change. Many of the initializers have been removed but you can +replace `.init(name:,context:,schema:)` or similar initializers with +`.header(name:,schema:)` (same goes for `query`, `path`, and `cookie`). So you change +your code in the following way: +```swift +// BEFORE +.init( + name: "name", + context: .header, + schema: .string +) + +// AFTER +.header( + name: "name", + schema: .string +) +``` + +Because the `ParameterContext` has taken on the `schemaOrContent` of the +`Parameter`, convenience constructors like `ParameterContext.header` (and +similar for the other locations) no longer make sense and have been removed. You +must also specify the schema or content, e.g. `ParameterContext.header(schema: .string)`. + ### 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 From ffc413a371fc9c4d537da0d0fe6a11b210822d53 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 10 Nov 2025 05:38:12 -0600 Subject: [PATCH 21/30] add new cookie paremeter style --- .../Parameter/ParameterSchemaContext.swift | 49 ++++++++++++++++++- .../ParameterSchemaContextStyle.swift | 19 +++++++ Sources/OpenAPIKit/_CoreReExport.swift | 4 -- .../ParameterSchemaContextStyle.swift | 4 +- Sources/OpenAPIKit30/_CoreReExport.swift | 4 -- Sources/OpenAPIKitCompat/Compat30To31.swift | 24 +++++++-- .../DocumentConversionTests.swift | 22 ++++++++- .../Parameter/ParameterSchemaTests.swift | 5 ++ 8 files changed, 113 insertions(+), 18 deletions(-) create mode 100644 Sources/OpenAPIKit/Parameter/ParameterSchemaContextStyle.swift rename Sources/{OpenAPIKitCore/Shared => OpenAPIKit30/Parameter}/ParameterSchemaContextStyle.swift (70%) diff --git a/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift b/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift index c3ef75243..c7b3b02fd 100644 --- a/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift +++ b/Sources/OpenAPIKit/Parameter/ParameterSchemaContext.swift @@ -12,7 +12,7 @@ extension OpenAPI.Parameter { /// /// See [OpenAPI Parameter Object](https://spec.openapis.org/oas/v3.1.1.html#parameter-object) /// and [OpenAPI Style Values](https://spec.openapis.org/oas/v3.1.1.html#style-values). - public struct SchemaContext: Equatable, Sendable { + public struct SchemaContext: HasConditionalWarnings, Sendable { public var style: Style public var explode: Bool public var allowReserved: Bool //defaults to false @@ -21,6 +21,8 @@ extension OpenAPI.Parameter { public var example: AnyCodable? public var examples: OpenAPI.Example.Map? + public let conditionalWarnings: [(any Condition, OpenAPI.Warning)] + public init(_ schema: JSONSchema, style: Style, explode: Bool, @@ -32,6 +34,8 @@ extension OpenAPI.Parameter { self.schema = .init(schema) self.example = example self.examples = nil + + self.conditionalWarnings = style.conditionalWarnings } public init(_ schema: JSONSchema, @@ -45,6 +49,8 @@ extension OpenAPI.Parameter { self.examples = nil self.explode = style.defaultExplode + + self.conditionalWarnings = style.conditionalWarnings } public init(schemaReference: OpenAPI.Reference, @@ -58,6 +64,8 @@ extension OpenAPI.Parameter { self.schema = .init(schemaReference) self.example = example self.examples = nil + + self.conditionalWarnings = style.conditionalWarnings } public init(schemaReference: OpenAPI.Reference, @@ -71,6 +79,8 @@ extension OpenAPI.Parameter { self.examples = nil self.explode = style.defaultExplode + + self.conditionalWarnings = style.conditionalWarnings } public init(_ schema: JSONSchema, @@ -84,6 +94,8 @@ extension OpenAPI.Parameter { self.schema = .init(schema) self.examples = examples self.example = examples.flatMap(OpenAPI.Content.firstExample(from:)) + + self.conditionalWarnings = style.conditionalWarnings } public init(_ schema: JSONSchema, @@ -97,6 +109,8 @@ extension OpenAPI.Parameter { self.example = examples.flatMap(OpenAPI.Content.firstExample(from:)) self.explode = style.defaultExplode + + self.conditionalWarnings = style.conditionalWarnings } public init(schemaReference: OpenAPI.Reference, @@ -110,6 +124,8 @@ extension OpenAPI.Parameter { self.schema = .init(schemaReference) self.examples = examples self.example = examples.flatMap(OpenAPI.Content.firstExample(from:)) + + self.conditionalWarnings = style.conditionalWarnings } public init(schemaReference: OpenAPI.Reference, @@ -123,10 +139,39 @@ extension OpenAPI.Parameter { self.example = examples.flatMap(OpenAPI.Content.firstExample(from:)) self.explode = style.defaultExplode + + self.conditionalWarnings = style.conditionalWarnings } } } +extension OpenAPI.Parameter.SchemaContext.Style { + fileprivate var conditionalWarnings: [(any Condition, OpenAPI.Warning)] { + let cookieStyleWarning: (any Condition, OpenAPI.Warning)? + if self != .cookie { + cookieStyleWarning = nil + } else { + cookieStyleWarning = OpenAPI.Document.ConditionalWarnings.version(lessThan: .v3_2_0, doesNotSupport: "The cookie style") + } + + + return [ + cookieStyleWarning + ].compactMap { $0 } + } +} + +extension OpenAPI.Parameter.SchemaContext: Equatable { + public static func == (_ lhs: Self, _ rhs: Self) -> Bool { + lhs.style == rhs.style + && lhs.allowReserved == rhs.allowReserved + && lhs.explode == rhs.explode + && lhs.schema == rhs.schema + && lhs.examples == rhs.examples + && lhs.example == rhs.example + } +} + extension OpenAPI.Parameter.SchemaContext { public static func schema(_ schema: JSONSchema, style: Style, @@ -278,6 +323,8 @@ extension OpenAPI.Parameter.SchemaContext { examples = examplesMap example = examplesMap.flatMap(OpenAPI.Content.firstExample(from:)) } + + self.conditionalWarnings = style.conditionalWarnings } } diff --git a/Sources/OpenAPIKit/Parameter/ParameterSchemaContextStyle.swift b/Sources/OpenAPIKit/Parameter/ParameterSchemaContextStyle.swift new file mode 100644 index 000000000..96260473e --- /dev/null +++ b/Sources/OpenAPIKit/Parameter/ParameterSchemaContextStyle.swift @@ -0,0 +1,19 @@ +// +// ParameterSchemaContextStyle.swift +// +// +// Created by Mathew Polzin on 12/18/22. +// + +extension OpenAPI.Parameter.SchemaContext { + public enum Style: String, CaseIterable, Codable, Sendable { + case form + case simple + case matrix + case label + case spaceDelimited + case pipeDelimited + case deepObject + case cookie + } +} diff --git a/Sources/OpenAPIKit/_CoreReExport.swift b/Sources/OpenAPIKit/_CoreReExport.swift index 997063193..17e2b37ea 100644 --- a/Sources/OpenAPIKit/_CoreReExport.swift +++ b/Sources/OpenAPIKit/_CoreReExport.swift @@ -31,10 +31,6 @@ public extension OpenAPI.SecurityScheme { typealias Location = OpenAPIKitCore.Shared.SecuritySchemeLocation } -public extension OpenAPI.Parameter.SchemaContext { - typealias Style = OpenAPIKitCore.Shared.ParameterSchemaContextStyle -} - public extension OpenAPI.Response { typealias StatusCode = OpenAPIKitCore.Shared.ResponseStatusCode } diff --git a/Sources/OpenAPIKitCore/Shared/ParameterSchemaContextStyle.swift b/Sources/OpenAPIKit30/Parameter/ParameterSchemaContextStyle.swift similarity index 70% rename from Sources/OpenAPIKitCore/Shared/ParameterSchemaContextStyle.swift rename to Sources/OpenAPIKit30/Parameter/ParameterSchemaContextStyle.swift index a3166d6dc..41d236e51 100644 --- a/Sources/OpenAPIKitCore/Shared/ParameterSchemaContextStyle.swift +++ b/Sources/OpenAPIKit30/Parameter/ParameterSchemaContextStyle.swift @@ -5,8 +5,8 @@ // Created by Mathew Polzin on 12/18/22. // -extension Shared { - public enum ParameterSchemaContextStyle: String, CaseIterable, Codable, Sendable { +extension OpenAPI.Parameter.SchemaContext { + public enum Style: String, CaseIterable, Codable, Sendable { case form case simple case matrix diff --git a/Sources/OpenAPIKit30/_CoreReExport.swift b/Sources/OpenAPIKit30/_CoreReExport.swift index 997063193..17e2b37ea 100644 --- a/Sources/OpenAPIKit30/_CoreReExport.swift +++ b/Sources/OpenAPIKit30/_CoreReExport.swift @@ -31,10 +31,6 @@ public extension OpenAPI.SecurityScheme { typealias Location = OpenAPIKitCore.Shared.SecuritySchemeLocation } -public extension OpenAPI.Parameter.SchemaContext { - typealias Style = OpenAPIKitCore.Shared.ParameterSchemaContextStyle -} - public extension OpenAPI.Response { typealias StatusCode = OpenAPIKitCore.Shared.ResponseStatusCode } diff --git a/Sources/OpenAPIKitCompat/Compat30To31.swift b/Sources/OpenAPIKitCompat/Compat30To31.swift index 06b210672..a80d74b3c 100644 --- a/Sources/OpenAPIKitCompat/Compat30To31.swift +++ b/Sources/OpenAPIKitCompat/Compat30To31.swift @@ -175,7 +175,7 @@ extension OpenAPIKit30.OpenAPI.Parameter.SchemaContext: To31 { if let newExamples { return OpenAPIKit.OpenAPI.Parameter.SchemaContext( schemaReference: .init(ref.to31()), - style: style, + style: style.to31(), explode: explode, allowReserved: allowReserved, examples: newExamples @@ -183,7 +183,7 @@ extension OpenAPIKit30.OpenAPI.Parameter.SchemaContext: To31 { } else { return OpenAPIKit.OpenAPI.Parameter.SchemaContext( schemaReference: .init(ref.to31()), - style: style, + style: style.to31(), explode: explode, allowReserved: allowReserved, example: example @@ -193,7 +193,7 @@ extension OpenAPIKit30.OpenAPI.Parameter.SchemaContext: To31 { if let newExamples { return OpenAPIKit.OpenAPI.Parameter.SchemaContext( schema.to31(), - style: style, + style: style.to31(), explode: explode, allowReserved: allowReserved, examples: newExamples @@ -201,7 +201,7 @@ extension OpenAPIKit30.OpenAPI.Parameter.SchemaContext: To31 { } else { return OpenAPIKit.OpenAPI.Parameter.SchemaContext( schema.to31(), - style: style, + style: style.to31(), explode: explode, allowReserved: allowReserved, example: example @@ -211,12 +211,26 @@ extension OpenAPIKit30.OpenAPI.Parameter.SchemaContext: To31 { } } +extension OpenAPIKit30.OpenAPI.Parameter.SchemaContext.Style: To31 { + fileprivate func to31() -> OpenAPIKit.OpenAPI.Parameter.SchemaContext.Style { + switch self { + case .form: .form + case .simple: .simple + case .matrix: .matrix + case .label: .label + case .spaceDelimited: .spaceDelimited + case .pipeDelimited: .pipeDelimited + case .deepObject: .deepObject + } + } +} + extension OpenAPIKit30.OpenAPI.Content.Encoding: To31 { fileprivate func to31() -> OpenAPIKit.OpenAPI.Content.Encoding { OpenAPIKit.OpenAPI.Content.Encoding( contentTypes: [contentType].compactMap { $0 }, headers: headers?.mapValues(eitherRefTo31), - style: style, + style: style.to31(), explode: explode, allowReserved: allowReserved ) diff --git a/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift b/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift index 4f73d05d2..11a0c75b0 100644 --- a/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift +++ b/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift @@ -1254,11 +1254,29 @@ fileprivate func assertEqualNewToOld(_ newEncoding: OpenAPIKit.OpenAPI.Content.E } else { XCTAssertNil(oldEncoding.headers) } - XCTAssertEqual(newEncoding.style, oldEncoding.style) + try assertEqualNewToOld(newEncoding.style, oldEncoding.style) XCTAssertEqual(newEncoding.explode, oldEncoding.explode) XCTAssertEqual(newEncoding.allowReserved, oldEncoding.allowReserved) } +fileprivate func assertEqualNewToOld(_ newStyle: OpenAPIKit.OpenAPI.Parameter.SchemaContext.Style, _ oldStyle: OpenAPIKit30.OpenAPI.Parameter.SchemaContext.Style) throws { + let equal: Bool + switch (newStyle, oldStyle) { + case (.form, .form): equal = true + case (.simple, .simple): equal = true + case (.matrix, .matrix): equal = true + case (.label, .label): equal = true + case (.spaceDelimited, .spaceDelimited): equal = true + case (.pipeDelimited, .pipeDelimited): equal = true + case (.deepObject, .deepObject): equal = true + default: equal = false + } + + if !equal { + XCTFail("New \(newStyle) is not equivalent to old \(oldStyle)") + } +} + fileprivate func assertEqualNewToOld(_ newHeader: OpenAPIKit.OpenAPI.Header, _ oldHeader: OpenAPIKit30.OpenAPI.Header) throws { XCTAssertEqual(newHeader.description, oldHeader.description) XCTAssertEqual(newHeader.required, oldHeader.required) @@ -1275,7 +1293,7 @@ fileprivate func assertEqualNewToOld(_ newHeader: OpenAPIKit.OpenAPI.Header, _ o } fileprivate func assertEqualNewToOld(_ newSchemaContext: OpenAPIKit.OpenAPI.Parameter.SchemaContext, _ oldSchemaContext: OpenAPIKit30.OpenAPI.Parameter.SchemaContext) throws { - XCTAssertEqual(newSchemaContext.style, oldSchemaContext.style) + try assertEqualNewToOld(newSchemaContext.style, oldSchemaContext.style) XCTAssertEqual(newSchemaContext.explode, oldSchemaContext.explode) XCTAssertEqual(newSchemaContext.allowReserved, oldSchemaContext.allowReserved) switch (newSchemaContext.schema, oldSchemaContext.schema) { diff --git a/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift b/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift index 5300f8f3b..0ac00d6f0 100644 --- a/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/ParameterSchemaTests.swift @@ -210,6 +210,11 @@ final class ParameterSchemaTests: XCTestCase { let t7 = Schema(.string, style: .deepObject) XCTAssertFalse(t7.explode) } + + public func test_cookie_style() { + let t1 = Schema(.string, style: .cookie) + XCTAssertEqual(t1.conditionalWarnings.count, 1) + } } // MARK: - Codable Tests From ebf4d71afebbf0559a6993baeb38de35a53594f7 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 10 Nov 2025 05:49:28 -0600 Subject: [PATCH 22/30] add missing conditional warning for querystring parameter location --- Sources/OpenAPIKit/Parameter/Parameter.swift | 34 ++++++++++++++++++- .../Parameter/ParameterTests.swift | 5 +++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Sources/OpenAPIKit/Parameter/Parameter.swift b/Sources/OpenAPIKit/Parameter/Parameter.swift index 1d0332a85..c7e8367cf 100644 --- a/Sources/OpenAPIKit/Parameter/Parameter.swift +++ b/Sources/OpenAPIKit/Parameter/Parameter.swift @@ -11,7 +11,7 @@ extension OpenAPI { /// OpenAPI Spec "Parameter Object" /// /// See [OpenAPI Parameter Object](https://spec.openapis.org/oas/v3.1.1.html#parameter-object). - public struct Parameter: Equatable, CodableVendorExtendable, Sendable { + public struct Parameter: HasConditionalWarnings, CodableVendorExtendable, Sendable { public var name: String /// OpenAPI Spec "in" property determines the `Context`. @@ -32,6 +32,8 @@ extension OpenAPI { /// where the values are anything codable. public var vendorExtensions: [String: AnyCodable] + public let conditionalWarnings: [(any Condition, OpenAPI.Warning)] + /// Whether or not this parameter is required. See the context /// which determines whether the parameter is required or not. public var required: Bool { context.required } @@ -84,10 +86,38 @@ extension OpenAPI { self.description = description self.deprecated = deprecated self.vendorExtensions = vendorExtensions + + self.conditionalWarnings = context.location.conditionalWarnings } } } +extension OpenAPI.Parameter: Equatable { + public static func == (_ lhs: Self, _ rhs: Self) -> Bool { + lhs.name == rhs.name + && lhs.context == rhs.context + && lhs.description == rhs.description + && lhs.deprecated == rhs.deprecated + && lhs.vendorExtensions == rhs.vendorExtensions + } +} + +extension OpenAPI.Parameter.Context.Location { + fileprivate var conditionalWarnings: [(any Condition, OpenAPI.Warning)] { + let querystringWarning: (any Condition, OpenAPI.Warning)? + if self != .querystring { + querystringWarning = nil + } else { + querystringWarning = OpenAPI.Document.ConditionalWarnings.version(lessThan: .v3_2_0, doesNotSupport: "The querystring parameter location") + } + + + return [ + querystringWarning + ].compactMap { $0 } + } +} + extension OpenAPI.Parameter { /// An array of parameters that are `Either` `Parameters` or references to parameters. /// @@ -595,6 +625,8 @@ extension OpenAPI.Parameter: Decodable { deprecated = try container.decodeIfPresent(Bool.self, forKey: .deprecated) ?? false vendorExtensions = try Self.extensions(from: decoder) + + conditionalWarnings = context.location.conditionalWarnings } } diff --git a/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift b/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift index bb8bd8035..554779cde 100644 --- a/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/ParameterTests.swift @@ -95,6 +95,11 @@ final class ParameterTests: XCTestCase { XCTAssertEqual(t1[0].parameterValue, OpenAPI.Parameter.cookie(name: "hello", schema: .string)) XCTAssertEqual(t1[4].reference, .component( named: "hello")) } + + func test_querystringLocation() { + let t1 = OpenAPI.Parameter.querystring(name: "string", content: [:]) + XCTAssertEqual(t1.conditionalWarnings.count, 1) + } } // MARK: - Codable Tests From ea62ddbbab04943026d3ddb7ad529fd2c167d7a3 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 10 Nov 2025 09:25:52 -0600 Subject: [PATCH 23/30] add new builtin validation for parameter schema styles --- Sources/OpenAPIKit/Parameter/Parameter.swift | 8 + .../Validator/Validation+Builtins.swift | 52 ++++ Sources/OpenAPIKit/Validator/Validator.swift | 15 +- .../Validator/BuiltinValidationTests.swift | 256 ++++++++++++++++++ 4 files changed, 324 insertions(+), 7 deletions(-) diff --git a/Sources/OpenAPIKit/Parameter/Parameter.swift b/Sources/OpenAPIKit/Parameter/Parameter.swift index c7e8367cf..40952463e 100644 --- a/Sources/OpenAPIKit/Parameter/Parameter.swift +++ b/Sources/OpenAPIKit/Parameter/Parameter.swift @@ -73,6 +73,14 @@ extension OpenAPI { } } + /// The parameter's schema `style`, if defined. Note that this is + /// guaranteed to be nil if the parameter has `content` defined. Use + /// the `schemaOrContent` property if you want to switch over the two + /// possibilities. + public var schemaStyle : SchemaContext.Style? { + schemaOrContent.schemaContextValue?.style + } + /// Create a parameter. public init( name: String, diff --git a/Sources/OpenAPIKit/Validator/Validation+Builtins.swift b/Sources/OpenAPIKit/Validator/Validation+Builtins.swift index 5df0cb34b..def7c7f79 100644 --- a/Sources/OpenAPIKit/Validator/Validation+Builtins.swift +++ b/Sources/OpenAPIKit/Validator/Validation+Builtins.swift @@ -505,6 +505,58 @@ extension Validation { } ) } + + /// Validate the OpenAPI Document's `Parameter`s all have styles that are + /// compatible with their locations per the table found at + /// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.2.0.md#style-values + /// + /// - Important: This is included in validation by default. + public static var parameterStyleAndLocationAreCompatible: Validation { + .init( + check: all( + Validation( + description: "the matrix style can only be used for the path location", + check: \.context.location == .path, + when: \.schemaStyle == .matrix + ), + Validation( + description: "the label style can only be used for the path location", + check: \.context.location == .path, + when: \.schemaStyle == .label + ), + Validation( + description: "the simple style can only be used for the path and header locations", + check: \.context.location == .path || \.context.location == .header, + when: \.schemaStyle == .simple + ), + Validation( + description: "the form style can only be used for the query and cookie locations", + check: \.context.location == .query || \.context.location == .cookie, + when: \.schemaStyle == .form + ), + Validation( + description: "the spaceDelimited style can only be used for the query location", + check: \.context.location == .query, + when: \.schemaStyle == .spaceDelimited + ), + Validation( + description: "the pipeDelimited style can only be used for the query location", + check: \.context.location == .query, + when: \.schemaStyle == .pipeDelimited + ), + Validation( + description: "the deepObject style can only be used for the query location", + check: \.context.location == .query, + when: \.schemaStyle == .deepObject + ), + Validation( + description: "the cookie style can only be used for the cookie location", + check: \.context.location == .cookie, + when: \.schemaStyle == .cookie + ) + ) + ) + } } /// Used by both the Path Item parameter check and the diff --git a/Sources/OpenAPIKit/Validator/Validator.swift b/Sources/OpenAPIKit/Validator/Validator.swift index 49e1b8fdc..66fcd8611 100644 --- a/Sources/OpenAPIKit/Validator/Validator.swift +++ b/Sources/OpenAPIKit/Validator/Validator.swift @@ -170,12 +170,12 @@ public final class Validator { /// - Parameters are unique within each Path Item. /// - Parameters are unique within each Operation. /// - Operation Ids are unique across the whole Document. - /// - All OpenAPI.References that refer to components in this - /// document can be found in the components dictionary. - /// - `Enum` must not be empty in the document's - /// Server Variable. - /// - `Default` must exist in the enum values in the document's - /// Server Variable. + /// - All OpenAPI.References that refer to components in this document can + /// be found in the components dictionary. + /// - `Enum` must not be empty in the document's Server Variable. + /// - `Default` must exist in the enum values in the document's Server + /// Variable. + /// - `Parameter` styles and locations are compatible with each other. /// public convenience init() { self.init(validations: [ @@ -193,7 +193,8 @@ public final class Validator { .init(.callbacksReferencesAreValid), .init(.pathItemReferencesAreValid), .init(.serverVariableEnumIsValid), - .init(.serverVariableDefaultExistsInEnum) + .init(.serverVariableDefaultExistsInEnum), + .init(.parameterStyleAndLocationAreCompatible) ]) } diff --git a/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift b/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift index 25a761ae9..57bf0d092 100644 --- a/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift +++ b/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift @@ -951,4 +951,260 @@ final class BuiltinValidationTests: XCTestCase { XCTAssertTrue((errorCollection?.values.first?.codingPath.map { $0.stringValue }.joined(separator: ".") ?? "").contains("testLink")) } } + + func test_badMatrixStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.query( + name: "test", + schemaOrContent: .schema(.init(.string, style: .matrix)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the matrix style can only be used for the path location") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badLabelStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.query( + name: "test", + schemaOrContent: .schema(.init(.string, style: .label)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the label style can only be used for the path location") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badSimpleStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.query( + name: "test", + schemaOrContent: .schema(.init(.string, style: .simple)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the simple style can only be used for the path and header locations") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badFormStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.header( + name: "test", + schemaOrContent: .schema(.init(.string, style: .form)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the form style can only be used for the query and cookie locations") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badSpaceDelimitedStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.header( + name: "test", + schemaOrContent: .schema(.init(.string, style: .spaceDelimited)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the spaceDelimited style can only be used for the query location") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badPipeDelimitedStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.header( + name: "test", + schemaOrContent: .schema(.init(.string, style: .pipeDelimited)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the pipeDelimited style can only be used for the query location") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badDeepObjectStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.header( + name: "test", + schemaOrContent: .schema(.init(.string, style: .deepObject)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the deepObject style can only be used for the query location") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } + + func test_badCookieStyleLocation_fails() throws { + let parameter = OpenAPI.Parameter.header( + name: "test", + schemaOrContent: .schema(.init(.string, style: .cookie)) + ) + + let document = OpenAPI.Document( + info: .init(title: "test", version: "1.0"), + servers: [], + paths: [ + "/hello": .init( + get: .init( + operationId: "testOperation", + parameters: [ + .parameter(parameter) + ], + responses: [:] + ) + ) + ], + components: .noComponents + ) + + let validator = Validator.blank.validating(.parameterStyleAndLocationAreCompatible) + + XCTAssertThrowsError(try document.validate(using: validator)) { error in + let errorCollection = error as? ValidationErrorCollection + XCTAssertEqual(errorCollection?.values.first?.reason, "Failed to satisfy: the cookie style can only be used for the cookie location") + XCTAssertEqual(errorCollection?.values.first?.codingPath.stringValue, ".paths[\'/hello\'].get.parameters[0]") + } + } } From 72cc8474d7adaed4a69968fa2f22a7010f8a7553 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 10 Nov 2025 09:35:19 -0600 Subject: [PATCH 24/30] update migration guide --- documentation/migration_guides/v5_migration_guide.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/documentation/migration_guides/v5_migration_guide.md b/documentation/migration_guides/v5_migration_guide.md index cabb0b268..54eac43e9 100644 --- a/documentation/migration_guides/v5_migration_guide.md +++ b/documentation/migration_guides/v5_migration_guide.md @@ -15,6 +15,9 @@ v5.10 and greater). Only relevant when compiling OpenAPIKit on iOS: Now v12+ is required. ### OpenAPI Specification Versions +There are no breaking changes for the `OpenAPIKit30` module (OAS 3.0.x +specification) in this section. + The OpenAPIKit module's `OpenAPI.Document.Version` enum gained `v3_1_2`, `v3_2_0` and `v3_2_x(x: Int)`. @@ -68,7 +71,7 @@ let httpMethod : OpenAPI.HttpMethod = .post ### Parameters There are no breaking changes for the `OpenAPIKit30` module (OAS 3.0.x -specification). +specification) in this section. For the `OpenAPIKit` module (OAS 3.1.x and 3.2.x versions) read on. @@ -149,6 +152,13 @@ Because the `ParameterContext` has taken on the `schemaOrContent` of the similar for the other locations) no longer make sense and have been removed. You must also specify the schema or content, e.g. `ParameterContext.header(schema: .string)`. +### Parameter Styles +There are no breaking changes for the `OpenAPIKit30` module (OAS 3.0.x +specification) in this section. + +A new `cookie` style has been added. Code that exhaustively switches on the +`OpenAPI.Parameter.SchemaContext.Style` enum will need to be updated. + ### 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 From a31904f85cd23c0ac44adf8569a1a9f2f5d12a9c Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 10 Nov 2025 10:21:58 -0600 Subject: [PATCH 25/30] Add response object summary field. make response object description optional --- .../OpenAPIConditionalWarnings.swift | 6 ++ Sources/OpenAPIKit/Response/Response.swift | 79 +++++++++++++++++-- .../ResponseErrorTests.swift | 30 ------- .../Response/ResponseTests.swift | 44 +++++++++++ 4 files changed, 122 insertions(+), 37 deletions(-) diff --git a/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift index ed4092da2..6e47cab74 100644 --- a/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift +++ b/Sources/OpenAPIKit/OpenAPIConditionalWarnings.swift @@ -51,5 +51,11 @@ internal extension OpenAPI.Document { return (DocumentVersionCondition(version: version, comparator: .lessThan), warning) } + + static func version(lessThan version: OpenAPI.Document.Version, doesNotAllowOptional subject: String) -> (any Condition, OpenAPI.Warning) { + let warning = OpenAPI.Warning.message("\(subject) cannot be nil for OpenAPI document versions lower than \(version.rawValue)") + + return (DocumentVersionCondition(version: version, comparator: .lessThan), warning) + } } } diff --git a/Sources/OpenAPIKit/Response/Response.swift b/Sources/OpenAPIKit/Response/Response.swift index af5d25365..b03c3ff03 100644 --- a/Sources/OpenAPIKit/Response/Response.swift +++ b/Sources/OpenAPIKit/Response/Response.swift @@ -11,8 +11,10 @@ extension OpenAPI { /// OpenAPI Spec "Response Object" /// /// See [OpenAPI Response Object](https://spec.openapis.org/oas/v3.1.1.html#response-object). - public struct Response: Equatable, CodableVendorExtendable, Sendable { - public var description: String + public struct Response: HasConditionalWarnings, CodableVendorExtendable, Sendable { + public var summary: String? + public var description: String? + public var headers: Header.Map? /// An empty Content map will be omitted from encoding. public var content: Content.Map @@ -26,22 +28,62 @@ extension OpenAPI { /// where the values are anything codable. public var vendorExtensions: [String: AnyCodable] + public let conditionalWarnings: [(any Condition, OpenAPI.Warning)] + public init( - description: String, + summary: String? = nil, + description: String? = nil, headers: Header.Map? = nil, content: Content.Map = [:], links: Link.Map = [:], vendorExtensions: [String: AnyCodable] = [:] ) { + self.summary = summary self.description = description self.headers = headers self.content = content self.links = links 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 description is nil, the document must be OAS version 3.2.0 or greater + notOptionalVersionWarning(fieldName: "description", value: description, minimumVersion: .v3_2_0) + ].compactMap { $0 } } } } +extension OpenAPI.Response: Equatable { + public static func == (_ lhs: Self, _ rhs: Self) -> Bool { + lhs.summary == rhs.summary + && lhs.description == rhs.description + && lhs.headers == rhs.headers + && lhs.content == rhs.content + && lhs.links == rhs.links + && 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 Response \(fieldName) field" + ) + } +} + +fileprivate func notOptionalVersionWarning(fieldName: String, value: Subject?, minimumVersion: OpenAPI.Document.Version) -> (any Condition, OpenAPI.Warning)? { + guard value == nil else { return nil } + + return OpenAPI.Document.ConditionalWarnings.version( + lessThan: minimumVersion, + doesNotAllowOptional: "The Response \(fieldName) field" + ) +} + extension OpenAPI.Response { public typealias Map = OrderedDictionary, OpenAPI.Response>> } @@ -72,7 +114,8 @@ extension OrderedDictionary where Key == OpenAPI.Response.StatusCode { extension Either where A == OpenAPI.Reference, B == OpenAPI.Response { public static func response( - description: String, + summary: String? = nil, + description: String? = nil, headers: OpenAPI.Header.Map? = nil, content: OpenAPI.Content.Map = [:], links: OpenAPI.Link.Map = [:] @@ -89,19 +132,27 @@ extension Either where A == OpenAPI.Reference, B == OpenAPI.Re } // MARK: - Describable -extension OpenAPI.Response: OpenAPIDescribable { +extension OpenAPI.Response: OpenAPISummarizable { public func overriddenNonNil(description: String?) -> OpenAPI.Response { guard let description = description else { return self } var response = self response.description = description return response } + + public func overriddenNonNil(summary: String?) -> OpenAPI.Response { + guard let summary = summary else { return self } + var response = self + response.summary = summary + return response + } } // MARK: - Codable extension OpenAPI.Response { internal enum CodingKeys: ExtendableCodingKey { + case summary case description case headers case content @@ -110,6 +161,7 @@ extension OpenAPI.Response { static var allBuiltinKeys: [CodingKeys] { return [ + .summary, .description, .headers, .content, @@ -123,6 +175,8 @@ extension OpenAPI.Response { init?(stringValue: String) { switch stringValue { + case "summary": + self = .summary case "description": self = .description case "headers": @@ -138,6 +192,8 @@ extension OpenAPI.Response { var stringValue: String { switch self { + case .summary: + return "summary" case .description: return "description" case .headers: @@ -157,7 +213,8 @@ extension OpenAPI.Response: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(description, forKey: .description) + try container.encodeIfPresent(summary, forKey: .summary) + try container.encodeIfPresent(description, forKey: .description) try container.encodeIfPresent(headers, forKey: .headers) if !content.isEmpty { @@ -179,13 +236,21 @@ extension OpenAPI.Response: Decodable { let container = try decoder.container(keyedBy: CodingKeys.self) do { - description = try container.decode(String.self, forKey: .description) + summary = try container.decodeIfPresent(String.self, forKey: .summary) + description = try container.decodeIfPresent(String.self, forKey: .description) headers = try container.decodeIfPresent(OpenAPI.Header.Map.self, forKey: .headers) content = try container.decodeIfPresent(OpenAPI.Content.Map.self, forKey: .content) ?? [:] links = try container.decodeIfPresent(OpenAPI.Link.Map.self, forKey: .links) ?? [:] 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 description is nil, the document must be OAS version 3.2.0 or greater + notOptionalVersionWarning(fieldName: "description", value: description, minimumVersion: .v3_2_0) + ].compactMap { $0 } + } catch let error as GenericError { throw OpenAPI.Error.Decoding.Response(error) diff --git a/Tests/OpenAPIKitErrorReportingTests/ResponseErrorTests.swift b/Tests/OpenAPIKitErrorReportingTests/ResponseErrorTests.swift index fba1f7fd3..ff178666a 100644 --- a/Tests/OpenAPIKitErrorReportingTests/ResponseErrorTests.swift +++ b/Tests/OpenAPIKitErrorReportingTests/ResponseErrorTests.swift @@ -52,36 +52,6 @@ final class ResponseErrorTests: XCTestCase { } } - func test_missingDescriptionResponseObject() { - let documentYML = - """ - openapi: "3.1.0" - info: - title: test - version: 1.0 - paths: - /hello/world: - get: - responses: - '200': - not-a-thing: hi - """ - - XCTAssertThrowsError(try testDecoder.decode(OpenAPI.Document.self, from: documentYML)) { error in - - let openAPIError = OpenAPI.Error(from: error) - - XCTAssertEqual(openAPIError.localizedDescription, "Found neither a $ref nor a Response in .responses.200 for the **GET** endpoint under `/hello/world`. \n\nResponse could not be decoded because:\nExpected to find `description` key but it is missing..") - XCTAssertEqual(openAPIError.codingPath.map { $0.stringValue }, [ - "paths", - "/hello/world", - "get", - "responses", - "200" - ]) - } - } - func test_badResponseExtension() { let documentYML = """ diff --git a/Tests/OpenAPIKitTests/Response/ResponseTests.swift b/Tests/OpenAPIKitTests/Response/ResponseTests.swift index 1f4367ff7..0d85c85ae 100644 --- a/Tests/OpenAPIKitTests/Response/ResponseTests.swift +++ b/Tests/OpenAPIKitTests/Response/ResponseTests.swift @@ -25,6 +25,28 @@ final class ResponseTests: XCTestCase { XCTAssertEqual(r2.description, "") XCTAssertEqual(r2.headers?["hello"]?.headerValue, header) XCTAssertEqual(r2.content, [.json: content]) + XCTAssertEqual(r2.conditionalWarnings.count, 0) + + // two OAS 3.2.0 warnings: summary is used and description is not + let r3 = OpenAPI.Response(summary: "", + content: [:]) + XCTAssertEqual(r3.summary, "") + XCTAssertNil(r3.description) + XCTAssertEqual(r3.conditionalWarnings.count, 2) + + // one OAS 3.2.0 warnings: summary is used + let r4 = OpenAPI.Response(summary: "", + description: "", + content: [:]) + XCTAssertEqual(r4.summary, "") + XCTAssertEqual(r4.description, "") + XCTAssertEqual(r4.conditionalWarnings.count, 1) + + // one OAS 3.2.0 warnings: description is not used + let r5 = OpenAPI.Response(content: [:]) + XCTAssertNil(r5.summary) + XCTAssertNil(r5.description) + XCTAssertEqual(r5.conditionalWarnings.count, 1) } func test_responseMap() { @@ -122,6 +144,18 @@ extension ResponseTests { } """ ) + + let response3 = OpenAPI.Response(summary: "", content: [:]) + let encodedResponse3 = try! orderUnstableTestStringFromEncoding(of: response3) + + assertJSONEquivalent( + encodedResponse3, + """ + { + "summary" : "" + } + """ + ) } func test_emptyDescriptionEmptyContent_decode() { @@ -157,6 +191,16 @@ extension ResponseTests { let response3 = try! orderUnstableDecode(OpenAPI.Response.self, from: responseData3) XCTAssertEqual(response3, OpenAPI.Response(description: "", headers: [:], content: [:])) + + let responseData4 = + """ + { + "summary" : "" + } + """.data(using: .utf8)! + let response4 = try! orderUnstableDecode(OpenAPI.Response.self, from: responseData4) + + XCTAssertEqual(response4, OpenAPI.Response(summary: "", content: [:])) } func test_populatedDescriptionPopulatedContent_encode() { From a9a85de699527f5656326081e0fb0ff7daca6c0a Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 11 Nov 2025 08:54:15 -0600 Subject: [PATCH 26/30] update migration guide --- documentation/migration_guides/v5_migration_guide.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/documentation/migration_guides/v5_migration_guide.md b/documentation/migration_guides/v5_migration_guide.md index 54eac43e9..0a94ebf12 100644 --- a/documentation/migration_guides/v5_migration_guide.md +++ b/documentation/migration_guides/v5_migration_guide.md @@ -159,6 +159,13 @@ specification) in this section. A new `cookie` style has been added. Code that exhaustively switches on the `OpenAPI.Parameter.SchemaContext.Style` enum will need to be updated. +### Response Objects +There are no breaking changes for the `OpenAPIKit30` module (OAS 3.0.x +specification) in this section. + +The Response Object `description` field is not optional so code may need to +change to account for it possibly being `nil`. + ### 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 From 0cd62a51a2bb954cf99c6f8779c63d6cf21848df Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Thu, 13 Nov 2025 10:17:14 -0600 Subject: [PATCH 27/30] allow components object to contain references in its entries --- .../Components+JSONReference.swift | 265 +++++++++++++++--- .../Components+Locatable.swift | 22 +- .../Components Object/Components.swift | 49 ++-- Sources/OpenAPIKit/JSONReference.swift | 21 +- Sources/OpenAPIKitCompat/Compat30To31.swift | 16 +- 5 files changed, 297 insertions(+), 76 deletions(-) diff --git a/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift b/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift index 0ca1f5caa..67e46a97e 100644 --- a/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift +++ b/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift @@ -10,30 +10,36 @@ import OpenAPIKitCore extension OpenAPI.Components { /// Check if the `Components` contains the given reference or not. /// - /// Look up a reference in this components dictionary. If you want a - /// non-throwing alternative, you can pull a `JSONReference.InternalReference` - /// out of the `reference` (which is of type `JSONReference`) and pass that to `contains` - /// instead. + /// This may in some cases mean that the `Components` entry for the given + /// reference is itself another reference (e.g. entries in the `responses` + /// dictionary are allowed to be references). + /// + /// If you want a non-throwing alternative, you can pull a + /// `JSONReference.InternalReference` out of the `reference` and pass that + /// to `contains` instead. /// /// - Throws: If the given reference cannot be checked against `Components` /// then this method will throw `ReferenceError`. This will occur when /// the given reference is a remote file reference. - public func contains(_ reference: OpenAPI.Reference) throws -> Bool { + public func contains(_ reference: OpenAPI.Reference) throws -> Bool { return try contains(reference.jsonReference) } /// Check if the `Components` contains the given reference or not. /// - /// Look up a reference in this components dictionary. If you want a - /// non-throwing alternative, you can pull a `JSONReference.InternalReference` - /// out of your `JSONReference` and pass that to `contains` - /// instead. + /// This may in some cases mean that the `Components` entry for the given + /// reference is itself another reference (e.g. entries in the `responses` + /// dictionary are allowed to be references). + /// + /// If you want a non-throwing alternative, you can pull a + /// `JSONReference.InternalReference` out of your `reference` and pass that + /// to `contains` instead. /// /// - Throws: If the given reference cannot be checked against `Components` /// then this method will throw `ReferenceError`. This will occur when /// the given reference is a remote file reference. - public func contains(_ reference: JSONReference) throws -> Bool { + public func contains(_ reference: JSONReference) throws -> Bool { guard case .internal(let localReference) = reference else { throw ReferenceError.cannotLookupRemoteReference } @@ -42,16 +48,34 @@ extension OpenAPI.Components { } /// Check if the `Components` contains the given internal reference or not. - public func contains(_ reference: JSONReference.InternalReference) -> Bool { - return reference.name - .flatMap(OpenAPI.ComponentKey.init(rawValue:)) - .map { self[keyPath: ReferenceType.openAPIComponentsKeyPath].contains(key: $0) } - ?? false + /// + /// This may in some cases mean that the `Components` entry for the given + /// reference is itself another reference (e.g. entries in the `responses` + /// dictionary are allowed to be references). + public func contains(_ reference: JSONReference.InternalReference) -> Bool { + switch ReferenceType.openAPIComponentsKeyPath { + case .a(let directPath): + return reference.name + .flatMap(OpenAPI.ComponentKey.init(rawValue:)) + .map { self[keyPath: directPath].contains(key: $0) } + ?? false + case .b(let referencePath): + return reference.name + .flatMap(OpenAPI.ComponentKey.init(rawValue:)) + .map { self[keyPath: referencePath].contains(key: $0) } + ?? false + } } - /// Retrieve a referenced item from the `Components` or - /// just return the item directly depending on what value - /// the `Either` contains. + /// Retrieve a referenced item from the `Components` or just return the + /// item directly depending on what value the `Either` contains. + /// + /// This function will follow subsequent refernences found within the + /// `Components` as long as no cycles are encountered. If a cycle is + /// encountered or a reference to a part of the document outside of the + /// `Components` is encountered then the function returns `nil`. + /// + /// If you want a throwing lookup, use the `lookup()` method. public subscript(_ maybeReference: Either, ReferenceType>) -> ReferenceType? { switch maybeReference { case .a(let reference): @@ -63,6 +87,11 @@ extension OpenAPI.Components { /// Retrieve item referenced from the `Components`. /// + /// This function will follow subsequent refernences found within the + /// `Components` as long as no cycles are encountered. If a cycle is + /// encountered or a reference to a part of the document outside of the + /// `Components` is encountered then the function returns `nil`. + /// /// If you want a throwing lookup, use the `lookup()` method. public subscript(_ reference: OpenAPI.Reference) -> ReferenceType? { @@ -71,6 +100,11 @@ extension OpenAPI.Components { /// Retrieve item referenced from the `Components`. /// + /// This function will follow subsequent refernences found within the + /// `Components` as long as no cycles are encountered. If a cycle is + /// encountered or a reference to a part of the document outside of the + /// `Components` is encountered then the function returns `nil`. + /// /// If you want a throwing lookup, use the `lookup()` method. public subscript(_ reference: JSONReference) -> ReferenceType? { guard case .internal(let localReference) = reference else { @@ -82,11 +116,57 @@ extension OpenAPI.Components { /// Retrieve item referenced from the `Components`. /// + /// This function will follow subsequent refernences found within the + /// `Components` as long as no cycles are encountered. If a cycle is + /// encountered or a reference to a part of the document outside of the + /// `Components` is encountered then the function returns `nil`. + /// /// If you want a throwing lookup, use the `lookup()` method. public subscript(_ reference: JSONReference.InternalReference) -> ReferenceType? { - return reference.name - .flatMap(OpenAPI.ComponentKey.init(rawValue:)) - .flatMap { self[keyPath: ReferenceType.openAPIComponentsKeyPath][$0] } + return try? lookup(reference) + } + + /// Pass a reference to a component. + /// `lookupOnce()` will return the component value if it is found + /// in the Components Object. + /// + /// The value may itself be a reference. If you want to follow all + /// references until the ReferenceType is found, use `lookup()`. + /// + /// If you want to look something up without throwing, you might want to use the subscript + /// operator on the `Components`. + /// + /// If you also want to fully dereference the value in question instead + /// of just looking it up see the various `dereference` functions + /// on this type for more information. + /// + /// If the `OpenAPI.Reference` has a `summary` or `description` then the referenced + /// object will have its `summary` and/or `description` overridden by that of the reference. + /// This only applies if the referenced object would normally have a summary/description. + /// + /// - Important: Looking up an external reference (i.e. one that points to another file) + /// is not currently supported by OpenAPIKit and will therefore always throw an error. + /// + /// - Throws: `ReferenceError.cannotLookupRemoteReference` or + /// `ReferenceError.missingOnLookup(name:,key:)` + public func lookupOnce(_ reference: OpenAPI.Reference) throws -> Either, ReferenceType> { + let value = try lookupOnce(reference.jsonReference) + + switch value { + case .a(let reference): + return .a( + reference + .overriddenNonNil(summary: reference.summary) + .overriddenNonNil(description: reference.description) + ) + + case .b(let direct): + return .b( + direct + .overriddenNonNil(summary: reference.summary) + .overriddenNonNil(description: reference.description) + ) + } } /// Pass a reference to a component. @@ -108,9 +188,8 @@ extension OpenAPI.Components { /// is not currently supported by OpenAPIKit and will therefore always throw an error. /// /// - Throws: `ReferenceError.cannotLookupRemoteReference` or - /// `MissingReferenceError.referenceMissingOnLookup(name:)` depending - /// on whether the reference points to another file or just points to a component in - /// the same file that cannot be found in the Components Object. + /// `ReferenceError.missingOnLookup(name:,key:)` or + /// `ReferenceCycleError` public func lookup(_ reference: OpenAPI.Reference) throws -> ReferenceType { return try lookup(reference.jsonReference) @@ -118,6 +197,32 @@ extension OpenAPI.Components { .overriddenNonNil(description: reference.description) } + /// Pass a reference to a component. + /// `lookupOnce()` will return the component value if it is found + /// in the Components Object. + /// + /// The value may itself be a reference. If you want to follow all + /// references until the ReferenceType is found, use `lookup()`. + /// + /// If you want to look something up without throwing, you might want to use the subscript + /// operator on the `Components`. + /// + /// If you also want to fully dereference the value in question instead + /// of just looking it up see the various `dereference` functions + /// on this type for more information. + /// + /// - Important: Looking up an external reference (i.e. one that points to another file) + /// is not currently supported by OpenAPIKit and will therefore always throw an error. + /// + /// - Throws: `ReferenceError.cannotLookupRemoteReference` or + /// `ReferenceError.missingOnLookup(name:,key:)` + public func lookupOnce(_ reference: JSONReference) throws -> Either, ReferenceType> { + guard case let .internal(internalReference) = reference else { + throw ReferenceError.cannotLookupRemoteReference + } + return try lookupOnce(internalReference) + } + /// Pass a reference to a component. /// `lookup()` will return the component value if it is found /// in the Components Object. @@ -133,19 +238,116 @@ extension OpenAPI.Components { /// is not currently supported by OpenAPIKit and will therefore always throw an error. /// /// - Throws: `ReferenceError.cannotLookupRemoteReference` or - /// `MissingReferenceError.referenceMissingOnLookup(name:)` depending - /// on whether the reference points to another file or just points to a component in - /// the same file that cannot be found in the Components Object. + /// `ReferenceError.missingOnLookup(name:,key:)` or + /// `ReferenceCycleError` public func lookup(_ reference: JSONReference) throws -> ReferenceType { - guard case .internal = reference else { + guard case let .internal(internalReference) = reference else { throw ReferenceError.cannotLookupRemoteReference } - guard let value = self[reference] else { + return try lookup(internalReference) + } + + internal func _lookup(_ reference: JSONReference, following visitedReferences: Set = .init()) throws -> ReferenceType { + guard case let .internal(internalReference) = reference else { + throw ReferenceError.cannotLookupRemoteReference + } + return try _lookup(internalReference, following: visitedReferences) + } + + /// Pass a reference to a component. + /// `lookupOnce()` will return the component value if it is found + /// in the Components Object. + /// + /// The value may itself be a reference. If you want to follow all + /// references until the ReferenceType is found, use `lookup()`. + /// + /// If you want to look something up without throwing, you might want to use the subscript + /// operator on the `Components`. + /// + /// If you also want to fully dereference the value in question instead + /// of just looking it up see the various `dereference` functions + /// on this type for more information. + /// + /// - Important: Looking up an external reference (i.e. one that points to another file) + /// is not currently supported by OpenAPIKit and will therefore always throw an error. + /// + /// - Throws: `ReferenceError.cannotLookupRemoteReference` or + /// `ReferenceError.missingOnLookup(name:,key:)` + public func lookupOnce(_ reference: JSONReference.InternalReference) throws -> Either, ReferenceType> { + let value: Either, ReferenceType>? + switch ReferenceType.openAPIComponentsKeyPath { + case .a(let directPath): + value = reference.name + .flatMap(OpenAPI.ComponentKey.init(rawValue:)) + .flatMap { self[keyPath: directPath][$0] } + .map { .b($0) } + + case .b(let referencePath): + value = reference.name + .flatMap(OpenAPI.ComponentKey.init(rawValue:)) + .flatMap { self[keyPath: referencePath][$0] } + } + guard let value else { throw ReferenceError.missingOnLookup(name: reference.name ?? "unnamed", key: ReferenceType.openAPIComponentsKey) } return value } + /// Pass a reference to a component. + /// `lookup()` will return the component value if it is found + /// in the Components Object. + /// + /// If you want to look something up without throwing, you might want to use the subscript + /// operator on the `Components`. + /// + /// If you also want to fully dereference the value in question instead + /// of just looking it up see the various `dereference` functions + /// on this type for more information. + /// + /// - Important: Looking up an external reference (i.e. one that points to another file) + /// is not currently supported by OpenAPIKit and will therefore always throw an error. + /// + /// - Throws: `ReferenceError.cannotLookupRemoteReference` or + /// `ReferenceError.missingOnLookup(name:,key:)` or + /// `ReferenceCycleError` + public func lookup(_ reference: JSONReference.InternalReference) throws -> ReferenceType { + return try _lookup(reference) + } + + internal func _lookup(_ reference: JSONReference.InternalReference, following visitedReferences: Set = .init()) throws -> ReferenceType { + if visitedReferences.contains(reference) { + throw ReferenceCycleError(ref: reference.rawValue) + } + + switch ReferenceType.openAPIComponentsKeyPath { + case .a(let directPath): + let value: ReferenceType? = reference.name + .flatMap(OpenAPI.ComponentKey.init(rawValue:)) + .flatMap { self[keyPath: directPath][$0] } + + guard let value else { + throw ReferenceError.missingOnLookup(name: reference.name ?? "unnamed", key: ReferenceType.openAPIComponentsKey) + } + return value + + case .b(let referencePath): + let possibleValue: Either, ReferenceType>? = reference.name + .flatMap(OpenAPI.ComponentKey.init(rawValue:)) + .flatMap { self[keyPath: referencePath][$0] } + + guard let possibleValue else { + throw ReferenceError.missingOnLookup(name: reference.name ?? "unnamed", key: ReferenceType.openAPIComponentsKey) + } + + switch possibleValue { + case .a(let newReference): + return try _lookup(newReference.jsonReference, following: visitedReferences.union([reference])) + case .b(let value): + return value + } + } + } + /// Pass an `Either` with a reference or a component. /// `lookup()` will return the component value if it is found /// in the Components Object. @@ -161,9 +363,8 @@ extension OpenAPI.Components { /// is not currently supported by OpenAPIKit and will therefore always throw an error. /// /// - Throws: `ReferenceError.cannotLookupRemoteReference` or - /// `MissingReferenceError.referenceMissingOnLookup(name:)` depending - /// on whether the reference points to another file or just points to a component in - /// the same file that cannot be found in the Components Object. + /// `ReferenceError.missingOnLookup(name:,key:)` or + /// `ReferenceCycleError` public func lookup(_ maybeReference: Either, ReferenceType>) throws -> ReferenceType { switch maybeReference { case .a(let reference): diff --git a/Sources/OpenAPIKit/Components Object/Components+Locatable.swift b/Sources/OpenAPIKit/Components Object/Components+Locatable.swift index c1a56f0f0..441ba805f 100644 --- a/Sources/OpenAPIKit/Components Object/Components+Locatable.swift +++ b/Sources/OpenAPIKit/Components Object/Components+Locatable.swift @@ -16,57 +16,57 @@ public protocol ComponentDictionaryLocatable: SummaryOverridable { /// This can be used to create a JSON path /// like `#/name1/name2/name3` static var openAPIComponentsKey: String { get } - static var openAPIComponentsKeyPath: WritableKeyPath> { get } + static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { get } } extension JSONSchema: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "schemas" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.schemas } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .a(\.schemas) } } extension OpenAPI.Response: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "responses" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.responses } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.responses) } } extension OpenAPI.Callbacks: ComponentDictionaryLocatable & SummaryOverridable { public static var openAPIComponentsKey: String { "callbacks" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.callbacks } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.callbacks) } } extension OpenAPI.Parameter: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "parameters" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.parameters } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.parameters) } } extension OpenAPI.Example: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "examples" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.examples } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.examples) } } extension OpenAPI.Request: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "requestBodies" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.requestBodies } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.requestBodies) } } extension OpenAPI.Header: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "headers" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.headers } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.headers) } } extension OpenAPI.SecurityScheme: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "securitySchemes" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.securitySchemes } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.securitySchemes) } } extension OpenAPI.Link: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "links" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.links } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .b(\.links) } } extension OpenAPI.PathItem: ComponentDictionaryLocatable { public static var openAPIComponentsKey: String { "pathItems" } - public static var openAPIComponentsKeyPath: WritableKeyPath> { \.pathItems } + public static var openAPIComponentsKeyPath: Either>, WritableKeyPath>> { .a(\.pathItems) } } /// A dereferenceable type can be recursively looked up in diff --git a/Sources/OpenAPIKit/Components Object/Components.swift b/Sources/OpenAPIKit/Components Object/Components.swift index 284ca030f..3218b1342 100644 --- a/Sources/OpenAPIKit/Components Object/Components.swift +++ b/Sources/OpenAPIKit/Components Object/Components.swift @@ -18,14 +18,14 @@ extension OpenAPI { public struct Components: Equatable, CodableVendorExtendable, Sendable { public var schemas: ComponentDictionary - public var responses: ComponentDictionary - public var parameters: ComponentDictionary - public var examples: ComponentDictionary - public var requestBodies: ComponentDictionary - public var headers: ComponentDictionary
- public var securitySchemes: ComponentDictionary - public var links: ComponentDictionary - public var callbacks: ComponentDictionary + public var responses: ComponentReferenceDictionary + public var parameters: ComponentReferenceDictionary + public var examples: ComponentReferenceDictionary + public var requestBodies: ComponentReferenceDictionary + public var headers: ComponentReferenceDictionary
+ public var securitySchemes: ComponentReferenceDictionary + public var links: ComponentReferenceDictionary + public var callbacks: ComponentReferenceDictionary public var pathItems: ComponentDictionary @@ -38,14 +38,14 @@ extension OpenAPI { public init( schemas: ComponentDictionary = [:], - responses: ComponentDictionary = [:], - parameters: ComponentDictionary = [:], - examples: ComponentDictionary = [:], - requestBodies: ComponentDictionary = [:], - headers: ComponentDictionary
= [:], - securitySchemes: ComponentDictionary = [:], - links: ComponentDictionary = [:], - callbacks: ComponentDictionary = [:], + responses: ComponentReferenceDictionary = [:], + parameters: ComponentReferenceDictionary = [:], + examples: ComponentReferenceDictionary = [:], + requestBodies: ComponentReferenceDictionary = [:], + headers: ComponentReferenceDictionary
= [:], + securitySchemes: ComponentReferenceDictionary = [:], + links: ComponentReferenceDictionary = [:], + callbacks: ComponentReferenceDictionary = [:], pathItems: ComponentDictionary = [:], vendorExtensions: [String: AnyCodable] = [:] ) { @@ -133,6 +133,7 @@ extension OpenAPI.Components { extension OpenAPI { public typealias ComponentDictionary = OrderedDictionary + public typealias ComponentReferenceDictionary = OrderedDictionary, T>> } // MARK: - Codable @@ -194,26 +195,26 @@ extension OpenAPI.Components: Decodable { schemas = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .schemas) ?? [:] - responses = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .responses) + responses = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .responses) ?? [:] - parameters = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .parameters) + parameters = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .parameters) ?? [:] - examples = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .examples) + examples = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .examples) ?? [:] - requestBodies = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .requestBodies) + requestBodies = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .requestBodies) ?? [:] - headers = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .headers) + headers = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .headers) ?? [:] - securitySchemes = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .securitySchemes) ?? [:] + securitySchemes = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .securitySchemes) ?? [:] - links = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .links) ?? [:] + links = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .links) ?? [:] - callbacks = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .callbacks) ?? [:] + callbacks = try container.decodeIfPresent(OpenAPI.ComponentReferenceDictionary.self, forKey: .callbacks) ?? [:] pathItems = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .pathItems) ?? [:] diff --git a/Sources/OpenAPIKit/JSONReference.swift b/Sources/OpenAPIKit/JSONReference.swift index 4966193d1..bc7c8a502 100644 --- a/Sources/OpenAPIKit/JSONReference.swift +++ b/Sources/OpenAPIKit/JSONReference.swift @@ -428,6 +428,20 @@ public protocol OpenAPISummarizable: OpenAPIDescribable { func overriddenNonNil(summary: String?) -> Self } +extension OpenAPI.Reference: OpenAPISummarizable { + public func overriddenNonNil(summary: String?) -> Self { + guard let summary else { return self } + + return .init(jsonReference, summary: summary, description: description) + } + + public func overriddenNonNil(description: String?) -> Self { + guard let description else { return self } + + return .init(jsonReference, summary: summary, description: description) + } +} + // MARK: - Codable extension JSONReference { @@ -558,7 +572,12 @@ extension JSONReference: ExternallyDereferenceable where ReferenceType: External let componentKey = try loader.componentKey(type: ReferenceType.self, at: url) let (component, messages): (ReferenceType, [Loader.Message]) = try await loader.load(url) var components = OpenAPI.Components() - components[keyPath: ReferenceType.openAPIComponentsKeyPath][componentKey] = component + switch ReferenceType.openAPIComponentsKeyPath { + case .a(let directPath): + components[keyPath: directPath][componentKey] = component + case .b(let referencePath): + components[keyPath: referencePath][componentKey] = .b(component) + } return (try components.reference(named: componentKey.rawValue, ofType: ReferenceType.self).jsonReference, components, messages) } } diff --git a/Sources/OpenAPIKitCompat/Compat30To31.swift b/Sources/OpenAPIKitCompat/Compat30To31.swift index a80d74b3c..2ab98b06c 100644 --- a/Sources/OpenAPIKitCompat/Compat30To31.swift +++ b/Sources/OpenAPIKitCompat/Compat30To31.swift @@ -652,14 +652,14 @@ extension OpenAPIKit30.OpenAPI.Components: To31 { fileprivate func to31() -> OpenAPIKit.OpenAPI.Components { OpenAPIKit.OpenAPI.Components( schemas: schemas.mapValues { $0.to31() }, - responses: responses.mapValues { $0.to31() }, - parameters: parameters.mapValues { $0.to31() }, - examples: examples.mapValues { $0.to31() }, - requestBodies: requestBodies.mapValues { $0.to31() }, - headers: headers.mapValues { $0.to31() }, - securitySchemes: securitySchemes.mapValues { $0.to31() }, - links: links.mapValues { $0.to31() }, - callbacks: callbacks.mapValues { $0.to31() }, + responses: responses.mapValues { .b($0.to31()) }, + parameters: parameters.mapValues { .b($0.to31()) }, + examples: examples.mapValues { .b($0.to31()) }, + requestBodies: requestBodies.mapValues { .b($0.to31()) }, + headers: headers.mapValues { .b($0.to31()) }, + securitySchemes: securitySchemes.mapValues { .b($0.to31()) }, + links: links.mapValues { .b($0.to31()) }, + callbacks: callbacks.mapValues { .b($0.to31()) }, vendorExtensions: vendorExtensions ) } From e83da2a62a6054ba2504c678bf574c2c544906b0 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Mon, 17 Nov 2025 10:59:56 -0600 Subject: [PATCH 28/30] add new direct convenience constructor, update tests, add documentation --- .../Components+JSONReference.swift | 2 +- .../Components Object/Components.swift | 79 ++++++++- .../Either/Either+Convenience.swift | 25 +++ .../OpenAPIDecodingErrors.swift | 4 +- .../DocumentConversionTests.swift | 52 ++++-- Tests/OpenAPIKitTests/ComponentsTests.swift | 150 +++++++++++++++++- .../Content/DereferencedContentTests.swift | 6 +- .../Document/DereferencedDocumentTests.swift | 4 +- .../Document/DocumentTests.swift | 4 +- .../Document/ResolvedDocumentTests.swift | 2 +- Tests/OpenAPIKitTests/EaseOfUseTests.swift | 8 +- .../OpenAPIReferenceTests.swift | 2 +- .../DereferencedOperationTests.swift | 10 +- .../Operation/ResolvedEndpointTests.swift | 8 +- .../DereferencedSchemaContextTests.swift | 4 +- .../Path Item/DereferencedPathItemTests.swift | 24 +-- .../Response/DereferencedResponseTests.swift | 4 +- .../DereferencedSchemaObjectTests.swift | 2 +- .../Validator/BuiltinValidationTests.swift | 6 +- .../Validation+ConvenienceTests.swift | 4 +- 20 files changed, 330 insertions(+), 70 deletions(-) diff --git a/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift b/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift index 67e46a97e..fc709c9b2 100644 --- a/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift +++ b/Sources/OpenAPIKit/Components Object/Components+JSONReference.swift @@ -416,7 +416,7 @@ extension OpenAPI.Components { public let ref: String public var description: String { - return "Encountered a JSON Schema $ref cycle that prevents fully dereferencing document at '\(ref)'. This type of reference cycle is not inherently problematic for JSON Schemas, but it does mean OpenAPIKit cannot fully resolve references because attempting to do so results in an infinite loop over any reference cycles. You should still be able to parse the document, just avoid requesting a `locallyDereferenced()` copy." + return "Encountered a JSON Schema $ref cycle that prevents fully resolving a reference at '\(ref)'. This type of reference cycle is not inherently problematic for JSON Schemas, but it does mean OpenAPIKit cannot fully resolve references because attempting to do so results in an infinite loop over any reference cycles. You should still be able to parse the document, just avoid requesting a `locallyDereferenced()` copy or fully looking up references in cycles. `lookupOnce()` is your best option in this case." } public var localizedDescription: String { diff --git a/Sources/OpenAPIKit/Components Object/Components.swift b/Sources/OpenAPIKit/Components Object/Components.swift index 3218b1342..035644c43 100644 --- a/Sources/OpenAPIKit/Components Object/Components.swift +++ b/Sources/OpenAPIKit/Components Object/Components.swift @@ -15,6 +15,36 @@ extension OpenAPI { /// /// This is a place to put reusable components to /// be referenced from other parts of the spec. + /// + /// Most of the components dictionaries can contain either the component + /// directly or a $ref to the component. This distinction can be seen in + /// the types as either `ComponentDictionary` (direct) or + /// `ComponentReferenceDictionary` (direct or by-reference). + /// + /// If you are building a Components Object in Swift you may choose to make + /// all of your components direct in which case the + /// `OpenAPI.Components.direct()` convenience constructor will save you + /// some typing and verbosity. + /// + /// **Example** + /// OpenAPI.Components( + /// parameters: [ "my_param": .parameter(.cookie(name: "my_param", schema: .string)) ] + /// ) + /// + /// // The above value is the same as the below value + /// + /// OpenAPI.Components.direct( + /// parameters: [ "my_param": .cookie(name: "my_param", schema: .string) ] + /// ) + /// + /// // However, the `init()` initializer does allow you to use references where desired + /// + /// OpenAPI.Components( + /// parameters: [ + /// "my_direct_param": .parameter(.cookie(name: "my_param", schema: .string)), + /// "my_param": .reference(.component(named: "my_direct_param")) + /// ] + /// ) public struct Components: Equatable, CodableVendorExtendable, Sendable { public var schemas: ComponentDictionary @@ -62,6 +92,37 @@ extension OpenAPI { self.vendorExtensions = vendorExtensions } + /// Construct components as "direct" entries (no references). When + /// building a document in Swift code, this is often sufficient and it + /// means you don't need to wrap every entry in an `Either`. + public static func direct( + schemas: ComponentDictionary = [:], + responses: ComponentDictionary = [:], + parameters: ComponentDictionary = [:], + examples: ComponentDictionary = [:], + requestBodies: ComponentDictionary = [:], + headers: ComponentDictionary
= [:], + securitySchemes: ComponentDictionary = [:], + links: ComponentDictionary = [:], + callbacks: ComponentDictionary = [:], + pathItems: ComponentDictionary = [:], + vendorExtensions: [String: AnyCodable] = [:] + ) -> Self { + .init( + schemas: schemas, + responses: responses.mapValues { .b($0) }, + parameters: parameters.mapValues { .b($0) }, + examples: examples.mapValues { .b($0) }, + requestBodies: requestBodies.mapValues { .b($0) }, + headers: headers.mapValues { .b($0) }, + securitySchemes: securitySchemes.mapValues { .b($0) }, + links: links.mapValues { .b($0) }, + callbacks: callbacks.mapValues { .b($0) }, + pathItems: pathItems, + vendorExtensions: vendorExtensions + ) + } + /// An empty OpenAPI Components Object. public static let noComponents: Components = .init() @@ -71,6 +132,12 @@ extension OpenAPI { } } +extension OpenAPI { + + public typealias ComponentDictionary = OrderedDictionary + public typealias ComponentReferenceDictionary = OrderedDictionary, T>> +} + extension OpenAPI.Components { public struct ComponentCollision: Swift.Error { public let componentType: String @@ -130,12 +197,6 @@ extension OpenAPI.Components { public static let componentNameExtension: String = "x-component-name" } -extension OpenAPI { - - public typealias ComponentDictionary = OrderedDictionary - public typealias ComponentReferenceDictionary = OrderedDictionary, T>> -} - // MARK: - Codable extension OpenAPI.Components: Encodable { public func encode(to encoder: Encoder) throws { @@ -219,6 +280,12 @@ extension OpenAPI.Components: Decodable { pathItems = try container.decodeIfPresent(OpenAPI.ComponentDictionary.self, forKey: .pathItems) ?? [:] vendorExtensions = try Self.extensions(from: decoder) + } catch let error as EitherDecodeNoTypesMatchedError { + if let underlyingError = OpenAPI.Error.Decoding.Document.eitherBranchToDigInto(error) { + throw (underlyingError.underlyingError ?? underlyingError) + } + + throw error } catch let error as DecodingError { if let underlyingError = error.underlyingError as? KeyDecodingError { throw GenericError( diff --git a/Sources/OpenAPIKit/Either/Either+Convenience.swift b/Sources/OpenAPIKit/Either/Either+Convenience.swift index f9cd238dc..bbc414460 100644 --- a/Sources/OpenAPIKit/Either/Either+Convenience.swift +++ b/Sources/OpenAPIKit/Either/Either+Convenience.swift @@ -131,6 +131,16 @@ extension Either where B == OpenAPI.Header { public var headerValue: B? { b } } +extension Either where B == OpenAPI.Callbacks { + /// Retrieve the callbacks if that is what this property contains. + public var callbacksValue: B? { b } +} + +extension Either where B == OpenAPI.SecurityScheme { + /// Retrieve the security scheme if that is what this property contains. + public var securitySchemeValue: B? { b } +} + // MARK: - Convenience constructors extension Either where A == Bool { /// Construct a boolean value. @@ -220,7 +230,22 @@ extension Either where B == OpenAPI.Response { public static func response(_ response: OpenAPI.Response) -> Self { .b(response) } } +extension Either where B == OpenAPI.Link { + /// Construct a link value. + public static func link(_ link: OpenAPI.Link) -> Self { .b(link) } +} + extension Either where B == OpenAPI.Header { /// Construct a header value. public static func header(_ header: OpenAPI.Header) -> Self { .b(header) } } + +extension Either where B == OpenAPI.Callbacks { + /// Construct a callbacks value. + public static func callbacks(_ callbacks: OpenAPI.Callbacks) -> Self { .b(callbacks) } +} + +extension Either where B == OpenAPI.SecurityScheme { + /// Construct a security scheme value. + public static func securityScheme(_ securityScheme: OpenAPI.SecurityScheme) -> Self { .b(securityScheme) } +} diff --git a/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIDecodingErrors.swift b/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIDecodingErrors.swift index 4111ab04c..760122c9d 100644 --- a/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIDecodingErrors.swift +++ b/Sources/OpenAPIKitCore/Encoding and Decoding Errors And Warnings/OpenAPIDecodingErrors.swift @@ -10,7 +10,7 @@ extension Error { public enum Decoding {} } -public enum ErrorCategory { +public enum ErrorCategory: Sendable { /// The type with the given name was expected but not found. case typeMismatch(expectedTypeName: String) /// One of two possible types were expected but neither was found. @@ -22,7 +22,7 @@ public enum ErrorCategory { /// Something inconsistent or disallowed according the OpenAPI Specification was found. case inconsistency(details: String) - public enum KeyValue { + public enum KeyValue: Sendable { case key case value } diff --git a/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift b/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift index 11a0c75b0..9568e15e1 100644 --- a/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift +++ b/Tests/OpenAPIKitCompatTests/DocumentConversionTests.swift @@ -834,8 +834,8 @@ final class DocumentConversionTests: XCTestCase { try assertEqualNewToOld(newDoc,oldDoc) - let newParameter1 = try XCTUnwrap(newDoc.components.parameters["param1"]) - let newParameter2 = try XCTUnwrap(newDoc.components.parameters["param2"]) + let newParameter1 = try XCTUnwrap(newDoc.components.parameters["param1"]?.b) + let newParameter2 = try XCTUnwrap(newDoc.components.parameters["param2"]?.b) try assertEqualNewToOld(newParameter1, parameter1) try assertEqualNewToOld(newParameter2, parameter2) @@ -1497,36 +1497,68 @@ fileprivate func assertEqualNewToOld(_ newComponents: OpenAPIKit.OpenAPI.Compone let oldSchema = try XCTUnwrap(oldComponents.schemas[key]) try assertEqualNewToOld(newSchema, oldSchema) } - for (key, newResponse) in newComponents.responses { + for (key, maybeNewResponse) in newComponents.responses { let oldResponse = try XCTUnwrap(oldComponents.responses[key]) + guard case let .b(newResponse) = maybeNewResponse else { + XCTFail("Found a reference to a response where one was not expected") + return + } try assertEqualNewToOld(newResponse, oldResponse) } - for (key, newParameter) in newComponents.parameters { + for (key, maybeNewParameter) in newComponents.parameters { let oldParameter = try XCTUnwrap(oldComponents.parameters[key]) + guard case let .b(newParameter) = maybeNewParameter else { + XCTFail("Found a reference to a parameter where one was not expected") + return + } try assertEqualNewToOld(newParameter, oldParameter) } - for (key, newExample) in newComponents.examples { + for (key, maybeNewExample) in newComponents.examples { let oldExample = try XCTUnwrap(oldComponents.examples[key]) + guard case let .b(newExample) = maybeNewExample else { + XCTFail("Found a reference to an example where one was not expected") + return + } assertEqualNewToOld(newExample, oldExample) } - for (key, newRequest) in newComponents.requestBodies { + for (key, maybeNewRequest) in newComponents.requestBodies { let oldRequest = try XCTUnwrap(oldComponents.requestBodies[key]) + guard case let .b(newRequest) = maybeNewRequest else { + XCTFail("Found a reference to a request where one was not expected") + return + } try assertEqualNewToOld(newRequest, oldRequest) } - for (key, newHeader) in newComponents.headers { + for (key, maybeNewHeader) in newComponents.headers { let oldHeader = try XCTUnwrap(oldComponents.headers[key]) + guard case let .b(newHeader) = maybeNewHeader else { + XCTFail("Found a reference to a header where one was not expected") + return + } try assertEqualNewToOld(newHeader, oldHeader) } - for (key, newSecurity) in newComponents.securitySchemes { + for (key, maybeNewSecurity) in newComponents.securitySchemes { let oldSecurity = try XCTUnwrap(oldComponents.securitySchemes[key]) + guard case let .b(newSecurity) = maybeNewSecurity else { + XCTFail("Found a reference to a security scheme where one was not expected") + return + } try assertEqualNewToOld(newSecurity, oldSecurity) } - for (key, newLink) in newComponents.links { + for (key, maybeNewLink) in newComponents.links { let oldLink = try XCTUnwrap(oldComponents.links[key]) + guard case let .b(newLink) = maybeNewLink else { + XCTFail("Found a reference to a link where one was not expected") + return + } try assertEqualNewToOld(newLink, oldLink) } - for (key, newCallbacks) in newComponents.callbacks { + for (key, maybeNewCallbacks) in newComponents.callbacks { let oldCallbacks = try XCTUnwrap(oldComponents.callbacks[key]) + guard case let .b(newCallbacks) = maybeNewCallbacks else { + XCTFail("Found a reference to a callbacks object where one was not expected") + return + } for (key, newCallback) in newCallbacks { let oldPathItem = try XCTUnwrap(oldCallbacks[key]) switch (newCallback) { diff --git a/Tests/OpenAPIKitTests/ComponentsTests.swift b/Tests/OpenAPIKitTests/ComponentsTests.swift index 8f603962b..3a7ad1d35 100644 --- a/Tests/OpenAPIKitTests/ComponentsTests.swift +++ b/Tests/OpenAPIKitTests/ComponentsTests.swift @@ -25,11 +25,111 @@ final class ComponentsTests: XCTestCase { XCTAssertFalse(c3.isEmpty) } + func test_directConstructor() { + let c1 = OpenAPI.Components( + schemas: [ + "one": .string + ], + responses: [ + "two": .response(.init(description: "hello", content: [:])) + ], + parameters: [ + "three": .parameter(.init(name: "hi", context: .query(content: [:]))) + ], + examples: [ + "four": .example(.init(value: .init(URL(string: "http://address.com")!))) + ], + requestBodies: [ + "five": .request(.init(content: [:])) + ], + headers: [ + "six": .header(.init(schema: .string)) + ], + securitySchemes: [ + "seven": .securityScheme(.http(scheme: "cool")) + ], + links: [ + "eight": .link(.init(operationId: "op1")) + ], + callbacks: [ + "nine": .callbacks([ + OpenAPI.CallbackURL(rawValue: "{$request.query.queryUrl}")!: .pathItem( + .init( + post: .init( + responses: [ + 200: .response( + description: "callback successfully processed" + ) + ] + ) + ) + ) + ]) + ], + pathItems: [ + "ten": .init(get: .init(responses: [200: .response(description: "response")])) + ], + vendorExtensions: ["x-specialFeature": .init(["hello", "world"])] + ) + + let c2 = OpenAPI.Components.direct( + schemas: [ + "one": .string + ], + responses: [ + "two": .init(description: "hello", content: [:]) + ], + parameters: [ + "three": .init(name: "hi", context: .query(content: [:])) + ], + examples: [ + "four": .init(value: .init(URL(string: "http://address.com")!)) + ], + requestBodies: [ + "five": .init(content: [:]) + ], + headers: [ + "six": .init(schema: .string) + ], + securitySchemes: [ + "seven": .http(scheme: "cool") + ], + links: [ + "eight": .init(operationId: "op1") + ], + callbacks: [ + "nine": [ + OpenAPI.CallbackURL(rawValue: "{$request.query.queryUrl}")!: .pathItem( + .init( + post: .init( + responses: [ + 200: .response( + description: "callback successfully processed" + ) + ] + ) + ) + ) + ] + ], + pathItems: [ + "ten": .init(get: .init(responses: [200: .response(description: "response")])) + ], + vendorExtensions: ["x-specialFeature": .init(["hello", "world"])] + ) + + XCTAssertEqual(c1, c2) + } + func test_referenceLookup() throws { let components = OpenAPI.Components( schemas: [ "hello": .string, "world": .integer(required: false) + ], + parameters: [ + "my_direct_param": .parameter(.cookie(name: "my_param", schema: .string)), + "my_param": .reference(.component(named: "my_direct_param")) ] ) @@ -50,11 +150,30 @@ final class ComponentsTests: XCTestCase { XCTAssertNil(components[ref5]) XCTAssertNil(components[ref6]) - let ref7 = JSONReference.external(URL(string: "hello.json")!) + let ref7 = JSONReference.component(named: "my_param") + + XCTAssertEqual(components[ref7], .cookie(name: "my_param", schema: .string)) + + let ref8 = JSONReference.external(URL(string: "hello.json")!) + + XCTAssertNil(components[ref8]) + + XCTAssertThrowsError(try components.contains(ref8)) + } + + func test_lookupOnce() throws { + let components = OpenAPI.Components( + parameters: [ + "my_direct_param": .parameter(.cookie(name: "my_param", schema: .string)), + "my_param": .reference(.component(named: "my_direct_param")) + ] + ) - XCTAssertNil(components[ref7]) + let ref1 = JSONReference.component(named: "my_param") + let ref2 = JSONReference.component(named: "my_direct_param") - XCTAssertThrowsError(try components.contains(ref7)) + XCTAssertEqual(try components.lookupOnce(ref1), .reference(.component(named: "my_direct_param"))) + XCTAssertEqual(try components.lookupOnce(ref2), .parameter(.cookie(name: "my_param", schema: .string))) } func test_failedExternalReferenceLookup() { @@ -91,7 +210,7 @@ final class ComponentsTests: XCTestCase { } func test_lookupEachType() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( schemas: [ "one": .string ], @@ -184,7 +303,10 @@ final class ComponentsTests: XCTestCase { "hello": .boolean ], links: [ - "linky": .init(operationId: "op 1") + "linky": .link(.init(operationId: "op 1")), + "linky_ref": .reference(.component(named: "linky")), + "cycle_start": .reference(.component(named: "cycle_end")), + "cycle_end": .reference(.component(named: "cycle_start")) ] ) @@ -214,6 +336,20 @@ final class ComponentsTests: XCTestCase { XCTAssertEqual((error as? OpenAPI.Components.ReferenceError)?.description, "Failed to look up a JSON Reference. 'hello' was not found in links.") } + let link2: Either, OpenAPI.Link> = .reference(.component(named: "linky")) + + XCTAssertEqual(try components.lookup(link2), .init(operationId: "op 1")) + + let link3: Either, OpenAPI.Link> = .reference(.component(named: "linky_ref")) + + XCTAssertEqual(try components.lookup(link3), .init(operationId: "op 1")) + + let link4: Either, OpenAPI.Link> = .reference(.component(named: "cycle_start")) + + XCTAssertThrowsError(try components.lookup(link4)) { error in + XCTAssertEqual((error as? OpenAPI.Components.ReferenceCycleError)?.description, "Encountered a JSON Schema $ref cycle that prevents fully resolving a reference at \'#/components/links/cycle_start\'. This type of reference cycle is not inherently problematic for JSON Schemas, but it does mean OpenAPIKit cannot fully resolve references because attempting to do so results in an infinite loop over any reference cycles. You should still be able to parse the document, just avoid requesting a `locallyDereferenced()` copy or fully looking up references in cycles. `lookupOnce()` is your best option in this case.") + } + let reference1: JSONReference = .component(named: "hello") let resolvedSchema2 = try components.lookup(reference1) @@ -276,7 +412,7 @@ extension ComponentsTests { } func test_maximal_encode() throws { - let t1 = OpenAPI.Components( + let t1 = OpenAPI.Components.direct( schemas: [ "one": .string ], @@ -498,7 +634,7 @@ extension ComponentsTests { XCTAssertEqual( decoded, - OpenAPI.Components( + OpenAPI.Components.direct( schemas: [ "one": .string ], diff --git a/Tests/OpenAPIKitTests/Content/DereferencedContentTests.swift b/Tests/OpenAPIKitTests/Content/DereferencedContentTests.swift index e3238b256..bf4ae9bb2 100644 --- a/Tests/OpenAPIKitTests/Content/DereferencedContentTests.swift +++ b/Tests/OpenAPIKitTests/Content/DereferencedContentTests.swift @@ -16,7 +16,7 @@ final class DereferencedContentTests: XCTestCase { } func test_oneExampleReferenced() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( examples: ["test": .init(value: .init("hello world"))] ) let t1 = try OpenAPI.Content( @@ -31,7 +31,7 @@ final class DereferencedContentTests: XCTestCase { } func test_multipleExamplesReferenced() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( examples: [ "test1": .init(value: .init("hello world")), "test2": .init(value: .a(URL(string: "http://website.com")!)) @@ -130,7 +130,7 @@ final class DereferencedContentTests: XCTestCase { } func test_referencedHeaderInEncoding() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( headers: [ "test": OpenAPI.Header(schema: .string) ] diff --git a/Tests/OpenAPIKitTests/Document/DereferencedDocumentTests.swift b/Tests/OpenAPIKitTests/Document/DereferencedDocumentTests.swift index 678223292..777b51e50 100644 --- a/Tests/OpenAPIKitTests/Document/DereferencedDocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/DereferencedDocumentTests.swift @@ -64,7 +64,7 @@ final class DereferencedDocumentTests: XCTestCase { } func test_noSecurityReferencedResponseInPath() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "test": .init(description: "success") ] @@ -92,7 +92,7 @@ final class DereferencedDocumentTests: XCTestCase { } func test_securityAndReferencedResponseInPath() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "test": .init(description: "success") ], diff --git a/Tests/OpenAPIKitTests/Document/DocumentTests.swift b/Tests/OpenAPIKitTests/Document/DocumentTests.swift index ce7d142e1..18d493db8 100644 --- a/Tests/OpenAPIKitTests/Document/DocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/DocumentTests.swift @@ -827,7 +827,7 @@ extension DocumentTests { info: .init(title: "API", version: "1.0"), servers: [], paths: [:], - components: .init( + components: .direct( securitySchemes: ["security": .init(type: .apiKey(name: "key", location: .header))] ), security: [[.component( named: "security"):[]]] @@ -902,7 +902,7 @@ extension DocumentTests { info: .init(title: "API", version: "1.0"), servers: [], paths: [:], - components: .init( + components: .direct( securitySchemes: ["security": .init(type: .apiKey(name: "key", location: .header))] ), security: [[.component( named: "security"):[]]] diff --git a/Tests/OpenAPIKitTests/Document/ResolvedDocumentTests.swift b/Tests/OpenAPIKitTests/Document/ResolvedDocumentTests.swift index 76aebf84b..06b538539 100644 --- a/Tests/OpenAPIKitTests/Document/ResolvedDocumentTests.swift +++ b/Tests/OpenAPIKitTests/Document/ResolvedDocumentTests.swift @@ -29,7 +29,7 @@ final class ResolvedDocumentTests: XCTestCase { } func test_documentWithSecurity() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( securitySchemes: [ "test": .apiKey(name: "api-key", location: .cookie) ] diff --git a/Tests/OpenAPIKitTests/EaseOfUseTests.swift b/Tests/OpenAPIKitTests/EaseOfUseTests.swift index d8ecabe81..b6e59547b 100644 --- a/Tests/OpenAPIKitTests/EaseOfUseTests.swift +++ b/Tests/OpenAPIKitTests/EaseOfUseTests.swift @@ -110,7 +110,7 @@ final class DeclarativeEaseOfUseTests: XCTestCase { ) ) ], - components: .init( + components: .direct( schemas: [ "string_schema": .string ], @@ -243,7 +243,7 @@ final class DeclarativeEaseOfUseTests: XCTestCase { post: testCREATE_endpoint ) - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( schemas: [ "string_schema": .string ], @@ -343,7 +343,7 @@ final class DeclarativeEaseOfUseTests: XCTestCase { } func test_securityRequirements() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( securitySchemes: [ "basic_auth": .init( type: .http(scheme: "basic", bearerFormat: nil), @@ -491,7 +491,7 @@ fileprivate let testWidgetSchema = JSONSchema.object( ] ) -fileprivate let testComponents = OpenAPI.Components( +fileprivate let testComponents = OpenAPI.Components.direct( schemas: [ "testWidgetSchema": testWidgetSchema ], diff --git a/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift b/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift index b192b1bbe..63110fe53 100644 --- a/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift +++ b/Tests/OpenAPIKitTests/OpenAPIReferenceTests.swift @@ -76,7 +76,7 @@ final class OpenAPIReferenceTests: XCTestCase { } func test_summaryAndDescriptionOverrides() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( schemas: [ "hello": .string(description: "description") ], diff --git a/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift b/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift index 1409cfa74..cc4cbc2c9 100644 --- a/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift +++ b/Tests/OpenAPIKitTests/Operation/DereferencedOperationTests.swift @@ -41,7 +41,7 @@ final class DereferencedOperationTests: XCTestCase { } func test_parameterReference() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( parameters: [ "test": .header( name: "test", @@ -77,7 +77,7 @@ final class DereferencedOperationTests: XCTestCase { } func test_requestReference() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( requestBodies: [ "test": OpenAPI.Request(content: [.json: .init(schema: .string)]) ] @@ -109,7 +109,7 @@ final class DereferencedOperationTests: XCTestCase { } func test_responseReference() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "test": .init(description: "test") ] @@ -139,7 +139,7 @@ final class DereferencedOperationTests: XCTestCase { } func test_securityReference() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( securitySchemes: ["requirement": .apiKey(name: "Api-Key", location: .header)] ) let t1 = try OpenAPI.Operation( @@ -163,7 +163,7 @@ final class DereferencedOperationTests: XCTestCase { } func test_dereferencedCallback() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( callbacks: [ "callback": [ OpenAPI.CallbackURL(rawValue: "{$url}")!: .pathItem( diff --git a/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift b/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift index dcac3c9bd..15e32f4fc 100644 --- a/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift +++ b/Tests/OpenAPIKitTests/Operation/ResolvedEndpointTests.swift @@ -302,7 +302,7 @@ final class ResolvedEndpointTests: XCTestCase { ] ) ], - components: .init( + components: .direct( securitySchemes: [ "secure1": .apiKey(name: "hi", location: .cookie), "secure2": .oauth2( @@ -357,7 +357,7 @@ final class ResolvedEndpointTests: XCTestCase { ] ) ], - components: .init( + components: .direct( securitySchemes: [ "secure1": .apiKey(name: "hi", location: .cookie), "secure2": .oauth2( @@ -411,7 +411,7 @@ final class ResolvedEndpointTests: XCTestCase { ] ) ], - components: .init( + components: .direct( securitySchemes: [ "secure1": .apiKey(name: "hi", location: .cookie), "secure2": .oauth2( @@ -510,7 +510,7 @@ final class ResolvedEndpointTests: XCTestCase { ] ) ], - components: .init( + components: .direct( securitySchemes: [ "secure1": .apiKey(name: "hi", location: .cookie), "secure2": .oauth2( diff --git a/Tests/OpenAPIKitTests/Parameter/DereferencedSchemaContextTests.swift b/Tests/OpenAPIKitTests/Parameter/DereferencedSchemaContextTests.swift index 5b6f7e85d..f7e07a8c0 100644 --- a/Tests/OpenAPIKitTests/Parameter/DereferencedSchemaContextTests.swift +++ b/Tests/OpenAPIKitTests/Parameter/DereferencedSchemaContextTests.swift @@ -22,7 +22,7 @@ final class DereferencedSchemaContextTests: XCTestCase { } func test_oneExampleReferenced() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( examples: ["test": .init(value: .init("hello world"))] ) let t1 = try OpenAPI.Parameter.SchemaContext( @@ -38,7 +38,7 @@ final class DereferencedSchemaContextTests: XCTestCase { } func test_multipleExamplesReferenced() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( examples: [ "test1": .init(value: .init("hello world")), "test2": .init(value: .a(URL(string: "http://website.com")!)) diff --git a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift index 3a48d3f33..465d69d59 100644 --- a/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift +++ b/Tests/OpenAPIKitTests/Path Item/DereferencedPathItemTests.swift @@ -65,7 +65,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_referencedParameter() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( parameters: [ "test": .init(name: "param", context: .header(schema: .string)) ] @@ -100,7 +100,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_referencedOperations() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -153,7 +153,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedGetResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "put": .init(description: "put resp"), "post": .init(description: "post resp"), @@ -181,7 +181,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedPutResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "post": .init(description: "post resp"), @@ -209,7 +209,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedPostResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -237,7 +237,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedDeleteResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -265,7 +265,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedOptionsResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -293,7 +293,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedHeadResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -321,7 +321,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedPatchResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -349,7 +349,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedTraceResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -377,7 +377,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedQueryResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), @@ -405,7 +405,7 @@ final class DereferencedPathItemTests: XCTestCase { } func test_missingReferencedAdditionalOperationResp() { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( responses: [ "get": .init(description: "get resp"), "put": .init(description: "put resp"), diff --git a/Tests/OpenAPIKitTests/Response/DereferencedResponseTests.swift b/Tests/OpenAPIKitTests/Response/DereferencedResponseTests.swift index a712027f8..8d15a86ff 100644 --- a/Tests/OpenAPIKitTests/Response/DereferencedResponseTests.swift +++ b/Tests/OpenAPIKitTests/Response/DereferencedResponseTests.swift @@ -36,7 +36,7 @@ final class DereferencedResponseTests: XCTestCase { } func test_referencedHeader() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( headers: [ "test": .init(schema: .string) ] @@ -94,7 +94,7 @@ final class DereferencedResponseTests: XCTestCase { } func test_referencedLink() throws { - let components = OpenAPI.Components( + let components = OpenAPI.Components.direct( links: [ "link1": .init(operationId: "linka") ] diff --git a/Tests/OpenAPIKitTests/Schema Object/DereferencedSchemaObjectTests.swift b/Tests/OpenAPIKitTests/Schema Object/DereferencedSchemaObjectTests.swift index 7126bb331..21502fbeb 100644 --- a/Tests/OpenAPIKitTests/Schema Object/DereferencedSchemaObjectTests.swift +++ b/Tests/OpenAPIKitTests/Schema Object/DereferencedSchemaObjectTests.swift @@ -508,7 +508,7 @@ final class DereferencedSchemaObjectTests: XCTestCase { XCTAssertThrowsError(try JSONSchema.reference(.component(named: "test")).dereferenced(in: components)) { error in XCTAssertEqual( String(describing: error), - "Encountered a JSON Schema $ref cycle that prevents fully dereferencing document at '#/components/schemas/test'. This type of reference cycle is not inherently problematic for JSON Schemas, but it does mean OpenAPIKit cannot fully resolve references because attempting to do so results in an infinite loop over any reference cycles. You should still be able to parse the document, just avoid requesting a `locallyDereferenced()` copy." + "Encountered a JSON Schema $ref cycle that prevents fully resolving a reference at '#/components/schemas/test'. This type of reference cycle is not inherently problematic for JSON Schemas, but it does mean OpenAPIKit cannot fully resolve references because attempting to do so results in an infinite loop over any reference cycles. You should still be able to parse the document, just avoid requesting a `locallyDereferenced()` copy or fully looking up references in cycles. `lookupOnce()` is your best option in this case." ) } } diff --git a/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift b/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift index 57bf0d092..0f9bac4fa 100644 --- a/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift +++ b/Tests/OpenAPIKitTests/Validator/BuiltinValidationTests.swift @@ -837,7 +837,7 @@ final class BuiltinValidationTests: XCTestCase { "/world": .reference(.component(named: "path1")), "/external": .reference(.external(URL(string: "https://other-world.com")!)) ], - components: .init( + components: .direct( schemas: [ "schema1": .object ], @@ -909,7 +909,7 @@ final class BuiltinValidationTests: XCTestCase { ) ) ], - components: .init( + components: .direct( links: [ "testLink": link ] @@ -936,7 +936,7 @@ final class BuiltinValidationTests: XCTestCase { ) ) ], - components: .init( + components: .direct( links: [ "testLink": link ] diff --git a/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift b/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift index 61ec37a7a..ae9704fb7 100644 --- a/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift +++ b/Tests/OpenAPIKitTests/Validator/Validation+ConvenienceTests.swift @@ -294,7 +294,7 @@ final class ValidationConvenienceTests: XCTestCase { ] ) ], - components: .init( + components: .direct( parameters: [ "test1": .init(name: "test", context: .header(content: [:])), "test2": .init(name: "test2", context: .query(content: [:])) @@ -336,7 +336,7 @@ final class ValidationConvenienceTests: XCTestCase { ] ) ], - components: .init( + components: .direct( parameters: [ "test1": .init(name: "test", context: .header(content: [:])), "test2": .init(name: "test2", context: .query(content: [:])) From 77bdcd253c4288e2b72877a6bc8c40dcce946c75 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 18 Nov 2025 08:26:47 -0600 Subject: [PATCH 29/30] fix README support table typos --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b1d83ca0a..9921233c5 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ OpenAPIKit follows semantic versioning despite the fact that the OpenAPI specifi |------------|-------|--------------------|-----------------------------------|--------------| | v3.x | 5.1+ | ✅ | | | | v4.x | 5.8+ | ✅ | ✅ | | -| v4.x | 5.8+ | ✅ | ✅ | ✅ | +| v5.x | 5.10+ | ✅ | ✅ | ✅ | - [Usage](#usage) - [Migration](#migration) From 99831b8daac0883437d1ed2ba33cdc50caffe484 Mon Sep 17 00:00:00 2001 From: Mathew Polzin Date: Tue, 18 Nov 2025 08:42:35 -0600 Subject: [PATCH 30/30] Add information on Components Object breaking changes to the migration guide --- .../migration_guides/v5_migration_guide.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/documentation/migration_guides/v5_migration_guide.md b/documentation/migration_guides/v5_migration_guide.md index 0a94ebf12..096fac59d 100644 --- a/documentation/migration_guides/v5_migration_guide.md +++ b/documentation/migration_guides/v5_migration_guide.md @@ -166,6 +166,55 @@ specification) in this section. The Response Object `description` field is not optional so code may need to change to account for it possibly being `nil`. +### Components Object +There are changes for the `OpenAPIKit30` module (OAS 3.0.x specification) in +this section. + +Entries in the Components Object's `responses`, `parameters`, `examples`, +`requestBodies`, `headers`, `securitySchemes`, `links`, and `callbacks` +dictionaries have all gained support for references. Note that `pathItems` and +`schemas` still do not support references (per the specification), though +`schemas` can be JSON references by their very nature already. + +This change fixes a gap in OpenAPIKit's ability to represent valid documents. + +If you are using subscript access or `lookup()` functions to retrieve entries +from the Components Object, you do _not_ need to change that code. These +functions have learned how to follow references they encounter until they land +on the type of entity being looked up. If you want the behavior of just +doing a regular lookup and passing the result back even if it is a reference, +you can use the new `lookupOnce()` function. The existing `lookup()` functions +can now throw an error they would never throw before: `ReferenceCycleError`. + +Error message phrasing has changed subtly which is unlikely to cause problems +but if you have tests that compare exact error messages then you may need to +update the test expectations. + +If you construct `Components` in-code then you have two options. You can swap +out existing calls to the `Components` `init()` initializer with calls to the +new `Components.direct()` convenience constructor or you can nest each component +entry in an `Either` like follows: +```swift +// BEFORE +Components( + parameters: [ + "param1": .cookie(name: "cookie", schema: .string) + ] +) + +// AFTER +Components( + parameters: [ + "param1": .parameter(.cookie(name: "cookie", schema: .string)) + ] +) +``` + +If your code uses the `static` `openAPIComponentsKeyPath` variable on types that +can be found in the Components Object (likely very uncommon), you will now need +to handle two possibilities: the key path either refers to an object (of generic +type `T`) or it refers to an `Either, T>`. + ### 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