diff --git a/Amplify/Categories/API/APICategory.swift b/Amplify/Categories/API/APICategory.swift index d09ef87cb2..4725180daa 100644 --- a/Amplify/Categories/API/APICategory.swift +++ b/Amplify/Categories/API/APICategory.swift @@ -11,7 +11,7 @@ final public class APICategory: Category { public var categoryType: CategoryType { .api } - + var plugins = [PluginKey: APICategoryPlugin]() /// Returns the plugin added to the category, if only one plugin is added. Accessing this property if no plugins @@ -49,7 +49,7 @@ final public class APICategory: Category { public var isConfigured = false // MARK: - Plugin handling - + /// Adds `plugin` to the list of Plugins that implement functionality for this category. /// /// - Parameter plugin: The Plugin to add diff --git a/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift index 59d5614dd9..10510fc7e0 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift @@ -6,16 +6,16 @@ // extension APICategory: APICategoryGraphQLBehavior { - + // MARK: - Request-based GraphQL operations public func query(request: GraphQLRequest) async throws -> GraphQLTask.Success { try await plugin.query(request: request) } - + public func mutate(request: GraphQLRequest) async throws -> GraphQLTask.Success { try await plugin.mutate(request: request) } - + public func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> { plugin.subscribe(request: request) } diff --git a/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift index e0e453f327..8daa59636d 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift @@ -8,7 +8,7 @@ import Foundation extension APICategory: APICategoryRESTBehavior { - + public func get(request: RESTRequest) async throws -> RESTTask.Success { try await plugin.get(request: request) } diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift index 841c4e1681..d149b5d945 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift @@ -18,7 +18,7 @@ public protocol APICategoryGraphQLBehavior: AnyObject { /// - listener: The event listener for the operation /// - Returns: The AmplifyOperation being enqueued func query(request: GraphQLRequest) async throws -> GraphQLTask.Success - + /// Perform a GraphQL mutate operation against a previously configured API. This operation /// will be asynchronous, with the callback accessible both locally and via the Hub. /// @@ -36,5 +36,7 @@ public protocol APICategoryGraphQLBehavior: AnyObject { /// - valueListener: Invoked when the GraphQL subscription receives a new value from the service /// - completionListener: Invoked when the subscription has terminated /// - Returns: The AmplifyInProcessReportingOperation being enqueued - func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> + func subscribe( + request: GraphQLRequest + ) -> AmplifyAsyncThrowingSequence> } diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift index 8fafc4c52d..0a4c33c27e 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift @@ -27,13 +27,13 @@ public protocol APICategoryRESTBehavior { /// - Parameter request: Contains information such as path, query parameters, body. /// - Returns: An operation that can be observed for its value func post(request: RESTRequest) async throws -> RESTTask.Success - + /// Perform an HTTP DELETE operation /// /// - Parameter request: Contains information such as path, query parameters, body. /// - Returns: An operation that can be observed for its value func delete(request: RESTRequest) async throws -> RESTTask.Success - + /// Perform an HTTP HEAD operation /// /// - Parameter request: Contains information such as path, query parameters, body. diff --git a/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift b/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift index 7b4b36ef59..ed2a6e2753 100644 --- a/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift +++ b/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift @@ -116,7 +116,7 @@ public final class RetryableGraphQLOperation: Operation, Ret self.operationFactory = operationFactory self.resultListener = resultListener } - + public override func main() { Task { start(request: await requestFactory()) diff --git a/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift b/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift index 796b3865a5..e73abe1c15 100644 --- a/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift +++ b/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift @@ -50,7 +50,7 @@ extension AnalyticsCategory { public func unregisterGlobalProperties(_ keys: String...) { plugin.unregisterGlobalProperties(keys.isEmpty ? nil : Set(keys)) } - + /// Registered global properties can be unregistered though this method. In case no keys are provided, *all* /// registered global properties will be unregistered. Duplicate keys will be ignored. This method can be called /// from `Amplify.Analytics` and is a wrapper for `unregisterGlobalProperties(_ keys: Set? = nil)` diff --git a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift index dfd92b9e92..8896be20ea 100644 --- a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift @@ -9,7 +9,11 @@ import Foundation extension AuthCategory: AuthCategoryBehavior { - public func signUp( username: String, password: String? = nil, options: AuthSignUpRequest.Options? = nil) async throws -> AuthSignUpResult { + public func signUp( + username: String, + password: String? = nil, + options: AuthSignUpRequest.Options? = nil + ) async throws -> AuthSignUpResult { return try await plugin.signUp(username: username, password: password, options: options) } @@ -19,7 +23,10 @@ extension AuthCategory: AuthCategoryBehavior { return try await plugin.confirmSignUp(for: username, confirmationCode: confirmationCode, options: options) } - public func resendSignUpCode(for username: String, options: AuthResendSignUpCodeRequest.Options? = nil) async throws -> AuthCodeDeliveryDetails { + public func resendSignUpCode( + for username: String, + options: AuthResendSignUpCodeRequest.Options? = nil + ) async throws -> AuthCodeDeliveryDetails { return try await plugin.resendSignUpCode(for: username, options: options) } @@ -46,14 +53,17 @@ extension AuthCategory: AuthCategoryBehavior { } #endif - public func confirmSignIn(challengeResponse: String, options: AuthConfirmSignInRequest.Options? = nil) async throws -> AuthSignInResult { + public func confirmSignIn( + challengeResponse: String, + options: AuthConfirmSignInRequest.Options? = nil + ) async throws -> AuthSignInResult { return try await plugin.confirmSignIn(challengeResponse: challengeResponse, options: options) } public func signOut(options: AuthSignOutRequest.Options? = nil) async -> AuthSignOutResult { return await plugin.signOut(options: options) } - + public func deleteUser() async throws { try await plugin.deleteUser() } @@ -62,8 +72,11 @@ extension AuthCategory: AuthCategoryBehavior { return try await plugin.fetchAuthSession(options: options) } - public func resetPassword(for username: String, options: AuthResetPasswordRequest.Options? = nil) async throws -> AuthResetPasswordResult { - return try await plugin.resetPassword(for: username,options: options) + public func resetPassword( + for username: String, + options: AuthResetPasswordRequest.Options? = nil + ) async throws -> AuthResetPasswordResult { + return try await plugin.resetPassword(for: username, options: options) } public func confirmResetPassword( @@ -72,7 +85,12 @@ extension AuthCategory: AuthCategoryBehavior { confirmationCode: String, options: AuthConfirmResetPasswordRequest.Options? = nil ) async throws { - try await plugin.confirmResetPassword(for: username, with: newPassword, confirmationCode: confirmationCode, options: options) + try await plugin.confirmResetPassword( + for: username, + with: newPassword, + confirmationCode: confirmationCode, + options: options + ) } public func setUpTOTP() async throws -> TOTPSetupDetails { diff --git a/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift b/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift index 104fb56a6f..a9da3b0099 100644 --- a/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift @@ -9,11 +9,16 @@ import Foundation extension AuthCategory: AuthCategoryDeviceBehavior { - public func fetchDevices( options: AuthFetchDevicesRequest.Options? = nil) async throws -> [AuthDevice] { + public func fetchDevices( + options: AuthFetchDevicesRequest.Options? = nil + ) async throws -> [AuthDevice] { return try await plugin.fetchDevices(options: options) } - public func forgetDevice( _ device: AuthDevice? = nil, options: AuthForgetDeviceRequest.Options? = nil) async throws { + public func forgetDevice( + _ device: AuthDevice? = nil, + options: AuthForgetDeviceRequest.Options? = nil + ) async throws { try await plugin.forgetDevice(device, options: options) } diff --git a/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift b/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift index 5c3fc21076..6589e03083 100644 --- a/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift @@ -13,11 +13,16 @@ extension AuthCategory: AuthCategoryUserBehavior { try await plugin.getCurrentUser() } - public func fetchUserAttributes(options: AuthFetchUserAttributesRequest.Options? = nil) async throws -> [AuthUserAttribute] { + public func fetchUserAttributes( + options: AuthFetchUserAttributesRequest.Options? = nil + ) async throws -> [AuthUserAttribute] { try await plugin.fetchUserAttributes(options: options) } - public func update(userAttribute: AuthUserAttribute, options: AuthUpdateUserAttributeRequest.Options? = nil) async throws -> AuthUpdateAttributeResult { + public func update( + userAttribute: AuthUserAttribute, + options: AuthUpdateUserAttributeRequest.Options? = nil + ) async throws -> AuthUpdateAttributeResult { try await plugin.update(userAttribute: userAttribute, options: options) } @@ -45,10 +50,18 @@ extension AuthCategory: AuthCategoryUserBehavior { public func confirm(userAttribute: AuthUserAttributeKey, confirmationCode: String, options: AuthConfirmUserAttributeRequest.Options? = nil) async throws { - try await plugin.confirm(userAttribute: userAttribute, confirmationCode: confirmationCode, options: options) + try await plugin.confirm( + userAttribute: userAttribute, + confirmationCode: confirmationCode, + options: options + ) } - public func update(oldPassword: String, to newPassword: String, options: AuthChangePasswordRequest.Options? = nil) async throws { + public func update( + oldPassword: String, + to newPassword: String, + options: AuthChangePasswordRequest.Options? = nil + ) async throws { try await plugin.update(oldPassword: oldPassword, to: newPassword, options: options) } diff --git a/Amplify/Categories/Auth/AuthCategoryBehavior.swift b/Amplify/Categories/Auth/AuthCategoryBehavior.swift index dd42213863..68f6cc2f7f 100644 --- a/Amplify/Categories/Auth/AuthCategoryBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategoryBehavior.swift @@ -24,7 +24,11 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - username: username to signUp /// - password: password as per the password policy of the provider /// - options: Parameters specific to plugin behavior - func signUp(username: String, password: String?, options: AuthSignUpRequest.Options?) async throws -> AuthSignUpResult + func signUp( + username: String, + password: String?, + options: AuthSignUpRequest.Options? + ) async throws -> AuthSignUpResult /// Confirms the `signUp` operation. /// @@ -44,7 +48,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - Parameters: /// - username: Username of the user to be confirmed. /// - options: Parameters specific to plugin behavior. - func resendSignUpCode(for username: String, options: AuthResendSignUpCodeRequest.Options?) async throws -> AuthCodeDeliveryDetails + func resendSignUpCode( + for username: String, + options: AuthResendSignUpCodeRequest.Options? + ) async throws -> AuthCodeDeliveryDetails /// SignIn to the authentication provider /// @@ -90,7 +97,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - Parameters: /// - challengeResponse: Challenge response required to confirm the next step in signIn flow /// - options: Parameters specific to plugin behavior. - func confirmSignIn(challengeResponse: String, options: AuthConfirmSignInRequest.Options?) async throws -> AuthSignInResult + func confirmSignIn( + challengeResponse: String, + options: AuthConfirmSignInRequest.Options? + ) async throws -> AuthSignInResult /// Sign out the currently logged-in user. /// @@ -122,12 +132,18 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - newPassword: new password for the user /// - confirmationCode: Received confirmation code /// - options: Parameters specific to plugin behavior - func confirmResetPassword(for username: String, with newPassword: String, confirmationCode: String, options: AuthConfirmResetPasswordRequest.Options?) async throws + func confirmResetPassword( + for username: String, + with newPassword: String, + confirmationCode: String, + options: AuthConfirmResetPasswordRequest.Options? + ) async throws /// Initiates TOTP Setup /// /// Invoke this operation to setup TOTP for the user while signed in. - /// Calling this method will initiate TOTP setup process and returns a shared secret that can be used to generate QR code. + /// Calling this method will initiate TOTP setup process and + /// returns a shared secret that can be used to generate QR code. /// The setup details also contains a URI generator helper that can be used to retireve a TOTP Setup URI. /// func setUpTOTP() async throws -> TOTPSetupDetails @@ -135,7 +151,8 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// Verifies TOTP Setup /// /// Invoke this operation to verify TOTP setup for the user while signed in. - /// Calling this method with the verification code from the associated Authenticator app will complete the TOTP setup process. + /// Calling this method with the verification code from the associated Authenticator app + /// will complete the TOTP setup process. /// /// - Parameters: /// - code: verification code from the associated Authenticator app diff --git a/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift b/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift index f3917109c7..ad9d106eaf 100644 --- a/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift @@ -17,22 +17,29 @@ public protocol AuthCategoryUserBehavior: AnyObject { /// /// - Parameters: /// - options: Parameters specific to plugin behavior - func fetchUserAttributes(options: AuthFetchUserAttributesRequest.Options?) async throws -> [AuthUserAttribute] + func fetchUserAttributes( + options: AuthFetchUserAttributesRequest.Options? + ) async throws -> [AuthUserAttribute] /// Update user attribute for the current user /// /// - Parameters: /// - userAttribute: Attribute that need to be updated /// - options: Parameters specific to plugin behavior - func update(userAttribute: AuthUserAttribute, options: AuthUpdateUserAttributeRequest.Options?) async throws -> AuthUpdateAttributeResult + func update( + userAttribute: AuthUserAttribute, + options: AuthUpdateUserAttributeRequest.Options? + ) async throws -> AuthUpdateAttributeResult /// Update a list of user attributes for the current user /// /// - Parameters: /// - userAttributes: List of attribtues that need ot be updated /// - options: Parameters specific to plugin behavior - func update(userAttributes: [AuthUserAttribute], - options: AuthUpdateUserAttributesRequest.Options?) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] + func update( + userAttributes: [AuthUserAttribute], + options: AuthUpdateUserAttributesRequest.Options? + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] /// Resends the confirmation code required to verify an attribute /// @@ -61,7 +68,11 @@ public protocol AuthCategoryUserBehavior: AnyObject { /// - userAttribute: Attribute to verify /// - confirmationCode: Confirmation code received /// - options: Parameters specific to plugin behavior - func confirm(userAttribute: AuthUserAttributeKey, confirmationCode: String, options: AuthConfirmUserAttributeRequest.Options?) async throws + func confirm( + userAttribute: AuthUserAttributeKey, + confirmationCode: String, + options: AuthConfirmUserAttributeRequest.Options? + ) async throws /// Update the current logged in user's password /// @@ -70,5 +81,9 @@ public protocol AuthCategoryUserBehavior: AnyObject { /// - oldPassword: Current password of the user /// - newPassword: New password to be updated /// - options: Parameters specific to plugin behavior - func update(oldPassword: String, to newPassword: String, options: AuthChangePasswordRequest.Options?) async throws + func update( + oldPassword: String, + to newPassword: String, + options: AuthChangePasswordRequest.Options? + ) async throws } diff --git a/Amplify/Categories/Auth/Models/AuthUserAttribute.swift b/Amplify/Categories/Auth/Models/AuthUserAttribute.swift index 01d77b6308..7990ffe276 100644 --- a/Amplify/Categories/Auth/Models/AuthUserAttribute.swift +++ b/Amplify/Categories/Auth/Models/AuthUserAttribute.swift @@ -28,7 +28,7 @@ public enum AuthUserAttributeKey { /// Attribute key for user's email case email - + /// Attribute key for user's email verfication status case emailVerified @@ -55,7 +55,7 @@ public enum AuthUserAttributeKey { /// Attribute key for user's phone number case phoneNumber - + /// Attribute key for user's phone number verficiation status case phoneNumberVerified @@ -64,19 +64,19 @@ public enum AuthUserAttributeKey { /// Attribute key for user's preferred user name case preferredUsername - + /// Attribute key for user's profile case profile - + /// Attribute key for user's identifier case sub - + /// Attribute key for time of user's information last updated case updatedAt - + /// Attribute key for user's web page case website - + /// Attribute key for user's time zone case zoneInfo @@ -90,4 +90,3 @@ public enum AuthUserAttributeKey { extension AuthUserAttributeKey: Hashable {} extension AuthUserAttributeKey: Equatable {} - diff --git a/Amplify/Categories/Auth/Models/DeliveryDestination.swift b/Amplify/Categories/Auth/Models/DeliveryDestination.swift index defa40d415..17a417d8ec 100644 --- a/Amplify/Categories/Auth/Models/DeliveryDestination.swift +++ b/Amplify/Categories/Auth/Models/DeliveryDestination.swift @@ -24,4 +24,3 @@ public enum DeliveryDestination { } extension DeliveryDestination: Equatable { } - diff --git a/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift b/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift index da8bbd1e7b..debdb449e4 100644 --- a/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift @@ -47,4 +47,3 @@ extension AuthFetchSessionRequest.Options { return AuthFetchSessionRequest.Options(forceRefresh: true) } } - diff --git a/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift b/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift index df1ca20da8..4d7e12093f 100644 --- a/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift @@ -52,7 +52,6 @@ public extension AuthSignOutRequest { #endif } - } #if os(iOS) || os(macOS) diff --git a/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift b/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift index 1852dc2564..f320daff43 100644 --- a/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift @@ -21,7 +21,7 @@ public struct AuthWebUISignInRequest: AmplifyOperationRequest { /// Presentation anchor on which the webUI is displayed public let presentationAnchor: AuthUIPresentationAnchor? - + public init(presentationAnchor: AuthUIPresentationAnchor?, authProvider: AuthProvider? = nil, options: Options) { @@ -37,7 +37,7 @@ public extension AuthWebUISignInRequest { /// Scopes to be defined for the sign in user public let scopes: [String]? - + /// Extra plugin specific options, only used in special circumstances when the existing options do not provide /// a way to utilize the underlying auth plugin functionality. See plugin documentation for expected /// key/values diff --git a/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift b/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift index ed400245f0..4d15a9bff1 100644 --- a/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift +++ b/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift @@ -17,7 +17,7 @@ extension DataStoreCategory: DataStoreBaseBehavior { byId id: String) async throws -> M? { try await plugin.query(modelType, byId: id) } - + public func query(_ modelType: M.Type, byIdentifier id: String) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { @@ -41,13 +41,13 @@ extension DataStoreCategory: DataStoreBaseBehavior { where predicate: QueryPredicate? = nil) async throws { try await plugin.delete(model, where: predicate) } - + public func delete(_ modelType: M.Type, withId id: String, where predicate: QueryPredicate? = nil) async throws { try await plugin.delete(modelType, withId: id, where: predicate) } - + public func delete(_ modelType: M.Type, withIdentifier id: String, where predicate: QueryPredicate? = nil) async throws @@ -60,7 +60,7 @@ extension DataStoreCategory: DataStoreBaseBehavior { where predicate: QueryPredicate? = nil) async throws where M: ModelIdentifiable { try await plugin.delete(modelType, withIdentifier: id, where: predicate) } - + public func delete(_ modelType: M.Type, where predicate: QueryPredicate) async throws { try await plugin.delete(modelType, where: predicate) diff --git a/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift b/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift index d6de0186f7..43aa4d3892 100644 --- a/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift +++ b/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift @@ -39,7 +39,7 @@ public protocol DataStoreBaseBehavior { func delete(_ modelType: M.Type, withId id: String, where predicate: QueryPredicate?) async throws - + func delete(_ modelType: M.Type, withIdentifier id: String, where predicate: QueryPredicate?) async throws where M: ModelIdentifiable, @@ -82,7 +82,7 @@ public protocol DataStoreSubscribeBehavior { /// Returns an AmplifyAsyncThrowingSequence for model changes (create, updates, delete) /// - Parameter modelType: The model type to observe func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence - + /// Returns a Publisher for query snapshots. /// /// - Parameters: diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift b/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift index 9b593b04e0..582d9bdc1c 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift @@ -40,7 +40,7 @@ public protocol ModelListProvider { associatedtype Element: Model func getState() -> ModelListProviderState - + /// Retrieve the array of `Element` from the data source asychronously. func load() async throws -> [Element] @@ -52,7 +52,7 @@ public protocol ModelListProvider { /// Asynchronously retrieve the next page as a new in-memory List object. Returns a failure if there /// is no next page of results. You can validate whether the list has another page with `hasNextPage()`. func getNextPage() async throws -> List - + /// Custom encoder func encode(to encoder: Encoder) throws } @@ -67,7 +67,7 @@ public struct AnyModelListProvider: ModelListProvider { private let hasNextPageClosure: () -> Bool private let getNextPageAsync: () async throws -> List private let encodeClosure: (Encoder) throws -> Void - + public init( provider: Provider ) where Provider.Element == Self.Element { @@ -81,7 +81,7 @@ public struct AnyModelListProvider: ModelListProvider { public func getState() -> ModelListProviderState { getStateClosure() } - + public func load() async throws -> [Element] { try await loadAsync() } @@ -93,7 +93,7 @@ public struct AnyModelListProvider: ModelListProvider { public func getNextPage() async throws -> List { try await getNextPageAsync() } - + public func encode(to encoder: Encoder) throws { try encodeClosure(encoder) } diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift index 2f61c3c562..98c93dfa00 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift @@ -6,7 +6,7 @@ // import Foundation - +// swiftlint:disable type_name /// Protocol used as a marker to detect when the type is a `LazyReference`. /// Used to retrieve either the `reference` or the `identifiers` of the Model directly, without having load a not /// loaded LazyReference. This is useful when translating the model object over to the payload required for the @@ -18,13 +18,14 @@ import Foundation /// application making any change to these `public` types should be backward compatible, otherwise it will be a breaking /// change. public protocol _LazyReferenceValue { - var _state: _LazyReferenceValueState { get } + var _state: _LazyReferenceValueState { get } // swiftlint:disable:this identifier_name } public enum _LazyReferenceValueState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(model: Model?) } +// swiftlint:enable type_name /// State of the ModelProvider /// @@ -43,11 +44,11 @@ public enum ModelProviderState { /// change. public protocol ModelProvider { associatedtype Element: Model - + func load() async throws -> Element? - + func getState() -> ModelProviderState - + func encode(to encoder: Encoder) throws } @@ -56,25 +57,25 @@ public protocol ModelProvider { /// application making any change to these `public` types should be backward compatible, otherwise it will be a breaking /// change. public struct AnyModelProvider: ModelProvider { - + private let loadAsync: () async throws -> Element? private let getStateClosure: () -> ModelProviderState private let encodeClosure: (Encoder) throws -> Void - + public init(provider: Provider) where Provider.Element == Self.Element { self.loadAsync = provider.load self.getStateClosure = provider.getState self.encodeClosure = provider.encode } - + public func load() async throws -> Element? { try await loadAsync() } - + public func getState() -> ModelProviderState { getStateClosure() } - + public func encode(to encoder: Encoder) throws { try encodeClosure(encoder) } diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift index b3d85be2d5..6dfafe2c1b 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift @@ -98,8 +98,14 @@ public enum ModelAssociation { return .belongsTo(associatedFieldName: nil, targetNames: targetNames) } - public static func hasMany(associatedWith: CodingKey? = nil, associatedFields: [CodingKey] = []) -> ModelAssociation { - return .hasMany(associatedFieldName: associatedWith?.stringValue, associatedFieldNames: associatedFields.map { $0.stringValue }) + public static func hasMany( + associatedWith: CodingKey? = nil, + associatedFields: [CodingKey] = [] + ) -> ModelAssociation { + return .hasMany( + associatedFieldName: associatedWith?.stringValue, + associatedFieldNames: associatedFields.map { $0.stringValue } + ) } @available(*, deprecated, message: "Use hasOne(associatedWith:targetNames:)") @@ -230,7 +236,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var _isBelongsToOrHasOne: Bool { + public var _isBelongsToOrHasOne: Bool { // swiftlint:disable:this identifier_name switch association { case .belongsTo, .hasOne: return true diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift index 2e01b9b12f..a627525ba9 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift @@ -12,12 +12,12 @@ extension ModelSchema { enum ExtractionError: Error { case unsupportedLazyReferenceIdentifier(name: String, value: JSONValue?) } - + var identifiers = [LazyReferenceIdentifier]() for identifierField in primaryKey.fields { let object = modelObject[identifierField.name] - + switch object { case .string(let identifierValue): identifiers.append(.init(name: identifierField.name, value: identifierValue)) @@ -28,7 +28,7 @@ extension ModelSchema { ) } } - + return identifiers } } diff --git a/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift b/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift index 7aafd0b49a..7c8e128853 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift @@ -8,16 +8,16 @@ import Foundation public struct ArrayLiteralListProvider: ModelListProvider { - + let elements: [Element] public init(elements: [Element]) { self.elements = elements } - + public func getState() -> ModelListProviderState { return .loaded(elements) } - + public func load() -> Result<[Element], CoreError> { .success(elements) } @@ -25,7 +25,7 @@ public struct ArrayLiteralListProvider: ModelListProvider { public func load(completion: @escaping (Result<[Element], CoreError>) -> Void) { completion(.success(elements)) } - + public func load() async throws -> [Element] { return elements } @@ -39,13 +39,13 @@ public struct ArrayLiteralListProvider: ModelListProvider { "Don't call this method", nil))) } - + public func getNextPage() async throws -> List { throw CoreError.clientValidation("No pagination on an array literal", "Don't call this method", nil) } - + public func encode(to encoder: Encoder) throws { try elements.encode(to: encoder) } diff --git a/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift b/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift index 8eb7b22a74..24dca4f26a 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift @@ -10,17 +10,17 @@ import Foundation // MARK: - DefaultModelProvider public struct DefaultModelProvider: ModelProvider { - + var loadedState: ModelProviderState - + public init(element: Element? = nil) { self.loadedState = .loaded(model: element) } - + public init(identifiers: [LazyReferenceIdentifier]?) { self.loadedState = .notLoaded(identifiers: identifiers) } - + public func load() async throws -> Element? { switch loadedState { case .notLoaded: @@ -29,11 +29,11 @@ public struct DefaultModelProvider: ModelProvider { return model } } - + public func getState() -> ModelProviderState { loadedState } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let identifiers): diff --git a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift index 9799282fcd..343b059225 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift @@ -13,7 +13,7 @@ import Combine public struct LazyReferenceIdentifier: Codable { public let name: String public let value: String - + public init(name: String, value: String) { self.name = name self.value = value @@ -34,21 +34,22 @@ struct LazyReferenceModelIdentifier: ModelIdentifierProtocol { var fields: [(name: String, value: Persistable)] } +// swiftlint: disable identifier_name /// This class represents a lazy reference to a `Model`, meaning that the reference /// may or may not exist at instantiation time. /// /// The default implementation `DefaultModelProvider` only handles in-memory data, therefore `get()` and /// `require()` will simply return the current `reference`. public class LazyReference: Codable, _LazyReferenceValue { - + /// Represents the data state of the `LazyModel`. enum LoadedState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(ModelType?) } - + var loadedState: LoadedState - + @_spi(LazyReference) public var _state: _LazyReferenceValueState { switch loadedState { @@ -58,10 +59,10 @@ public class LazyReference: Codable, _LazyReferenceValue { return .loaded(model: model) } } - + /// The provider for fulfilling list behaviors let modelProvider: AnyModelProvider - + public init(modelProvider: AnyModelProvider) { self.modelProvider = modelProvider switch self.modelProvider.getState() { @@ -71,21 +72,21 @@ public class LazyReference: Codable, _LazyReferenceValue { self.loadedState = .notLoaded(identifiers: identifiers) } } - + // MARK: - Initializers - + public convenience init(_ reference: ModelType?) { let modelProvider = DefaultModelProvider(element: reference).eraseToAnyModelProvider() self.init(modelProvider: modelProvider) } - + public convenience init(identifiers: [LazyReferenceIdentifier]?) { let modelProvider = DefaultModelProvider(identifiers: identifiers).eraseToAnyModelProvider() self.init(modelProvider: modelProvider) } - + // MARK: - Codable implementation - + /// Decodable implementation is delegated to the ModelProviders. required convenience public init(from decoder: Decoder) throws { for modelDecoder in ModelProviderRegistry.decoders.get() { @@ -100,8 +101,7 @@ public class LazyReference: Codable, _LazyReferenceValue { if let element = try? ModelType(from: decoder) { self.init(element) return - } - else { + } else { let identifiers = try ModelType.schema.lazyReferenceIdentifiers(from: object) self.init(identifiers: identifiers) return @@ -111,14 +111,14 @@ public class LazyReference: Codable, _LazyReferenceValue { } self.init(identifiers: nil) } - + /// Encodable implementation is delegated to the underlying ModelProviders. public func encode(to encoder: Encoder) throws { try modelProvider.encode(to: encoder) } - + // MARK: - APIs - + /// This function is responsible for retrieving the model reference. In the default /// implementation this means simply returning the existing `reference`, but different /// storage mechanisms can implement their own logic to fetch data, @@ -135,7 +135,7 @@ public class LazyReference: Codable, _LazyReferenceValue { return element } } - + /// The equivalent of `get()` but aimed to retrieve references that are considered /// non-optional. However, referential integrity issues and/or availability constraints /// might affect how required data is fetched. In such scenarios the implementation diff --git a/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift b/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift index aee10e9e53..283cc53ff7 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift @@ -26,13 +26,13 @@ public class List: Collection, Codable, ExpressibleByArrayLite /// The current state of lazily loaded list var loadedState: LoadedState - + /// Boolean property to check if list is loaded public var isLoaded: Bool { if case .loaded = loadedState { return true } - + return false } @@ -70,7 +70,6 @@ public class List: Collection, Codable, ExpressibleByArrayLite } } - // MARK: - Initializers public init(listProvider: AnyModelListProvider) { diff --git a/Amplify/Categories/DataStore/Model/PropertyPath.swift b/Amplify/Categories/DataStore/Model/PropertyPath.swift index 93c24d41c9..212430f56d 100644 --- a/Amplify/Categories/DataStore/Model/PropertyPath.swift +++ b/Amplify/Categories/DataStore/Model/PropertyPath.swift @@ -32,7 +32,7 @@ public protocol PropertyPath { /// i.e. a `struct` representing another `Model`. /// /// - SeeAlso: `ModelPath` -public protocol PropertyContainerPath : PropertyPath { +public protocol PropertyContainerPath: PropertyPath { /// func getKeyPath() -> String @@ -43,7 +43,7 @@ public protocol PropertyContainerPath : PropertyPath { } extension PropertyContainerPath { - + public func getKeyPath() -> String { var metadata = getMetadata() var path = [String]() @@ -80,7 +80,7 @@ public struct FieldPath: PropertyPath { /// var blog: ModelPath { BlogModelPath(name: "blog", parent: self) } /// } /// ``` -open class ModelPath : PropertyContainerPath { +open class ModelPath: PropertyContainerPath { private let metadata: PropertyPathMetadata @@ -123,11 +123,11 @@ open class ModelPath : PropertyContainerPath { public func time(_ name: String) -> FieldPath { FieldPath(name: name, parent: self) } - + public func int(_ name: String) -> FieldPath { FieldPath(name: name, parent: self) } - + public func double(_ name: String) -> FieldPath { FieldPath(name: name, parent: self) } diff --git a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift index 9907557f32..efbbbfb673 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation extension TimeZone { @@ -31,7 +30,7 @@ extension TimeZone { } } - +// swiftlint:disable identifier_name /// ISO8601 Time Zone formats /// - Note: /// `±hh:mm:ss` is not a standard of ISO8601 date formate. It's supported by `AWSDateTime` exclusively. @@ -39,7 +38,7 @@ extension TimeZone { /// references: /// https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators /// https://docs.aws.amazon.com/appsync/latest/devguide/scalars.html#graph-ql-aws-appsync-scalars -fileprivate enum ISO8601TimeZoneFormat { +private enum ISO8601TimeZoneFormat { case utc, hh, hhmm, hh_mm, hh_mm_ss var format: String { @@ -98,14 +97,13 @@ fileprivate enum ISO8601TimeZoneFormat { } } -fileprivate enum ISO8601TimeZonePart { +private enum ISO8601TimeZonePart { case utc case hh(hours: Int) case hhmm(hours: Int, minutes: Int) case hh_mm(hours: Int, minuts: Int) case hh_mm_ss(hours: Int, minutes: Int, seconds: Int) - static func from(iso8601DateString: String) -> ISO8601TimeZonePart? { return tryExtract(from: iso8601DateString, with: .utc) ?? tryExtract(from: iso8601DateString, with: .hh) @@ -116,7 +114,7 @@ fileprivate enum ISO8601TimeZonePart { } } -fileprivate func tryExtract( +private func tryExtract( from dateString: String, with format: ISO8601TimeZoneFormat ) -> ISO8601TimeZonePart? { @@ -148,3 +146,4 @@ fileprivate func tryExtract( case .hh_mm_ss: return .hh_mm_ss(hours: parts[0], minutes: parts[1], seconds: parts[2]) } } +// swiftlint:enable identifier_name diff --git a/Amplify/Categories/DataStore/Query/QueryField.swift b/Amplify/Categories/DataStore/Query/QueryField.swift index 07a573945f..9d29967569 100644 --- a/Amplify/Categories/DataStore/Query/QueryField.swift +++ b/Amplify/Categories/DataStore/Query/QueryField.swift @@ -61,10 +61,6 @@ public struct QueryField: QueryFieldOperation { public let name: String - init(name: String) { - self.name = name - } - // MARK: - beginsWith public func beginsWith(_ value: String) -> QueryPredicateOperation { return QueryPredicateOperation(field: name, operator: .beginsWith(value)) diff --git a/Amplify/Categories/DataStore/Query/QueryOperator.swift b/Amplify/Categories/DataStore/Query/QueryOperator.swift index 18578eb552..2fcb50ccd2 100644 --- a/Amplify/Categories/DataStore/Query/QueryOperator.swift +++ b/Amplify/Categories/DataStore/Query/QueryOperator.swift @@ -18,7 +18,7 @@ public enum QueryOperator: Encodable { case notContains(_ value: String) case between(start: Persistable, end: Persistable) case beginsWith(_ value: String) - + public func evaluate(target: Any) -> Bool { switch self { case .notEqual(let predicateValue): @@ -51,17 +51,17 @@ public enum QueryOperator: Encodable { } return false } - + private enum CodingKeys: String, CodingKey { case type case value case start case end } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - + switch self { case .notEqual(let value): try container.encode("notEqual", forKey: .type) @@ -76,32 +76,32 @@ public enum QueryOperator: Encodable { case .lessOrEqual(let value): try container.encode("lessOrEqual", forKey: .type) try container.encode(value, forKey: .value) - + case .lessThan(let value): try container.encode("lessThan", forKey: .type) try container.encode(value, forKey: .value) - + case .greaterOrEqual(let value): try container.encode("greaterOrEqual", forKey: .type) try container.encode(value, forKey: .value) - + case .greaterThan(let value): try container.encode("greaterThan", forKey: .type) try container.encode(value, forKey: .value) - + case .contains(let value): try container.encode("contains", forKey: .type) try container.encode(value, forKey: .value) - + case .notContains(let value): try container.encode("notContains", forKey: .type) try container.encode(value, forKey: .value) - + case .between(let start, let end): try container.encode("between", forKey: .type) try container.encode(start, forKey: .start) try container.encode(end, forKey: .end) - + case .beginsWith(let value): try container.encode("beginsWith", forKey: .type) try container.encode(value, forKey: .value) diff --git a/Amplify/Categories/DataStore/Query/QueryPredicate.swift b/Amplify/Categories/DataStore/Query/QueryPredicate.swift index 5d242502a1..78bdf9f051 100644 --- a/Amplify/Categories/DataStore/Query/QueryPredicate.swift +++ b/Amplify/Categories/DataStore/Query/QueryPredicate.swift @@ -92,9 +92,9 @@ public class QueryPredicateGroup: QueryPredicate, Encodable { return !predicate.evaluate(target: target) } } - + // MARK: - Encodable conformance - + private enum CodingKeys: String, CodingKey { case type case predicates @@ -111,15 +111,15 @@ public class QueryPredicateGroup: QueryPredicate, Encodable { try _encode(encoder) } } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type.rawValue, forKey: .type) - + let anyPredicates = predicates.map(AnyQueryPredicate.init) try container.encode(anyPredicates, forKey: .predicates) } - + } public class QueryPredicateOperation: QueryPredicate, Encodable { diff --git a/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift b/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift index 0e1d802b87..ae669c73f9 100644 --- a/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift +++ b/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift @@ -11,7 +11,7 @@ extension DataStoreCategory: DataStoreSubscribeBehavior { public func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence { return plugin.observe(modelType) } - + public func observeQuery(for modelType: M.Type, where predicate: QueryPredicate? = nil, sort sortInput: QuerySortInput? = nil) diff --git a/Amplify/Categories/Hub/HubChannel.swift b/Amplify/Categories/Hub/HubChannel.swift index ba68e0f85a..0979ac95c3 100644 --- a/Amplify/Categories/Hub/HubChannel.swift +++ b/Amplify/Categories/Hub/HubChannel.swift @@ -25,7 +25,7 @@ public enum HubChannel { case logging case predictions - + case pushNotifications case storage diff --git a/Amplify/Categories/Logging/Internal/BroadcastLogger.swift b/Amplify/Categories/Logging/Internal/BroadcastLogger.swift index 267d19c084..849c93533b 100644 --- a/Amplify/Categories/Logging/Internal/BroadcastLogger.swift +++ b/Amplify/Categories/Logging/Internal/BroadcastLogger.swift @@ -11,23 +11,23 @@ /// /// - Tag: BroadcastLogger final class BroadcastLogger { - + /// The default LogLevel used when no targets are available. /// /// - Tag: LogProxy.defaultLogLevel var defaultLogLevel: Amplify.LogLevel = .error - + private let targets: [Logger] - + /// - Tag: BroadcastLogger.init init(targets: [Logger]) { self.targets = targets } - + } extension BroadcastLogger: Logger { - + var logLevel: Amplify.LogLevel { get { if let logger = targets.first { @@ -42,27 +42,27 @@ extension BroadcastLogger: Logger { } } } - + func error(_ message: @autoclosure () -> String) { targets.forEach { $0.error(message()) } } - + func error(error: Error) { targets.forEach { $0.error(error: error) } } - + func warn(_ message: @autoclosure () -> String) { targets.forEach { $0.warn(message()) } } - + func info(_ message: @autoclosure () -> String) { targets.forEach { $0.info(message()) } } - + func debug(_ message: @autoclosure () -> String) { targets.forEach { $0.debug(message()) } } - + func verbose(_ message: @autoclosure () -> String) { targets.forEach { $0.verbose(message()) } } diff --git a/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift b/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift index 8a9bee7890..4c691fd65c 100644 --- a/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift +++ b/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift @@ -27,11 +27,11 @@ extension LoggingCategory: CategoryConfigurable { try plugin.configure(using: configuration?.plugins[plugin.key]) self.plugins[plugin.key] = plugin - + if plugin.key != AWSUnifiedLoggingPlugin.key, let consolePlugin = try? self.getPlugin(for: AWSUnifiedLoggingPlugin.key) { try consolePlugin.configure(using: configuration?.plugins[consolePlugin.key]) } - + configurationState = .configured } diff --git a/Amplify/Categories/Logging/LogLevel.swift b/Amplify/Categories/Logging/LogLevel.swift index 57f92a81da..cee8acfff4 100644 --- a/Amplify/Categories/Logging/LogLevel.swift +++ b/Amplify/Categories/Logging/LogLevel.swift @@ -15,7 +15,7 @@ public extension Amplify { case debug case verbose case none - + public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let rawString = try? container.decode(String.self).lowercased() { diff --git a/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift b/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift index 8c3defed2d..082b38ee67 100644 --- a/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift +++ b/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift @@ -37,28 +37,28 @@ extension LoggingCategory: LoggingCategoryClientBehavior { } return BroadcastLogger(targets: targets) } - + public func enable() { for plugin in plugins.values { plugin.enable() } } - + public func disable() { for plugin in plugins.values { plugin.disable() } } - + public func logger(forNamespace namespace: String) -> Logger { var targets = [Logger]() for plugin in plugins.values { targets.append(plugin.logger(forNamespace: namespace)) } return BroadcastLogger(targets: targets) - + } - + public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { var targets = [Logger]() for plugin in plugins.values { diff --git a/Amplify/Categories/Logging/LoggingCategory+Logger.swift b/Amplify/Categories/Logging/LoggingCategory+Logger.swift index 33fe94b76b..29f1e95c16 100644 --- a/Amplify/Categories/Logging/LoggingCategory+Logger.swift +++ b/Amplify/Categories/Logging/LoggingCategory+Logger.swift @@ -47,7 +47,7 @@ extension LoggingCategory: Logger { for (_, plugin) in plugins { plugin.default.verbose(message()) } - + } } diff --git a/Amplify/Categories/Logging/LoggingCategory.swift b/Amplify/Categories/Logging/LoggingCategory.swift index 6ec7268d8a..b1dbd0e159 100644 --- a/Amplify/Categories/Logging/LoggingCategory.swift +++ b/Amplify/Categories/Logging/LoggingCategory.swift @@ -19,7 +19,7 @@ final public class LoggingCategory: Category { /// After a custom plugin is added and `configure` is invoked case configured } - + let lock: NSLocking = NSLock() public let categoryType = CategoryType.logging @@ -57,7 +57,7 @@ final public class LoggingCategory: Category { /// For any external cases, Logging is always ready to be used. Internal configuration state is tracked via a /// different mechanism var isConfigured: Bool { - return plugins.count > 0 + return !plugins.isEmpty } var plugins: [PluginKey: LoggingCategoryPlugin] = Amplify.getLoggingCategoryPluginLookup(loggingPlugin: AWSUnifiedLoggingPlugin()) diff --git a/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift b/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift index 33525272ac..44a089635f 100644 --- a/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift +++ b/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift @@ -15,16 +15,16 @@ public protocol LoggingCategoryClientBehavior { /// Returns a category-specific logger. Defaults to using `Amplify.Logging.logLevel`. func logger(forCategory category: String) -> Logger - + /// enable plugin func enable() - + /// disable plugin func disable() - + /// adding namespace to match Android implementation func logger(forNamespace namespace: String) -> Logger - + /// new api to support category and namespace func logger(forCategory category: String, forNamespace namespace: String) -> Logger } diff --git a/Amplify/Categories/Notifications/NotificationsCategory.swift b/Amplify/Categories/Notifications/NotificationsCategory.swift index 7e9e929653..02c4122b6f 100644 --- a/Amplify/Categories/Notifications/NotificationsCategory.swift +++ b/Amplify/Categories/Notifications/NotificationsCategory.swift @@ -11,7 +11,7 @@ import Foundation public final class NotificationsCategory { /// The Push Notifications category - public internal(set) var Push = PushNotificationsCategory() + public internal(set) var Push = PushNotificationsCategory() // swiftlint:disable:this identifier_name /// The current available subcategories that have been configured var subcategories: [NotificationsSubcategoryBehaviour] { diff --git a/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift b/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift index df0a825451..7d6da59e62 100644 --- a/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift +++ b/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift @@ -8,7 +8,7 @@ import Foundation /// The configuration for the Notifications category -public struct NotificationsCategoryConfiguration: CategoryConfiguration { +public struct NotificationsCategoryConfiguration: CategoryConfiguration { /// Plugins public let plugins: [String: JSONValue] diff --git a/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift b/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift index c151422856..4eff36dc84 100644 --- a/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift +++ b/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift @@ -12,15 +12,15 @@ extension PushNotificationsCategory: PushNotificationsCategoryBehaviour { public func identifyUser(userId: String, userProfile: UserProfile? = nil) async throws { try await plugin.identifyUser(userId: userId, userProfile: userProfile) } - + public func registerDevice(apnsToken: Data) async throws { try await plugin.registerDevice(apnsToken: apnsToken) } - + public func recordNotificationReceived(_ userInfo: Notifications.Push.UserInfo) async throws { try await plugin.recordNotificationReceived(userInfo) } - + #if !os(tvOS) public func recordNotificationOpened(_ response: UNNotificationResponse) async throws { try await plugin.recordNotificationOpened(response) diff --git a/Amplify/Categories/Predictions/Models/Language.swift b/Amplify/Categories/Predictions/Models/Language.swift index 941ea94e43..484ef1ac1e 100644 --- a/Amplify/Categories/Predictions/Models/Language.swift +++ b/Amplify/Categories/Predictions/Models/Language.swift @@ -8,6 +8,7 @@ import Foundation extension Predictions { + // swiftlint:disable file_length type_body_length public struct Language: Equatable, Decodable { public let code: String @@ -2404,3 +2405,4 @@ extension Predictions.Language { self = .init(code: languageCode) } } +// swiftlint:enable file_length type_body_length diff --git a/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift b/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift index 652548eda6..c5639603fa 100644 --- a/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift +++ b/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift @@ -21,7 +21,6 @@ public protocol PredictionsCategoryBehavior { options: Predictions.Identify.Options? ) async throws -> Output - /// /// - Parameters: /// - request: diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift index 896abd89c1..39f66964a0 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift @@ -13,7 +13,7 @@ extension Predictions.Identify.Text { public let words: [Predictions.IdentifiedWord]? public let rawLineText: [String]? public let identifiedLines: [Predictions.IdentifiedLine]? - + public init( fullText: String?, words: [Predictions.IdentifiedWord]?, diff --git a/Amplify/Core/Category/CategoryType.swift b/Amplify/Core/Category/CategoryType.swift index 254c2d7a2a..9ff9c5b216 100644 --- a/Amplify/Core/Category/CategoryType.swift +++ b/Amplify/Core/Category/CategoryType.swift @@ -57,7 +57,7 @@ public enum CategoryType: String { /// /// - Tag: CategoryType.predictions case predictions - + /// Push Notifications /// /// - Tag: CategoryType.pushNotifications diff --git a/Amplify/Core/Configuration/Internal/Amplify+Reset.swift b/Amplify/Core/Configuration/Internal/Amplify+Reset.swift index 2975f75166..9a2239fe4b 100644 --- a/Amplify/Core/Configuration/Internal/Amplify+Reset.swift +++ b/Amplify/Core/Configuration/Internal/Amplify+Reset.swift @@ -51,7 +51,7 @@ extension Amplify { ModelListDecoderRegistry.reset() ModelProviderRegistry.reset() log.verbose("Resetting ModelRegistry, ModelListDecoderRegistry, ModelProviderRegistry finished") - + #if os(iOS) await MainActor.run { devMenu = nil diff --git a/Amplify/Core/Error/CoreError.swift b/Amplify/Core/Error/CoreError.swift index 623635fb5c..f6c628c764 100644 --- a/Amplify/Core/Error/CoreError.swift +++ b/Amplify/Core/Error/CoreError.swift @@ -14,7 +14,7 @@ public enum CoreError { /// /// - Tag: CoreError.listOperation case listOperation(ErrorDescription, RecoverySuggestion, Error? = nil) - + /// A client side validation error occured. /// /// - Tag: CoreError.clientValidation diff --git a/Amplify/Core/Support/Amplify+Publisher.swift b/Amplify/Core/Support/Amplify+Publisher.swift index f74b49ed47..98501d9cee 100644 --- a/Amplify/Core/Support/Amplify+Publisher.swift +++ b/Amplify/Core/Support/Amplify+Publisher.swift @@ -9,7 +9,7 @@ import Combine public extension Amplify { - + /// Get Combine Publishers for Amplify APIs. /// /// Provides static methods to create Combine Publishers from Tasks and @@ -37,7 +37,7 @@ public extension Amplify { _ operation: @escaping @Sendable () async throws -> Success ) -> AnyPublisher { let task = Task(operation: operation) - return Future() { promise in + return Future { promise in Task { do { let value = try await task.value @@ -47,7 +47,7 @@ public extension Amplify { } } } - .handleEvents(receiveCancel: { task.cancel() } ) + .handleEvents(receiveCancel: { task.cancel() }) .eraseToAnyPublisher() } @@ -69,16 +69,16 @@ public extension Amplify { _ operation: @escaping @Sendable () async -> Success ) -> AnyPublisher { let task = Task(operation: operation) - return Future() { promise in + return Future { promise in Task { let value = await task.value promise(.success(value)) } } - .handleEvents(receiveCancel: { task.cancel() } ) + .handleEvents(receiveCancel: { task.cancel() }) .eraseToAnyPublisher() } - + /// Create a Combine Publisher for a given AsyncSequence. /// /// Example Usage @@ -113,7 +113,6 @@ public extension Amplify { // This is necessary to prevent the sequence from continuing to send values for a time // after cancellation in the case of a fast Iterator. try Task.checkCancellation() - subject.send(value) } subject.send(completion: .finished) diff --git a/Amplify/Core/Support/AmplifyAsyncSequence.swift b/Amplify/Core/Support/AmplifyAsyncSequence.swift index 95b3a5b631..b98c0f17bb 100644 --- a/Amplify/Core/Support/AmplifyAsyncSequence.swift +++ b/Amplify/Core/Support/AmplifyAsyncSequence.swift @@ -13,8 +13,8 @@ public class AmplifyAsyncSequence: AsyncSequence, Cancellable public typealias Iterator = AsyncStream.Iterator private var asyncStream: AsyncStream! = nil private var continuation: AsyncStream.Continuation! = nil - private var parent: Cancellable? = nil - + private var parent: Cancellable? + public private(set) var isCancelled: Bool = false public init(parent: Cancellable? = nil, diff --git a/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift b/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift index 9ece6896b9..38772392da 100644 --- a/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift +++ b/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift @@ -13,7 +13,7 @@ public class AmplifyAsyncThrowingSequence: AsyncSequence, Can public typealias Iterator = AsyncThrowingStream.Iterator private var asyncStream: AsyncThrowingStream! = nil private var continuation: AsyncThrowingStream.Continuation! = nil - private var parent: Cancellable? = nil + private var parent: Cancellable? public private(set) var isCancelled: Bool = false diff --git a/Amplify/Core/Support/AmplifyOperation.swift b/Amplify/Core/Support/AmplifyOperation.swift index de556a597e..07d122d68c 100644 --- a/Amplify/Core/Support/AmplifyOperation.swift +++ b/Amplify/Core/Support/AmplifyOperation.swift @@ -61,7 +61,6 @@ open class AmplifyOperation.Promise! #endif - /// Creates an AmplifyOperation for the specified reequest. /// /// ## Events diff --git a/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift b/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift index 74c578c87f..fb56c6df18 100644 --- a/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift +++ b/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift @@ -10,10 +10,12 @@ import Foundation import Combine #endif -public class AmplifyOperationTaskAdapter: AmplifyTask { +public class AmplifyOperationTaskAdapter: AmplifyTask { let operation: AmplifyOperation let childTask: ChildTask - var resultToken: UnsubscribeToken? = nil + var resultToken: UnsubscribeToken? public init(operation: AmplifyOperation) { self.operation = operation @@ -60,11 +62,14 @@ public class AmplifyOperationTaskAdapter: AmplifyTask, AmplifyInProcessReportingTask { +public class AmplifyInProcessReportingOperationTaskAdapter: AmplifyTask, AmplifyInProcessReportingTask { let operation: AmplifyInProcessReportingOperation let childTask: ChildTask - var resultToken: UnsubscribeToken? = nil - var inProcessToken: UnsubscribeToken? = nil + var resultToken: UnsubscribeToken? + var inProcessToken: UnsubscribeToken? public init(operation: AmplifyInProcessReportingOperation) { self.operation = operation diff --git a/Amplify/Core/Support/AmplifyTask.swift b/Amplify/Core/Support/AmplifyTask.swift index b40ffff779..915f0f06b6 100644 --- a/Amplify/Core/Support/AmplifyTask.swift +++ b/Amplify/Core/Support/AmplifyTask.swift @@ -69,7 +69,7 @@ public extension AmplifyInProcessReportingTask where InProcess == Progress { /// using [Progress](x-source-tag://Progress). /// /// - Tag: AmplifyInProcessReportingTask.progress - var progress : AmplifyAsyncSequence { + var progress: AmplifyAsyncSequence { get async { await inProcess } diff --git a/Amplify/Core/Support/AsyncSequence+forEach.swift b/Amplify/Core/Support/AsyncSequence+forEach.swift index c38279648c..6a579bad27 100644 --- a/Amplify/Core/Support/AsyncSequence+forEach.swift +++ b/Amplify/Core/Support/AsyncSequence+forEach.swift @@ -16,5 +16,5 @@ public extension AsyncSequence { try await block(element) } } - + } diff --git a/Amplify/Core/Support/AtomicDictionary.swift b/Amplify/Core/Support/AtomicDictionary.swift index 52e6f9de4c..fee9411e87 100644 --- a/Amplify/Core/Support/AtomicDictionary.swift +++ b/Amplify/Core/Support/AtomicDictionary.swift @@ -46,7 +46,7 @@ public final class AtomicDictionary { public func set(value: Value, forKey key: Key) { lock.execute { self.value[key] = value } } - + public subscript(key: Key) -> Value? { get { getValue(forKey: key) @@ -70,7 +70,7 @@ extension AtomicDictionary: ExpressibleByDictionaryLiteral { extension AtomicDictionary: Sequence { typealias Iterator = DictionaryIterator - + public func makeIterator() -> DictionaryIterator { lock.execute { value.makeIterator() diff --git a/Amplify/Core/Support/ChildTask.swift b/Amplify/Core/Support/ChildTask.swift index 63d0e7c62d..b9fa73adad 100644 --- a/Amplify/Core/Support/ChildTask.swift +++ b/Amplify/Core/Support/ChildTask.swift @@ -12,9 +12,9 @@ import Foundation actor ChildTask: BufferingSequence { typealias Element = InProcess private let parent: Cancellable - private var inProcessChannel: AmplifyAsyncSequence? = nil + private var inProcessChannel: AmplifyAsyncSequence? private var valueContinuations: [CheckedContinuation] = [] - private var storedResult: Result? = nil + private var storedResult: Result? private var isCancelled = false var inProcess: AmplifyAsyncSequence { diff --git a/Amplify/Core/Support/Fatal.swift b/Amplify/Core/Support/Fatal.swift index deee767414..fa1600351d 100644 --- a/Amplify/Core/Support/Fatal.swift +++ b/Amplify/Core/Support/Fatal.swift @@ -10,8 +10,6 @@ import Foundation // Credit: Dave DeLong // https://forums.swift.org/t/introducing-namespacing-for-common-swift-error-scenarios/10773 -import Foundation - /// An umbrella type supplying static members to handle common /// and conventional exit scenarios. public enum Fatal { diff --git a/Amplify/Core/Support/Optional+Extension.swift b/Amplify/Core/Support/Optional+Extension.swift index 0d3a6ad3c2..4efb0d736f 100644 --- a/Amplify/Core/Support/Optional+Extension.swift +++ b/Amplify/Core/Support/Optional+Extension.swift @@ -4,7 +4,6 @@ // // SPDX-License-Identifier: Apache-2.0 // - import Foundation diff --git a/Amplify/Core/Support/TaskQueue.swift b/Amplify/Core/Support/TaskQueue.swift index 687f088b8a..f281c57e1c 100644 --- a/Amplify/Core/Support/TaskQueue.swift +++ b/Amplify/Core/Support/TaskQueue.swift @@ -10,7 +10,7 @@ import Foundation /// A helper for executing asynchronous work serially. public actor TaskQueue { private var previousTask: Task? - + public init() {} /// Serializes asynchronous requests made from an async context diff --git a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift index b54dada954..7a3b10d54a 100644 --- a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift +++ b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift @@ -122,7 +122,7 @@ final class HubDispatchOperation: Operation { guard let listeners = delegate?.listeners else { return } - + let dispatcher = SerialDispatcher(channel: channel, payload: payload) dispatcher.dispatch(to: listeners) } diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift index 643ce293d3..50f8c484ff 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift @@ -29,7 +29,7 @@ final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { let subsystem: String var enabled: Bool = true private let lock = NSLock() - + /// Initializes the logging system with a default log, and immediately registers a default logger public init() { self.subsystem = Bundle.main.bundleIdentifier ?? "com.amazonaws.amplify.AWSUnifiedLoggingPlugin" @@ -102,7 +102,7 @@ extension AWSUnifiedLoggingPlugin { wrapper.logLevel = logLevel return wrapper } - + public func enable() { enabled = true lock.execute { @@ -111,7 +111,7 @@ extension AWSUnifiedLoggingPlugin { } } } - + public func disable() { enabled = false lock.execute { @@ -120,12 +120,12 @@ extension AWSUnifiedLoggingPlugin { } } } - + public func logger(forNamespace namespace: String) -> Logger { let wrapper = logWrapper(for: namespace) return wrapper } - + public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { let wrapper = logWrapper(for: category + namespace) return wrapper diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift index 76de5e93ca..751f4a9eda 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift @@ -11,7 +11,7 @@ public struct ConsoleLoggingConfiguration: Codable { public init(enable: Bool = true) { self.enable = enable } - + public let enable: Bool } @@ -55,8 +55,7 @@ extension ConsoleLoggingConfiguration { static func decodeConfiguration(from data: Data) throws -> ConsoleLoggingConfiguration? { do { if let configuration = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], - let configurationJson = configuration["consoleLoggingPlugin"] as? [String: Any] - { + let configurationJson = configuration["consoleLoggingPlugin"] as? [String: Any] { let decoder = JSONDecoder() let data = try JSONSerialization.data(withJSONObject: configurationJson) let consoleLoggingConfiguration = try decoder.decode(ConsoleLoggingConfiguration.self, from: data) @@ -79,4 +78,3 @@ extension ConsoleLoggingConfiguration { return nil } } - diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift index 4f5f38a417..ad3087d867 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift @@ -9,9 +9,9 @@ import os.log final class OSLogWrapper: Logger { private let osLog: OSLog - + var enabled: Bool = true - + var getLogLevel: () -> LogLevel public var logLevel: LogLevel { diff --git a/Amplify/DevMenu/Amplify+DevMenu.swift b/Amplify/DevMenu/Amplify+DevMenu.swift index 8a9b6bef73..856e00d815 100644 --- a/Amplify/DevMenu/Amplify+DevMenu.swift +++ b/Amplify/DevMenu/Amplify+DevMenu.swift @@ -44,8 +44,10 @@ extension Amplify { return loggingPlugin #endif } - - static func getLoggingCategoryPluginLookup(loggingPlugin: LoggingCategoryPlugin) -> [PluginKey: LoggingCategoryPlugin] { + + static func getLoggingCategoryPluginLookup( + loggingPlugin: LoggingCategoryPlugin + ) -> [PluginKey: LoggingCategoryPlugin] { #if os(iOS) #if DEBUG if isDevMenuEnabled() { diff --git a/Amplify/DevMenu/Data/LogEntryHelper.swift b/Amplify/DevMenu/Data/LogEntryHelper.swift index 5b39c85eac..65fa2229da 100644 --- a/Amplify/DevMenu/Data/LogEntryHelper.swift +++ b/Amplify/DevMenu/Data/LogEntryHelper.swift @@ -25,7 +25,8 @@ struct LogEntryHelper { /// Helper function to fetch logs from `PersistentLoggingPlugin` static func getLogHistory() -> [LogEntryItem] { - if let loggingPlugin: PersistentLoggingPlugin = Amplify.Logging.plugins.first(where: { $0.key == DevMenuStringConstants.persistentLoggingPluginKey})?.value as? PersistentLoggingPlugin { + if let loggingPlugin: PersistentLoggingPlugin = Amplify.Logging.plugins.first(where: { + $0.key == DevMenuStringConstants.persistentLoggingPluginKey})?.value as? PersistentLoggingPlugin { if let logger: PersistentLogWrapper = loggingPlugin.default as? PersistentLogWrapper { return logger.getLogHistory() } diff --git a/Amplify/DevMenu/Data/PluginInfoHelper.swift b/Amplify/DevMenu/Data/PluginInfoHelper.swift index d539a7e6f3..c14d4a05e8 100644 --- a/Amplify/DevMenu/Data/PluginInfoHelper.swift +++ b/Amplify/DevMenu/Data/PluginInfoHelper.swift @@ -13,35 +13,35 @@ struct PluginInfoHelper { static func getPluginInformation() -> [PluginInfoItem] { var pluginList = [PluginInfoItem]() - + pluginList.append(contentsOf: Amplify.Analytics.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.API.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Auth.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.DataStore.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Hub.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Logging.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Predictions.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Storage.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) diff --git a/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift b/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift index 8bc0218bae..04f41016a1 100644 --- a/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift +++ b/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift @@ -27,19 +27,19 @@ public class PersistentLoggingPlugin: LoggingCategoryPlugin { public func logger(forCategory category: String) -> Logger { return plugin.logger(forCategory: category) } - + public func enable() { plugin.enable() } - + public func disable() { plugin.disable() } - + public func logger(forNamespace namespace: String) -> Logger { plugin.logger(forNamespace: namespace) } - + public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { plugin.logger(forCategory: category, forNamespace: namespace) } diff --git a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift index 593e4ab047..2746528644 100644 --- a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift +++ b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift @@ -33,11 +33,11 @@ public actor AsyncExpectation { public var isFulfilled: Bool { state == .fulfilled } - + public func setShouldTrigger(_ shouldTrigger: Bool) { self.isInverted = !shouldTrigger } - + public func setExpectedFulfillmentCount(_ count: Int) { self.expectedFulfillmentCount = count } diff --git a/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift b/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift index a4bea03173..a4dbea7c0a 100644 --- a/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift +++ b/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift @@ -86,7 +86,7 @@ final class AsyncExpectationTests: XCTestCase { let delay = 0.01 let notYetDone = asyncExpectation(description: "not yet done", isInverted: true) let done = asyncExpectation(description: "done") - + let task = Task { await AsyncRunner().run() XCTAssertTrue(Task.isCancelled) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift index 002cba23a1..6948f9195d 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift @@ -19,7 +19,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func query(request: GraphQLRequest) async throws -> GraphQLTask.Success { let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .query), session: session, @@ -41,7 +41,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func mutate(request: GraphQLRequest) async throws -> GraphQLTask.Success { let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .mutation), session: session, @@ -69,7 +69,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> { let request = request.toOperationRequest(operationType: .subscription) let runner = AWSGraphQLSubscriptionTaskRunner(request: request, diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift index c60ce3e017..59642d79c0 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift @@ -23,7 +23,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func get(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .get) @@ -52,7 +52,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func put(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .put) @@ -81,7 +81,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func post(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .post) @@ -109,7 +109,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func patch(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .patch) @@ -137,7 +137,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func delete(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .delete) @@ -166,7 +166,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func head(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .head) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift index 605b9d50ba..c6050bb2d7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift @@ -19,13 +19,13 @@ public struct AppSyncListDecoder: ModelListDecoder { let appSyncAssociatedFields: [String] let apiName: String? } - + /// Used by the custom decoder implemented in the `List` type to detect if the payload can be /// decoded to an AppSyncListProvider. public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelListProvider? { self.shouldDecodeToAppSyncListProvider(modelType: modelType, decoder: decoder)?.eraseToAnyModelListProvider() } - + static func shouldDecodeToAppSyncListProvider(modelType: ModelType.Type, decoder: Decoder) -> AppSyncListProvider? { if let listPayload = try? AppSyncListPayload.init(from: decoder) { log.verbose("Creating loaded list of \(modelType.modelName)") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift index 88388999ab..2edf147c1b 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift @@ -92,7 +92,7 @@ public class AppSyncListProvider: ModelListProvider { return .loaded(elements) } } - + public func load() async throws -> [Element] { switch loadedState { case .loaded(let elements, _, _): @@ -101,7 +101,7 @@ public class AppSyncListProvider: ModelListProvider { return try await load(associatedIdentifiers: associatedIdentifiers, associatedFields: associatedFields) } } - + //// Internal `load` to perform the retrieval of the first page and storing it in memory func load(associatedIdentifiers: [String], associatedFields: [String]) async throws -> [Element] { @@ -113,7 +113,7 @@ public class AppSyncListProvider: ModelListProvider { filter = predicate.graphQLFilter(for: Element.schema) } else { var queryPredicates: [QueryPredicateOperation] = [] - + let columnNames = columnNames(fields: associatedFields, Element.schema) let predicateValues = zip(columnNames, associatedIdentifiers) for (identifierName, identifierValue) in predicateValues { @@ -123,8 +123,7 @@ public class AppSyncListProvider: ModelListProvider { let groupedQueryPredicates = QueryPredicateGroup(type: .and, predicates: queryPredicates) filter = groupedQueryPredicates.graphQLFilter(for: Element.schema) } - - + let request = GraphQLRequest.listQuery(responseType: JSONValue.self, modelSchema: Element.schema, filter: filter, @@ -142,7 +141,7 @@ public class AppSyncListProvider: ModelListProvider { AWSAppSyncListResponse from: \(graphQLData) """, "", nil) } - + self.loadedState = .loaded(elements: listResponse.items, nextToken: listResponse.nextToken, filter: filter) @@ -163,7 +162,7 @@ public class AppSyncListProvider: ModelListProvider { throw error } } - + public func hasNextPage() -> Bool { switch loadedState { case .loaded(_, let nextToken, _): @@ -172,7 +171,7 @@ public class AppSyncListProvider: ModelListProvider { return false } } - + public func getNextPage() async throws -> List { guard case .loaded(_, let nextTokenOptional, let filter) = loadedState else { throw CoreError.clientValidation(""" @@ -219,7 +218,7 @@ public class AppSyncListProvider: ModelListProvider { throw error } } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let associatedIdentifiers, let associatedFields): @@ -239,9 +238,9 @@ public class AppSyncListProvider: ModelListProvider { try elements.encode(to: encoder) } } - + // MARK: - Helpers - + /// Retrieve the column names for the specified field `field` for this schema. func columnNames(fields: [String], _ modelSchema: ModelSchema) -> [String] { // Associated field names have already been resolved from the parent model's has-many targetNames @@ -257,14 +256,14 @@ public class AppSyncListProvider: ModelListProvider { case .belongsTo(_, let targetNames), .hasOne(_, let targetNames): guard !targetNames.isEmpty else { return [defaultFieldName] - + } return targetNames default: return fields } } - + } extension AppSyncListProvider: DefaultLogger { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift index fd6b1f22e2..9fc1da75b7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift @@ -12,22 +12,22 @@ import Amplify /// inside an `AppSyncModelProvider` when decoding to the `LazyReference` as a "not yet loaded" Reference. If the data payload /// can be decoded to the Model, then the model provider is created as a "loaded" reference. public struct AppSyncModelDecoder: ModelProviderDecoder { - + public static let AppSyncSource = "AppSync" - + /// Metadata that contains metadata of a model, specifically the identifiers used to hydrate the model. struct Metadata: Codable { let identifiers: [LazyReferenceIdentifier] let apiName: String? let source: String - + init(identifiers: [LazyReferenceIdentifier], apiName: String?, source: String = AppSyncSource) { self.identifiers = identifiers self.apiName = apiName self.source = source } } - + public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelProvider? { if let metadata = try? Metadata(from: decoder) { if metadata.source == AppSyncSource { @@ -37,12 +37,12 @@ public struct AppSyncModelDecoder: ModelProviderDecoder { return nil } } - + if let model = try? ModelType.init(from: decoder) { log.verbose("Creating loaded model \(model)") return AppSyncModelProvider(model: model).eraseToAnyModelProvider() } - + return nil } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift index b929e77eb6..31cb93303a 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift @@ -10,7 +10,7 @@ import Foundation /// Holds the methods to traverse and maniupulate the response data object by injecting public struct AppSyncModelMetadataUtils { - + // A fairly light check to make sure the payload is an object and we have the schema for `addMetadata`. // Note: `addMetadata` should be very tightly checking the associated fields to determine when it should add // metadata. Do we still need to do this anymore? @@ -65,12 +65,12 @@ public struct AppSyncModelMetadataUtils { encoder.dateEncodingStrategy = ModelDateFormatting.encodingStrategy let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy - + // Iterate over the associations of the model and for each association, either create the identifier metadata // for lazy loading belongs-to or create the model association metadata for lazy loading has-many. // The metadata gets decoded to the LazyReference and List implementations respectively. for modelField in modelSchema.fields.values { - + // Scenario: Belongs-to associations. For the current `modelField` that is a belongs-to association, // retrieve the data and attempt to decode to the association's modelType. If it can be decoded, // this means it is eager loaded and does not need to be lazy loaded. If it cannot, extract the @@ -81,7 +81,7 @@ public struct AppSyncModelMetadataUtils { case .object(let modelObject) = nestedModelJSON, let associatedModelName = modelField.associatedModelName, let associatedModelType = ModelRegistry.modelType(from: associatedModelName) { - + // Scenario: Belongs-To Primary Keys only are available for lazy loading if let modelIdentifierMetadata = createModelIdentifierMetadata(associatedModelType, modelObject: modelObject, @@ -105,11 +105,11 @@ public struct AppSyncModelMetadataUtils { } // otherwise do nothing to the data. } - + // Scenario: Has-Many eager loaded or empty payloads. if modelField.isArray && modelField.hasAssociation, let associatedModelName = modelField.associatedModelName { - + // Scenario: Has-many items array is missing. // Store the association data (parent's identifier and field name) // This allows the list to perform lazy loading of child items using parent identifier as the predicate @@ -127,7 +127,7 @@ public struct AppSyncModelMetadataUtils { """) } } - + // Scenario: Has-Many items array is eager loaded as `nestedModelJSON` // If the model types allow for lazy loading, inject the metadata at each item of `nestedModelJSON` else if let nestedModelJSON = modelJSON[modelField.name], @@ -135,17 +135,17 @@ public struct AppSyncModelMetadataUtils { case .array(var graphQLDataArray) = graphQLDataObject["items"], let associatedModelType = ModelRegistry.modelType(from: associatedModelName), associatedModelType.rootPath != nil { - + for (index, item) in graphQLDataArray.enumerated() { let modelJSON = AppSyncModelMetadataUtils.addMetadata(toModel: item, apiName: apiName) graphQLDataArray[index] = modelJSON } - + graphQLDataObject["items"] = JSONValue.array(graphQLDataArray) let payload = AppSyncListPayload(graphQLData: JSONValue.object(graphQLDataObject), apiName: apiName, variables: nil) - + if let serializedPayload = try? encoder.encode(payload), let payloadJSON = try? decoder.decode(JSONValue.self, from: serializedPayload) { log.verbose("Adding [\(modelField.name): \(payloadJSON)]") @@ -159,7 +159,7 @@ public struct AppSyncModelMetadataUtils { return JSONValue.object(modelJSON) } - + /// Extract the identifiers from the `modelObject`. The number of identifiers extracted compared to the number of /// fields on the `modelObject` is useful determining if the `modelOject` is eager or lazy loaded. If the identifiers /// plus one additional field (`__typename`) doesn't match the number of keys on the `modelObject` then there @@ -185,7 +185,7 @@ public struct AppSyncModelMetadataUtils { return nil } } - + /// Retrieve just the identifiers from the current model. These identifiers are later used /// for creating `AppSyncListDecoder.Metadata` payloads for decoding. static func retrieveIdentifiers(_ modelJSON: [String: JSONValue], _ schema: ModelSchema) -> [String]? { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift index f71f08194e..ed717eec64 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift @@ -10,27 +10,27 @@ import Amplify import AWSPluginsCore public class AppSyncModelProvider: ModelProvider { - + let apiName: String? - + var loadedState: ModelProviderState - + // Creates a "not loaded" provider init(metadata: AppSyncModelDecoder.Metadata) { self.loadedState = .notLoaded(identifiers: metadata.identifiers) self.apiName = metadata.apiName } - + // Creates a "loaded" provider init(model: ModelType?) { self.loadedState = .loaded(model: model) self.apiName = nil } - + // MARK: - APIs - + public func load() async throws -> ModelType? { - + switch loadedState { case .notLoaded(let identifiers): guard let identifiers = identifiers else { @@ -54,11 +54,11 @@ public class AppSyncModelProvider: ModelProvider { return element } } - + public func getState() -> ModelProviderState { loadedState } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let identifiers): diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift index 6be2ea5a5d..bc5be0d627 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift @@ -16,7 +16,7 @@ class AuthTokenProviderWrapper: AuthTokenProvider { init(tokenAuthProvider: AmplifyAuthTokenProvider) { self.wrappedAuthTokenProvider = tokenAuthProvider } - + func getUserPoolAccessToken() async throws -> String { try await wrappedAuthTokenProvider.getLatestAuthToken() } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift index 2d639afca4..a0b33d5825 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift @@ -10,9 +10,9 @@ import AWSPluginsCore import Foundation struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { - + static let AWSDateISO8601DateFormat2 = "yyyyMMdd'T'HHmmss'Z'" - + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib let authTokenProvider: AuthTokenProvider @@ -34,14 +34,14 @@ struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { forHTTPHeaderField: URLRequestConstants.Header.xAmzDate) mutableRequest.addValue(userAgent, forHTTPHeaderField: URLRequestConstants.Header.userAgent) - + let token: String do { token = try await authTokenProvider.getUserPoolAccessToken() } catch { throw APIError.operationError("Failed to retrieve authorization token.", "", error) } - + mutableRequest.setValue(token, forHTTPHeaderField: "authorization") return mutableRequest as URLRequest } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift index 4ad5159992..d012985a63 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift @@ -17,7 +17,7 @@ struct IAMURLRequestInterceptor: URLRequestInterceptor { let region: AWSRegionType let endpointType: AWSAPICategoryPluginEndpointType private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib - + init(iamCredentialsProvider: IAMCredentialsProvider, region: AWSRegionType, endpointType: AWSAPICategoryPluginEndpointType) { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift index 859981e321..a6115ff171 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift @@ -154,8 +154,7 @@ final public class AWSGraphQLOperation: GraphQLOperation { getEndpointConfig(from: request).flatMap { endpointConfig in do { if let pluginOptions = request.options.pluginOptions as? AWSPluginOptions, - let authType = pluginOptions.authType - { + let authType = pluginOptions.authType { return .success(try pluginConfig.interceptorsForEndpoint( withConfig: endpointConfig, authType: authType diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift index a9bf16eee9..b8e42644cc 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift @@ -16,7 +16,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, public var request: GraphQLOperationRequest public var context = InternalTaskAsyncThrowingSequenceContext>() - + let pluginConfig: AWSAPICategoryPluginConfiguration let subscriptionConnectionFactory: SubscriptionConnectionFactory let authService: AWSAuthServiceBehavior @@ -28,7 +28,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, private var running = false private let subscriptionQueue = DispatchQueue(label: "AWSGraphQLSubscriptionOperation.subscriptionQueue") - + init(request: Request, pluginConfig: AWSAPICategoryPluginConfiguration, subscriptionConnectionFactory: SubscriptionConnectionFactory, @@ -40,7 +40,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, self.authService = authService self.apiAuthProviderFactory = apiAuthProviderFactory } - + public func cancel() { subscriptionQueue.sync { if let subscriptionItem = subscriptionItem, let subscriptionConnection = subscriptionConnection { @@ -50,7 +50,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, } } } - + public func run() async throws { guard !running else { return } running = true @@ -116,9 +116,9 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, urlRequest.setValue(userAgent, forHTTPHeaderField: URLRequestConstants.Header.userAgent) return urlRequest } - + // MARK: - Subscription callbacks - + private func onAsyncSubscriptionEvent(event: SubscriptionItemEvent) { switch event { case .connection(let subscriptionConnectionEvent): @@ -166,7 +166,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, // payload is the right thing to do. Another option would be to propagate a GraphQL error, but // leave the subscription alive. // see https://github.com/aws-amplify/amplify-swift/issues/2577 - + fail(APIError.operationError("Failed to deserialize", "", error)) } } @@ -204,7 +204,7 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri let subscriptionConnectionFactory: SubscriptionConnectionFactory let authService: AWSAuthServiceBehavior private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib - + var subscriptionConnection: SubscriptionConnection? var subscriptionItem: SubscriptionItem? var apiAuthProviderFactory: APIAuthProviderFactory @@ -318,7 +318,7 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri } // MARK: - Subscription callbacks - + private func onAsyncSubscriptionEvent(event: SubscriptionItemEvent) { switch event { case .connection(let subscriptionConnectionEvent): diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift index 68c55eadc6..bb4a87396d 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift @@ -52,7 +52,7 @@ public class AWSHTTPURLResponse: HTTPURLResponse { public override class var supportsSecureCoding: Bool { return true } - + public override func encode(with coder: NSCoder) { coder.encode(body, forKey: "body") coder.encode(response, forKey: "response") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift index 3dfcfe25ae..9045d31e03 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift @@ -177,7 +177,7 @@ public extension AmplifyReachability { func startNotifier() throws { guard !notifierRunning else { return } - let callback: SCNetworkReachabilityCallBack = { reachability, flags, info in + let callback: SCNetworkReachabilityCallBack = { _, flags, info in guard let info = info else { return } // `weakifiedReachability` is guaranteed to exist by virtue of our diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift index 99195734fe..c5bf5e5dc9 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift @@ -20,31 +20,31 @@ import Network public class AmplifyReachability { public var allowsCellularConnection: Bool - + // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default - + public var connection: AmplifyReachability.Connection { guard networkReachability.currentPath.status != .unsatisfied else { return .unavailable } - + // If we're reachable but not running on a device, we must be in Wi-Fi if !isRunningOnDevice { return .wifi } - + if networkReachability.currentPath.usesInterfaceType(.wifi) { return .wifi } - + if networkReachability.currentPath.usesInterfaceType(.cellular) { return allowsCellularConnection ? .cellular : .unavailable } - + return .unavailable } - + private let networkReachability: NWPathMonitor private let notificationQueue: DispatchQueue private var isRunningOnDevice: Bool = { @@ -54,7 +54,7 @@ public class AmplifyReachability { return true #endif }() - + public init( networkReachability: NWPathMonitor = NWPathMonitor(), allowsCellularConnection: Bool = true, @@ -73,22 +73,22 @@ public class AmplifyReachability { ) self.notificationQueue = notificationQueue } - + deinit { stopNotifier() } - + // MARK: - *** Notifier methods *** public func startNotifier() throws { guard networkReachability.pathUpdateHandler == nil else { return } - networkReachability.pathUpdateHandler = { [weak self] path in + networkReachability.pathUpdateHandler = { [weak self] _ in guard let self = self else { return } self.notificationQueue.async { self.notificationCenter.post(name: .reachabilityChanged, object: self) } } } - + public func stopNotifier() { networkReachability.pathUpdateHandler = nil } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift index 57af2aa6fb..bfaf333a7f 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift @@ -10,7 +10,7 @@ import AWSPluginsCore import Foundation extension GraphQLResponseDecoder { - + /* The sequence of `responseType` checking attempts to decode to specific types before falling back to (5) serializing the data and letting the default decode run its course (6). @@ -39,7 +39,7 @@ extension GraphQLResponseDecoder { graphQLData = graphQLDataWithTypeName } let serializedJSON: Data - + if request.responseType == AnyModel.self { // 2 let anyModel = try AnyModel(modelJSON: graphQLData) serializedJSON = try encoder.encode(anyModel) @@ -89,7 +89,7 @@ extension GraphQLResponseDecoder { let variablesData = try JSONSerialization.data(withJSONObject: variables) return try decoder.decode([String: JSONValue].self, from: variablesData) } - + // The Swift DataStore plugin has a dependency on using `__typename` from the response data. // For example, DataStore will use the type `MutationSync` to decode the model with sync metadata by // pulling out the modelName from `__typename` and use that to decode to the actual model type. diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift index 58c6bae833..130e3d4167 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift @@ -31,7 +31,7 @@ extension GraphQLRequest { responseType: responseType.self, decodePath: document.name) } - + static func getRequest(_ modelType: M.Type, byIdentifiers identifiers: [LazyReferenceIdentifier], apiName: String?) -> GraphQLRequest { @@ -39,9 +39,9 @@ extension GraphQLRequest { operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(identifiers: identifiers)) - + let document = documentBuilder.build() - + return GraphQLRequest(apiName: apiName, document: document.stringValue, variables: document.variables, diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift index fbf204c971..1b145420f0 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation extension Result { + // swiftlint:disable:next identifier_name func flatMapAsync(_ f: (Success) async -> Result) async -> Result { switch self { case .success(let value): diff --git a/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift b/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift index 2f0a3f62d8..91d56f9763 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift @@ -33,7 +33,7 @@ public protocol APICategoryGraphQLCallbackBehavior { @discardableResult func mutate(request: GraphQLRequest, listener: GraphQLOperation.ResultListener?) -> GraphQLOperation - + func subscribe(request: GraphQLRequest, valueListener: GraphQLSubscriptionOperation.InProcessListener?, completionListener: GraphQLSubscriptionOperation.ResultListener?) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift index 039215ff5f..e0aac8de36 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift @@ -16,7 +16,7 @@ public struct AWSPluginOptions { /// name of the model public let modelName: String? - + public init(authType: AWSAuthorizationType?, modelName: String?) { self.authType = authType self.modelName = modelName diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift index 1f3edd8786..cce327aed2 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift @@ -42,7 +42,7 @@ public protocol AuthModeStrategy: AnyObject { init() func authTypesFor(schema: ModelSchema, operation: ModelOperation) async -> AWSAuthorizationTypeIterator - + func authTypesFor(schema: ModelSchema, operations: [ModelOperation]) async -> AWSAuthorizationTypeIterator } @@ -95,7 +95,7 @@ public class AWSDefaultAuthModeStrategy: AuthModeStrategy { operation: ModelOperation) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: []) } - + public func authTypesFor(schema: ModelSchema, operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: []) @@ -197,7 +197,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { operation: ModelOperation) async -> AWSAuthorizationTypeIterator { return await authTypesFor(schema: schema, operations: [operation]) } - + /// Returns the union of authorization types for the provided schema for the given list of operations /// - Parameters: /// - schema: model schema @@ -213,7 +213,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { } }) .sorted(by: AWSMultiAuthModeStrategy.comparator) - + // if there isn't a user signed in, returns only public or custom rules if let authDelegate = authDelegate, await !authDelegate.isUserLoggedIn() { sortedRules = sortedRules.filter { rule in @@ -225,5 +225,5 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { } return AWSAuthorizationTypeIterator(withValues: applicableAuthTypes) } - + } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift index ab72c799a8..d0c279314c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift @@ -69,7 +69,7 @@ public class AWSAuthService: AWSAuthServiceBehavior { } return .success(convertedDictionary) } - + /// Retrieves the Cognito token from the AuthCognitoTokensProvider public func getUserPoolAccessToken() async throws -> String { let authSession = try await Amplify.Auth.fetchAuthSession() diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift index e984116ede..6c302cc928 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift @@ -17,7 +17,7 @@ public protocol AWSAuthServiceBehavior: AnyObject { /// Retrieves the identity identifier of for the Auth service func getIdentityID() async throws -> String - + /// Retrieves the token from the Auth token provider func getUserPoolAccessToken() async throws -> String } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift index a74a36e390..36d71a87e8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift @@ -17,37 +17,41 @@ import Amplify /// /// Types conforming to the `AuthSession` protocol support an `isSignedIn` flag. `isSignedIn` is true if a user has /// successfully completed a `signIn` flow, and has not subsequently signed out. -public protocol AWSAuthSessionBehavior : AuthSession { +public protocol AWSAuthSessionBehavior: AuthSession { - /// The concrete type holding the OIDC tokens from the authentication provider. Generally, this type will have at least - /// methods for retrieving an identity token and an access token. + /// The concrete type holding the OIDC tokens from the authentication provider. + /// Generally, this type will have at least methods for retrieving an identity token and an access token. associatedtype Tokens /// The result of the most recent attempt to get AWS Credentials. There is no guarantee that the credentials /// are not expired, but conforming types may have logic in place to automatically refresh the credentials. - /// The credentials may be fore either the unauthenticated or authenticated role, depending on the configuration of the - /// identity pool and the tokens used to retrieve the identity ID from Cognito. + /// The credentials may be fore either the unauthenticated or authenticated role, depending on the + /// configuration of the identity pool and the tokens used to retrieve the identity ID from Cognito. /// /// If the most recent attempt caused an error, the result will contain the details of the error. var awsCredentialsResult: Result { get } + // swiftlint:disable line_length /// The result of the most recent attempt to get a /// [Cognito identity pool identity ID](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html#CognitoIdentity-GetId-response-IdentityId). - /// The identityID may represent either an unauthenticated or authenticated identity, depending on the configuration of the - /// identity pool and the tokens used to retrieve the identity ID from Cognito. + /// The identityID may represent either an unauthenticated or authenticated identity, + /// depending on the configuration of the identity pool and the tokens used to + /// retrieve the identity ID from Cognito. /// /// If the most recent attempt caused an error, the result will contain the details of the error. var identityIdResult: Result { get } + // swiftlint:enable line_length - /// The result of the most recent attempt to get the current user's `sub` (unique User ID). Depending on the underlying - /// implementation, the details of the user ID may vary, but it is expected that this value is the `sub` claim of the - /// OIDC identity and access tokens. + /// The result of the most recent attempt to get the current user's `sub` (unique User ID). + /// Depending on the underlying implementation, the details of the user ID may vary, + /// but it is expected that this value is the `sub` claim of the OIDC identity and access tokens. /// /// If the most recent attempt caused an error, the result will contain the details of the error. var userSubResult: Result { get } - /// The result of the most recent attempt to get the current user's `sub` (unique User ID). Depending on the underlying - /// implementation, the details of the tokens may vary, but it is expected that the type will have at least methods for + /// The result of the most recent attempt to get the current user's `sub` (unique User ID). + /// Depending on the underlying implementation, + /// the details of the tokens may vary, but it is expected that the type will have at least methods for /// retrieving an identity token and an access token. /// /// If the most recent attempt caused an error, the result will contain the details of the error. diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift index 4da2777291..015f2e8395 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift @@ -46,7 +46,10 @@ public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { signatureType: .requestHeaders, signingAlgorithm: .sigv4) - let httpRequest = await AWSSigV4Signer.sigV4SignedRequest(requestBuilder: requestBuilder, signingConfig: signingConfig) + let httpRequest = await AWSSigV4Signer.sigV4SignedRequest( + requestBuilder: requestBuilder, + signingConfig: signingConfig + ) return httpRequest } catch let error { throw AuthError.unknown("Unable to sign request", error) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift index e9e6c7e6ac..c08e8821c8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift @@ -13,7 +13,7 @@ public protocol AuthAWSCredentialsProvider { func getAWSCredentials() -> Result } -public extension AuthAWSCredentialsProvider where Self:AWSAuthSessionBehavior { +public extension AuthAWSCredentialsProvider where Self: AWSAuthSessionBehavior { /// Return the most recent Result of fetching the AWS Credentials. If the temporary credentials are expired, returns /// a `AuthError.sessionExpired` failure. func getAWSCredentials() -> Result { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift index fe8d6bad45..f58cef8ce3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift @@ -15,7 +15,7 @@ public protocol AuthCognitoIdentityProvider { func getUserSub() -> Result } -public extension AuthCognitoIdentityProvider where Self:AWSAuthSessionBehavior { +public extension AuthCognitoIdentityProvider where Self: AWSAuthSessionBehavior { func getIdentityId() -> Result { identityIdResult } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift index b6fe5442e2..4c79d1d77b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift @@ -19,7 +19,7 @@ public struct BasicUserPoolTokenProvider: AuthTokenProvider { public init(authService: AWSAuthServiceBehavior) { self.authService = authService } - + public func getUserPoolAccessToken() async throws -> String { try await authService.getUserPoolAccessToken() } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift index ee6c00b1e0..3b7ccee072 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift @@ -46,7 +46,10 @@ extension KeychainStatus: CustomStringConvertible { case .itemNotFound: return "The specified item could not be found in the keychain." case .missingEntitlement: - return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." + return """ + Internal error when a required entitlement isn't present, + client has neither application-identifier nor keychain-access-groups entitlements. + """ case .unexpectedError(let status): return "Unexpected error has occurred with status: \(status)." } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift index e1f6934490..cbacba2e44 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift @@ -8,6 +8,7 @@ import Foundation import Security +// swiftlint:disable identifier_name public protocol KeychainStoreBehavior { @_spi(KeychainStore) @@ -16,14 +17,14 @@ public protocol KeychainStoreBehavior { /// - Parameter key: A String key use to look up the value in the Keychain /// - Returns: A string value func _getString(_ key: String) throws -> String - + @_spi(KeychainStore) /// Get a data value from the Keychain based on the key. /// This System Programming Interface (SPI) may have breaking changes in future updates. /// - Parameter key: A String key use to look up the value in the Keychain /// - Returns: A data value func _getData(_ key: String) throws -> Data - + @_spi(KeychainStore) /// Set a key-value pair in the Keychain. /// This System Programming Interface (SPI) may have breaking changes in future updates. @@ -31,7 +32,7 @@ public protocol KeychainStoreBehavior { /// - value: A string value to store in Keychain /// - key: A String key for the value to store in the Keychain func _set(_ value: String, key: String) throws - + @_spi(KeychainStore) /// Set a key-value pair in the Keychain. /// This iSystem Programming Interface (SPI) may have breaking changes in future updates. @@ -39,13 +40,13 @@ public protocol KeychainStoreBehavior { /// - value: A data value to store in Keychain /// - key: A String key for the value to store in the Keychain func _set(_ value: Data, key: String) throws - + @_spi(KeychainStore) /// Remove key-value pair from Keychain based on the provided key. /// This System Programming Interface (SPI) may have breaking changes in future updates. /// - Parameter key: A String key to delete the key-value pair func _remove(_ key: String) throws - + @_spi(KeychainStore) /// Removes all key-value pair in the Keychain. /// This System Programming Interface (SPI) may have breaking changes in future updates. @@ -187,7 +188,7 @@ public struct KeychainStore: KeychainStoreBehavior { throw KeychainStoreError.securityError(status) } } - + @_spi(KeychainStore) /// Removes all key-value pair in the Keychain. /// This System Programming Interface (SPI) may have breaking changes in future updates. @@ -219,7 +220,7 @@ extension KeychainStore { static let AttributeLabel = String(kSecAttrLabel) static let AttributeComment = String(kSecAttrComment) static let AttributeAccessible = String(kSecAttrAccessible) - + /** Attribute Accessible Constants */ static let AttributeAccessibleAfterFirstUnlockThisDeviceOnly = String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) @@ -234,8 +235,9 @@ extension KeychainStore { /** Value Type Key Constants */ static let ValueData = String(kSecValueData) - + /** Indicates whether to treat macOS keychain items like iOS keychain items without setting kSecAttrSynchronizable */ static let UseDataProtectionKeyChain = String(kSecUseDataProtectionKeychain) } } +// swiftlint:enable identifier_name diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift index 5d81c8b8d1..a638b2879b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift @@ -12,7 +12,7 @@ struct KeychainStoreAttributes { var itemClass: String = KeychainStore.Constants.ClassGenericPassword var service: String var accessGroup: String? - + } extension KeychainStoreAttributes { @@ -23,7 +23,7 @@ extension KeychainStoreAttributes { KeychainStore.Constants.AttributeService: service, KeychainStore.Constants.UseDataProtectionKeyChain: kCFBooleanTrue ] - + if let accessGroup = accessGroup { query[KeychainStore.Constants.AttributeAccessGroup] = accessGroup } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift index c288ec0b38..4de28d4697 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift @@ -78,7 +78,9 @@ extension KeychainStoreError: AmplifyError { } return """ To use Auth in a macOS project, you'll need to enable the Keychain Sharing capability. - This capability is required because Auth uses the Data Protection Keychain on macOS as a platform best practice. See TN3137: macOS keychain APIs and implementations for more information on how Keychain works on macOS and the Keychain Sharing entitlement. + This capability is required because Auth uses the Data Protection Keychain on macOS as + a platform best practice. See TN3137: macOS keychain APIs and implementations for more + information on how Keychain works on macOS and the Keychain Sharing entitlement. For more information on adding capabilities to your application, see Xcode Capabilities. """ #else diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift index 4c70689a10..0cf0f79d04 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift @@ -198,7 +198,7 @@ private extension AuthRules { return authType == provider.toAWSAuthorizationType() } } - + func filterBy(ownerFieldType: ModelFieldType, modelSchema: ModelSchema) -> AuthRules { return filter { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift index 72ed86a415..7d17b01e57 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -18,7 +18,7 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { private let lastSync: Int64? private let graphQLType: GraphQLOperationType private var primaryKeysOnly: Bool - + public init(version: Int? = nil, lastSync: Int64? = nil, graphQLType: GraphQLOperationType, @@ -93,8 +93,10 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { if !primaryKeysOnly || graphQLType == .mutation { // Continue to add version fields for all levels, for backwards compatibility // Reduce the selection set only when the type is "subscription" and "query" - // (specifically for syncQuery). Selection set for mutation should not be reduced because it needs to be the full selection set to send mutation events to older iOS clients, which do not have the reduced subscription - // selection set. subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the + // (specifically for syncQuery). Selection set for mutation should not be reduced + // because it needs to be the full selection set to send mutation events to older iOS clients, + // which do not have the reduced subscription selection set. + // subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the // LazyReference type. selectionSet.children.forEach { child in addConflictResolution(selectionSet: child, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift index 3a42420f98..7a7ef66cfb 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift @@ -15,7 +15,7 @@ public struct ModelDecorator: ModelBasedGraphQLDocumentDecorator { private let model: Model private let mutationType: GraphQLMutationType - + public init(model: Model, mutationType: GraphQLMutationType) { self.model = model self.mutationType = mutationType diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift index fb23beb1c1..07a9a2d523 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift @@ -14,7 +14,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { private var identifierFields = [(name: String, value: GraphQLDocumentValueRepresentable, type: String)]() public init(model: Model, schema: ModelSchema) { - + var firstField = true self.identifierFields = model.identifier(schema: schema).fields.compactMap { fieldName, _ in guard let value = model.graphQLInputForPrimaryKey(modelFieldName: fieldName, @@ -29,7 +29,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { } } } - + public init(identifierFields: [(name: String, value: Persistable)]) { var firstField = true identifierFields.forEach { name, value in @@ -37,7 +37,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { firstField = false } } - + public init(identifiers: [LazyReferenceIdentifier]) { var firstField = true identifiers.forEach({ identifier in diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift index 0b89ba83e6..2f86d9cb44 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift @@ -20,7 +20,7 @@ public struct GraphQLQuery: SingleDirectiveGraphQLDocument { self.inputs = inputs self.selectionSet = selectionSet } - + @available(*, deprecated, message: """ Init with modelType is deprecated, use init with modelSchema instead. """) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift index be0558530b..a737d57d2f 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift @@ -36,7 +36,7 @@ public struct ModelBasedGraphQLDocumentBuilder { if primaryKeysOnly && ModelRegistry.modelType(from: modelSchema.name)?.rootPath == nil { primaryKeysOnly = false } - + switch operationType { case .query: self.document = GraphQLQuery(modelSchema: modelSchema, primaryKeysOnly: primaryKeysOnly) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift index b779199e53..cdc367dde3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift @@ -44,7 +44,7 @@ protocol ModelSyncGraphQLRequestFactory { subscriptionType: GraphQLSubscriptionType, claims: IdentityClaimsDictionary, authType: AWSAuthorizationType?) -> GraphQLRequest - + static func syncQuery(modelSchema: ModelSchema, where predicate: QueryPredicate?, limit: Int?, @@ -210,7 +210,7 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { decodePath: document.name, options: requestOptions) } - + public static func syncQuery(modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, limit: Int? = nil, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift index 6e55f0d929..7229c4ea1b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift @@ -56,12 +56,12 @@ protocol ModelGraphQLRequestFactory { byIdentifier id: String, includes: IncludedAssociations) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default - + static func get(_ modelType: M.Type, byIdentifier id: ModelIdentifier, includes: IncludedAssociations) -> GraphQLRequest where M: ModelIdentifiable - + // MARK: Mutation /// Creates a `GraphQLRequest` that represents a mutation of a given `type` for a `model` instance. @@ -181,7 +181,7 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { type: GraphQLMutationType) -> GraphQLRequest { mutation(of: model, modelSchema: model.schema, where: predicate, includes: includes, type: type) } - + public static func mutation(of model: M, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, @@ -190,12 +190,12 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) - + if let modelPath = M.rootPath as? ModelPath { let associations = includes(modelPath) documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } - + switch type { case .create: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) @@ -239,14 +239,14 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { responseType: M?.self, decodePath: document.name) } - + public static func get(_ modelType: M.Type, byIdentifier id: String, includes: IncludedAssociations = { _ in [] }) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { return .get(modelType, byId: id, includes: includes) } - + public static func get(_ modelType: M.Type, byIdentifier id: ModelIdentifier, includes: IncludedAssociations = { _ in [] }) -> GraphQLRequest @@ -254,20 +254,20 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) - + if let modelPath = modelType.rootPath as? ModelPath { let associations = includes(modelPath) documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } documentBuilder.add(decorator: ModelIdDecorator(identifierFields: id.fields)) let document = documentBuilder.build() - + return GraphQLRequest(document: document.stringValue, variables: document.variables, responseType: M?.self, decodePath: document.name) } - + public static func list(_ modelType: M.Type, where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index 18acdaa684..2e4c075b2c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -39,7 +39,7 @@ extension Model { for (modelField, modelFieldValue) in fields { let name = modelField.name - + guard let value = modelFieldValue else { // Scenario: When there is no model field value, set `nil` for removal of values or deassociation. // 1. It is unnessessary to set `nil` values for create mutations. @@ -68,7 +68,7 @@ extension Model { // 3. Set field values to `nil` for removal of values. input.updateValue(nil, forKey: name) } - + continue } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift index 61ab94efe8..b926808de4 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift @@ -56,14 +56,14 @@ extension SelectionSet { if field._isBelongsToOrHasOne { recursive = false } - + let child = SelectionSet(value: .init(name: field.name, fieldType: .model)) if primaryKeysOnly { child.withModelFields(schema.primaryKey.fields, recursive: recursive, primaryKeysOnly: primaryKeysOnly) } else { child.withModelFields(schema.graphQLFields, recursive: recursive, primaryKeysOnly: primaryKeysOnly) } - + self.addChild(settingParentOf: child) } } else { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift index bcecd4e60e..d6723f4835 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift @@ -13,7 +13,7 @@ public struct ModelSyncMetadata: Model { /// The timestamp (in Unix seconds) at which the last sync was started, as reported by the service public var lastSync: Int64? - + /// The sync predicate for this model, extracted out from the sync expression. public var syncPredicate: String? diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift index 9ddac1677d..718e3348f6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift @@ -37,7 +37,6 @@ extension MutationSyncMetadata { } } - extension MutationSyncMetadata: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier public typealias IdentifierFormat = ModelIdentifierFormat.Default diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift index f779aa7fbe..6ba1ab83aa 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift @@ -23,4 +23,3 @@ public func baseClientEngine( #endif return baseClientEngine } - diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift index 863fa636bf..49c3adf55b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift @@ -10,7 +10,7 @@ import ClientRuntime @_spi(InternalAmplifyPluginExtension) public class UserAgentSuffixAppender: AWSPluginExtension { @_spi(InternalHttpEngineProxy) - public var target: HttpClientEngine? = nil + public var target: HttpClientEngine? public let suffix: String private let userAgentKey = "User-Agent" diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift index 8c5d7cfa62..d0d87929a9 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift @@ -42,7 +42,7 @@ public class MockAWSAuthService: AWSAuthServiceBehavior { return identityId ?? "IdentityId" } - + public func getUserPoolAccessToken() async throws -> String { interactions.append(#function) if let error = getTokenError {