From f95724342a7d5da13070a4859f6db0f9d79fafe1 Mon Sep 17 00:00:00 2001 From: gh-action-runner Date: Thu, 6 Jun 2024 18:23:49 +0000 Subject: [PATCH] Squashed 'apollo-ios/' changes from 522176b7..3188d6a6 3188d6a6 Added Existential Any requirement (apollographql/apollo-ios-dev#379) git-subtree-dir: apollo-ios git-subtree-split: 3188d6a60184e826ac51a526d35a362aeba2cb9d --- Package.swift | 15 ++++-- Sources/Apollo/ApolloClient.swift | 30 ++++++------ Sources/Apollo/ApolloClientProtocol.swift | 28 +++++------ Sources/Apollo/ApolloErrorInterceptor.swift | 10 ++-- Sources/Apollo/ApolloInterceptor.swift | 4 +- Sources/Apollo/ApolloStore.swift | 20 ++++---- .../AutomaticPersistedQueryInterceptor.swift | 4 +- Sources/Apollo/CacheReadInterceptor.swift | 8 ++-- Sources/Apollo/CacheWriteInterceptor.swift | 4 +- Sources/Apollo/DataLoader.swift | 2 +- .../Apollo/DefaultInterceptorProvider.swift | 2 +- Sources/Apollo/DispatchQueue+Optional.swift | 4 +- .../CacheDataExecutionSource.swift | 2 +- .../NetworkResponseExecutionSource.swift | 6 +-- .../SelectionSetModelExecutionSource.swift | 6 +-- Sources/Apollo/GraphQLExecutionSource.swift | 4 +- Sources/Apollo/GraphQLExecutor.swift | 8 ++-- Sources/Apollo/GraphQLQueryWatcher.swift | 12 ++--- Sources/Apollo/GraphQLResult.swift | 2 +- Sources/Apollo/GraphQLResultNormalizer.swift | 2 +- Sources/Apollo/HTTPRequest.swift | 4 +- Sources/Apollo/InterceptorProvider.swift | 4 +- Sources/Apollo/InterceptorRequestChain.swift | 22 ++++----- Sources/Apollo/JSONRequest.swift | 6 +-- .../JSONResponseParsingInterceptor.swift | 4 +- Sources/Apollo/JSONSerializationFormat.swift | 2 +- Sources/Apollo/MaxRetryInterceptor.swift | 4 +- .../Apollo/MultipartResponseDeferParser.swift | 2 +- .../MultipartResponseParsingInterceptor.swift | 10 ++-- .../MultipartResponseSubscriptionParser.swift | 2 +- Sources/Apollo/NetworkFetchInterceptor.swift | 4 +- Sources/Apollo/NetworkTransport.swift | 8 ++-- Sources/Apollo/PossiblyDeferred.swift | 4 +- Sources/Apollo/RequestChain.swift | 14 +++--- .../Apollo/RequestChainNetworkTransport.swift | 22 ++++----- Sources/Apollo/ResponseCodeInterceptor.swift | 4 +- Sources/Apollo/URLSessionClient.swift | 10 ++-- Sources/Apollo/UploadRequest.swift | 8 ++-- Sources/ApolloAPI/GraphQLOperation.swift | 4 +- .../JSONStandardTypeConversions.swift | 2 +- Sources/ApolloAPI/ObjectData.swift | 8 ++-- Sources/ApolloAPI/SchemaMetadata.swift | 2 +- .../ApolloAPI/SchemaTypes/InputObject.swift | 4 +- Sources/ApolloAPI/Selection.swift | 2 +- Sources/ApolloAPI/SelectionSet.swift | 2 +- .../ApolloSQLite/SQLiteNormalizedCache.swift | 6 +-- Sources/ApolloTestSupport/TestMock.swift | 8 ++-- .../DefaultImplementation/WebSocket.swift | 18 ++++---- .../WebSocketStream.swift | 10 ++-- .../ApolloWebSocket/OperationMessage.swift | 4 +- .../SplitNetworkTransport.swift | 14 +++--- Sources/ApolloWebSocket/WebSocketClient.swift | 10 ++-- Sources/ApolloWebSocket/WebSocketError.swift | 2 +- Sources/ApolloWebSocket/WebSocketTask.swift | 2 +- .../ApolloWebSocket/WebSocketTransport.swift | 46 +++++++++---------- 55 files changed, 228 insertions(+), 223 deletions(-) diff --git a/Package.swift b/Package.swift index 118afae79..b0d35db3d 100644 --- a/Package.swift +++ b/Package.swift @@ -34,14 +34,16 @@ let package = Package( ], resources: [ .copy("Resources/PrivacyInfo.xcprivacy") - ] + ], + swiftSettings: [.enableUpcomingFeature("ExistentialAny")] ), .target( name: "ApolloAPI", dependencies: [], resources: [ .copy("Resources/PrivacyInfo.xcprivacy") - ] + ], + swiftSettings: [.enableUpcomingFeature("ExistentialAny")] ), .target( name: "ApolloSQLite", @@ -51,7 +53,8 @@ let package = Package( ], resources: [ .copy("Resources/PrivacyInfo.xcprivacy") - ] + ], + swiftSettings: [.enableUpcomingFeature("ExistentialAny")] ), .target( name: "ApolloWebSocket", @@ -60,14 +63,16 @@ let package = Package( ], resources: [ .copy("Resources/PrivacyInfo.xcprivacy") - ] + ], + swiftSettings: [.enableUpcomingFeature("ExistentialAny")] ), .target( name: "ApolloTestSupport", dependencies: [ "Apollo", "ApolloAPI" - ] + ], + swiftSettings: [.enableUpcomingFeature("ExistentialAny")] ), .plugin( name: "Install CLI", diff --git a/Sources/Apollo/ApolloClient.swift b/Sources/Apollo/ApolloClient.swift index b45c9f48d..189084372 100644 --- a/Sources/Apollo/ApolloClient.swift +++ b/Sources/Apollo/ApolloClient.swift @@ -25,12 +25,12 @@ public enum CachePolicy: Hashable { /// /// - Parameters: /// - result: The result of a performed operation. Will have a `GraphQLResult` with any parsed data and any GraphQL errors on `success`, and an `Error` on `failure`. -public typealias GraphQLResultHandler = (Result, Error>) -> Void +public typealias GraphQLResultHandler = (Result, any Error>) -> Void /// The `ApolloClient` class implements the core API for Apollo by conforming to `ApolloClientProtocol`. public class ApolloClient { - let networkTransport: NetworkTransport + let networkTransport: any NetworkTransport public let store: ApolloStore @@ -50,7 +50,7 @@ public class ApolloClient { /// - Parameters: /// - networkTransport: A network transport used to send operations to a server. /// - store: A store used as a local cache. Note that if the `NetworkTransport` or any of its dependencies takes a store, you should make sure the same store is passed here so that it can be cleared properly. - public init(networkTransport: NetworkTransport, store: ApolloStore) { + public init(networkTransport: any NetworkTransport, store: ApolloStore) { self.networkTransport = networkTransport self.store = store } @@ -73,7 +73,7 @@ public class ApolloClient { extension ApolloClient: ApolloClientProtocol { public func clearCache(callbackQueue: DispatchQueue = .main, - completion: ((Result) -> Void)? = nil) { + completion: ((Result) -> Void)? = nil) { self.store.clearCache(callbackQueue: callbackQueue, completion: completion) } @@ -81,10 +81,10 @@ extension ApolloClient: ApolloClientProtocol { query: Query, cachePolicy: CachePolicy = .default, contextIdentifier: UUID? = nil, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, queue: DispatchQueue = .main, resultHandler: GraphQLResultHandler? = nil - ) -> Cancellable { + ) -> (any Cancellable) { return self.networkTransport.send(operation: query, cachePolicy: cachePolicy, contextIdentifier: contextIdentifier, @@ -109,7 +109,7 @@ extension ApolloClient: ApolloClientProtocol { query: Query, cachePolicy: CachePolicy = .default, refetchOnFailedUpdates: Bool = true, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, callbackQueue: DispatchQueue = .main, resultHandler: @escaping GraphQLResultHandler ) -> GraphQLQueryWatcher { @@ -128,10 +128,10 @@ extension ApolloClient: ApolloClientProtocol { mutation: Mutation, publishResultToStore: Bool = true, contextIdentifier: UUID? = nil, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, queue: DispatchQueue = .main, resultHandler: GraphQLResultHandler? = nil - ) -> Cancellable { + ) -> (any Cancellable) { return self.networkTransport.send( operation: mutation, cachePolicy: publishResultToStore ? .default : .fetchIgnoringCacheCompletely, @@ -148,11 +148,11 @@ extension ApolloClient: ApolloClientProtocol { public func upload( operation: Operation, files: [GraphQLFile], - context: RequestContext? = nil, + context: (any RequestContext)? = nil, queue: DispatchQueue = .main, resultHandler: GraphQLResultHandler? = nil - ) -> Cancellable { - guard let uploadingTransport = self.networkTransport as? UploadingNetworkTransport else { + ) -> (any Cancellable) { + guard let uploadingTransport = self.networkTransport as? (any UploadingNetworkTransport) else { assertionFailure("Trying to upload without an uploading transport. Please make sure your network transport conforms to `UploadingNetworkTransport`.") queue.async { resultHandler?(.failure(ApolloClientError.noUploadTransport)) @@ -170,10 +170,10 @@ extension ApolloClient: ApolloClientProtocol { public func subscribe( subscription: Subscription, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, queue: DispatchQueue = .main, resultHandler: @escaping GraphQLResultHandler - ) -> Cancellable { + ) -> any Cancellable { return self.networkTransport.send(operation: subscription, cachePolicy: .default, contextIdentifier: nil, @@ -192,7 +192,7 @@ extension ApolloClient { public func watch( query: Query, cachePolicy: CachePolicy = .default, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, callbackQueue: DispatchQueue = .main, resultHandler: @escaping GraphQLResultHandler ) -> GraphQLQueryWatcher { diff --git a/Sources/Apollo/ApolloClientProtocol.swift b/Sources/Apollo/ApolloClientProtocol.swift index deb877ec3..e10102d21 100644 --- a/Sources/Apollo/ApolloClientProtocol.swift +++ b/Sources/Apollo/ApolloClientProtocol.swift @@ -15,7 +15,7 @@ public protocol ApolloClientProtocol: AnyObject { /// - Parameters: /// - callbackQueue: The queue to fall back on. Should default to the main queue. /// - completion: [optional] A completion closure to execute when clearing has completed. Should default to nil. - func clearCache(callbackQueue: DispatchQueue, completion: ((Result) -> Void)?) + func clearCache(callbackQueue: DispatchQueue, completion: ((Result) -> Void)?) /// Fetches a query from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. /// @@ -30,9 +30,9 @@ public protocol ApolloClientProtocol: AnyObject { func fetch(query: Query, cachePolicy: CachePolicy, contextIdentifier: UUID?, - context: RequestContext?, + context: (any RequestContext)?, queue: DispatchQueue, - resultHandler: GraphQLResultHandler?) -> Cancellable + resultHandler: GraphQLResultHandler?) -> (any Cancellable) /// Watches a query by first fetching an initial result from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. After the initial fetch, the returned query watcher object will get notified whenever any of the data the query result depends on changes in the local cache, and calls the result handler again with the new result. /// @@ -45,7 +45,7 @@ public protocol ApolloClientProtocol: AnyObject { /// - Returns: A query watcher object that can be used to control the watching behavior. func watch(query: Query, cachePolicy: CachePolicy, - context: RequestContext?, + context: (any RequestContext)?, callbackQueue: DispatchQueue, resultHandler: @escaping GraphQLResultHandler) -> GraphQLQueryWatcher @@ -62,9 +62,9 @@ public protocol ApolloClientProtocol: AnyObject { func perform(mutation: Mutation, publishResultToStore: Bool, contextIdentifier: UUID?, - context: RequestContext?, + context: (any RequestContext)?, queue: DispatchQueue, - resultHandler: GraphQLResultHandler?) -> Cancellable + resultHandler: GraphQLResultHandler?) -> (any Cancellable) /// Uploads the given files with the given operation. /// @@ -77,9 +77,9 @@ public protocol ApolloClientProtocol: AnyObject { /// - Returns: An object that can be used to cancel an in progress request. func upload(operation: Operation, files: [GraphQLFile], - context: RequestContext?, + context: (any RequestContext)?, queue: DispatchQueue, - resultHandler: GraphQLResultHandler?) -> Cancellable + resultHandler: GraphQLResultHandler?) -> (any Cancellable) /// Subscribe to a subscription /// @@ -91,9 +91,9 @@ public protocol ApolloClientProtocol: AnyObject { /// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs. /// - Returns: An object that can be used to cancel an in progress subscription. func subscribe(subscription: Subscription, - context: RequestContext?, + context: (any RequestContext)?, queue: DispatchQueue, - resultHandler: @escaping GraphQLResultHandler) -> Cancellable + resultHandler: @escaping GraphQLResultHandler) -> any Cancellable } // MARK: - Backwards Compatibilty Extension @@ -112,10 +112,10 @@ public extension ApolloClientProtocol { func fetch( query: Query, cachePolicy: CachePolicy, - context: RequestContext?, + context: (any RequestContext)?, queue: DispatchQueue, resultHandler: GraphQLResultHandler? - ) -> Cancellable { + ) -> (any Cancellable) { self.fetch( query: query, cachePolicy: cachePolicy, @@ -138,10 +138,10 @@ public extension ApolloClientProtocol { func perform( mutation: Mutation, publishResultToStore: Bool, - context: RequestContext?, + context: (any RequestContext)?, queue: DispatchQueue, resultHandler: GraphQLResultHandler? - ) -> Cancellable { + ) -> (any Cancellable) { self.perform( mutation: mutation, publishResultToStore: publishResultToStore, diff --git a/Sources/Apollo/ApolloErrorInterceptor.swift b/Sources/Apollo/ApolloErrorInterceptor.swift index cb7cdc364..8b088e837 100644 --- a/Sources/Apollo/ApolloErrorInterceptor.swift +++ b/Sources/Apollo/ApolloErrorInterceptor.swift @@ -14,9 +14,9 @@ public protocol ApolloErrorInterceptor { /// - response: [optional] The response, if one was received /// - completion: The completion closure to fire when the operation has completed. Note that if you call `retry` on the chain, you will not want to call the completion block in this method. func handleErrorAsync( - error: Error, - chain: RequestChain, - request: HTTPRequest, - response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) + error: any Error, + chain: any RequestChain, + request: HTTPRequest, + response: HTTPResponse?, + completion: @escaping (Result, any Error>) -> Void) } diff --git a/Sources/Apollo/ApolloInterceptor.swift b/Sources/Apollo/ApolloInterceptor.swift index 81b36c676..c999f298a 100644 --- a/Sources/Apollo/ApolloInterceptor.swift +++ b/Sources/Apollo/ApolloInterceptor.swift @@ -20,8 +20,8 @@ public protocol ApolloInterceptor { /// - response: [optional] The response, if received /// - completion: The completion block to fire when data needs to be returned to the UI. func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) + completion: @escaping (Result, any Error>) -> Void) } diff --git a/Sources/Apollo/ApolloStore.swift b/Sources/Apollo/ApolloStore.swift index a960b9c21..09729513a 100644 --- a/Sources/Apollo/ApolloStore.swift +++ b/Sources/Apollo/ApolloStore.swift @@ -22,16 +22,16 @@ public protocol ApolloStoreSubscriber: AnyObject { /// The `ApolloStore` class acts as a local cache for normalized GraphQL results. public class ApolloStore { - private let cache: NormalizedCache + private let cache: any NormalizedCache private let queue: DispatchQueue - internal var subscribers: [ApolloStoreSubscriber] = [] + internal var subscribers: [any ApolloStoreSubscriber] = [] /// Designated initializer /// - Parameters: /// - cache: An instance of `normalizedCache` to use to cache results. /// Defaults to an `InMemoryNormalizedCache`. - public init(cache: NormalizedCache = InMemoryNormalizedCache()) { + public init(cache: any NormalizedCache = InMemoryNormalizedCache()) { self.cache = cache self.queue = DispatchQueue(label: "com.apollographql.ApolloStore", attributes: .concurrent) } @@ -47,7 +47,7 @@ public class ApolloStore { /// - Parameters: /// - callbackQueue: The queue to call the completion block on. Defaults to `DispatchQueue.main`. /// - completion: [optional] A completion block to be called after records are merged into the cache. - public func clearCache(callbackQueue: DispatchQueue = .main, completion: ((Result) -> Void)? = nil) { + public func clearCache(callbackQueue: DispatchQueue = .main, completion: ((Result) -> Void)? = nil) { queue.async(flags: .barrier) { let result = Result { try self.cache.clear() } DispatchQueue.returnResultAsyncIfNeeded( @@ -65,7 +65,7 @@ public class ApolloStore { /// to assist in de-duping cache hits for watchers. /// - callbackQueue: The queue to call the completion block on. Defaults to `DispatchQueue.main`. /// - completion: [optional] A completion block to be called after records are merged into the cache. - public func publish(records: RecordSet, identifier: UUID? = nil, callbackQueue: DispatchQueue = .main, completion: ((Result) -> Void)? = nil) { + public func publish(records: RecordSet, identifier: UUID? = nil, callbackQueue: DispatchQueue = .main, completion: ((Result) -> Void)? = nil) { queue.async(flags: .barrier) { do { let changedKeys = try self.cache.merge(records: records) @@ -90,7 +90,7 @@ public class ApolloStore { /// - Parameters: /// - subscriber: A subscriber to receive content change notificatons. To avoid a retain cycle, /// ensure you call `unsubscribe` on this subscriber before it goes out of scope. - public func subscribe(_ subscriber: ApolloStoreSubscriber) { + public func subscribe(_ subscriber: any ApolloStoreSubscriber) { queue.async(flags: .barrier) { self.subscribers.append(subscriber) } @@ -101,7 +101,7 @@ public class ApolloStore { /// - Parameters: /// - subscriber: A subscribe that has previously been added via `subscribe`. To avoid retain cycles, /// call `unsubscribe` on all active subscribers before they go out of scope. - public func unsubscribe(_ subscriber: ApolloStoreSubscriber) { + public func unsubscribe(_ subscriber: any ApolloStoreSubscriber) { queue.async(flags: .barrier) { self.subscribers = self.subscribers.filter({ $0 !== subscriber }) } @@ -116,7 +116,7 @@ public class ApolloStore { public func withinReadTransaction( _ body: @escaping (ReadTransaction) throws -> T, callbackQueue: DispatchQueue? = nil, - completion: ((Result) -> Void)? = nil + completion: ((Result) -> Void)? = nil ) { self.queue.async { do { @@ -146,7 +146,7 @@ public class ApolloStore { public func withinReadWriteTransaction( _ body: @escaping (ReadWriteTransaction) throws -> T, callbackQueue: DispatchQueue? = nil, - completion: ((Result) -> Void)? = nil + completion: ((Result) -> Void)? = nil ) { self.queue.async(flags: .barrier) { do { @@ -201,7 +201,7 @@ public class ApolloStore { } public class ReadTransaction { - fileprivate let cache: NormalizedCache + fileprivate let cache: any NormalizedCache fileprivate lazy var loader: DataLoader = DataLoader(self.cache.loadRecords) fileprivate lazy var executor = GraphQLExecutor( diff --git a/Sources/Apollo/AutomaticPersistedQueryInterceptor.swift b/Sources/Apollo/AutomaticPersistedQueryInterceptor.swift index d42bd72bd..5de2506a0 100644 --- a/Sources/Apollo/AutomaticPersistedQueryInterceptor.swift +++ b/Sources/Apollo/AutomaticPersistedQueryInterceptor.swift @@ -30,10 +30,10 @@ public struct AutomaticPersistedQueryInterceptor: ApolloInterceptor { public init() {} public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) { + completion: @escaping (Result, any Error>) -> Void) { guard let jsonRequest = request as? JSONRequest, jsonRequest.autoPersistQueries else { diff --git a/Sources/Apollo/CacheReadInterceptor.swift b/Sources/Apollo/CacheReadInterceptor.swift index 111a1df45..4c8acebdc 100644 --- a/Sources/Apollo/CacheReadInterceptor.swift +++ b/Sources/Apollo/CacheReadInterceptor.swift @@ -18,10 +18,10 @@ public struct CacheReadInterceptor: ApolloInterceptor { } public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) { + completion: @escaping (Result, any Error>) -> Void) { switch Operation.operationType { case .mutation, @@ -115,8 +115,8 @@ public struct CacheReadInterceptor: ApolloInterceptor { private func fetchFromCache( for request: HTTPRequest, - chain: RequestChain, - completion: @escaping (Result, Error>) -> Void) { + chain: any RequestChain, + completion: @escaping (Result, any Error>) -> Void) { self.store.load(request.operation) { loadResult in guard !chain.isCancelled else { diff --git a/Sources/Apollo/CacheWriteInterceptor.swift b/Sources/Apollo/CacheWriteInterceptor.swift index 350e8845b..a06c267e1 100644 --- a/Sources/Apollo/CacheWriteInterceptor.swift +++ b/Sources/Apollo/CacheWriteInterceptor.swift @@ -28,10 +28,10 @@ public struct CacheWriteInterceptor: ApolloInterceptor { } public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) { + completion: @escaping (Result, any Error>) -> Void) { guard request.cachePolicy != .fetchIgnoringCacheCompletely else { // If we're ignoring the cache completely, we're not writing to it. diff --git a/Sources/Apollo/DataLoader.swift b/Sources/Apollo/DataLoader.swift index fa959c22f..2f6afd72a 100644 --- a/Sources/Apollo/DataLoader.swift +++ b/Sources/Apollo/DataLoader.swift @@ -2,7 +2,7 @@ final class DataLoader { public typealias BatchLoad = (Set) throws -> [Key: Value] private var batchLoad: BatchLoad - private var cache: [Key: Result] = [:] + private var cache: [Key: Result] = [:] private var pendingLoads: Set = [] public init(_ batchLoad: @escaping BatchLoad) { diff --git a/Sources/Apollo/DefaultInterceptorProvider.swift b/Sources/Apollo/DefaultInterceptorProvider.swift index bef366f9a..bbce79581 100644 --- a/Sources/Apollo/DefaultInterceptorProvider.swift +++ b/Sources/Apollo/DefaultInterceptorProvider.swift @@ -44,7 +44,7 @@ open class DefaultInterceptorProvider: InterceptorProvider { ] } - open func additionalErrorInterceptor(for operation: Operation) -> ApolloErrorInterceptor? { + open func additionalErrorInterceptor(for operation: Operation) -> (any ApolloErrorInterceptor)? { return nil } } diff --git a/Sources/Apollo/DispatchQueue+Optional.swift b/Sources/Apollo/DispatchQueue+Optional.swift index 4836b81f8..f87e0195e 100644 --- a/Sources/Apollo/DispatchQueue+Optional.swift +++ b/Sources/Apollo/DispatchQueue+Optional.swift @@ -15,8 +15,8 @@ extension DispatchQueue { } static func returnResultAsyncIfNeeded(on callbackQueue: DispatchQueue?, - action: ((Result) -> Void)?, - result: Result) { + action: ((Result) -> Void)?, + result: Result) { if let action = action { self.performAsyncIfNeeded(on: callbackQueue) { action(result) diff --git a/Sources/Apollo/ExecutionSources/CacheDataExecutionSource.swift b/Sources/Apollo/ExecutionSources/CacheDataExecutionSource.swift index 9aa665e53..c1794a1eb 100644 --- a/Sources/Apollo/ExecutionSources/CacheDataExecutionSource.swift +++ b/Sources/Apollo/ExecutionSources/CacheDataExecutionSource.swift @@ -64,7 +64,7 @@ struct CacheDataExecutionSource: GraphQLExecutionSource { return transaction.loadObject(forKey: reference.key) } - func computeCacheKey(for object: Record, in schema: SchemaMetadata.Type) -> CacheKey? { + func computeCacheKey(for object: Record, in schema: any SchemaMetadata.Type) -> CacheKey? { return object.key } diff --git a/Sources/Apollo/ExecutionSources/NetworkResponseExecutionSource.swift b/Sources/Apollo/ExecutionSources/NetworkResponseExecutionSource.swift index 108e492ed..5d2c97556 100644 --- a/Sources/Apollo/ExecutionSources/NetworkResponseExecutionSource.swift +++ b/Sources/Apollo/ExecutionSources/NetworkResponseExecutionSource.swift @@ -25,10 +25,10 @@ public struct NetworkResponseExecutionSource: GraphQLExecutionSource, CacheKeyCo struct DataTransformer: _ObjectData_Transformer { func transform(_ value: AnyHashable) -> (any ScalarType)? { switch value { - case let scalar as ScalarType: + case let scalar as any ScalarType: return scalar - case let customScalar as CustomScalarType: - return customScalar._jsonValue as? ScalarType + case let customScalar as any CustomScalarType: + return customScalar._jsonValue as? (any ScalarType) default: return nil } } diff --git a/Sources/Apollo/ExecutionSources/SelectionSetModelExecutionSource.swift b/Sources/Apollo/ExecutionSources/SelectionSetModelExecutionSource.swift index 6a72f4e88..047a937e5 100644 --- a/Sources/Apollo/ExecutionSources/SelectionSetModelExecutionSource.swift +++ b/Sources/Apollo/ExecutionSources/SelectionSetModelExecutionSource.swift @@ -22,10 +22,10 @@ struct SelectionSetModelExecutionSource: GraphQLExecutionSource, CacheKeyComputi struct DataTransformer: _ObjectData_Transformer { func transform(_ value: AnyHashable) -> (any ScalarType)? { switch value { - case let scalar as ScalarType: + case let scalar as any ScalarType: return scalar - case let customScalar as CustomScalarType: - return customScalar._jsonValue as? ScalarType + case let customScalar as any CustomScalarType: + return customScalar._jsonValue as? (any ScalarType) default: return nil } } diff --git a/Sources/Apollo/GraphQLExecutionSource.swift b/Sources/Apollo/GraphQLExecutionSource.swift index 6c79f0652..c312b044f 100644 --- a/Sources/Apollo/GraphQLExecutionSource.swift +++ b/Sources/Apollo/GraphQLExecutionSource.swift @@ -39,7 +39,7 @@ public protocol GraphQLExecutionSource { /// - Returns: A cache key for normalizing the object in the cache. If `nil` is returned the /// object is assumed to be stored in the cache with no normalization. The executor will /// construct a cache key based on the object's path in its enclosing operation. - func computeCacheKey(for object: RawObjectData, in schema: SchemaMetadata.Type) -> CacheKey? + func computeCacheKey(for object: RawObjectData, in schema: any SchemaMetadata.Type) -> CacheKey? } /// A type of `GraphQLExecutionSource` that uses the user defined cache key computation @@ -53,7 +53,7 @@ public protocol CacheKeyComputingExecutionSource: GraphQLExecutionSource { } extension CacheKeyComputingExecutionSource { - @_spi(Execution) public func computeCacheKey(for object: RawObjectData, in schema: SchemaMetadata.Type) -> CacheKey? { + @_spi(Execution) public func computeCacheKey(for object: RawObjectData, in schema: any SchemaMetadata.Type) -> CacheKey? { let dataWrapper = opaqueObjectDataWrapper(for: object) return schema.cacheKey(for: dataWrapper) } diff --git a/Sources/Apollo/GraphQLExecutor.swift b/Sources/Apollo/GraphQLExecutor.swift index c52363b75..67323a5fe 100644 --- a/Sources/Apollo/GraphQLExecutor.swift +++ b/Sources/Apollo/GraphQLExecutor.swift @@ -7,7 +7,7 @@ import ApolloAPI public class ObjectExecutionInfo { let rootType: any RootSelectionSet.Type let variables: GraphQLOperation.Variables? - let schema: SchemaMetadata.Type + let schema: any SchemaMetadata.Type private(set) var responsePath: ResponsePath = [] private(set) var cachePath: ResponsePath = [] fileprivate(set) var fulfilledFragments: Set @@ -15,7 +15,7 @@ public class ObjectExecutionInfo { fileprivate init( rootType: any RootSelectionSet.Type, variables: GraphQLOperation.Variables?, - schema: SchemaMetadata.Type, + schema: (any SchemaMetadata.Type), responsePath: ResponsePath, cachePath: ResponsePath ) { @@ -30,7 +30,7 @@ public class ObjectExecutionInfo { fileprivate init( rootType: any RootSelectionSet.Type, variables: GraphQLOperation.Variables?, - schema: SchemaMetadata.Type, + schema: (any SchemaMetadata.Type), withRootCacheReference root: CacheReference? = nil ) { self.rootType = rootType @@ -158,7 +158,7 @@ public struct GraphQLExecutionError: Error, LocalizedError { public var pathString: String { path.description } /// The error that occurred during parsing. - public let underlying: Error + public let underlying: any Error /// A description of the error which includes the path where the error occurred. public var errorDescription: String? { diff --git a/Sources/Apollo/GraphQLQueryWatcher.swift b/Sources/Apollo/GraphQLQueryWatcher.swift index 18e20b8b0..7c62776aa 100644 --- a/Sources/Apollo/GraphQLQueryWatcher.swift +++ b/Sources/Apollo/GraphQLQueryWatcher.swift @@ -7,7 +7,7 @@ import ApolloAPI /// /// NOTE: The store retains the watcher while subscribed. You must call `cancel()` on your query watcher when you no longer need results. Failure to call `cancel()` before releasing your reference to the returned watcher will result in a memory leak. public final class GraphQLQueryWatcher: Cancellable, ApolloStoreSubscriber { - weak var client: ApolloClientProtocol? + weak var client: (any ApolloClientProtocol)? public let query: Query /// Determines if the watcher should perform a network fetch when it's watched objects have @@ -21,13 +21,13 @@ public final class GraphQLQueryWatcher: Cancellable, Apollo private let callbackQueue: DispatchQueue private let contextIdentifier = UUID() - private let context: RequestContext? + private let context: (any RequestContext)? private class WeakFetchTaskContainer { - weak var cancellable: Cancellable? + weak var cancellable: (any Cancellable)? var cachePolicy: CachePolicy? - fileprivate init(_ cancellable: Cancellable?, _ cachePolicy: CachePolicy?) { + fileprivate init(_ cancellable: (any Cancellable)?, _ cachePolicy: CachePolicy?) { self.cancellable = cancellable self.cachePolicy = cachePolicy } @@ -47,10 +47,10 @@ public final class GraphQLQueryWatcher: Cancellable, Apollo /// - context: [optional] A context that is being passed through the request chain. Defaults to `nil`. /// - callbackQueue: The queue for the result handler. Defaults to the main queue. /// - resultHandler: The result handler to call with changes. - public init(client: ApolloClientProtocol, + public init(client: any ApolloClientProtocol, query: Query, refetchOnFailedUpdates: Bool = true, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, callbackQueue: DispatchQueue = .main, resultHandler: @escaping GraphQLResultHandler) { self.client = client diff --git a/Sources/Apollo/GraphQLResult.swift b/Sources/Apollo/GraphQLResult.swift index f1f2b0280..d357f8891 100644 --- a/Sources/Apollo/GraphQLResult.swift +++ b/Sources/Apollo/GraphQLResult.swift @@ -65,7 +65,7 @@ extension GraphQLResult { var val: Any = value if let value = value as? DataDict { val = value._data - } else if let value = value as? CustomScalarType { + } else if let value = value as? (any CustomScalarType) { val = value._jsonValue } if let dict = val as? [String: Any] { diff --git a/Sources/Apollo/GraphQLResultNormalizer.swift b/Sources/Apollo/GraphQLResultNormalizer.swift index e37b3d306..3b49a7b03 100644 --- a/Sources/Apollo/GraphQLResultNormalizer.swift +++ b/Sources/Apollo/GraphQLResultNormalizer.swift @@ -72,7 +72,7 @@ final class RawJSONResultNormalizer: BaseGraphQLResultNormalizer {} final class SelectionSetDataResultNormalizer: BaseGraphQLResultNormalizer { override final func accept(customScalar: JSONValue, info: FieldExecutionInfo) -> JSONValue? { - if let customScalar = customScalar as? JSONEncodable { + if let customScalar = customScalar as? (any JSONEncodable) { return customScalar._jsonValue } return customScalar diff --git a/Sources/Apollo/HTTPRequest.swift b/Sources/Apollo/HTTPRequest.swift index 99b1f35d7..1a56a468e 100644 --- a/Sources/Apollo/HTTPRequest.swift +++ b/Sources/Apollo/HTTPRequest.swift @@ -22,7 +22,7 @@ open class HTTPRequest: Hashable { public let contextIdentifier: UUID? /// [optional] A context that is being passed through the request chain. - public let context: RequestContext? + public let context: (any RequestContext)? /// Designated Initializer /// @@ -44,7 +44,7 @@ open class HTTPRequest: Hashable { clientVersion: String, additionalHeaders: [String: String], cachePolicy: CachePolicy = .default, - context: RequestContext? = nil) { + context: (any RequestContext)? = nil) { self.graphQLEndpoint = graphQLEndpoint self.operation = operation self.contextIdentifier = contextIdentifier diff --git a/Sources/Apollo/InterceptorProvider.swift b/Sources/Apollo/InterceptorProvider.swift index c2ec81ff8..f4aaa0cb0 100644 --- a/Sources/Apollo/InterceptorProvider.swift +++ b/Sources/Apollo/InterceptorProvider.swift @@ -15,14 +15,14 @@ public protocol InterceptorProvider { /// Provides an additional error interceptor for any additional handling of errors /// before returning to the UI, such as logging. /// - Parameter operation: The operation to provide an additional error interceptor for - func additionalErrorInterceptor(for operation: Operation) -> ApolloErrorInterceptor? + func additionalErrorInterceptor(for operation: Operation) -> (any ApolloErrorInterceptor)? } /// MARK: - Default Implementation public extension InterceptorProvider { - func additionalErrorInterceptor(for operation: Operation) -> ApolloErrorInterceptor? { + func additionalErrorInterceptor(for operation: Operation) -> (any ApolloErrorInterceptor)? { return nil } } diff --git a/Sources/Apollo/InterceptorRequestChain.swift b/Sources/Apollo/InterceptorRequestChain.swift index df6315e78..60b4cc965 100644 --- a/Sources/Apollo/InterceptorRequestChain.swift +++ b/Sources/Apollo/InterceptorRequestChain.swift @@ -7,7 +7,7 @@ import ApolloAPI final public class InterceptorRequestChain: Cancellable, RequestChain { public enum ChainError: Error, LocalizedError { - case invalidIndex(chain: RequestChain, index: Int) + case invalidIndex(chain: any RequestChain, index: Int) case noInterceptors case unknownInterceptor(id: String) @@ -31,7 +31,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { @Atomic public var isCancelled: Bool = false /// Something which allows additional error handling to occur when some kind of error has happened. - public var additionalErrorHandler: ApolloErrorInterceptor? + public var additionalErrorHandler: (any ApolloErrorInterceptor)? /// Creates a chain with the given interceptor array. /// @@ -59,7 +59,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { /// - completion: The completion closure to call when the request has completed. public func kickoff( request: HTTPRequest, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { assert(self.currentIndex == 0, "The interceptor index should be zero when calling this method") @@ -91,7 +91,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { public func proceedAsync( request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { let nextIndex = self.currentIndex + 1 @@ -116,7 +116,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { request: HTTPRequest, response: HTTPResponse?, interceptor: any ApolloInterceptor, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { guard let currentIndex = interceptorIndexes[interceptor.id] else { self.handleErrorAsync( @@ -142,7 +142,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { interceptorIndex: Int, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { guard !self.isCancelled else { // Do not proceed, this chain has been cancelled. @@ -192,7 +192,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { // If an interceptor adheres to `Cancellable`, it should have its in-flight work cancelled as well. for interceptor in self.interceptors { - if let cancellableInterceptor = interceptor as? Cancellable { + if let cancellableInterceptor = interceptor as? (any Cancellable) { cancellableInterceptor.cancel() } } @@ -205,7 +205,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { /// - completion: The completion closure to call when the request has completed. public func retry( request: HTTPRequest, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { guard !self.isCancelled else { // Don't retry something that's been cancelled. @@ -225,10 +225,10 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { /// - response: The response, as far as it has been constructed. /// - completion: The completion closure to call when work is complete. public func handleErrorAsync( - _ error: Error, + _ error: any Error, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { guard !self.isCancelled else { return @@ -264,7 +264,7 @@ final public class InterceptorRequestChain: Cancellable, RequestChain { public func returnValueAsync( for request: HTTPRequest, value: GraphQLResult, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { guard !self.isCancelled else { return diff --git a/Sources/Apollo/JSONRequest.swift b/Sources/Apollo/JSONRequest.swift index 9c54529a7..a7b487a83 100644 --- a/Sources/Apollo/JSONRequest.swift +++ b/Sources/Apollo/JSONRequest.swift @@ -6,7 +6,7 @@ import ApolloAPI /// A request which sends JSON related to a GraphQL operation. open class JSONRequest: HTTPRequest { - public let requestBodyCreator: RequestBodyCreator + public let requestBodyCreator: any RequestBodyCreator public let autoPersistQueries: Bool public let useGETForQueries: Bool @@ -50,11 +50,11 @@ open class JSONRequest: HTTPRequest { clientVersion: String, additionalHeaders: [String: String] = [:], cachePolicy: CachePolicy = .default, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, autoPersistQueries: Bool = false, useGETForQueries: Bool = false, useGETForPersistedQueryRetry: Bool = false, - requestBodyCreator: RequestBodyCreator = ApolloRequestBodyCreator() + requestBodyCreator: any RequestBodyCreator = ApolloRequestBodyCreator() ) { self.autoPersistQueries = autoPersistQueries self.useGETForQueries = useGETForQueries diff --git a/Sources/Apollo/JSONResponseParsingInterceptor.swift b/Sources/Apollo/JSONResponseParsingInterceptor.swift index 6e35ce917..d96b86bd8 100644 --- a/Sources/Apollo/JSONResponseParsingInterceptor.swift +++ b/Sources/Apollo/JSONResponseParsingInterceptor.swift @@ -34,10 +34,10 @@ public struct JSONResponseParsingInterceptor: ApolloInterceptor { public init() { } public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) { guard let createdResponse = response else { chain.handleErrorAsync( diff --git a/Sources/Apollo/JSONSerializationFormat.swift b/Sources/Apollo/JSONSerializationFormat.swift index 7f62161ef..b87a714f6 100644 --- a/Sources/Apollo/JSONSerializationFormat.swift +++ b/Sources/Apollo/JSONSerializationFormat.swift @@ -4,7 +4,7 @@ import ApolloAPI #endif public final class JSONSerializationFormat { - public class func serialize(value: JSONEncodable) throws -> Data { + public class func serialize(value: any JSONEncodable) throws -> Data { return try JSONSerialization.sortedData(withJSONObject: value._jsonValue) } diff --git a/Sources/Apollo/MaxRetryInterceptor.swift b/Sources/Apollo/MaxRetryInterceptor.swift index ed25961ab..4adc90bfc 100644 --- a/Sources/Apollo/MaxRetryInterceptor.swift +++ b/Sources/Apollo/MaxRetryInterceptor.swift @@ -30,10 +30,10 @@ public class MaxRetryInterceptor: ApolloInterceptor { } public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) { + completion: @escaping (Result, any Error>) -> Void) { guard self.hitCount <= self.maxRetries else { let error = RetryError.hitMaxRetryCount( count: self.maxRetries, diff --git a/Sources/Apollo/MultipartResponseDeferParser.swift b/Sources/Apollo/MultipartResponseDeferParser.swift index f39a9e05e..e0eefe5dc 100644 --- a/Sources/Apollo/MultipartResponseDeferParser.swift +++ b/Sources/Apollo/MultipartResponseDeferParser.swift @@ -10,7 +10,7 @@ struct MultipartResponseDeferParser: MultipartResponseSpecificationParser { data: Data, boundary: String, dataHandler: ((Data) -> Void), - errorHandler: ((Error) -> Void) + errorHandler: ((any Error) -> Void) ) { // TODO: Will be implemented in #3146 } diff --git a/Sources/Apollo/MultipartResponseParsingInterceptor.swift b/Sources/Apollo/MultipartResponseParsingInterceptor.swift index 0c20e274b..04dba1c8f 100644 --- a/Sources/Apollo/MultipartResponseParsingInterceptor.swift +++ b/Sources/Apollo/MultipartResponseParsingInterceptor.swift @@ -20,7 +20,7 @@ public struct MultipartResponseParsingInterceptor: ApolloInterceptor { } } - private static let responseParsers: [String: MultipartResponseSpecificationParser.Type] = [ + private static let responseParsers: [String: any MultipartResponseSpecificationParser.Type] = [ MultipartResponseSubscriptionParser.protocolSpec: MultipartResponseSubscriptionParser.self ] @@ -29,10 +29,10 @@ public struct MultipartResponseParsingInterceptor: ApolloInterceptor { public init() { } public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation { guard let response else { @@ -86,7 +86,7 @@ public struct MultipartResponseParsingInterceptor: ApolloInterceptor { ) } - let errorHandler: ((Error) -> Void) = { parserError in + let errorHandler: ((any Error) -> Void) = { parserError in chain.handleErrorAsync( parserError, request: request, @@ -116,6 +116,6 @@ protocol MultipartResponseSpecificationParser { data: Data, boundary: String, dataHandler: ((Data) -> Void), - errorHandler: ((Error) -> Void) + errorHandler: ((any Error) -> Void) ) } diff --git a/Sources/Apollo/MultipartResponseSubscriptionParser.swift b/Sources/Apollo/MultipartResponseSubscriptionParser.swift index dec316522..1498b4ff3 100644 --- a/Sources/Apollo/MultipartResponseSubscriptionParser.swift +++ b/Sources/Apollo/MultipartResponseSubscriptionParser.swift @@ -44,7 +44,7 @@ struct MultipartResponseSubscriptionParser: MultipartResponseSpecificationParser data: Data, boundary: String, dataHandler: ((Data) -> Void), - errorHandler: ((Error) -> Void) + errorHandler: ((any Error) -> Void) ) { guard let dataString = String(data: data, encoding: .utf8) else { errorHandler(ParsingError.cannotParseResponseData) diff --git a/Sources/Apollo/NetworkFetchInterceptor.swift b/Sources/Apollo/NetworkFetchInterceptor.swift index 92ccd79b5..4b7636b3d 100644 --- a/Sources/Apollo/NetworkFetchInterceptor.swift +++ b/Sources/Apollo/NetworkFetchInterceptor.swift @@ -18,10 +18,10 @@ public class NetworkFetchInterceptor: ApolloInterceptor, Cancellable { } public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) { + completion: @escaping (Result, any Error>) -> Void) { let urlRequest: URLRequest do { diff --git a/Sources/Apollo/NetworkTransport.swift b/Sources/Apollo/NetworkTransport.swift index 6b0cd953e..e594f9462 100644 --- a/Sources/Apollo/NetworkTransport.swift +++ b/Sources/Apollo/NetworkTransport.swift @@ -21,9 +21,9 @@ public protocol NetworkTransport: AnyObject { func send(operation: Operation, cachePolicy: CachePolicy, contextIdentifier: UUID?, - context: RequestContext?, + context: (any RequestContext)?, callbackQueue: DispatchQueue, - completionHandler: @escaping (Result, Error>) -> Void) -> Cancellable + completionHandler: @escaping (Result, any Error>) -> Void) -> any Cancellable /// The name of the client to send as a header value. var clientName: String { get } @@ -108,7 +108,7 @@ public protocol UploadingNetworkTransport: NetworkTransport { func upload( operation: Operation, files: [GraphQLFile], - context: RequestContext?, + context: (any RequestContext)?, callbackQueue: DispatchQueue, - completionHandler: @escaping (Result,Error>) -> Void) -> Cancellable + completionHandler: @escaping (Result,any Error>) -> Void) -> any Cancellable } diff --git a/Sources/Apollo/PossiblyDeferred.swift b/Sources/Apollo/PossiblyDeferred.swift index 4b3f294a2..b706399d9 100644 --- a/Sources/Apollo/PossiblyDeferred.swift +++ b/Sources/Apollo/PossiblyDeferred.swift @@ -45,7 +45,7 @@ extension Sequence { @_spi(Execution) public enum PossiblyDeferred { /// An immediate success or failure value, represented as a `Result` instance. - case immediate(Result) + case immediate(Result) /// A deferred value that will be lazily evaluated by invoking the associated throwing closure. case deferred(() throws -> Value) @@ -135,7 +135,7 @@ public enum PossiblyDeferred { /// instance. /// - Returns: A `PossiblyDeferred` instance with the result of evaluating `transform` /// as the new failure value if this instance represents a failure. - func mapError(_ transform: @escaping (Error) -> Error) -> PossiblyDeferred { + func mapError(_ transform: @escaping (any Error) -> any Error) -> PossiblyDeferred { switch self { case .immediate(let result): return .immediate(result.mapError(transform)) diff --git a/Sources/Apollo/RequestChain.swift b/Sources/Apollo/RequestChain.swift index a0034f632..363c26c94 100644 --- a/Sources/Apollo/RequestChain.swift +++ b/Sources/Apollo/RequestChain.swift @@ -5,41 +5,41 @@ import ApolloAPI public protocol RequestChain: Cancellable { func kickoff( request: HTTPRequest, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation @available(*, deprecated, renamed: "proceedAsync(request:response:interceptor:completion:)") func proceedAsync( request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation func proceedAsync( request: HTTPRequest, response: HTTPResponse?, interceptor: any ApolloInterceptor, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation func cancel() func retry( request: HTTPRequest, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation func handleErrorAsync( - _ error: Error, + _ error: any Error, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation func returnValueAsync( for request: HTTPRequest, value: GraphQLResult, - completion: @escaping (Result, Error>) -> Void + completion: @escaping (Result, any Error>) -> Void ) where Operation : GraphQLOperation var isCancelled: Bool { get } diff --git a/Sources/Apollo/RequestChainNetworkTransport.swift b/Sources/Apollo/RequestChainNetworkTransport.swift index fd9199526..fecbb28f9 100644 --- a/Sources/Apollo/RequestChainNetworkTransport.swift +++ b/Sources/Apollo/RequestChainNetworkTransport.swift @@ -8,7 +8,7 @@ import ApolloAPI open class RequestChainNetworkTransport: NetworkTransport { /// The interceptor provider to use when constructing a request chain - let interceptorProvider: InterceptorProvider + let interceptorProvider: any InterceptorProvider /// The GraphQL endpoint URL to use. public let endpointURL: URL @@ -40,7 +40,7 @@ open class RequestChainNetworkTransport: NetworkTransport { /// The `RequestBodyCreator` object used to build your `URLRequest`. /// /// Defaults to an ``ApolloRequestBodyCreator`` initialized with the default configuration. - public var requestBodyCreator: RequestBodyCreator + public var requestBodyCreator: any RequestBodyCreator /// Designated initializer /// @@ -52,11 +52,11 @@ open class RequestChainNetworkTransport: NetworkTransport { /// - requestBodyCreator: The `RequestBodyCreator` object to use to build your `URLRequest`. Defaults to the provided `ApolloRequestBodyCreator` implementation. /// - useGETForQueries: Pass `true` if you want to use `GET` instead of `POST` for queries, for example to take advantage of a CDN. Defaults to `false`. /// - useGETForPersistedQueryRetry: Pass `true` to use `GET` instead of `POST` for a retry of a persisted query. Defaults to `false`. - public init(interceptorProvider: InterceptorProvider, + public init(interceptorProvider: any InterceptorProvider, endpointURL: URL, additionalHeaders: [String: String] = [:], autoPersistQueries: Bool = false, - requestBodyCreator: RequestBodyCreator = ApolloRequestBodyCreator(), + requestBodyCreator: any RequestBodyCreator = ApolloRequestBodyCreator(), useGETForQueries: Bool = false, useGETForPersistedQueryRetry: Bool = false) { self.interceptorProvider = interceptorProvider @@ -83,7 +83,7 @@ open class RequestChainNetworkTransport: NetworkTransport { for operation: Operation, cachePolicy: CachePolicy, contextIdentifier: UUID? = nil, - context: RequestContext? = nil + context: (any RequestContext)? = nil ) -> HTTPRequest { let request = JSONRequest( operation: operation, @@ -126,9 +126,9 @@ open class RequestChainNetworkTransport: NetworkTransport { operation: Operation, cachePolicy: CachePolicy = .default, contextIdentifier: UUID? = nil, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, callbackQueue: DispatchQueue = .main, - completionHandler: @escaping (Result, Error>) -> Void) -> Cancellable { + completionHandler: @escaping (Result, any Error>) -> Void) -> any Cancellable { let chain = makeChain(operation: operation, callbackQueue: callbackQueue) let request = self.constructRequest( @@ -144,7 +144,7 @@ open class RequestChainNetworkTransport: NetworkTransport { private func makeChain( operation: Operation, callbackQueue: DispatchQueue = .main - ) -> RequestChain { + ) -> any RequestChain { let interceptors = self.interceptorProvider.interceptors(for: operation) let chain = InterceptorRequestChain(interceptors: interceptors, callbackQueue: callbackQueue) chain.additionalErrorHandler = self.interceptorProvider.additionalErrorInterceptor(for: operation) @@ -168,7 +168,7 @@ extension RequestChainNetworkTransport: UploadingNetworkTransport { public func constructUploadRequest( for operation: Operation, with files: [GraphQLFile], - context: RequestContext? = nil, + context: (any RequestContext)? = nil, manualBoundary: String? = nil) -> HTTPRequest { UploadRequest(graphQLEndpoint: self.endpointURL, @@ -185,9 +185,9 @@ extension RequestChainNetworkTransport: UploadingNetworkTransport { public func upload( operation: Operation, files: [GraphQLFile], - context: RequestContext?, + context: (any RequestContext)?, callbackQueue: DispatchQueue = .main, - completionHandler: @escaping (Result, Error>) -> Void) -> Cancellable { + completionHandler: @escaping (Result, any Error>) -> Void) -> any Cancellable { let request = self.constructUploadRequest(for: operation, with: files, context: context) let chain = makeChain(operation: operation, callbackQueue: callbackQueue) diff --git a/Sources/Apollo/ResponseCodeInterceptor.swift b/Sources/Apollo/ResponseCodeInterceptor.swift index 2c94ff7cd..b4d1837c2 100644 --- a/Sources/Apollo/ResponseCodeInterceptor.swift +++ b/Sources/Apollo/ResponseCodeInterceptor.swift @@ -50,10 +50,10 @@ public struct ResponseCodeInterceptor: ApolloInterceptor { public init() {} public func interceptAsync( - chain: RequestChain, + chain: any RequestChain, request: HTTPRequest, response: HTTPResponse?, - completion: @escaping (Result, Error>) -> Void) { + completion: @escaping (Result, any Error>) -> Void) { guard response?.httpResponse.isSuccessful == true else { diff --git a/Sources/Apollo/URLSessionClient.swift b/Sources/Apollo/URLSessionClient.swift index 88226b88a..5f10bc532 100644 --- a/Sources/Apollo/URLSessionClient.swift +++ b/Sources/Apollo/URLSessionClient.swift @@ -14,7 +14,7 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat case noHTTPResponse(request: URLRequest?) case sessionBecameInvalidWithoutUnderlyingError case dataForRequestNotFound(request: URLRequest?) - case networkError(data: Data, response: HTTPURLResponse?, underlying: Error) + case networkError(data: Data, response: HTTPURLResponse?, underlying: any Error) case sessionInvalidated case missingMultipartBoundary case cannotParseBoundaryData @@ -40,10 +40,10 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat } /// A completion block to be called when the raw task has completed, with the raw information from the session - public typealias RawCompletion = (Data?, HTTPURLResponse?, Error?) -> Void + public typealias RawCompletion = (Data?, HTTPURLResponse?, (any Error)?) -> Void /// A completion block returning a result. On `.success` it will contain a tuple with non-nil `Data` and its corresponding `HTTPURLResponse`. On `.failure` it will contain an error. - public typealias Completion = (Result<(Data, HTTPURLResponse), Error>) -> Void + public typealias Completion = (Result<(Data, HTTPURLResponse), any Error>) -> Void @Atomic private var tasks: [Int: TaskData] = [:] @@ -169,7 +169,7 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat // MARK: - URLSessionDelegate - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) { let finalError = error ?? URLSessionClientError.sessionBecameInvalidWithoutUnderlyingError for task in self.tasks.values { task.completionBlock(.failure(finalError)) @@ -212,7 +212,7 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat open func urlSession(_ session: URLSession, task: URLSessionTask, - didCompleteWithError error: Error?) { + didCompleteWithError error: (any Error)?) { defer { self.clear(task: task.taskIdentifier) } diff --git a/Sources/Apollo/UploadRequest.swift b/Sources/Apollo/UploadRequest.swift index d2aacdfb5..761a375fc 100644 --- a/Sources/Apollo/UploadRequest.swift +++ b/Sources/Apollo/UploadRequest.swift @@ -6,7 +6,7 @@ import ApolloAPI /// A request class allowing for a multipart-upload request. open class UploadRequest: HTTPRequest { - public let requestBodyCreator: RequestBodyCreator + public let requestBodyCreator: any RequestBodyCreator public let files: [GraphQLFile] public let manualBoundary: String? @@ -31,8 +31,8 @@ open class UploadRequest: HTTPRequest { additionalHeaders: [String: String] = [:], files: [GraphQLFile], manualBoundary: String? = nil, - context: RequestContext? = nil, - requestBodyCreator: RequestBodyCreator = ApolloRequestBodyCreator()) { + context: (any RequestContext)? = nil, + requestBodyCreator: any RequestBodyCreator = ApolloRequestBodyCreator()) { self.requestBodyCreator = requestBodyCreator self.files = files self.manualBoundary = manualBoundary @@ -79,7 +79,7 @@ open class UploadRequest: HTTPRequest { var variables = fields["variables"] as? JSONEncodableDictionary ?? JSONEncodableDictionary() for fieldName in fieldsForFiles { if let value = variables[fieldName], - let arrayValue = value as? [JSONEncodable] { + let arrayValue = value as? [any JSONEncodable] { let arrayOfNils: [NSNull?] = arrayValue.map { _ in NSNull() } variables.updateValue(arrayOfNils, forKey: fieldName) } else { diff --git a/Sources/ApolloAPI/GraphQLOperation.swift b/Sources/ApolloAPI/GraphQLOperation.swift index 8cd6ca5d1..01ef19377 100644 --- a/Sources/ApolloAPI/GraphQLOperation.swift +++ b/Sources/ApolloAPI/GraphQLOperation.swift @@ -54,7 +54,7 @@ public struct OperationDefinition: Sendable { } public protocol GraphQLOperation: AnyObject, Hashable { - typealias Variables = [String: GraphQLOperationVariableValue] + typealias Variables = [String: any GraphQLOperationVariableValue] static var operationName: String { get } static var operationType: GraphQLOperationType { get } @@ -119,7 +119,7 @@ extension Array: GraphQLOperationVariableValue where Element: GraphQLOperationVariableValue & Hashable {} extension Dictionary: GraphQLOperationVariableValue -where Key == String, Value == GraphQLOperationVariableValue { +where Key == String, Value == any GraphQLOperationVariableValue { @inlinable public var _jsonEncodableValue: (any JSONEncodable)? { _jsonEncodableObject } @inlinable public var _jsonEncodableObject: JSONEncodableDictionary { compactMapValues { $0._jsonEncodableValue } diff --git a/Sources/ApolloAPI/JSONStandardTypeConversions.swift b/Sources/ApolloAPI/JSONStandardTypeConversions.swift index 6805b4ca3..a531fee4b 100644 --- a/Sources/ApolloAPI/JSONStandardTypeConversions.swift +++ b/Sources/ApolloAPI/JSONStandardTypeConversions.swift @@ -150,7 +150,7 @@ extension JSONObject: JSONDecodable { extension Array: JSONEncodable { @inlinable public var _jsonValue: JSONValue { return map { element -> JSONValue in - if case let element as JSONEncodable = element { + if case let element as any JSONEncodable = element { return element._jsonValue } else { fatalError("Array is only JSONEncodable if Element is") diff --git a/Sources/ApolloAPI/ObjectData.swift b/Sources/ApolloAPI/ObjectData.swift index 17f0a81e2..96c2044d1 100644 --- a/Sources/ApolloAPI/ObjectData.swift +++ b/Sources/ApolloAPI/ObjectData.swift @@ -8,11 +8,11 @@ public protocol _ObjectData_Transformer { /// sources, using a `_transformer` to ensure the raw data from different sources (which may be in /// different formats) can be consumed with a consistent API. public struct ObjectData { - public let _transformer: _ObjectData_Transformer + public let _transformer: any _ObjectData_Transformer public let _rawData: [String: AnyHashable] public init( - _transformer: _ObjectData_Transformer, + _transformer: any _ObjectData_Transformer, _rawData: [String: AnyHashable] ) { self._transformer = _transformer @@ -55,11 +55,11 @@ public struct ObjectData { /// This type wraps data from different sources, using a `_transformer` to ensure the raw data from /// different sources (which may be in different formats) can be consumed with a consistent API. public struct ListData { - public let _transformer: _ObjectData_Transformer + public let _transformer: any _ObjectData_Transformer public let _rawData: [AnyHashable] public init( - _transformer: _ObjectData_Transformer, + _transformer: any _ObjectData_Transformer, _rawData: [AnyHashable] ) { self._transformer = _transformer diff --git a/Sources/ApolloAPI/SchemaMetadata.swift b/Sources/ApolloAPI/SchemaMetadata.swift index bc27667bf..39ace54fb 100644 --- a/Sources/ApolloAPI/SchemaMetadata.swift +++ b/Sources/ApolloAPI/SchemaMetadata.swift @@ -6,7 +6,7 @@ public protocol SchemaMetadata { /// A ``SchemaConfiguration`` that provides custom configuration for the generated GraphQL schema. - static var configuration: SchemaConfiguration.Type { get } + static var configuration: any SchemaConfiguration.Type { get } /// Maps each object in a `GraphQLResponse` to the ``Object`` type representing the /// response object. diff --git a/Sources/ApolloAPI/SchemaTypes/InputObject.swift b/Sources/ApolloAPI/SchemaTypes/InputObject.swift index cb8389dfe..36c6f477d 100644 --- a/Sources/ApolloAPI/SchemaTypes/InputObject.swift +++ b/Sources/ApolloAPI/SchemaTypes/InputObject.swift @@ -22,9 +22,9 @@ extension InputObject { /// A structure that wraps the underlying data dictionary used by `InputObject`s. public struct InputDict: GraphQLOperationVariableValue, Hashable { - private var data: [String: GraphQLOperationVariableValue] + private var data: [String: any GraphQLOperationVariableValue] - public init(_ data: [String: GraphQLOperationVariableValue] = [:]) { + public init(_ data: [String: any GraphQLOperationVariableValue] = [:]) { self.data = data } diff --git a/Sources/ApolloAPI/Selection.swift b/Sources/ApolloAPI/Selection.swift index 46c62c4e3..badedc064 100644 --- a/Sources/ApolloAPI/Selection.swift +++ b/Sources/ApolloAPI/Selection.swift @@ -60,7 +60,7 @@ public enum Selection { @inlinable static public func field( _ name: String, alias: String? = nil, - _ type: OutputTypeConvertible.Type, + _ type: any OutputTypeConvertible.Type, arguments: [String: InputValue]? = nil ) -> Selection { .field(.init(name, alias: alias, type: type._asOutputType, arguments: arguments)) diff --git a/Sources/ApolloAPI/SelectionSet.swift b/Sources/ApolloAPI/SelectionSet.swift index d8ceca55d..f017bf113 100644 --- a/Sources/ApolloAPI/SelectionSet.swift +++ b/Sources/ApolloAPI/SelectionSet.swift @@ -59,7 +59,7 @@ public protocol SelectionSet: Hashable { /// The GraphQL type for the `SelectionSet`. /// /// This may be a concrete type (`Object`) or an abstract type (`Interface`, or `Union`). - static var __parentType: ParentType { get } + static var __parentType: any ParentType { get } /// The data of the underlying GraphQL object represented by the generated selection set. var __data: DataDict { get } diff --git a/Sources/ApolloSQLite/SQLiteNormalizedCache.swift b/Sources/ApolloSQLite/SQLiteNormalizedCache.swift index b8c276c89..04b552359 100644 --- a/Sources/ApolloSQLite/SQLiteNormalizedCache.swift +++ b/Sources/ApolloSQLite/SQLiteNormalizedCache.swift @@ -13,7 +13,7 @@ public final class SQLiteNormalizedCache { private let shouldVacuumOnClear: Bool - let database: SQLiteDatabase + let database: any SQLiteDatabase /// Designated initializer /// @@ -22,14 +22,14 @@ public final class SQLiteNormalizedCache { /// - shouldVacuumOnClear: If the database should also be `VACCUM`ed on clear to remove all traces of info. Defaults to `false` since this involves a performance hit, but this should be used if you are storing any Personally Identifiable Information in the cache. /// - Throws: Any errors attempting to open or create the database. public init(fileURL: URL, - databaseType: SQLiteDatabase.Type = SQLiteDotSwiftDatabase.self, + databaseType: any SQLiteDatabase.Type = SQLiteDotSwiftDatabase.self, shouldVacuumOnClear: Bool = false) throws { self.database = try databaseType.init(fileURL: fileURL) self.shouldVacuumOnClear = shouldVacuumOnClear try self.database.createRecordsTableIfNeeded() } - public init(database: SQLiteDatabase, + public init(database: any SQLiteDatabase, shouldVacuumOnClear: Bool = false) throws { self.database = database self.shouldVacuumOnClear = shouldVacuumOnClear diff --git a/Sources/ApolloTestSupport/TestMock.swift b/Sources/ApolloTestSupport/TestMock.swift index 3fa32324f..ca64132bd 100644 --- a/Sources/ApolloTestSupport/TestMock.swift +++ b/Sources/ApolloTestSupport/TestMock.swift @@ -97,7 +97,7 @@ public class Mock: AnyMock, Hashable { public var _selectionSetMockData: JSONObject { _data.mapValues { - if let mock = $0.base as? AnyMock { + if let mock = $0.base as? (any AnyMock) { return mock._selectionSetMockData } if let mockArray = $0 as? Array { @@ -156,11 +156,11 @@ public protocol MockFieldValue { } extension Interface: MockFieldValue { - public typealias MockValueCollectionType = Array + public typealias MockValueCollectionType = Array } extension Union: MockFieldValue { - public typealias MockValueCollectionType = Array + public typealias MockValueCollectionType = Array } extension Optional: MockFieldValue where Wrapped: MockFieldValue { @@ -193,7 +193,7 @@ fileprivate extension Array { private func _unsafelyConvertToSelectionSetData(element: Any) -> AnyHashable? { switch element { - case let element as AnyMock: + case let element as any AnyMock: return element._selectionSetMockData case let innerArray as Array: diff --git a/Sources/ApolloWebSocket/DefaultImplementation/WebSocket.swift b/Sources/ApolloWebSocket/DefaultImplementation/WebSocket.swift index 9e4c182c9..38e87a300 100644 --- a/Sources/ApolloWebSocket/DefaultImplementation/WebSocket.swift +++ b/Sources/ApolloWebSocket/DefaultImplementation/WebSocket.swift @@ -132,13 +132,13 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. - public weak var delegate: WebSocketClientDelegate? + public weak var delegate: (any WebSocketClientDelegate)? // Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = DispatchQueue.main public var onConnect: (() -> Void)? - public var onDisconnect: ((Error?) -> Void)? + public var onDisconnect: (((any Error)?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((Data) -> Void)? public var onPong: ((Data?) -> Void)? @@ -152,7 +152,7 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock public var enableCompression = true #if os(Linux) #else - public var security: SSLTrustValidator? + public var security: (any SSLTrustValidator)? public var enabledSSLCipherSuites: [SSLCipherSuite]? #endif @@ -172,7 +172,7 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock /// Note: Will return `false` from the getter and no-op the setter for implementations that do not conform to `SOCKSProxyable`. public var enableSOCKSProxy: Bool { get { - guard let stream = stream as? SOCKSProxyable else { + guard let stream = stream as? (any SOCKSProxyable) else { // If it's not proxyable, then the proxy can't be enabled return false } @@ -181,7 +181,7 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock } set { - guard var stream = stream as? SOCKSProxyable else { + guard var stream = stream as? (any SOCKSProxyable) else { // If it's not proxyable, there's nothing to do here. return } @@ -203,7 +203,7 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock var compressor:Compressor? = nil } - private var stream: WebSocketStream + private var stream: any WebSocketStream private var connected = false private var isConnecting = false private let mutex = NSLock() @@ -534,14 +534,14 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock processInputStream() } - public func streamDidError(error: Error?) { + public func streamDidError(error: (any Error)?) { disconnectStream(error) } /** Disconnect the stream object and notifies the delegate. */ - private func disconnectStream(_ error: Error?, runDelegate: Bool = true) { + private func disconnectStream(_ error: (any Error)?, runDelegate: Bool = true) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { @@ -1105,7 +1105,7 @@ public final class WebSocket: NSObject, WebSocketClient, StreamDelegate, WebSock /** Used to preform the disconnect delegate */ - private func doDisconnect(_ error: Error?) { + private func doDisconnect(_ error: (any Error)?) { guard !didDisconnect else { return } didDisconnect = true isConnecting = false diff --git a/Sources/ApolloWebSocket/DefaultImplementation/WebSocketStream.swift b/Sources/ApolloWebSocket/DefaultImplementation/WebSocketStream.swift index 88f978a28..95047f5e7 100644 --- a/Sources/ApolloWebSocket/DefaultImplementation/WebSocketStream.swift +++ b/Sources/ApolloWebSocket/DefaultImplementation/WebSocketStream.swift @@ -12,7 +12,7 @@ import Foundation protocol WebSocketStreamDelegate: AnyObject { func newBytesInStream() - func streamDidError(error: Error?) + func streamDidError(error: (any Error)?) } public protocol SOCKSProxyable { @@ -24,13 +24,13 @@ public protocol SOCKSProxyable { // This protocol is to allow custom implemention of the underlining stream. // This way custom socket libraries (e.g. linux) can be used protocol WebSocketStream { - var delegate: WebSocketStreamDelegate? { get set } + var delegate: (any WebSocketStreamDelegate)? { get set } func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, - completion: @escaping ((Error?) -> Void)) + completion: @escaping (((any Error)?) -> Void)) func write(data: Data) -> Int func read() -> Data? @@ -46,12 +46,12 @@ class FoundationStream : NSObject, WebSocketStream, StreamDelegate, SOCKSProxyab private let workQueue = DispatchQueue(label: "com.apollographql.websocket", attributes: []) private var inputStream: InputStream? private var outputStream: OutputStream? - weak var delegate: WebSocketStreamDelegate? + weak var delegate: (any WebSocketStreamDelegate)? let BUFFER_MAX = 4096 var enableSOCKSProxy = false - func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) { + func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping (((any Error)?) -> Void)) { var readStream: Unmanaged? var writeStream: Unmanaged? let h = url.host! as NSString diff --git a/Sources/ApolloWebSocket/OperationMessage.swift b/Sources/ApolloWebSocket/OperationMessage.swift index 001b091c0..a2d369ff2 100644 --- a/Sources/ApolloWebSocket/OperationMessage.swift +++ b/Sources/ApolloWebSocket/OperationMessage.swift @@ -115,12 +115,12 @@ struct ParseHandler { let type: String? let id: String? let payload: JSONObject? - let error: Error? + let error: (any Error)? init(_ type: String?, _ id: String?, _ payload: JSONObject?, - _ error: Error?) { + _ error: (any Error)?) { self.type = type self.id = id self.payload = payload diff --git a/Sources/ApolloWebSocket/SplitNetworkTransport.swift b/Sources/ApolloWebSocket/SplitNetworkTransport.swift index c35f362e2..ea4c921e4 100644 --- a/Sources/ApolloWebSocket/SplitNetworkTransport.swift +++ b/Sources/ApolloWebSocket/SplitNetworkTransport.swift @@ -6,8 +6,8 @@ import ApolloAPI /// A network transport that sends subscriptions using one `NetworkTransport` and other requests using another `NetworkTransport`. Ideal for sending subscriptions via a web socket but everything else via HTTP. public class SplitNetworkTransport { - private let uploadingNetworkTransport: UploadingNetworkTransport - private let webSocketNetworkTransport: NetworkTransport + private let uploadingNetworkTransport: any UploadingNetworkTransport + private let webSocketNetworkTransport: any NetworkTransport public var clientName: String { let httpName = self.uploadingNetworkTransport.clientName @@ -34,7 +34,7 @@ public class SplitNetworkTransport { /// - Parameters: /// - uploadingNetworkTransport: An `UploadingNetworkTransport` to use for non-subscription requests. Should generally be a `RequestChainNetworkTransport` or something similar. /// - webSocketNetworkTransport: A `NetworkTransport` to use for subscription requests. Should generally be a `WebSocketTransport` or something similar. - public init(uploadingNetworkTransport: UploadingNetworkTransport, webSocketNetworkTransport: NetworkTransport) { + public init(uploadingNetworkTransport: any UploadingNetworkTransport, webSocketNetworkTransport: any NetworkTransport) { self.uploadingNetworkTransport = uploadingNetworkTransport self.webSocketNetworkTransport = webSocketNetworkTransport } @@ -47,9 +47,9 @@ extension SplitNetworkTransport: NetworkTransport { public func send(operation: Operation, cachePolicy: CachePolicy, contextIdentifier: UUID? = nil, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, callbackQueue: DispatchQueue = .main, - completionHandler: @escaping (Result, Error>) -> Void) -> Cancellable { + completionHandler: @escaping (Result, any Error>) -> Void) -> any Cancellable { if Operation.operationType == .subscription { return webSocketNetworkTransport.send(operation: operation, cachePolicy: cachePolicy, @@ -75,9 +75,9 @@ extension SplitNetworkTransport: UploadingNetworkTransport { public func upload( operation: Operation, files: [GraphQLFile], - context: RequestContext?, + context: (any RequestContext)?, callbackQueue: DispatchQueue = .main, - completionHandler: @escaping (Result, Error>) -> Void) -> Cancellable { + completionHandler: @escaping (Result, any Error>) -> Void) -> any Cancellable { return uploadingNetworkTransport.upload(operation: operation, files: files, context: context, diff --git a/Sources/ApolloWebSocket/WebSocketClient.swift b/Sources/ApolloWebSocket/WebSocketClient.swift index 91b0e887c..8f73fe568 100644 --- a/Sources/ApolloWebSocket/WebSocketClient.swift +++ b/Sources/ApolloWebSocket/WebSocketClient.swift @@ -12,7 +12,7 @@ public protocol WebSocketClient: AnyObject { /// /// - Note: The `WebSocketTransport` will set itself as the delgate for the client. Consumers /// should set themselves as the delegate for the `WebSocketTransport` to observe events. - var delegate: WebSocketClientDelegate? { get set } + var delegate: (any WebSocketClientDelegate)? { get set } /// `DispatchQueue` where the websocket client should call all delegate callbacks. var callbackQueue: DispatchQueue { get set } @@ -38,23 +38,23 @@ public protocol WebSocketClientDelegate: AnyObject { /// The websocket client has started a connection to the server. /// - Parameter socket: The `WebSocketClient` that sent the delegate event. - func websocketDidConnect(socket: WebSocketClient) + func websocketDidConnect(socket: any WebSocketClient) /// The websocket client has disconnected from the server. /// - Parameters: /// - socket: The `WebSocketClient` that sent the delegate event. /// - error: An optional error if an error occured. - func websocketDidDisconnect(socket: WebSocketClient, error: Error?) + func websocketDidDisconnect(socket: any WebSocketClient, error: (any Error)?) /// The websocket client received message text from the server /// - Parameters: /// - socket: The `WebSocketClient` that sent the delegate event. /// - text: The text received from the server. - func websocketDidReceiveMessage(socket: WebSocketClient, text: String) + func websocketDidReceiveMessage(socket: any WebSocketClient, text: String) /// The websocket client received data from the server /// - Parameters: /// - socket: The `WebSocketClient` that sent the delegate event. /// - data: The data received from the server. - func websocketDidReceiveData(socket: WebSocketClient, data: Data) + func websocketDidReceiveData(socket: any WebSocketClient, data: Data) } diff --git a/Sources/ApolloWebSocket/WebSocketError.swift b/Sources/ApolloWebSocket/WebSocketError.swift index f9655ecaa..a314e80fa 100644 --- a/Sources/ApolloWebSocket/WebSocketError.swift +++ b/Sources/ApolloWebSocket/WebSocketError.swift @@ -35,7 +35,7 @@ public struct WebSocketError: Error, LocalizedError { public let payload: JSONObject? /// The underlying error, or nil if one was not returned - public let error: Error? + public let error: (any Error)? /// The kind of problem which occurred. public let kind: ErrorKind diff --git a/Sources/ApolloWebSocket/WebSocketTask.swift b/Sources/ApolloWebSocket/WebSocketTask.swift index b2557fda5..01369803a 100644 --- a/Sources/ApolloWebSocket/WebSocketTask.swift +++ b/Sources/ApolloWebSocket/WebSocketTask.swift @@ -16,7 +16,7 @@ final class WebSocketTask: Cancellable { /// - Parameter completionHandler: A completion handler to fire when the operation has a result. init(_ ws: WebSocketTransport, _ operation: Operation, - _ completionHandler: @escaping (_ result: Result) -> Void) { + _ completionHandler: @escaping (_ result: Result) -> Void) { sequenceNumber = ws.sendHelper(operation: operation, resultHandler: completionHandler) transport = ws } diff --git a/Sources/ApolloWebSocket/WebSocketTransport.swift b/Sources/ApolloWebSocket/WebSocketTransport.swift index 91d67c51d..9405ae153 100644 --- a/Sources/ApolloWebSocket/WebSocketTransport.swift +++ b/Sources/ApolloWebSocket/WebSocketTransport.swift @@ -9,13 +9,13 @@ import Foundation public protocol WebSocketTransportDelegate: AnyObject { func webSocketTransportDidConnect(_ webSocketTransport: WebSocketTransport) func webSocketTransportDidReconnect(_ webSocketTransport: WebSocketTransport) - func webSocketTransport(_ webSocketTransport: WebSocketTransport, didDisconnectWithError error:Error?) + func webSocketTransport(_ webSocketTransport: WebSocketTransport, didDisconnectWithError error:(any Error)?) } public extension WebSocketTransportDelegate { func webSocketTransportDidConnect(_ webSocketTransport: WebSocketTransport) {} func webSocketTransportDidReconnect(_ webSocketTransport: WebSocketTransport) {} - func webSocketTransport(_ webSocketTransport: WebSocketTransport, didDisconnectWithError error:Error?) {} + func webSocketTransport(_ webSocketTransport: WebSocketTransport, didDisconnectWithError error:(any Error)?) {} func webSocketTransport(_ webSocketTransport: WebSocketTransport, didReceivePingData: Data?) {} func webSocketTransport(_ webSocketTransport: WebSocketTransport, didReceivePongData: Data?) {} } @@ -24,12 +24,12 @@ public extension WebSocketTransportDelegate { /// A network transport that uses web sockets requests to send GraphQL subscription operations to a server. public class WebSocketTransport { - public weak var delegate: WebSocketTransportDelegate? + public weak var delegate: (any WebSocketTransportDelegate)? - let websocket: WebSocketClient + let websocket: any WebSocketClient let store: ApolloStore? private(set) var config: Configuration - @Atomic var error: Error? + @Atomic var error: (any Error)? let serializationFormat = JSONSerializationFormat.self /// non-private for testing - you should not use this directly @@ -49,7 +49,7 @@ public class WebSocketTransport { private var queue: [Int: String] = [:] - private var subscribers = [String: (Result) -> Void]() + private var subscribers = [String: (Result) -> Void]() private var subscriptions : [String: String] = [:] let processingQueue = DispatchQueue(label: "com.apollographql.WebSocketTransport") @@ -96,10 +96,10 @@ public class WebSocketTransport { /// [optional]The payload to send on connection. Defaults to an empty `JSONEncodableDictionary`. public fileprivate(set) var connectingPayload: JSONEncodableDictionary? /// The `RequestBodyCreator` to use when serializing requests. Defaults to an `ApolloRequestBodyCreator`. - public let requestBodyCreator: RequestBodyCreator + public let requestBodyCreator: any RequestBodyCreator /// The `OperationMessageIdCreator` used to generate a unique message identifier per request. /// Defaults to `ApolloSequencedOperationMessageIdCreator`. - public let operationMessageIdCreator: OperationMessageIdCreator + public let operationMessageIdCreator: any OperationMessageIdCreator /// The designated initializer public init( @@ -110,8 +110,8 @@ public class WebSocketTransport { allowSendingDuplicates: Bool = true, connectOnInit: Bool = true, connectingPayload: JSONEncodableDictionary? = [:], - requestBodyCreator: RequestBodyCreator = ApolloRequestBodyCreator(), - operationMessageIdCreator: OperationMessageIdCreator = ApolloSequencedOperationMessageIdCreator() + requestBodyCreator: any RequestBodyCreator = ApolloRequestBodyCreator(), + operationMessageIdCreator: any OperationMessageIdCreator = ApolloSequencedOperationMessageIdCreator() ) { self.clientName = clientName self.clientVersion = clientVersion @@ -130,7 +130,7 @@ public class WebSocketTransport { /// Note: Will return `false` from the getter and no-op the setter for implementations that do not conform to `SOCKSProxyable`. public var enableSOCKSProxy: Bool { get { - guard let websocket = websocket as? SOCKSProxyable else { + guard let websocket = websocket as? (any SOCKSProxyable) else { // If it's not proxyable, then the proxy can't be enabled return false } @@ -139,7 +139,7 @@ public class WebSocketTransport { } set { - guard var websocket = websocket as? SOCKSProxyable else { + guard var websocket = websocket as? (any SOCKSProxyable) else { // If it's not proxyable, there's nothing to do here. return } @@ -156,7 +156,7 @@ public class WebSocketTransport { /// - config: A `WebSocketTransport.Configuration` object with options for configuring the /// web socket connection. Defaults to a configuration with default values. public init( - websocket: WebSocketClient, + websocket: any WebSocketClient, store: ApolloStore? = nil, config: Configuration = Configuration() ) { @@ -253,7 +253,7 @@ public class WebSocketTransport { } } - private func notifyErrorAllHandlers(_ error: Error) { + private func notifyErrorAllHandlers(_ error: any Error) { for (_, handler) in subscribers { handler(.failure(error)) } @@ -323,7 +323,7 @@ public class WebSocketTransport { self.websocket.delegate = nil } - func sendHelper(operation: Operation, resultHandler: @escaping (_ result: Result) -> Void) -> String? { + func sendHelper(operation: Operation, resultHandler: @escaping (_ result: Result) -> Void) -> String? { let body = config.requestBodyCreator.requestBody(for: operation, sendQueryDocument: true, autoPersistQuery: false) @@ -438,11 +438,11 @@ extension WebSocketTransport: NetworkTransport { operation: Operation, cachePolicy: CachePolicy, contextIdentifier: UUID? = nil, - context: RequestContext? = nil, + context: (any RequestContext)? = nil, callbackQueue: DispatchQueue = .main, - completionHandler: @escaping (Result, Error>) -> Void) -> Cancellable { + completionHandler: @escaping (Result, any Error>) -> Void) -> any Cancellable { - func callCompletion(with result: Result, Error>) { + func callCompletion(with result: Result, any Error>) { callbackQueue.async { completionHandler(result) } @@ -497,7 +497,7 @@ extension WebSocketTransport: NetworkTransport { extension WebSocketTransport: WebSocketClientDelegate { - public func websocketDidConnect(socket: WebSocketClient) { + public func websocketDidConnect(socket: any WebSocketClient) { self.handleConnection() } @@ -525,7 +525,7 @@ extension WebSocketTransport: WebSocketClientDelegate { self.reconnected = true } - public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { + public func websocketDidDisconnect(socket: any WebSocketClient, error: (any Error)?) { self.$socketConnectionState.mutate { $0 = .disconnected } if let error = error { handleDisconnection(with: error) @@ -536,7 +536,7 @@ extension WebSocketTransport: WebSocketClientDelegate { } } - private func handleDisconnection(with error: Error) { + private func handleDisconnection(with error: any Error) { // Set state to `.failed`, and grab its previous value. let previousState: SocketConnectionState = self.$socketConnectionState.mutate { socketConnectionState in let previousState = socketConnectionState @@ -590,11 +590,11 @@ extension WebSocketTransport: WebSocketClientDelegate { } } - public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + public func websocketDidReceiveMessage(socket: any WebSocketClient, text: String) { self.processMessage(text: text) } - public func websocketDidReceiveData(socket: WebSocketClient, data: Data) { + public func websocketDidReceiveData(socket: any WebSocketClient, data: Data) { self.processMessage(data: data) }